From: Erich Keane Date: Mon, 4 May 2015 23:09:37 +0000 (-0700) Subject: Integrated WIFI/ETHERNET adapters to single IPAdapter. X-Git-Tag: 1.2.0+RC1~1751 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=b2b9c7d9e130e14c07d42f2b2f07baa90108c336;p=platform%2Fupstream%2Fiotivity.git Integrated WIFI/ETHERNET adapters to single IPAdapter. Removed all eth,wifi adapter files and created ipadater files for easy access. Sconscripts,Resource Layer modified to adapt IPV4 instead of ethernet and wifi. Added network monitoring code for ipadapter. As its interface change and on 4 platforms, many changes are inevitable. Change-Id: Ib4db996e8a29ffc7f8955e9d0d7280c023d3d64d Signed-off-by: jw1103.kim Signed-off-by: vimala.v Signed-off-by: Erich Keane Reviewed-on: https://gerrit.iotivity.org/gerrit/752 Tested-by: jenkins-iotivity --- diff --git a/arduino.scons b/arduino.scons index 01da529..2f40e74 100644 --- a/arduino.scons +++ b/arduino.scons @@ -23,13 +23,22 @@ ## Import('env') +# Add 'SHIELD' build option, let user select board network connection type +vars = Variables() +if 'IP' in env.get('TARGET_TRANSPORT'): + vars.Add(EnumVariable('SHIELD', 'Network connection type', 'WIFI', ['ETH', 'WIFI'])) +elif 'BLE' in env.get('TARGET_TRANSPORT'): + vars.Add(EnumVariable('SHIELD', 'Network connection type', 'RBL_NRF8001', ['RBL_NRF8001'])) +vars.Update(env) +Help(vars.GenerateHelpText(env)) + env.ImportLib('SPI') -if 'ETHERNET' in env.get('TARGET_TRANSPORT'): +if 'ETH' in env.get('SHIELD'): env.ImportLib('Ethernet') -if 'WIFI' in env.get('TARGET_TRANSPORT'): +if 'WIFI' in env.get('SHIELD'): env.ImportLib('WiFi') env.AppendUnique(CPPDEFINES = ['ARDUINOWIFI']) -if 'BLE' in env.get('TARGET_TRANSPORT'): +if 'RBL_NRF8001' in env.get('SHIELD'): env.ImportLib('BLE') env.ImportLib('RBL_nRF8001') diff --git a/auto_build.sh b/auto_build.sh index e3c2bd2..ea12dd6 100755 --- a/auto_build.sh +++ b/auto_build.sh @@ -46,12 +46,12 @@ function build() fi echo "*********** Build for arduino avr *************" - scons resource TARGET_OS=arduino UPLOAD=false BOARD=mega TARGET_ARCH=avr TARGET_TRANSPORT=ETHERNET NET=Ethernet RELEASE=$3 - scons resource TARGET_OS=arduino UPLOAD=false BOARD=mega TARGET_ARCH=avr TARGET_TRANSPORT=WIFI NET=Wifi RELEASE=$3 + scons resource TARGET_OS=arduino UPLOAD=false BOARD=mega TARGET_ARCH=avr TARGET_TRANSPORT=IP SHIELD=ETH RELEASE=$3 + scons resource TARGET_OS=arduino UPLOAD=false BOARD=mega TARGET_ARCH=avr TARGET_TRANSPORT=IP SHIELD=WIFI RELEASE=$3 echo "*********** Build for arduino arm *************" - scons resource TARGET_OS=arduino UPLOAD=false BOARD=arduino_due_x TARGET_ARCH=arm TARGET_TRANSPORT=ETHERNET NET=Ethernet RELEASE=$3 - scons resource TARGET_OS=arduino UPLOAD=false BOARD=arduino_due_x TARGET_ARCH=arm TARGET_TRANSPORT=WIFI NET=Wifi RELEASE=$3 + scons resource TARGET_OS=arduino UPLOAD=false BOARD=arduino_due_x TARGET_ARCH=arm TARGET_TRANSPORT=IP SHIELD=ETH RELEASE=$3 + scons resource TARGET_OS=arduino UPLOAD=false BOARD=arduino_due_x TARGET_ARCH=arm TARGET_TRANSPORT=IP SHIELD=WIFI RELEASE=$3 if [ $(uname -s) = "Darwin" ] then diff --git a/build_common/SConscript b/build_common/SConscript index b2d73a5..1a65752 100644 --- a/build_common/SConscript +++ b/build_common/SConscript @@ -68,9 +68,9 @@ help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no' help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host])) if target_os in targets_disallow_multitransport: - help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ETHERNET', ['WIFI', 'BT', 'BLE', 'ETHERNET'])) + help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'IP', ['BT', 'BLE', 'IP'])) else: - help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'WIFI', 'BT', 'BLE', 'ETHERNET'])) + help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP'])) help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os])) help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1'))) diff --git a/build_common/linux/SConscript b/build_common/linux/SConscript index 5c67e25..2b26879 100644 --- a/build_common/linux/SConscript +++ b/build_common/linux/SConscript @@ -17,7 +17,7 @@ if env.get('LOGGING'): env.AppendUnique(CPPDEFINES = ['-DTB_LOG']) env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__']) -env.AppendUnique(CFLAGS = ['-std=c99']) +env.AppendUnique(CFLAGS = ['-std=gnu99']) env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC']) env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread']) diff --git a/resource/csdk/connectivity/SConscript b/resource/csdk/connectivity/SConscript index 17db6bf..6b65115 100644 --- a/resource/csdk/connectivity/SConscript +++ b/resource/csdk/connectivity/SConscript @@ -20,13 +20,13 @@ if target_os in targets_disallow_multitransport: if 'ALL' in transport: if target_os == 'linux': - env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER', 'ETHERNET_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER']) + env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER']) elif target_os == 'tizen': - env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER', 'NO_ETHERNET_ADAPTER','EDR_ADAPTER','LE_ADAPTER']) + env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER']) elif target_os == 'darwin': - env.AppendUnique(CPPDEFINES = ['NO_WIFI_ADAPTER','ETHERNET_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER']) + env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','NO_EDR_ADAPTER','NO_LE_ADAPTER']) else: - env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER', 'ETHERNET_ADAPTER','EDR_ADAPTER','LE_ADAPTER']) + env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER']) print "CA Transport is ALL" else: if 'BT' in transport: @@ -49,16 +49,11 @@ else: else: env.AppendUnique(CPPDEFINES = ['NO_LE_ADAPTER']) - if 'WIFI' in transport: - env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER']) - print "CA Transport is WIFI" + if 'IP' in transport: + env.AppendUnique(CPPDEFINES = ['IP_ADAPTER']) + print "CA Transport is IP" else: - env.AppendUnique(CPPDEFINES = ['NO_WIFI_ADAPTER']) - if 'ETHERNET' in transport: - env.AppendUnique(CPPDEFINES = ['ETHERNET_ADAPTER']) - print "CA Transport is ETHERNET" - else: - env.AppendUnique(CPPDEFINES = ['NO_ETHERNET_ADAPTER']) + env.AppendUnique(CPPDEFINES = ['NO_IP_ADAPTER']) env.SConscript('./src/SConscript') diff --git a/resource/csdk/connectivity/api/cacommon.h b/resource/csdk/connectivity/api/cacommon.h index 7ad9d97..e3c2981 100644 --- a/resource/csdk/connectivity/api/cacommon.h +++ b/resource/csdk/connectivity/api/cacommon.h @@ -19,12 +19,12 @@ ******************************************************************/ /** - * @file - * This file contains the common data structures between Resource , CA and adapters. + * @file cacommon.h + * @brief This file contains the common data structures between Resource , CA and adapters */ -#ifndef __CA_COMMON_H_ -#define __CA_COMMON_H_ +#ifndef CA_COMMON_H_ +#define CA_COMMON_H_ #include #include @@ -106,16 +106,16 @@ typedef char *CAURI_t; typedef char *CAToken_t; /** - * @enum CAConnectivityType_t + * @enum CATransportType_t * @brief Different connectivities that are handled in Connectivity Abstraction */ typedef enum { - CA_ETHERNET = (1 << 0), /**< Ethernet Connection */ - CA_WIFI = (1 << 1), /**< WIFI Connection */ - CA_EDR = (1 << 2), /**< EDR Connection */ - CA_LE = (1 << 3) /**< LE Connection */ -} CAConnectivityType_t; + CA_IPV4 = (1 << 0), /**< IPV4 Transport Type */ + CA_IPV6 = (1 << 1), /**< IPV6 Transport Type */ + CA_EDR = (1 << 2), /**< EDR Transport Type */ + CA_LE = (1 << 3) /**< LE Transport Type */ +} CATransportType_t; /** * @enum CANetworkStatus_t @@ -149,7 +149,7 @@ typedef union } LE; /** - * @brief IP Information for wifi and ethernet ports + * @brief IP Information */ struct { @@ -191,7 +191,7 @@ typedef struct CAURI_t resourceUri; /**< Resource URI information **/ CAAddress_t addressInfo; /**< Remote Endpoint address **/ - CAConnectivityType_t connectivityType; /**< Connectivity of the endpoint**/ + CATransportType_t transportType; /**< Transport Type of the endpoint**/ bool isSecured; /**< Secure connection**/ } CARemoteEndpoint_t; @@ -202,7 +202,7 @@ typedef struct typedef struct { CAURI_t resourceUri; /**< Resource URI information **/ - CAConnectivityType_t connectivityType; /**< Connectivity of the endpoint**/ + CATransportType_t transportType; /**< Transport type of the endpoint**/ } CAGroupEndpoint_t; /** @@ -211,7 +211,7 @@ typedef struct typedef struct { CAAddress_t addressInfo; /**< Address of the interface **/ - CAConnectivityType_t type; /**< Connectivity of local device **/ + CATransportType_t type; /**< Transport type of local device **/ bool isSecured; /**< Secure connection**/ } CALocalConnectivity_t; @@ -337,5 +337,5 @@ typedef struct } /* extern "C" */ #endif -#endif //#ifndef __CA_COMMON_H_ +#endif //#ifndef CA_COMMON_H_ diff --git a/resource/csdk/connectivity/api/cainterface.h b/resource/csdk/connectivity/api/cainterface.h index 9f6fd36..91c29c5 100644 --- a/resource/csdk/connectivity/api/cainterface.h +++ b/resource/csdk/connectivity/api/cainterface.h @@ -144,14 +144,14 @@ CAResult_t CARegisterDTLSCredentialsHandler( * Remote endpoint * \n For ex : coap://10.11.12.13:4545/resource_uri ( for IP) * \n coap://10:11:12:13:45:45/resource_uri ( for BT) - * @param connectivityType [IN] Connectivity type of the endpoint + * @param transportType [IN] Transport type of the endpoint * @param object [OUT] Endpoint object which contains the above parsed data * @return #CA_STATUS_OK or #CA_STATUS_FAILED * @remark The created Remote endpoint can be freed using CADestroyRemoteEndpoint() API. * @see CADestroyRemoteEndpoint */ CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, - const CAConnectivityType_t connectivityType, + const CATransportType_t transportType, CARemoteEndpoint_t **object); /** diff --git a/resource/csdk/connectivity/build/How_To_Build.txt b/resource/csdk/connectivity/build/How_To_Build.txt index 5b2c5b0..7a64501 100644 --- a/resource/csdk/connectivity/build/How_To_Build.txt +++ b/resource/csdk/connectivity/build/How_To_Build.txt @@ -96,18 +96,17 @@ Note :- Currently Mega & Due build is supported. 3) Execute following command to start build : For Arduino Mega - $ scons TARGET_OS=arduino TARGET_TRANSPORT= TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= + $ scons TARGET_OS=arduino TARGET_TRANSPORT= SHIELD= TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= For Arduino Due - $ scons TARGET_OS=arduino TARGET_TRANSPORT= TARGET_ARCH=arm BOARD=arduino_due_x_dbg ARDUINO_HOME= + $ scons TARGET_OS=arduino TARGET_TRANSPORT= SHIELD= TARGET_ARCH=arm BOARD=arduino_due_x_dbg ARDUINO_HOME= NOTE: BOARD=arduino_due_x_dbg|arduino_due_x. Default is arduino_due_x_dbg. Possible values for are: - -> ETHERNET : - $ scons TARGET_OS=arduino TARGET_TRANSPORT=ETHERNET TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= - -> WIFI : - $ scons TARGET_OS=arduino TARGET_TRANSPORT=WIFI TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= + -> IP : + $ scons TARGET_OS=arduino TARGET_TRANSPORT=IP SHIELD=WIFI TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= + $ scons TARGET_OS=arduino TARGET_TRANSPORT=IP SHIELD=ETH TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= -> BLE : - $ scons TARGET_OS=arduino TARGET_TRANSPORT=BLE TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= + $ scons TARGET_OS=arduino TARGET_TRANSPORT=BLE SHIELD=RBL_NRF8001 TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= Note :- Only single transport can be built at a time for Arduino. @@ -115,11 +114,11 @@ For Arduino Due 5) After building sample, script will try to install on "/dev/ttyACM0" port in 'sudo' mode. To skip installation, set command line argument 'UPLOAD=false'. - "scons TARGET_OS=arduino TARGET_TRANSPORT=ETHERNET TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= UPLOAD=false" + "scons TARGET_OS=arduino TARGET_TRANSPORT=IP SHIELD=ETH TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= UPLOAD=false" 6) To set BLE Shield Name, include the option DEVICE_NAME during scons build. - -> $ scons TARGET_OS=arduino TARGET_TRANSPORT=ETHERNET TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= DEVICE_NAME=OIC + -> $ scons TARGET_OS=arduino TARGET_TRANSPORT=BLE SHIELD=RBL_NRF8001 TARGET_ARCH=avr BOARD=mega ARDUINO_HOME= DEVICE_NAME=OIC Specified Device name length MUST be less than 10 characters. RBL Library has this limitation. By Default DEVICE_NAME=OIC-DEVICE, if device name option is not specified diff --git a/resource/csdk/connectivity/build/SConscript b/resource/csdk/connectivity/build/SConscript index 76dad2e..93a102a 100644 --- a/resource/csdk/connectivity/build/SConscript +++ b/resource/csdk/connectivity/build/SConscript @@ -60,7 +60,7 @@ help_vars = Variables() help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', False)) help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host])) -help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'WIFI', 'BT', 'BLE', 'ETHERNET'])) +help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'BT', 'BLE', 'IP'])) help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os])) help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1'))) help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload)) diff --git a/resource/csdk/connectivity/build/arduino/arduino.scons b/resource/csdk/connectivity/build/arduino/arduino.scons index 36aac14..b6919e7 100644 --- a/resource/csdk/connectivity/build/arduino/arduino.scons +++ b/resource/csdk/connectivity/build/arduino/arduino.scons @@ -3,12 +3,21 @@ ## Import('env') +# Add 'SHIELD' build option, let user select board network connection type +vars = Variables() +if 'IP' in env.get('TARGET_TRANSPORT'): + vars.Add(EnumVariable('SHIELD', 'Network connection type', 'WIFI', ['ETH', 'WIFI'])) +elif 'BLE' in env.get('TARGET_TRANSPORT'): + vars.Add(EnumVariable('SHIELD', 'Network connection type', 'RBL_NRF8001', ['RBL_NRF8001'])) +vars.Update(env) +Help(vars.GenerateHelpText(env)) + env.ImportLib('SPI') -if 'ETHERNET' in env.get('TARGET_TRANSPORT'): +if 'ETH' in env.get('SHIELD'): env.ImportLib('Ethernet') -if 'WIFI' in env.get('TARGET_TRANSPORT'): +if 'WIFI' in env.get('SHIELD'): env.ImportLib('WiFi') -if 'BLE' in env.get('TARGET_TRANSPORT'): +if 'RBL_NRF8001' in env.get('SHIELD'): env.ImportLib('BLE') env.ImportLib('RBL_nRF8001') diff --git a/resource/csdk/connectivity/build/tizen/SConscript b/resource/csdk/connectivity/build/tizen/SConscript index 3c72392..bc87889 100644 --- a/resource/csdk/connectivity/build/tizen/SConscript +++ b/resource/csdk/connectivity/build/tizen/SConscript @@ -52,7 +52,7 @@ target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # 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(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'WIFI', 'ETHERNET', 'BT', 'BLE'])) +help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'IP', 'BT', 'BLE'])) help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os])) help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1'))) help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF'))) diff --git a/resource/csdk/connectivity/build/tizen/gbsbuild.sh b/resource/csdk/connectivity/build/tizen/gbsbuild.sh index 385fe5b..36131d1 100644 --- a/resource/csdk/connectivity/build/tizen/gbsbuild.sh +++ b/resource/csdk/connectivity/build/tizen/gbsbuild.sh @@ -28,7 +28,7 @@ mkdir ./tmp mkdir ./tmp/con/ cp -R ./* $sourcedir/tmp/con cp -R ./SConscript $sourcedir/tmp/con -cp -R ./src/wifi_adapter/SConscript $sourcedir/tmp/con/src/wifi_adapter/ +cp -R ./src/ip_adapter/SConscript $sourcedir/tmp/con/src/ip_adapter/ cp -R ./src/bt_le_adapter/SConscript $sourcedir/tmp/con/src/bt_le_adapter/ cp -R ./src/bt_edr_adapter/SConscript $sourcedir/tmp/con/src/bt_edr_adapter/ cp -R ./common/SConscript $sourcedir/tmp/con/common/ diff --git a/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec b/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec index a8689a3..0002cc0 100644 --- a/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec +++ b/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec @@ -45,8 +45,7 @@ cp -f %{ROOTDIR}/con/lib/libcoap-4.1.1/libcoap.a %{buildroot}/%{_libdir} cp -rf %{ROOTDIR}/con/api/cacommon.h* %{DEST_INC_DIR}/ cp -rf %{ROOTDIR}/con/inc/caadapterinterface.h* %{DEST_INC_DIR}/ cp -rf %{ROOTDIR}/con/common/inc/cathreadpool.h* %{DEST_INC_DIR}/ -cp -rf %{ROOTDIR}/con/inc/cawifiadapter.h* %{DEST_INC_DIR}/ -cp -rf %{ROOTDIR}/con/inc/caethernetadapter.h* %{DEST_INC_DIR}/ +cp -rf %{ROOTDIR}/con/inc/caipadapter.h* %{DEST_INC_DIR}/ cp -rf %{ROOTDIR}/con/inc/caedradapter.h* %{DEST_INC_DIR}/ cp -rf %{ROOTDIR}/con/inc/caleadapter.h* %{DEST_INC_DIR}/ cp -rf %{ROOTDIR}/con/api/cainterface.h* %{DEST_INC_DIR}/ diff --git a/resource/csdk/connectivity/build/tizen/scons/SConscript b/resource/csdk/connectivity/build/tizen/scons/SConscript index 318d954..f2d562f 100644 --- a/resource/csdk/connectivity/build/tizen/scons/SConscript +++ b/resource/csdk/connectivity/build/tizen/scons/SConscript @@ -20,7 +20,7 @@ if env.get('LOGGING'): env.ParseConfig("pkg-config --cflags --libs capi-network-wifi dlog glib-2.0") if 'ALL' in transport: - env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER', 'NO_ETHERNET_ADAPTER','EDR_ADAPTER','LE_ADAPTER']) + env.AppendUnique(CPPDEFINES = ['NO_IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER']) print "CA Transport is ALL" else: if 'BT' in transport: @@ -35,12 +35,5 @@ else: else: env.AppendUnique(CPPDEFINES = ['NO_LE_ADAPTER']) - if 'WIFI' in transport: - env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER']) - print "CA Transport is WIFI" - else: - env.AppendUnique(CPPDEFINES = ['NO_WIFI_ADAPTER']) - - env.SConscript(['../con/lib/libcoap-4.1.1/SConscript']) env.SConscript(['../con/SConscript']) diff --git a/resource/csdk/connectivity/inc/caadapterinterface.h b/resource/csdk/connectivity/inc/caadapterinterface.h index 92cb186..d51c41f 100644 --- a/resource/csdk/connectivity/inc/caadapterinterface.h +++ b/resource/csdk/connectivity/inc/caadapterinterface.h @@ -24,8 +24,8 @@ * This file contains the APIs for adapters to be implemented. */ -#ifndef __CA_ADAPTER_INTERFACE_H_ -#define __CA_ADAPTER_INTERFACE_H_ +#ifndef CA_ADAPTER_INTERFACE_H_ +#define CA_ADAPTER_INTERFACE_H_ #include "cacommon.h" @@ -157,10 +157,10 @@ typedef struct /** * @brief This will be used during the registration of adapters call backs to the common logic - * @see CAConnectivityHandler_t , CAConnectivityType_t + * @see CAConnectivityHandler_t , CATransportType_t */ typedef void (*CARegisterConnectivityCallback)(CAConnectivityHandler_t handler, - CAConnectivityType_t cType); + CATransportType_t cType); /** * @brief This will be used during the recive of network requests and response. @@ -179,5 +179,5 @@ typedef void (*CANetworkChangeCallback)(CALocalConnectivity_t *info, CANetworkSt } /* extern "C" */ #endif -#endif // __CA_ADAPTER_INTERFACE_H_ +#endif // CA_ADAPTER_INTERFACE_H_ diff --git a/resource/csdk/connectivity/inc/caadapternetdtls.h b/resource/csdk/connectivity/inc/caadapternetdtls.h index e93259f..86a7322 100644 --- a/resource/csdk/connectivity/inc/caadapternetdtls.h +++ b/resource/csdk/connectivity/inc/caadapternetdtls.h @@ -128,8 +128,7 @@ typedef struct CACacheMessage */ typedef enum { - DTLS_ETHERNET = 0, - DTLS_WIFI + DTLS_IP = 0, } eDtlsAdapterType_t; /** diff --git a/resource/csdk/connectivity/inc/caadapterutils.h b/resource/csdk/connectivity/inc/caadapterutils.h index 5822383..a9552ee 100644 --- a/resource/csdk/connectivity/inc/caadapterutils.h +++ b/resource/csdk/connectivity/inc/caadapterutils.h @@ -24,12 +24,13 @@ * This file contains common utility function for CA transport adaptors. */ -#ifndef _CA_ADAPTER_UTILS_H_ -#define _CA_ADAPTER_UTILS_H_ +#ifndef CA_ADAPTER_UTILS_H_ +#define CA_ADAPTER_UTILS_H_ #include "cacommon.h" #include "logger.h" #include "pdu.h" +#include "uarraylist.h" #ifdef __cplusplus extern "C" @@ -67,12 +68,43 @@ extern "C" } \ /** + * @brief Length of network interface name. + */ +#define CA_INTERFACE_NAME_SIZE 16 + +/** * @def IPV4_ADDR_ONE_OCTECT_LEN * @brief Macro to allocate memory for ipv4 address in the form of uint8_t. */ #define IPV4_ADDR_ONE_OCTECT_LEN 4 /** + * @brief Network Interface Information. + */ +typedef struct +{ + char ipAddress[CA_IPADDR_SIZE]; /**< Address of the interface **/ + char subnetMask[CA_IPADDR_SIZE]; /**< Maintains interface subnetmask **/ + char interfaceName[CA_INTERFACE_NAME_SIZE]; /**< Interface name**/ +} CANetInfo_t; + +/** + * @brief unicast and multicast server information. + */ +typedef struct +{ + int socketFd; /**< Socket decriptor **/ + char ipAddress[CA_IPADDR_SIZE]; /**< Address of the ip **/ + uint16_t port; /**< Server port number **/ + bool isSecured; /**< Indicates secured server **/ + bool isServerStarted; /**< Indicates server started **/ + bool isMulticastServer; /**< Indicates multicast server **/ + char ifAddr[CA_IPADDR_SIZE]; /**< Address of the multicast interface **/ + char interfaceName[CA_INTERFACE_NAME_SIZE]; /**< Interface Name **/ + char subNetMask[CA_IPADDR_SIZE]; /**< Subnet Mask **/ +} CAServerInfo_t; + +/** * @brief To log the PDU data */ void CALogPDUData(coap_pdu_t *pdu); @@ -81,8 +113,7 @@ void CALogPDUData(coap_pdu_t *pdu); * @fn CAAdapterCreateLocalEndpoint * @brief Create CALocalConnectivity_t instance. */ -CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CAConnectivityType_t type, - const char *address); +CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CATransportType_t type, const char *address); /** * @fn CAAdapterCopyLocalEndpoint @@ -100,8 +131,8 @@ void CAAdapterFreeLocalEndpoint(CALocalConnectivity_t *localEndPoint); * @fn CAAdapterCreateRemoteEndpoint * @brief Allocate CARemoteEndpoint_t instance. */ -CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CAConnectivityType_t type, - const char *address, const char *resourceUri); +CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CATransportType_t type, const char *address, + const char *resourceUri); /** * @fn CAAdapterCopyRemoteEndpoint @@ -134,8 +165,102 @@ CAResult_t CAParseIPv4AddressInternal(const char *ipAddrStr, uint8_t *ipAddr, */ bool CAAdapterIsSameSubnet(const char *ipAddress1, const char *ipAddress2, const char *netMask); +/** + * @brief Used to check the multicast server is running or not. + * + * @param serverInfoList [IN] Server information list. + * @param ipAddress [IN] Interface address of the server. + * @param multicastAddress [IN] Multicast address of the server. + * @param port [IN] Port number of the server. + * + * @return true or false. + */ +bool CAIsMulticastServerStarted(const u_arraylist_t *serverInfoList, const char *ipAddress, + const char *multicastAddress, uint16_t port); + +/** + * @brief Used to check the unicast server is running or not. + * + * @param serverInfoList [IN] Server information list. + * @param ipAddress [IN] Ip address of the server. + * @param port [IN] Port number of the server. + * + * @return true or false. + */ +bool CAIsUnicastServerStarted(const u_arraylist_t *serverInfoList, const char *ipAddress, + uint16_t port); + +/** + * @brief Used to get the port number based on given information. + * + * @param serverInfoList [IN] Server information list. + * @param ipAddress [IN] Ip address of the server. + * @param isSecured [IN] specifies whether to get secured or normal unicast server port. + * + * @return positive value on success and 0 on error. + */ +uint16_t CAGetServerPort(const u_arraylist_t *serverInfoList, const char *ipAddress, + bool isSecured); + +/** + * @brief Used to get the socket fd for given server information. + * + * @param serverInfoList [IN] Server information list. + * @param ipAddress [IN] Ip address of the server. + * @param isSecured [IN] To check whether it is secured server or not. + * @param isMulticast [IN] To check whether it is multicast server or not. + * @param type [IN] CA_IPV4, CA_IPV6 etc. + + * @return positive value on success and -1 on error. + */ +int CAGetSocketFdForUnicastServer(const u_arraylist_t *serverInfoList, const char *ipAddress, + bool isSecured, bool isMulticast, CATransportType_t type); + +/** + * @brief Used to add the server information into serverinfo list + * + * @param serverInfoList [INOUT] server information list. + * @param info [IN] server informations like ip, port. + * + * @return #CA_STATUS_OK or Appropriate error code + * @retval #CA_STATUS_OK Successful + * @retval #CA_STATUS_INVALID_PARAM Invalid input data + * @retval #CA_STATUS_FAILED Initialization failed + */ +CAResult_t CAAddServerInfo(u_arraylist_t *serverInfoList, CAServerInfo_t *info); + +/** + * @brief Used to remove the server information based on socket fd from server info list. + * + * @param serverInfoList [INOUT] server information list. + * @param sockFd [IN] Socket descriptor. + * + * @return None + */ +void CARemoveServerInfo(u_arraylist_t *serverInfoList, int sockFd); + +/** + * @brief Used to clear the memory of network inteface list + * Memory pointed by infoList will become invalid after this function call. + * + * @param infoList [IN] Network interface list. + * + * @return None + */ +void CAClearNetInterfaceInfoList(u_arraylist_t *infoList); + +/** + * @brief Used to clear the memory of server info list. + * Memory pointed by serverInfoList will become invalid after this function call. + * + * @param infoList [IN] Server information list. + * + * @return None + */ +void CAClearServerInfoList(u_arraylist_t *serverInfoList); + #ifdef __cplusplus } /* extern "C" */ #endif -#endif // _CA_ADAPTER_UTILS_H_ +#endif // CA_ADAPTER_UTILS_H_ diff --git a/resource/csdk/connectivity/inc/cainterfacecontroller.h b/resource/csdk/connectivity/inc/cainterfacecontroller.h index 79fbf27..c68310b 100644 --- a/resource/csdk/connectivity/inc/cainterfacecontroller.h +++ b/resource/csdk/connectivity/inc/cainterfacecontroller.h @@ -24,8 +24,8 @@ * This file contains common utility function for CA transport adaptors. */ -#ifndef __CA_INTERFACE_CONTROLLER_H_ -#define __CA_INTERFACE_CONTROLLER_H_ +#ifndef CA_INTERFACE_CONTROLLER_H_ +#define CA_INTERFACE_CONTROLLER_H_ #include "caadapterinterface.h" #include "cathreadpool.h" /* for thread pool */ @@ -58,17 +58,17 @@ void CASetNetworkChangeCallback(CANetworkChangeCallback callback); /** * @brief Starting different connectivity adapters based on the network selection. - * @param connectivity [IN] network type that want to start - * @return none + * @param transportType [IN] interested network for starting + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) */ -CAResult_t CAStartAdapter(CAConnectivityType_t connectivity); +CAResult_t CAStartAdapter(CATransportType_t transportType); /** * @brief Stopping different connectivity adapters based on the network un-selection. - * @param connectivity [IN] network type that want to stop + * @param transportType [IN] network type that want to stop * @return none */ -void CAStopAdapter(CAConnectivityType_t connectivity); +void CAStopAdapter(CATransportType_t transportType); /** * @brief Get network information such as ipaddress and mac information @@ -118,5 +118,5 @@ void CATerminateAdapters(); } /* extern "C" */ #endif -#endif //#ifndef __CA_INTERFACE_CONTROLLER_H_ +#endif //#ifndef CA_INTERFACE_CONTROLLER_H_ diff --git a/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h b/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h index 95942f4..a781500 100644 --- a/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h +++ b/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h @@ -24,8 +24,8 @@ * This file contains the APIs for the interface controller. */ -#ifndef __CA_INTERFACE_CONTROLLER_SINGLETHREAD_H_ -#define __CA_INTERFACE_CONTROLLER_SINGLETHREAD_H_ +#ifndef CA_INTERFACE_CONTROLLER_SINGLETHREAD_H_ +#define CA_INTERFACE_CONTROLLER_SINGLETHREAD_H_ #include "caadapterinterface.h" @@ -61,17 +61,17 @@ void CASetNetworkChangeCallback(CANetworkChangeCallback callback); /** * @brief Starting different connectivity adapters based on the network selection. - * @param connectivity [IN] network type that want to stop - * @return none + * @param transportType [IN] network type that want to stop + * @return none */ -CAResult_t CAStartAdapter(CAConnectivityType_t connectivity); +CAResult_t CAStartAdapter(CATransportType_t transportType); /** * @brief Stopping different connectivity adapters based on the network un-selection. - * @param connectivity [IN] un selected network for stopping the packets transfer + * @param transportType [IN] un selected network for stopping the packets transfer * @return none */ -void CAStopAdapter(CAConnectivityType_t connectivity); +void CAStopAdapter(CATransportType_t transportType); /** * @brief Get network information such as ipaddress and mac information. Gets the network diff --git a/resource/csdk/connectivity/inc/caethernetadapter.h b/resource/csdk/connectivity/inc/caipadapter.h similarity index 66% rename from resource/csdk/connectivity/inc/caethernetadapter.h rename to resource/csdk/connectivity/inc/caipadapter.h index 482c699..fc1e697 100644 --- a/resource/csdk/connectivity/inc/caethernetadapter.h +++ b/resource/csdk/connectivity/inc/caipadapter.h @@ -1,4 +1,4 @@ -/* **************************************************************** +/****************************************************************** * * Copyright 2014 Samsung Electronics All Rights Reserved. * @@ -19,13 +19,11 @@ ******************************************************************/ /** - * @file - * - * This file contains the APIs for Ethernet Adapter. + * @file caipadapter.h + * @brief This file contains the APIs for IP Adapter. */ - -#ifndef __CA_ETHERNET_ADAPTER_H__ -#define __CA_ETHERNET_ADAPTER_H__ +#ifndef CA_IP_ADAPTER_H_ +#define CA_IP_ADAPTER_H_ #include "cacommon.h" #include "caadapterinterface.h" @@ -37,8 +35,8 @@ extern "C" #endif /** - * @brief API to initialize Ethernet Interface. - * @param registerCallback [IN] Callback to register ETHERNET interfaces to Connectivity + * @brief API to initialize IP Interface. + * @param registerCallback [IN] Callback to register IP interfaces to Connectivity * Abstraction Layer * @param networkPacketCallback [IN] Callback to notify request and response messages from server(s) * started at Connectivity Abstraction Layer. @@ -47,86 +45,87 @@ extern "C" * @param handle [IN] Threadpool Handle * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAInitializeEthernet(CARegisterConnectivityCallback registerCallback, - CANetworkPacketReceivedCallback networkPacketCallback, - CANetworkChangeCallback netCallback, ca_thread_pool_t handle); + CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback networkPacketCallback, + CANetworkChangeCallback netCallback, ca_thread_pool_t handle); + /** - * @brief Start Ethernet Interface adapter. + * @brief Start IP Interface adapter. * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAStartEthernet(); +CAResult_t CAStartIP(); /** * @brief Start listening server for receiving multicast search requests * Transport Specific Behavior: - * Ethernet Starts Multicast Server on a particular interface and prefixed port number and + * IP Starts Multicast Server on a particular interface and prefixed port number and * as per OIC Specification. * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAStartEthernetListeningServer(); +CAResult_t CAStartIPListeningServer(); /** * @brief Start discovery servers for receiving multicast advertisements * Transport Specific Behavior: - * Ethernet Starts Start multicast server on a particular interface and prefixed port + * IP Starts Start multicast server on a particular interface and prefixed port * number as per OIC Specification * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAStartEthernetDiscoveryServer(); +CAResult_t CAStartIPDiscoveryServer(); /** * @brief Sends data to the endpoint using the adapter connectivity. * @param endpoint [IN] Remote Endpoint information (like ipaddress , port, - * reference uri and connectivity type) to which the unicast data has to be sent. + * reference uri and transport type) to which the unicast data has to be sent. * @param data [IN] Data which is 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 -1 indicates error. * @remarks dataLen must be > 0. */ -int32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, +int32_t CASendIPUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen); /** - * @brief Sends Multicast data to the endpoint using the Ethernet connectivity. + * @brief Sends Multicast data to the endpoint using the IP connectivity. * @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 -1 indicates error. * @remarks dataLen must be > 0. */ -int32_t CASendEthernetMulticastData(const void *data, uint32_t dataLen); +int32_t CASendIPMulticastData(const void *data, uint32_t dataLen); /** - * @brief Get Ethernet Connectivity network information + * @brief Get IP Connectivity network information * @param info [OUT] Local connectivity information structures * @param size [OUT] Number of local connectivity structures. * @return #CA_STATUS_OK or Appropriate error code * @remarks info is allocated in this API and should be freed by the caller. */ -CAResult_t CAGetEthernetInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size); +CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size); /** * @brief Read Synchronous API callback. * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAReadEthernetData(); +CAResult_t CAReadIPData(); /** * @brief Stops Unicast, Multicast servers and close the sockets. * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAStopEthernet(); +CAResult_t CAStopIP(); /** - * @brief Terminate the Ethernet connectivity adapter. + * @brief Terminate the IP connectivity adapter. * Configuration information will be deleted from further use * @return NONE */ -void CATerminateEthernet(); +void CATerminateIP(); #ifdef __cplusplus } /* extern "C" */ #endif -#endif // #ifndef __CA_ETHERNET_ADAPTER_H__ +#endif // #ifndef CA_IP_ADAPTER_H_ diff --git a/resource/csdk/connectivity/inc/caethernetadapter_singlethread.h b/resource/csdk/connectivity/inc/caipadapter_singlethread.h similarity index 72% rename from resource/csdk/connectivity/inc/caethernetadapter_singlethread.h rename to resource/csdk/connectivity/inc/caipadapter_singlethread.h index 8b5c734..2969878 100644 --- a/resource/csdk/connectivity/inc/caethernetadapter_singlethread.h +++ b/resource/csdk/connectivity/inc/caipadapter_singlethread.h @@ -1,4 +1,4 @@ -/* **************************************************************** +/****************************************************************** * * Copyright 2014 Samsung Electronics All Rights Reserved. * @@ -19,13 +19,11 @@ ******************************************************************/ /** - * @file - * - * This file contains the APIs for Ethernet Adapter. + * @file caipadapter_singlethread.h + * @brief This file contains the APIs for IP Adapter. */ - -#ifndef __CA_ETHERNET_ADAPTER_SINGLETHREAD_H__ -#define __CA_ETHERNET_ADAPTER_SINGLETHREAD_H__ +#ifndef CA_IP_ADAPTER_SINGLETHREAD_H_ +#define CA_IP_ADAPTER_SINGLETHREAD_H_ #include "cacommon.h" #include "caadapterinterface.h" @@ -36,8 +34,8 @@ extern "C" #endif /** - * @brief API to initialize Ethernet Interface. - * @param registerCallback [IN] Callback to register ETHERNET interfaces to Connectivity + * @brief API to initialize IP Interface. + * @param registerCallback [IN] Callback to register IP interfaces to Connectivity * Abstraction Layer * @param networkPacketCallback [IN] Callback to notify request and response messages from server(s) * started at Connectivity Abstraction Layer. @@ -45,33 +43,33 @@ extern "C" * Abstraction Layer. * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAInitializeEthernet(CARegisterConnectivityCallback registerCallback, +CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback, CANetworkPacketReceivedCallback networkPacketCallback, CANetworkChangeCallback netCallback); /** - * @brief Start Ethernet Interface adapter. + * @brief Start IP Interface adapter. * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAStartEthernet(); +CAResult_t CAStartIP(); /** * @brief Start listening server for receiving multicast search requests * Transport Specific Behavior: - * Ethernet Starts Multicast Server on all available IPs and prefixed port number and + * IP Starts Multicast Server on all available IPs and prefixed port number and * as per OIC Specification. * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAStartEthernetListeningServer(); +CAResult_t CAStartIPListeningServer(); /** * @brief Start discovery servers for receiving multicast advertisements * Transport Specific Behavior: - * Ethernet Starts multicast server on all available IPs and prefixed port + * IP Starts multicast server on all available IPs and prefixed port * number as per OIC Specification * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAStartEthernetDiscoveryServer(); +CAResult_t CAStartIPDiscoveryServer(); /** * @brief Sends data to the endpoint using the adapter connectivity. @@ -82,49 +80,49 @@ CAResult_t CAStartEthernetDiscoveryServer(); * @return The number of bytes sent on the network. Return value equal to -1 indicates error. * @remark dataLen must be > 0. */ -int32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, +int32_t CASendIPUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen); /** - * @brief Send Multicast data to the endpoint using the Ethernet connectivity. + * @brief Send Multicast data to the endpoint using the IP connectivity. * @param data [IN] Data which is 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 -1 indicates error. * @remark dataLen must be > 0. */ -int32_t CASendEthernetMulticastData(const void *data, uint32_t dataLen); +int32_t CASendIPMulticastData(const void *data, uint32_t dataLen); /** - * @brief Get Ethernet Connectivity network information + * @brief Get IP Connectivity network information * @param info [OUT] Local connectivity information structures * @param size [OUT] Number of local connectivity structures. * @return #CA_STATUS_OK or Appropriate error code * @remarks info is allocated in this API and should be freed by the caller. */ -CAResult_t CAGetEthernetInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size); +CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size); /** * @brief Read Synchronous API callback. * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAReadEthernetData(); +CAResult_t CAReadIPData(); /** * @brief Stops Unicast, Multicast servers and close the sockets. * @return #CA_STATUS_OK or Appropriate error code */ -CAResult_t CAStopEthernet(); +CAResult_t CAStopIP(); /** * @brief Terminate the Ethernet connectivity adapter. * Configuration information will be deleted from further use * @return NONE */ -void CATerminateEthernet(); +void CATerminateIP(); #ifdef __cplusplus } /* extern "C" */ #endif -#endif // #ifndef __CA_ETHERNET_ADAPTER_SINGLETHREAD_H__ +#endif // #ifndef CA_IP_ADAPTER_SINGLETHREAD_H_ diff --git a/resource/csdk/connectivity/inc/cawifiinterface.h b/resource/csdk/connectivity/inc/caipinterface.h similarity index 54% rename from resource/csdk/connectivity/inc/cawifiinterface.h rename to resource/csdk/connectivity/inc/caipinterface.h index 28bc84a..abc7b93 100644 --- a/resource/csdk/connectivity/inc/cawifiinterface.h +++ b/resource/csdk/connectivity/inc/caipinterface.h @@ -1,4 +1,4 @@ -/* **************************************************************** +/****************************************************************** * * Copyright 2014 Samsung Electronics All Rights Reserved. * @@ -19,19 +19,18 @@ ******************************************************************/ /** - * @file - * - * This file provides APIs for WIFI adapter - client, server, network - * monitor modules. + * @file caipinterface.h + * @brief This file provides APIs IP client/server/network monitor modules */ -#ifndef _CA_WIFI_INTERFACE_H_ -#define _CA_WIFI_INTERFACE_H_ +#ifndef CA_IP_INTERFACE_H_ +#define CA_IP_INTERFACE_H_ #include #include "cacommon.h" #include "cathreadpool.h" +#include "uarraylist.h" #ifdef __cplusplus extern "C" @@ -44,48 +43,52 @@ extern "C" */ typedef enum { - CA_UNICAST_SERVER = 0, /**< Unicast Server */ - CA_MULTICAST_SERVER, /**< Multicast Server */ - CA_SECURED_UNICAST_SERVER /**< Secured Unicast Server */ + CA_UNICAST_SERVER = 0, /**< Unicast Server */ + CA_MULTICAST_SERVER, /**< Multicast Server */ + CA_SECURED_UNICAST_SERVER /**< Secured Unicast Server */ } CAAdapterServerType_t; /** * @brief Callback to be notified on reception of any data from remote OIC devices. + * * @param ipAddress [IN] IP address of remote OIC device. * @param port [IN] Port number on which data is received. * @param data [IN] Data received from remote OIC device. * @param dataLength [IN] Length of data in bytes. - * @param isSecure [IN] Indicates the data is secure or not. + * @param isSecured [IN] Indicates the data is secure or not. + * * @return NONE - * @pre Callback must be registered using CAWiFiSetPacketReceiveCallback() + * @pre Callback must be registered using CAIPSetPacketReceiveCallback() */ -typedef void (*CAWiFiPacketReceivedCallback)(const char *ipAddress, uint16_t port, - const void *data, uint32_t dataLength, bool isSecure); +typedef void (*CAIPPacketReceivedCallback)(const char *ipAddress, uint16_t port, + const void *data, uint32_t dataLength, + bool isSecured); /** * @brief Callback to be notified when exception occures on multicast/unicast server. * @param type [IN] Type of server(#CAAdapterServerType_t) * @return NONE - * @pre Callback must be registered using CAWiFiSetExceptionCallback() + * @pre Callback must be registered using CAIPSetExceptionCallback() */ -typedef void (*CAWiFiExceptionCallback)(CAAdapterServerType_t type); +typedef void (*CAIPExceptionCallback)(CAAdapterServerType_t type); /** - * @brief Initialize WIFI server + * @brief Initialize IP server + * * @param threadPool [IN] Thread pool for managing Unicast/Multicast server threads. + * * @return #CA_STATUS_OK or Appropriate error code * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_INVALID_PARAM Invalid input data * @retval #CA_STATUS_FAILED Initialization failed */ -CAResult_t CAWiFiInitializeServer(const ca_thread_pool_t threadPool); - +CAResult_t CAIPInitializeServer(const ca_thread_pool_t threadPool); /** - * @brief Terminate WIFI server + * @brief Terminate IP server * @return NONE */ -void CAWiFiTerminateServer(void); +void CAIPTerminateServer(); /** * @brief Start multicast server for specified multicast address and port @@ -93,8 +96,7 @@ void CAWiFiTerminateServer(void); * @param localAddress [IN] Local adapter address to which server to be binded. * @param multicastAddress [IN] Multicast group address. * @param multicastPort [IN,OUT] Port number on which server will be running. If binding - the port failed, server starts in the next available port. - * @param serverFD [OUT] Multicast server socket FD. + * the port failed, server starts in the next available port. * * @return #CA_STATUS_OK or Appropriate error code * @retval #CA_STATUS_OK Successful @@ -102,19 +104,18 @@ void CAWiFiTerminateServer(void); * @retval #CA_SERVER_STARTED_ALREADY Multicast server is already started and running. * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAWiFiStartMulticastServer(const char *localAddress, const char *multicastAddress, - uint16_t multicastPort, int *serverFD); +CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress, + uint16_t multicastPort); /** * @brief Start unicast server for specified local address and port * * @param localAddress [IN] Local adapter address to which server to be binded. * @param port [IN,OUT] Port number on which server will be running. If binding - the port failed, server starts in the next available port. + * the port failed, server starts in the next available port. * @param forceStart [IN] Indicate whether to start server forcesfully on specified port * or not. - * @param isSecured [IN] True if the secure server to be started, otherwise false. - * @param serverFD [OUT] Unicast server socket FD. + * @param secured [IN] True if the secure server to be started, otherwise false. * * @return #CA_STATUS_OK or Appropriate error code * @retval #CA_STATUS_OK Successful @@ -122,92 +123,98 @@ CAResult_t CAWiFiStartMulticastServer(const char *localAddress, const char *mult * @retval #CA_SERVER_STARTED_ALREADY Unicast server is already started and running. * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAWiFiStartUnicastServer(const char *localAddress, uint16_t *port, - bool forceStart, bool isSecured, - int *serverFD); +CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port, bool forceStart, + bool secured); /** - * @brief Stop multicast server. + * @brief Stop servers that are running in particular interface address. + * + * @param interfaceAddress [IN] interface address in which servers are running. * * @return #CA_STATUS_OK or Appropriate error code * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAWiFiStopMulticastServer(void); +CAResult_t CAIPStopServer(const char *interfaceAddress); /** - * @brief Stop unicast server. + * @brief Used to stop all unicast and multicast servers. * * @return #CA_STATUS_OK or Appropriate error code * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAWiFiStopUnicastServer(); +CAResult_t CAIPStopAllServers(); -#ifdef __WITH_DTLS__ /** - * @brief Stop secured unicast server. + * @brief Used to get the socket fd based on index value of server info list. * - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_FAILED Operation failed + * @param index [IN] Index where we need socket fd value. + * @param isSecured [IN] For secured unicast server or normal server. + * + * @return positive value on success and -1 on error. */ -CAResult_t CAWiFiStopSecureUnicastServer(); -#endif +int CAGetSocketFdFromUnicastIPServerbyIndex(int16_t index, bool isSecured); /** - * @brief Get the Unicast Server Information if it is started + * @brief Used to get the number of unicast server currently running. * - * @param isSecured [IN] true if the secure server information needed, otherwise false. - * @param ipAddress [OUT] IP address on which server is binded and running. - * @param port [OUT]Port number on which server is running - * @param serverFD [OUT]Server socket fd. + * @param isSecured [IN] To identify whether its secured unicast server or normal server. * - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_INVALID_PARAM Invalid input data - * @retval #CA_STATUS_FAILED Operation failed - * @remarks ipAddress must be freed using free(). + * @return positive value on success and -1 on error. */ -CAResult_t CAWiFiGetUnicastServerInfo(bool isSecured, char **ipAddress, uint16_t *port, - int *serverFD); +int16_t CAGetNumberOfUnicastIPServers(bool isSecured); /** - * @brief Set this callback for receiving data packets from peer devices. + * @brief Used to get the stored socket fd for corresponding ipAddress. * - * @param callback [IN] Callback to be notified on reception of unicast/multicast data packets. + * @param ipAddress [IN] IpAddress of server. + * @param isSecured [IN] Used to check the server is secured or not. + * @param isMulticast [IN] To identify whether its for multicast or unicast. * - * @return NONE + * @return socket fd on success and -1 on error. */ -void CAWiFiSetPacketReceiveCallback(CAWiFiPacketReceivedCallback callback); +int CAGetSocketFdFromUnicastIPServer(const char *ipAddress, bool isSecured, bool isMulticast); /** - * @brief Set this callback for receiving exception notifications. + * @brief Used to get the port number to the corresponding ip for giving interface info. * - * @param callback [IN] Callback to be notified on occurance of exception on running servers. + * @param ipAddress [IN] IpAddress of server. + * @param isSecured [IN] Used to check the server is secured or not. * - * @return NONE + * @return port number on success and -1 on error. */ -void CAWiFiSetExceptionCallback(CAWiFiExceptionCallback callback); +uint16_t CAGetServerPortNum(const char *ipAddress, bool isSecured); /** - * @brief Set socket description for sending unicast UDP data. Once the Unicast server is started, - * the same socket descriptor is used for sending the Unicast UDP data. + * @brief Used to get the port number for corresponding ipAddress. + * + * @param serverInfoList [OUT] ServerInfoList holds unicast and multicast server informations. + * + * @return #CA_STATUS_OK or Appropriate error code + * @retval #CA_STATUS_OK Successful + * @retval #CA_STATUS_INVALID_PARAM Invalid input data + * @retval #CA_STATUS_FAILED Initialization failed + */ +CAResult_t CAGetIPServerInfoList(u_arraylist_t **serverInfoList); + +/** + * @brief Set this callback for receiving data packets from peer devices. + * + * @param callback [IN] Callback to be notified on reception of unicast/multicast data packets. * - * @param socketFD [IN] Socket descriptor used for sending UDP data. * @return NONE */ -void CAWiFiSetUnicastSocket(int socketFD); +void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback); -#ifdef __WITH_DTLS__ /** - * @brief Set socket description for sending secured (encrypted) unicast UDP data + * @brief Set this callback for receiving exception notifications. + * + * @param callback [IN] Callback to be notified on occurance of exception on running servers. * - * @param socketFD [IN] Socket descriptor used for sending secured (encrypted) UDP data. * @return NONE */ -void CAWiFiSetSecureUnicastSocket(int socketFD); -#endif +void CAIPSetExceptionCallback(CAIPExceptionCallback callback); /** * @brief API to send unicast UDP data @@ -222,23 +229,22 @@ void CAWiFiSetSecureUnicastSocket(int socketFD); * @return The number of bytes sent on the network. Returns 0 on error. * @remarks isSecure will be ignored when isMulticast is true. */ -uint32_t CAWiFiSendData(const char *remoteAddress, uint16_t port, - const void *data, uint32_t dataLength, - bool isMulticast, bool isSecured); +uint32_t CAIPSendData(const char *remoteAddress, uint16_t port, const void *data, + uint32_t dataLength, bool isMulticast, bool isSecure); /** - * @brief Callback to be notified when wifi adapter connection state changes. + * @brief Callback to be notified when IP adapter connection state changes. * * @param ipAddress [IN] IP address of remote OIC device. * @param status [IN] Connection status either #CA_INTERFACE_UP or #CA_INTERFACE_DOWN. * @return NONE - * @pre Callback must be registered using CAWiFiSetConnectionStateChangeCallback() + * @pre Callback must be registered using CAIPSetConnectionStateChangeCallback() */ -typedef void (*CAWiFiConnectionStateChangeCallback)(const char *ipAddress, - CANetworkStatus_t status); +typedef void (*CAIPConnectionStateChangeCallback)(const char *ipAddress, + CANetworkStatus_t status); /** - * @brief Initialize Wifi network monitor + * @brief Initialize IP network monitor * * @param threadPool [IN] Thread pool for managing network monitor thread. * @@ -247,37 +253,36 @@ typedef void (*CAWiFiConnectionStateChangeCallback)(const char *ipAddress, * @retval #CA_STATUS_INVALID_PARAM Invalid input data * @retval #CA_STATUS_FAILED Initialization failed */ -CAResult_t CAWiFiInitializeNetworkMonitor(const ca_thread_pool_t threadPool); +CAResult_t CAIPInitializeNetworkMonitor(const ca_thread_pool_t threadPool); /** - * @brief Terminate WIFI network monitor + * @brief Terminate IP network monitor by removing interface list. * @return NONE */ -void CAWiFiTerminateNetworkMonitor(void); +void CAIPTerminateNetworkMonitor(); /** - * @brief Start network monitoring process. + * @brief Start network monitoring process. It will start the monitor thread. * * @return #CA_STATUS_OK or Appropriate error code * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAWiFiStartNetworkMonitor(void); +CAResult_t CAIPStartNetworkMonitor(); /** - * @brief Stop network monitoring process. + * @brief Stop network monitoring process. It will stop the monitor thread. * * @return #CA_STATUS_OK or Appropriate error code * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAWiFiStopNetworkMonitor(void); +CAResult_t CAIPStopNetworkMonitor(); /** * @brief Get local adapter network information. * - * @param interfaceName [OUT] Local adapter interface name - * @param ipAddress [OUT] IP address + * @param netInterfaceList [OUT] network interface information list * * @return #CA_STATUS_OK or Appropriate error code * @retval #CA_STATUS_OK Successful @@ -285,11 +290,12 @@ CAResult_t CAWiFiStopNetworkMonitor(void); * @retval #CA_STATUS_FAILED Operation failed * @remarks interfaceName and ipAddress must be freed using free(). */ -CAResult_t CAWiFiGetInterfaceInfo(char **interfaceName, char **ipAddress); +CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList); /** * @brief Get local adapter network subnet mask. * + * @param ipAddress [IN] IpAddress which is used for getting subnet mask. * @param subnetMask [OUT] Local adapter interface subnet mask * * @return #CA_STATUS_OK or Appropriate error code @@ -298,26 +304,25 @@ CAResult_t CAWiFiGetInterfaceInfo(char **interfaceName, char **ipAddress); * @retval #CA_STATUS_FAILED Operation failed * @remarks subnetMask must be freed using free(). */ -CAResult_t CAWiFiGetInterfaceSubnetMask(char **subnetMask); +CAResult_t CAIPGetInterfaceSubnetMask(const char *ipAddress, char **subnetMask); /** - * @brief Get WIFI adapter connection state. + * @brief Get IP adapter connection state. * - * @return True if WIFI adapter is connected, otherwise false + * @return True if IP adapter is connected, otherwise false */ -bool CAWiFiIsConnected(void); + bool CAIPIsConnected(); /** - * @brief Set callback for receiving local wifi adapter connection status. + * @brief Set callback for receiving local IP adapter connection status. * - * @param callback [IN] Callback to be notified when local WIFI adapter connection state changes. + * @param callback [IN] Callback to be notified when IP adapter connection state changes. * @return NONE */ -void CAWiFiSetConnectionStateChangeCallback(CAWiFiConnectionStateChangeCallback callback); +void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback); #ifdef __cplusplus } #endif -#endif //_CA_WIFI_INTERFACE_H_ - +#endif //CA_IP_INTERFACE_H_ diff --git a/resource/csdk/connectivity/inc/caethernetinterface_singlethread.h b/resource/csdk/connectivity/inc/caipinterface_singlethread.h similarity index 77% rename from resource/csdk/connectivity/inc/caethernetinterface_singlethread.h rename to resource/csdk/connectivity/inc/caipinterface_singlethread.h index e0ee6e8..e0d11a0 100644 --- a/resource/csdk/connectivity/inc/caethernetinterface_singlethread.h +++ b/resource/csdk/connectivity/inc/caipinterface_singlethread.h @@ -1,4 +1,4 @@ -/* **************************************************************** +/****************************************************************** * * Copyright 2014 Samsung Electronics All Rights Reserved. * @@ -19,13 +19,12 @@ ******************************************************************/ /** - * @file - * - * This file provides APIs ethernet client/server/network monitor modules. + * @file caipinterface_singlethread.h + * @brief This file provides APIs IP client/server/network monitor modules */ -#ifndef _CA_ETHERNET_INTERFACE_SINGLETHREAD_H_ -#define _CA_ETHERNET_INTERFACE_SINGLETHREAD_H_ +#ifndef CA_IP_INTERFACE_SINGLETHREAD_H_ +#define CA_IP_INTERFACE_SINGLETHREAD_H_ #include @@ -54,33 +53,33 @@ typedef enum * @param data [IN] Data received from remote OIC device. * @param dataLength [IN] Length of data in bytes. * @return NONE - * @pre Callback must be registered using CAEthernetSetPacketReceiveCallback() + * @pre Callback must be registered using CAIPSetPacketReceiveCallback() */ -typedef void (*CAEthernetPacketReceivedCallback)(const char *ipAddress, uint32_t port, +typedef void (*CAIPPacketReceivedCallback)(const char *ipAddress, uint16_t port, const void *data, uint32_t dataLength); /** * @brief Callback to be notified when exception occures on multicast/unicast server. * @param type [IN] Type of server(#CAAdapterServerType_t) * @return NONE - * @pre Callback must be registered using CAEthernetSetExceptionCallback() + * @pre Callback must be registered using CAIPSetExceptionCallback() */ -typedef void (*CAEthernetExceptionCallback)(CAAdapterServerType_t type); +typedef void (*CAIPExceptionCallback)(CAAdapterServerType_t type); /** - * @brief Initialize Ethernet server + * @brief Initialize IP server * @return #CA_STATUS_OK or Appropriate error code * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_INVALID_PARAM Invalid input data * @retval #CA_STATUS_FAILED Initialization failed */ -CAResult_t CAEthernetInitializeServer(void); +CAResult_t CAIPInitializeServer(void); /** - * @brief Terminate Ethernet server + * @brief Terminate IP server * @return NONE */ -void CAEthernetTerminateServer(void); +void CAIPTerminateServer(void); /** * @brief Start multicast server for specified multicast address and port @@ -97,7 +96,7 @@ void CAEthernetTerminateServer(void); * @retval #CA_SERVER_STARTED_ALREADY Multicast server is already started and running. * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAEthernetStartMulticastServer(const char *localAddress, const char *multicastAddress, +CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress, uint16_t multicastPort, int *serverFD); /** @@ -116,7 +115,7 @@ CAResult_t CAEthernetStartMulticastServer(const char *localAddress, const char * * @retval #CA_SERVER_STARTED_ALREADY Unicast server is already started and running. * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAEthernetStartUnicastServer(const char *localAddress, uint16_t *port, +CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port, bool forceStart, int *serverFD); /** @@ -126,7 +125,7 @@ CAResult_t CAEthernetStartUnicastServer(const char *localAddress, uint16_t *port * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAEthernetStopMulticastServer(void); +CAResult_t CAIPStopMulticastServer(void); /** * @brief Stop unicast server. @@ -135,8 +134,9 @@ CAResult_t CAEthernetStopMulticastServer(void); * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAEthernetStopUnicastServer(); +CAResult_t CAIPStopUnicastServer(); +#ifdef __WITH_DTLS__ /** * @brief Stop secured unicast server. * @@ -144,7 +144,8 @@ CAResult_t CAEthernetStopUnicastServer(); * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAEthernetStopSecureUnicastServer(); +CAResult_t CAIPStopSecureUnicastServer(); +#endif /** * @brief Get the Unicast Server Information if it is started @@ -158,7 +159,7 @@ CAResult_t CAEthernetStopSecureUnicastServer(); * @retval #CA_STATUS_FAILED Operation failed * @remarks ipAddress must be freed using free(). */ -CAResult_t CAEthernetGetUnicastServerInfo(char **ipAddress, int16_t *port, int *serverFD); +CAResult_t CAIPGetUnicastServerInfo(char **ipAddress, uint16_t *port, int *serverFD); /** * @brief Set this callback for receiving data packets from peer devices. @@ -166,13 +167,13 @@ CAResult_t CAEthernetGetUnicastServerInfo(char **ipAddress, int16_t *port, int * * * @return NONE */ -void CAEthernetSetPacketReceiveCallback(CAEthernetPacketReceivedCallback callback); +void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback); /** * @brief Pull the Received Data * @return NONE */ -void CAEthernetPullData(); +void CAIPPullData(); /** * @brief Set this callback for receiving exception notifications. @@ -181,7 +182,7 @@ void CAEthernetPullData(); * * @return NONE */ -void CAEthernetSetExceptionCallback(CAEthernetExceptionCallback callback); +void CAIPSetExceptionCallback(CAIPExceptionCallback callback); /** * @brief Set socket description for sending unicast UDP data. Once the Unicast server is started, @@ -190,22 +191,24 @@ void CAEthernetSetExceptionCallback(CAEthernetExceptionCallback callback); * @param socketFD [IN] Socket descriptor used for sending UDP data. * @return NONE */ -void CAEthernetSetUnicastSocket(int socketFD); +void CAIPSetUnicastSocket(int socketFD); /** * @brief Set the port number for sending unicast UDP data * @param port [IN] Port number used for sending UDP data. * @return NONE */ -void CAEthernetSetUnicastPort(uint16_t port); +void CAIPSetUnicastPort(uint16_t port); +#ifdef __WITH_DTLS__ /** * @brief Set socket description for sending secured (encrypted) unicast UDP data * * @param socketFD [IN] Socket descriptor used for sending secured (encrypted) UDP data. * @return NONE */ -void CAEthernetSetSecureUnicastSocket(int socketFD); +void CAIPSetSecureUnicastSocket(int socketFD); +#endif /** * @brief API to send unicast UDP data @@ -218,34 +221,34 @@ void CAEthernetSetSecureUnicastSocket(int socketFD); * * @return The number of bytes sent on the network. Returns 0 on error. */ -uint32_t CAEthernetSendData(const char *remoteAddress, uint16_t port, +uint32_t CAIPSendData(const char *remoteAddress, uint16_t port, const char *buf, uint32_t bufLen, bool isMulticast); /** - * @brief Callback to be notified when ethernet adapter connection state changes. + * @brief Callback to be notified when IP adapter connection state changes. * * @param ipAddress [IN] IP address of remote OIC device. * @param status [IN] Connection status either #CA_INTERFACE_UP or #CA_INTERFACE_DOWN. * @return NONE - * @pre Callback must be registered using CAEthernetSetConnectionStateChangeCallback() + * @pre Callback must be registered using CAIPSetConnectionStateChangeCallback() */ -typedef void (*CAEthernetConnectionStateChangeCallback)(const char *ipAddress, +typedef void (*CAIPConnectionStateChangeCallback)(const char *ipAddress, CANetworkStatus_t status); /** - * @brief Initialize Ethernet network monitor + * @brief Initialize IP network monitor * @return #CA_STATUS_OK or Appropriate error code * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_INVALID_PARAM Invalid input data * @retval #CA_STATUS_FAILED Initialization failed */ -CAResult_t CAEthernetInitializeNetworkMonitor(void); +CAResult_t CAIPInitializeNetworkMonitor(void); /** - * @brief Terminate Ethernet network monitor + * @brief Terminate IP network monitor * @return NONE */ -void CAEthernetTerminateNetworkMonitor(void); +void CAIPTerminateNetworkMonitor(void); /** * @brief Start network monitoring process. @@ -254,7 +257,7 @@ void CAEthernetTerminateNetworkMonitor(void); * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAEthernetStartNetworkMonitor(void); +CAResult_t CAIPStartNetworkMonitor(void); /** * @brief Stop network monitoring process. @@ -263,7 +266,7 @@ CAResult_t CAEthernetStartNetworkMonitor(void); * @retval #CA_STATUS_OK Successful * @retval #CA_STATUS_FAILED Operation failed */ -CAResult_t CAEthernetStopNetworkMonitor(void); +CAResult_t CAIPStopNetworkMonitor(void); /** * @brief Get local adapter network information. @@ -277,14 +280,14 @@ CAResult_t CAEthernetStopNetworkMonitor(void); * @retval #CA_STATUS_FAILED Operation failed * @remarks interfaceName and ipAddress must be freed using free(). */ -CAResult_t CAEthernetGetInterfaceInfo(char **interfaceName, char **ipAddress); +CAResult_t CAIPGetInterfaceInfo(char **ipAddress, char **interfaceName); /** * @brief Get Ethernet adapter connection state. * * @return True if Ethernet adapter is connected, otherwise false */ -bool CAEthernetIsConnected(void); +bool CAIPIsConnected(void); /** * @brief Set callback for receiving local ethernet adapter connection status. @@ -293,12 +296,12 @@ bool CAEthernetIsConnected(void); * changes. * @return NONE */ -void CAEthernetSetConnectionStateChangeCallback - (CAEthernetConnectionStateChangeCallback callback); +void CAIPSetConnectionStateChangeCallback + (CAIPConnectionStateChangeCallback callback); #ifdef __cplusplus } #endif -#endif //_CA_ETHERNET_INTERFACE_SINGLETHREAD_H_ +#endif //CA_IP_INTERFACE_SINGLETHREAD_H_ diff --git a/resource/csdk/connectivity/inc/canetworkconfigurator.h b/resource/csdk/connectivity/inc/canetworkconfigurator.h index 8605c15..a407aea 100644 --- a/resource/csdk/connectivity/inc/canetworkconfigurator.h +++ b/resource/csdk/connectivity/inc/canetworkconfigurator.h @@ -24,8 +24,8 @@ * This file contains utility function for network configurations. */ -#ifndef CA_NETWORK_CONFIGURATOR_H_ -#define CA_NETWORK_CONFIGURATOR_H_ +#ifndef NETWORK_CONFIGURATOR_H_ +#define NETWORK_CONFIGURATOR_H_ #include "cacommon.h" #include "uarraylist.h" @@ -37,17 +37,17 @@ extern "C" /** * @brief Add network type to the selected networks for network packets reception - * @param connectivityType [IN] connectivity type that needs to be added + * @param transportType [IN] Transport type that needs to be added * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) */ -CAResult_t CAAddNetworkType(CAConnectivityType_t connectivityType); +CAResult_t CAAddNetworkType(CATransportType_t transportType); /** * @brief Remove network type from the selected configuration - * @param connectivityType [IN] connectivity type that needs to be removed + * @param transportType [IN] Transport type that needs to be removed * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) */ -CAResult_t CARemoveNetworkType(CAConnectivityType_t connectivityType); +CAResult_t CARemoveNetworkType(CATransportType_t transportType); /** * @brief Get selected network information @@ -74,5 +74,5 @@ CAResult_t CATerminateNetworkType(); } /* extern "C" */ #endif -#endif //#ifndef CA_NETWORK_CONFIGURATOR_H_ +#endif //#ifndef NETWORK_CONFIGURATOR_H_ diff --git a/resource/csdk/connectivity/inc/caremotehandler.h b/resource/csdk/connectivity/inc/caremotehandler.h index 985a814..528f7ac 100644 --- a/resource/csdk/connectivity/inc/caremotehandler.h +++ b/resource/csdk/connectivity/inc/caremotehandler.h @@ -24,8 +24,8 @@ * This file contains common utility function for remote endpoints. */ -#ifndef __CA_REMOTE_HANDLER_H_ -#define __CA_REMOTE_HANDLER_H_ +#ifndef CA_REMOTE_HANDLER_H_ +#define CA_REMOTE_HANDLER_H_ #include "cacommon.h" @@ -43,22 +43,23 @@ CARemoteEndpoint_t *CACloneRemoteEndpoint(const CARemoteEndpoint_t *endpoint); /** * @brief Creates a new remote endpoint from the input uri - * @param uri [IN] absolute uri information to create remote endpoint - * @param connectivityType [IN] connectivity type of the endpoint + * @param uri [IN] absolute uri information to create remote endpoint + * @param transportType [IN] transport type of the endpoint * @return remote endpoint created */ CARemoteEndpoint_t *CACreateRemoteEndpointUriInternal(const CAURI_t uri, - const CAConnectivityType_t connectivityType); + const CATransportType_t transportType); /** * @brief Creates a new remote endpoint from the input and other information - * @param resourceUri [IN] absolute uri information to create remote endpoint - * @param addr [IN] address of the endpoint - * @param type [IN] connectivity type of the endpoint + * @param resourceUri [IN] absolute uri information to create remote endpoint + * @param addr [IN] address of the endpoint + * @param type [IN] transport type of the endpoint * @return remote endpoint created */ CARemoteEndpoint_t *CACreateRemoteEndpointInternal(const CAURI_t resourceUri, - const CAAddress_t addr, const CAConnectivityType_t type); + const CAAddress_t addr, + const CATransportType_t type); /** * @brief Destroy remote endpoint @@ -99,5 +100,5 @@ void CADestroyResponseInfoInternal(CAResponseInfo_t *response); } /* extern "C" */ #endif -#endif //#ifndef __CA_REMOTE_HANDLER_H_ +#endif //#ifndef CA_REMOTE_HANDLER_H_ diff --git a/resource/csdk/connectivity/inc/caretransmission.h b/resource/csdk/connectivity/inc/caretransmission.h index aef0f65..996612e 100644 --- a/resource/csdk/connectivity/inc/caretransmission.h +++ b/resource/csdk/connectivity/inc/caretransmission.h @@ -33,8 +33,8 @@ #include "uarraylist.h" #include "cacommon.h" -/** CA_ETHERNET, CA_WIFI, CA_EDR, CA_LE **/ -#define DEFAULT_RETRANSMISSION_TYPE (CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE) +/** CA_IPV4, CA_EDR, CA_LE **/ +#define DEFAULT_RETRANSMISSION_TYPE (CA_IPV4 | CA_EDR | CA_LE) /** default ACK time is 2 sec.(CoAP) **/ #define DEFAULT_ACK_TIMEOUT_SEC 2 @@ -55,8 +55,8 @@ typedef void (*CATimeoutCallback_t)(const CARemoteEndpoint_t *endpoint, const vo typedef struct { - /** retransmission support connectivity type **/ - CAConnectivityType_t supportType; + /** retransmission support transport type **/ + CATransportType_t supportType; /** retransmission trying count **/ uint8_t tryingCount; diff --git a/resource/csdk/connectivity/inc/caretransmission_singlethread.h b/resource/csdk/connectivity/inc/caretransmission_singlethread.h index 3947b6c..f91d8d6 100644 --- a/resource/csdk/connectivity/inc/caretransmission_singlethread.h +++ b/resource/csdk/connectivity/inc/caretransmission_singlethread.h @@ -31,8 +31,8 @@ #include "uarraylist.h" #include "cacommon.h" -/** CA_ETHERNET, CA_WIFI, CA_LE **/ -#define DEFAULT_RETRANSMISSION_TYPE (CA_ETHERNET | CA_WIFI | CA_LE) +/** CA_IPV4, CA_LE **/ +#define DEFAULT_RETRANSMISSION_TYPE (CA_IPV4 | CA_LE) /** default retransmission trying count is 4. **/ #define DEFAULT_RETRANSMISSION_COUNT 4 @@ -50,8 +50,8 @@ typedef void (*CATimeoutCallback_t)(const CARemoteEndpoint_t *endpoint, const vo typedef struct { - /** retransmission support connectivity type **/ - CAConnectivityType_t supportType; + /** retransmission support transport type **/ + CATransportType_t supportType; /** retransmission trying count **/ uint8_t tryingCount; diff --git a/resource/csdk/connectivity/inc/cawifiadapter_singlethread.h b/resource/csdk/connectivity/inc/cawifiadapter_singlethread.h deleted file mode 100644 index 8a82ccf..0000000 --- a/resource/csdk/connectivity/inc/cawifiadapter_singlethread.h +++ /dev/null @@ -1,130 +0,0 @@ -/* **************************************************************** - * - * Copyright 2014 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -/** - * @file - * - * This file contains the APIs for WiFi Adapter. - */ - -#ifndef __CA_WIFI_ADAPTER_SINGLETHREAD_H__ -#define __CA_WIFI_ADAPTER_SINGLETHREAD_H__ - -#include "cacommon.h" -#include "caadapterinterface.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/** - * @brief Initialize WIFI Interface. - * @param registerCallback [IN] Callback to register WIFI interfaces to Connectivity - * Abstraction Layer - * @param networkPacketCallback [IN] Callback to notify request and response messages from server(s) - * started at Connectivity Abstraction Layer. - * @param netCallback [IN] Callback to notify the network additions to Connectivity - * Abstraction Layer. - * @return #CA_STATUS_OK or Appropriate error code - */ -CAResult_t CAInitializeWIFI(CARegisterConnectivityCallback registerCallback, - CANetworkPacketReceivedCallback networkPacketCallback, - CANetworkChangeCallback netCallback); - -/** - * @brief Start WIFI Interface adapter. - * @return #CA_STATUS_OK or Appropriate error code - */ -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 Appropriate error code - */ -CAResult_t CAStartWIFIListeningServer(); - -/** - * @brief Start WIFI Discovery Server 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 Appropriate error code - */ -CAResult_t CAStartWIFIDiscoveryServer(); - -/** - * @brief Sends data to the endpoint using the adapter connectivity. - * @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 to be sent. - * @param dataLen [IN] Size of data to be sent. - * @return The number of bytes sent on the network. Returns -1 on error. - * @remarks dataLen must be > 0. - */ -int32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, - uint32_t dataLen); - -/** - * @brief Sends Multicast data to the endpoint using the WIFI connectivity. - * @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. Returns -1 on error. - * @remarks dataLen must be > 0. - */ -int32_t CASendWIFIMulticastData(const 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 Appropriate error code - * @remarks info is allocated in this API and should be freed by the caller. - */ -CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size); - -/** - * @brief Read Synchronous API callback. - * @return #CA_STATUS_OK or Appropriate error code - */ -CAResult_t CAReadWIFIData(); - -/** - * @brief WIFI Stops Unicast, Multicast servers and close the sockets. - * @return #CA_STATUS_OK or Appropriate error code - */ -CAResult_t CAStopWIFI(); - -/** - * @brief Terminate the WIFI connectivity adapter. - * Configuration information will be deleted from further use - * @return NONE - */ -void CATerminateWIFI(); - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif // #ifndef __CA_WIFI_ADAPTER_SINGLETHREAD_H__ - diff --git a/resource/csdk/connectivity/inc/cawifiinterface_singlethread.h b/resource/csdk/connectivity/inc/cawifiinterface_singlethread.h deleted file mode 100644 index fb4c217..0000000 --- a/resource/csdk/connectivity/inc/cawifiinterface_singlethread.h +++ /dev/null @@ -1,300 +0,0 @@ -/* **************************************************************** - * - * Copyright 2014 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -/** - * @file - * - * This file provides APIs for WIFI adapter - client, server, network - * monitor modules. - */ - -#ifndef _CA_WIFI_INTERFACE_SINGLETHREAD_H_ -#define _CA_WIFI_INTERFACE_SINGLETHREAD_H_ - -#include - -#include "cacommon.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/** - * @enum CAAdapterServerType_t - * @brief Enum for defining different server types. - */ -typedef enum -{ - CA_UNICAST_SERVER = 0, /**< Unicast Server */ - CA_MULTICAST_SERVER, /**< Multicast Server */ - CA_SECURED_UNICAST_SERVER /**< Secured Unicast Server */ -} CAAdapterServerType_t; - -/** - * @brief Callback to be notified on reception of any data from remote OIC devices. - * @param ipAddress [IN] IP address of remote OIC device. - * @param port [IN] Port number on which data is received. - * @param data [IN] Data received from remote OIC device. - * @param dataLength [IN] Length of data in bytes. - * @return NONE - * @pre Callback must be registered using CAWiFiSetPacketReceiveCallback() - */ -typedef void (*CAWiFiPacketReceivedCallback)(const char *ipAddress, uint32_t port, - const void *data, uint32_t dataLength); - -/** - * @brief Callback to be notified when exception occures on multicast/unicast server. - * @param type [IN] Type of server(#CAAdapterServerType_t) - * @return NONE - * @pre Callback must be registered using CAWiFiSetExceptionCallback() - */ -typedef void (*CAWiFiExceptionCallback)(CAAdapterServerType_t type); - -/** - * @brief Initialize WIFI server - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_INVALID_PARAM Invalid input data - * @retval #CA_STATUS_FAILED Initialization failed - */ -CAResult_t CAWiFiInitializeServer(void); - -/** - * @brief Terminate WIFI server - * @return NONE - */ -void CAWiFiTerminateServer(void); - -/** - * @brief Start multicast server for specified multicast address and port - * - * @param localAddress [IN] Local adapter address to which server to be binded. - * @param multicastAddress [IN] Multicast group address. - * @param multicastPort [IN,OUT] Port number on which server will be running. If binding - the port failed, server starts in the next available port. - * @param serverFD [OUT] Multicast server socket FD. - * - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_INVALID_PARAM Invalid input data - * @retval #CA_SERVER_STARTED_ALREADY Multicast server is already started and running. - * @retval #CA_STATUS_FAILED Operation failed - */ -CAResult_t CAWiFiStartMulticastServer(const char *localAddress, const char *multicastAddress, - int16_t multicastPort, int *serverFD); - -/** - * @brief Start unicast server for specified local address and port - * - * @param localAddress [IN] Local adapter address to which server to be binded. - * @param port [IN,OUT] Port number on which server will be running. If binding - the port failed, server starts in the next available port. - * @param forceStart [IN] Indicate whether to start server forcesfully on specified port - * or not. - * @param serverFD [OUT] Unicast server socket FD. - * - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_INVALID_PARAM Invalid input data - * @retval #CA_SERVER_STARTED_ALREADY Unicast server is already started and running. - * @retval #CA_STATUS_FAILED Operation failed - */ -CAResult_t CAWiFiStartUnicastServer(const char *localAddress, int16_t *port, - bool forceStart, int *serverFD); - -/** - * @brief Stop multicast server. - * - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_FAILED Operation failed - */ -CAResult_t CAWiFiStopMulticastServer(void); - -/** - * @brief Stop unicast server. - * - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_FAILED Operation failed - */ -CAResult_t CAWiFiStopUnicastServer(); - -#ifdef __WITH_DTLS__ -/** - * @brief Stop secured unicast server. - * - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_FAILED Operation failed - */ -CAResult_t CAWiFiStopSecureUnicastServer(); -#endif - -/** - * @brief Get the Unicast Server Information if it is started - * @param ipAddress [OUT] IP address on which server is binded and running. - * @param port [OUT]Port number on which server is running - * @param serverFD [OUT]Server socket fd. - * - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_INVALID_PARAM Invalid input data - * @retval #CA_STATUS_FAILED Operation failed - * @remarks ipAddress must be freed using free(). - */ -CAResult_t CAWiFiGetUnicastServerInfo(char **ipAddress, int16_t *port, int *serverFD); - -/** - * @brief Set this callback for receiving data packets from peer devices. - * @param callback [IN] Callback to be notified on reception of unicast/multicast data packets. - * - * @return NONE - */ -void CAWiFiSetPacketReceiveCallback(CAWiFiPacketReceivedCallback callback); - -/** - * @brief Pull the Received Data - * @return NONE - */ -void CAWiFiPullData(); - -/** - * @brief Set this callback for receiving exception notifications. - * - * @param callback [IN] Callback to be notified on occurance of exception on running servers. - * - * @return NONE - */ -void CAWiFiSetExceptionCallback(CAWiFiExceptionCallback callback); - -/** - * @brief Set socket description for sending unicast UDP data. Once the Unicast server is started, - * the same socket descriptor is used for sending the Unicast UDP data. - * - * @param socketFD [IN] Socket descriptor used for sending UDP data. - * @return NONE - */ -void CAWiFiSetUnicastSocket(int socketFD); - -#ifdef __WITH_DTLS__ -/** - * @brief Set socket description for sending secured (encrypted) unicast UDP data - * - * @param socketFD [IN] Socket descriptor used for sending secured (encrypted) UDP data. - * @return NONE - */ -void CAWiFiSetSecureUnicastSocket(int socketFD); -#endif - -/** - * @brief API to send unicast UDP data - * - * @param remoteAddress [IN] IP address to which data needs to be sent. - * @param port [IN] Port to which data needs to be send. - * @param data [IN] Data to be send. - * @param dataLength [IN] Length of data in bytes - * @param isMulticast [IN] Whether data needs to be sent to multicast ip - * - * @return The number of bytes sent on the network. Returns 0 on error. - */ -uint32_t CAWiFiSendData(const char *remoteAddress, uint32_t port, - const void *data, uint32_t dataLength, bool isMulticast); - -/** - * @brief Callback to be notified when wifi adapter connection state changes. - * - * @param ipAddress [IN] IP address of remote OIC device. - * @param status [IN] Connection status either #CA_INTERFACE_UP or #CA_INTERFACE_DOWN. - * @return NONE - * @pre Callback must be registered using CAWiFiSetConnectionStateChangeCallback() - */ -typedef void (*CAWiFiConnectionStateChangeCallback)(const char *ipAddress, - CANetworkStatus_t status); - -/** - * @brief Initialize Wifi network monitor - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_INVALID_PARAM Invalid input data - * @retval #CA_STATUS_FAILED Initialization failed - */ -CAResult_t CAWiFiInitializeNetworkMonitor(void); - -/** - * @brief Terminate WIFI network monitor - * @return NONE - */ -void CAWiFiTerminateNetworkMonitor(void); - -/** - * @brief Start network monitoring process. - * - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_FAILED Operation failed - */ -CAResult_t CAWiFiStartNetworkMonitor(void); - -/** - * @brief Stop network monitoring process. - * - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_FAILED Operation failed - */ -CAResult_t CAWiFiStopNetworkMonitor(void); - -/** - * @brief Get local adapter network information. - * - * @param interfaceName [OUT] Local adapter interface name - * @param ipAddress [OUT] IP address - * - * @return #CA_STATUS_OK or Appropriate error code - * @retval #CA_STATUS_OK Successful - * @retval #CA_STATUS_INVALID_PARAM Invalid input data - * @retval #CA_STATUS_FAILED Operation failed - * @remarks interfaceName and ipAddress must be freed using free(). - */ -CAResult_t CAWiFiGetInterfaceInfo(char **interfaceName, char **ipAddress); - -/** - * @brief Get WIFI adapter connection state. - * - * @return True if WIFI adapter is connected, otherwise false - */ -bool CAWiFiIsConnected(void); - -/** - * @brief Set callback for receiving local wifi adapter connection status. - * - * @param callback [IN] Callback to be notified when local WIFI adapter connection state changes. - * @return NONE - */ -void CAWiFiSetConnectionStateChangeCallback(CAWiFiConnectionStateChangeCallback callback); - -#ifdef __cplusplus -} -#endif - -#endif //_CA_WIFI_INTERFACE_SINGLETHREAD_H_ - diff --git a/resource/csdk/connectivity/samples/android/sample_service/jni/ResourceModel.c b/resource/csdk/connectivity/samples/android/sample_service/jni/ResourceModel.c index d7c5853..aba8cff 100644 --- a/resource/csdk/connectivity/samples/android/sample_service/jni/ResourceModel.c +++ b/resource/csdk/connectivity/samples/android/sample_service/jni/ResourceModel.c @@ -36,7 +36,7 @@ int get_secure_information(CAPayload_t payLoad); CAResult_t get_network_type(int selectedNetwork); void callback(char *subject, char *receivedData); -CAConnectivityType_t g_selectedNwType = CA_WIFI; +CATransportType_t g_selectedNwType = CA_IPV4; static CAToken_t g_lastRequestToken = NULL; static uint8_t g_lastRequestTokenLength; static const char SECURE_COAPS_PREFIX[] = "coaps://"; @@ -704,7 +704,7 @@ void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* re securePort, object->resourceUri); CARemoteEndpoint_t *endpoint = NULL; - if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->connectivityType, &endpoint)) + if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint)) { LOGI("Failed to create duplicate of remote endpoint!\n"); return; @@ -724,13 +724,13 @@ void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* LOGI("##########Received response from remote device #############\n"); LOGI("Uri: %s\n", object->resourceUri); - if(object->connectivityType == CA_EDR) + if(object->transportType == CA_EDR) { LOGI("Remote Address: %s\n", object->addressInfo.BT.btMacAddress); - } else if(object->connectivityType == CA_LE) + } else if(object->transportType == CA_LE) { LOGI("Remote Address: %s\n", object->addressInfo.LE.leMacAddress); - } else if(object->connectivityType == CA_WIFI) + } else if(object->transportType == CA_IPV4) { LOGI("Remote Address: %s\n", object->addressInfo.IP.ipAddress); } @@ -743,13 +743,13 @@ void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* callback("received response from remote device", "#######"); callback("Uri: ", object->resourceUri); - if(object->connectivityType == CA_EDR) + if(object->transportType == CA_EDR) { callback("Remote Address: ", (char*) object->addressInfo.BT.btMacAddress); - } else if(object->connectivityType == CA_LE) + } else if(object->transportType == CA_LE) { callback("Remote Address: ", (char*) object->addressInfo.LE.leMacAddress); - } else if(object->connectivityType == CA_WIFI) + } else if(object->transportType == CA_IPV4) { callback("Remote Address: ", (char*) object->addressInfo.IP.ipAddress); } @@ -879,14 +879,9 @@ CAResult_t get_network_type(int selectedNetwork) { return CA_NOT_SUPPORTED; } - if (number & CA_ETHERNET) + if (number & CA_IPV4) { - g_selectedNwType = CA_ETHERNET; - return CA_STATUS_OK; - } - if (number & CA_WIFI) - { - g_selectedNwType = CA_WIFI; + g_selectedNwType = CA_IPV4; return CA_STATUS_OK; } if (number & CA_EDR) diff --git a/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/CAWiFiInterface.java b/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/caipinterface.java similarity index 76% rename from resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/CAWiFiInterface.java rename to resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/caipinterface.java index fc415b5..c6e5e78 100644 --- a/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/CAWiFiInterface.java +++ b/resource/csdk/connectivity/samples/android/sample_service/src/org/iotivity/jar/caipinterface.java @@ -9,18 +9,18 @@ import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.util.Log; -public class CAWiFiInterface { +public class caipinterface { - private static String TAG = "CAWiFiInterface"; + private static String TAG = "caipinterface"; private static Context mContext = null; - public CAWiFiInterface(Context context) { - Log.d(TAG, "CAWiFiInterface"); + public caipinterface(Context context) { + Log.d(TAG, "caipinterface"); mContext = context; - registerWiFiStateReceiver(); + registerIpStateReceiver(); } - private void registerWiFiStateReceiver() { + private void registerIpStateReceiver() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); @@ -35,21 +35,21 @@ public class CAWiFiInterface { public void onReceive(Context context, Intent intent) { if (intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_DISABLED) { - CAWiFiStateDisabled(); + CAIPStateDisabled(); } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo nwInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if(nwInfo.isConnected()) { - CAWiFiStateEnabled(); + CAIPStateEnabled(); } } } }; - public native static void CAWiFiStateEnabled(); + public native static void CAIPStateEnabled(); - public native static void CAWiFiStateDisabled(); + public native static void CAIPStateDisabled(); } diff --git a/resource/csdk/connectivity/samples/arduino/SConscript b/resource/csdk/connectivity/samples/arduino/SConscript index de01c69..660cd72 100644 --- a/resource/csdk/connectivity/samples/arduino/SConscript +++ b/resource/csdk/connectivity/samples/arduino/SConscript @@ -11,6 +11,11 @@ sample_env.AppendUnique(CPPPATH = [root_dir + '/inc/']) sample_env.AppendUnique(CPPPATH = [root_dir + '/lib/libcoap-4.1.1/']) sample_env.AppendUnique(CPPPATH = [root_dir + 'common/inc/']) +if env.get('SHIELD') == 'WIFI': + sample_env.AppendUnique(CPPDEFINES = ['ARDUINOWIFI']) +elif env.get('SHIELD') == 'ETH': + sample_env.AppendUnique(CPPDEFINES = ['ARDUINOETH']) + sample_dir = './samples/arduino/' arduino_simplecs = sample_env.Program('CASample', 'casample.cpp') env.CreateBin('CASample') diff --git a/resource/csdk/connectivity/samples/arduino/casample.cpp b/resource/csdk/connectivity/samples/arduino/casample.cpp index 1377b99..f22eb1c 100644 --- a/resource/csdk/connectivity/samples/arduino/casample.cpp +++ b/resource/csdk/connectivity/samples/arduino/casample.cpp @@ -29,12 +29,10 @@ #include "cainterface.h" #include "Arduino.h" -#ifdef ETHERNET_ADAPTER -#include "Ethernet.h" -#endif - -#ifdef WIFI_ADAPTER +#ifdef ARDUINOWIFI #include "WiFi.h" +#elif defined ARDUINOETH +#include "Ethernet.h" #endif #include "oic_malloc.h" @@ -97,12 +95,11 @@ void GetData(char *readInput, size_t bufferLength, size_t *dataLength) (*dataLength) = len; } -CAConnectivityType_t GetConnectivityType() +CATransportType_t GetConnectivityType() { char type[2] = {0}; Serial.println("Select network"); - Serial.println("ETHERNET: 0"); - Serial.println("WIFI: 1"); + Serial.println("IPv4: 0"); Serial.println("EDR: 2"); Serial.println("LE: 3"); @@ -111,20 +108,18 @@ CAConnectivityType_t GetConnectivityType() if (0 >= typeLen) { Serial.println("i/p err,default ethernet"); - return CA_ETHERNET; + return CA_IPV4; } switch (type[0]) { case '0': - return CA_ETHERNET; - case '1': - return CA_WIFI; + return CA_IPV4; case '2': return CA_EDR; case '3': return CA_LE; } - return CA_ETHERNET; + return CA_IPV4; } void setup() @@ -298,7 +293,7 @@ void FindResource() void SendRequest() { char buf[MAX_BUF_LEN] = {0}; - CAConnectivityType_t selectedNetwork; + CATransportType_t selectedNetwork; selectedNetwork = GetConnectivityType(); Serial.println("============"); @@ -385,7 +380,7 @@ void SendRequestAll() { char buf[MAX_BUF_LEN] = {0}; - CAConnectivityType_t selectedNetwork; + CATransportType_t selectedNetwork; selectedNetwork = GetConnectivityType(); Serial.println("========="); @@ -414,7 +409,7 @@ void SendRequestAll() CAGroupEndpoint_t *group = NULL; group = (CAGroupEndpoint_t *)OICMalloc(sizeof(CAGroupEndpoint_t)); - group->connectivityType = endpoint->connectivityType; + group->transportType = endpoint->transportType; group->resourceUri = endpoint->resourceUri; // create token @@ -560,7 +555,7 @@ void AdvertiseResource() void SendNotification() { char buf[MAX_BUF_LEN] = {0}; - CAConnectivityType_t selectedNetwork; + CATransportType_t selectedNetwork; selectedNetwork = GetConnectivityType(); Serial.println("============"); @@ -624,8 +619,7 @@ void SelectNetwork() Serial.println("============"); Serial.println("Select network"); - Serial.println("ETHERNET: 0"); - Serial.println("WIFI: 1"); + Serial.println("IPv4: 0"); Serial.println("EDR: 2"); Serial.println("LE: 3\n"); @@ -642,22 +636,7 @@ void SelectNetwork() { case 0: { -#ifdef ETHERNET_ADAPTER - // 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) - { - Serial.print("Failed: "); - Serial.println(error); - return; - } -#endif - } - break; - case 1: - { -#ifdef WIFI_ADAPTER +#ifdef ARDUINOWIFI const char ssid[] = "SSID"; // your network SSID (name) const char pass[] = "SSID_Password"; // your network password int16_t status = WL_IDLE_STATUS; // the Wifi radio's status @@ -676,6 +655,16 @@ void SelectNetwork() // Connect to WPA/WPA2 network: status = WiFi.begin((char *)ssid, pass); } +#elif defined ARDUINOETH + // 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) + { + Serial.print("Failed: "); + Serial.println(error); + return; + } #endif } break; @@ -687,7 +676,7 @@ void SelectNetwork() break; } - CASelectNetwork(CAConnectivityType_t(1<connectivityType = endpoint->connectivityType; + group->transportType = endpoint->transportType; group->resourceUri = endpoint->resourceUri; // create token @@ -910,8 +910,7 @@ void select_network() { printf("\n=============================================\n"); printf("\tselect network\n"); - printf("ETHERNET : 0\n"); - printf("WIFI : 1\n"); + printf("IPv4 : 0\n"); printf("EDR : 2\n"); printf("LE : 3\n"); printf("select : "); @@ -947,8 +946,7 @@ void unselect_network() { printf("\n=============================================\n"); printf("\tunselect enabled network\n"); - printf("ETHERNET : 0\n"); - printf("WIFI : 1\n"); + printf("IPv4 : 0\n"); printf("EDR : 2\n"); printf("LE : 3\n"); printf("select : "); @@ -1046,7 +1044,7 @@ void get_network_info() for (index = 0; index < tempSize; index++) { printf("Type: %d\n", tempInfo[index].type); - if (CA_WIFI == tempInfo[index].type || CA_ETHERNET == tempInfo[index].type) + if (CA_IPV4 == tempInfo[index].type) { printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress); printf("Port: %d\n", tempInfo[index].addressInfo.IP.port); @@ -1086,12 +1084,12 @@ void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *re printf("##########received request from remote device #############\n"); printf("Uri: %s\n", object->resourceUri); - if (CA_WIFI == object->connectivityType || CA_ETHERNET == object->connectivityType) + if (CA_IPV4 == object->transportType) { printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress, object->addressInfo.IP.port, object->isSecured); } - else if (CA_EDR == object->connectivityType) + else if (CA_EDR == object->transportType) { printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress); } @@ -1114,7 +1112,7 @@ void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *re //Check if this has secure communication information if (requestInfo->info.payload && - (CA_WIFI == object->connectivityType || CA_ETHERNET == object->connectivityType)) + (CA_IPV4 == object->transportType)) { int securePort = get_secure_information(requestInfo->info.payload); if (0 < securePort) //Set the remote endpoint secure details and send response @@ -1138,7 +1136,7 @@ void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *re object->addressInfo.IP.port, object->resourceUri); CARemoteEndpoint_t *endpoint = NULL; - if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->connectivityType, &endpoint)) + if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint)) { printf("Failed to create duplicate of remote endpoint!\n"); return; @@ -1160,12 +1158,12 @@ void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t * { printf("##########Received response from remote device #############\n"); printf("Uri: %s\n", object->resourceUri); - if (CA_WIFI == object->connectivityType || CA_ETHERNET == object->connectivityType) + if (CA_IPV4 == object->transportType) { printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress, object->addressInfo.IP.port, object->isSecured); } - else if (CA_EDR == object->connectivityType) + else if (CA_EDR == object->transportType) { printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress); } @@ -1289,7 +1287,7 @@ void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info) responseInfo.result = responseCode; responseInfo.info = responseData; - // send response (connectivityType from remoteEndpoint of request Info) + // send response (transportType from remoteEndpoint of request Info) CAResult_t res = CASendResponse(endpoint, &responseInfo); if (CA_STATUS_OK != res) { @@ -1382,9 +1380,8 @@ CAResult_t get_network_type() printf("\n=============================================\n"); printf("\tselect network type\n"); - printf("ETHERNET : 0\n"); - printf("WIFI : 1\n"); - printf("EDR : 2\n"); + printf("IPv4 : 0\n"); + printf("BT : 2\n"); printf("LE : 3\n"); printf("select : "); @@ -1401,14 +1398,9 @@ CAResult_t get_network_type() { return CA_NOT_SUPPORTED; } - if (number & CA_ETHERNET) - { - g_selected_nw_type = CA_ETHERNET; - return CA_STATUS_OK; - } - if (number & CA_WIFI) + if (number & CA_IPV4) { - g_selected_nw_type = CA_WIFI; + g_selected_nw_type = CA_IPV4; return CA_STATUS_OK; } if (number & CA_EDR) diff --git a/resource/csdk/connectivity/samples/tizen/SConscript b/resource/csdk/connectivity/samples/tizen/SConscript index 73717f3..be3619b 100644 --- a/resource/csdk/connectivity/samples/tizen/SConscript +++ b/resource/csdk/connectivity/samples/tizen/SConscript @@ -52,7 +52,7 @@ target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # 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(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'WIFI', 'ETHERNET', 'BT', 'BLE'])) +help_vars.Add(ListVariable('TARGET_TRANSPORT', 'Target transport', 'ALL', ['ALL', 'IP', 'BT', 'BLE'])) help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os])) help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1'))) diff --git a/resource/csdk/connectivity/samples/tizen/casample.c b/resource/csdk/connectivity/samples/tizen/casample.c index e863125..68bfd8d 100644 --- a/resource/csdk/connectivity/samples/tizen/casample.c +++ b/resource/csdk/connectivity/samples/tizen/casample.c @@ -18,44 +18,25 @@ * ******************************************************************/ +#include +#include +#include #include #include #include -#include #include -#include +#include #include #include "cacommon.h" #include "cainterface.h" -#ifdef __WITH_DTLS__ -#include "ocsecurityconfig.h" -#endif -/** - * @def MAX_BUF_LEN - * @brief maximum buffer length - */ -#define MAX_BUF_LEN 1024 - -/** - * @def MAX_OPT_LEN - * @brief maximum option length - */ -#define MAX_OPT_LEN 16 +static GMainLoop *mainloop = NULL; -/** - * @def PORT_LENGTH - * @brief maximum port length - */ -#define PORT_LENGTH 5 +pthread_t thread; -/** - * @def SECURE_DEFAULT_PORT - * @brief default secured port - */ -#define SECURE_DEFAULT_PORT 5684 +#define MAX_BUF_LEN 1024 +#define MAX_OPT_LEN 16 -#define RESOURCE_URI_LENGTH 14 /** * @def RS_IDENTITY @@ -67,51 +48,48 @@ */ #define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA") -static GMainLoop *g_mainloop = NULL; -pthread_t thread; -int g_received; -uint16_t g_local_secure_port = SECURE_DEFAULT_PORT; -CAConnectivityType_t g_selected_nw_type = CA_WIFI; -const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"}; - -char get_menu(); -void process(); -CAResult_t get_network_type(); -CAResult_t get_input_data(char *buf, int32_t length); - -void start_listening_server(); -void start_discovery_server(); -void find_resource(); -void send_request(); -void send_request_all(); -void advertise_resource(); -void send_notification(); -void select_network(); -void unselect_network(); -void handle_request_response(); -void find_fixed_resource(); -void get_network_info(); - -void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo); -void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo); -void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info); -void get_resource_uri(char *URI, char *resourceURI, int length); -int get_secure_information(CAPayload_t payLoad); - -static CAToken_t g_last_request_token = NULL; -static const char SECURE_COAPS_PREFIX[] = "coaps://"; -static const char SECURE_INFO_DATA[] = - "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"]," - "\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}"; -static const char NORMAL_INFO_DATA[] = - "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"]," - "\"if\":[\"oc.mi.def\"],\"obs\":1}}]}"; +int g_received = 0; +int g_localUnicastPort = 0; +int g_localSecurePort = 0; +CATransportType_t g_selected_nw_type = CA_IPV4; +const char* g_messageType[] = {"CON", "NON", "ACK", "RESET"}; + +char PrintOptions(); +void Process(); +CAResult_t GetNetworkType(); + +CAResult_t Initialize(); +void StartListeningServer(); +void StartDiscoveryServer(); +void FindResource(); +void SendRequest(); +void SendRequestAll(); +void SendResponse(); +void AdvertiseResource(); +void SendNotification(); +void SelectNetwork(); +void UnselectNetwork(); +void HandleRequestResponse(); +void FindFixedResource(); +void GetNetworkInfo(); + +void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo); +void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo); +void SendRequestTemp(CARemoteEndpoint_t *endpoint, CAToken_t token); +void GetResourceUri(char *URI, char *resourceURI, int length); +int GetSecureInformation(CAPayload_t payLoad); + +static CAToken_t g_lastRequestToken = NULL; +static const char g_secureInfoData[] = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"]," + "\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}"; +static const char g_normalInfoData[] = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"]," + "\"if\":[\"oc.mi.def\"],\"obs\":1}}]}"; #ifdef __WITH_DTLS__ static CADtlsPskCredsBlob_t *pskCredsBlob = NULL; -void clearDtlsCredentialInfo() +void ClearDtlsCredentialInfo() { printf("clearDtlsCredentialInfo IN\n"); if (pskCredsBlob) @@ -130,12 +108,11 @@ void clearDtlsCredentialInfo() printf("clearDtlsCredentialInfo OUT\n"); } -// Internal API. Invoked by CA stack to retrieve credentials from this module. +// Internal API. Invoked by CA stack to retrieve credentials from this module void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo) { printf("CAGetDtlsPskCredentials IN\n"); - - if(NULL == credInfo) + if(!credInfo) { printf("Invalid credential container"); return; @@ -165,17 +142,17 @@ void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo) printf("CAGetDtlsPskCredentials OUT\n"); } -CAResult_t SetCredentials() +bool SetCredentials() { printf("SetCredentials IN\n"); - pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t)); + pskCredsBlob = (CADtlsPskCredsBlob_t *)calloc(1, sizeof(CADtlsPskCredsBlob_t)); if (NULL == pskCredsBlob) { printf("Memory allocation failed!\n"); - return CA_MEMORY_ALLOC_FAILED; + return false; } - memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN); + memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN); pskCredsBlob->num = 1; pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num)); @@ -183,105 +160,79 @@ CAResult_t SetCredentials() { printf("Memory allocation failed!\n"); free(pskCredsBlob); - return CA_MEMORY_ALLOC_FAILED; + return false; } memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN); memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN); printf("SetCredentials OUT\n"); - return CA_STATUS_OK; + return true; } #endif -void GMainLoopThread() -{ - g_main_loop_run(g_mainloop); -} - -CAResult_t Initialize() +void pthread_func() { - g_mainloop = g_main_loop_new(NULL, FALSE); - if(!g_mainloop) - { - printf("g_main_loop_new failed\n"); - return CA_STATUS_FAILED; - } - - int result = pthread_create(&thread, NULL, (void *) &GMainLoopThread, NULL); - if (result < 0) - { - printf("pthread_create failed in initialize\n"); - return CA_STATUS_FAILED; - } - - CAResult_t res = CAInitialize(); - if (res != CA_STATUS_OK) - { - printf("CAInitialize fail\n"); - } - return res; + g_main_loop_run(mainloop); } int main() { - int ret = system("clear"); - // shell invoke error: 127, others: -1 - if (127 == ret || -1 == ret) - { - printf("Terminal Clear Error: %d\n", ret); - } + system("clear"); - printf("=============================================\n"); + printf("\n=============================================\n"); printf("\t\tsample main\n"); printf("=============================================\n"); - CAResult_t res = Initialize(); - if (CA_STATUS_OK != res) - { - printf("Initialization is failed\n"); - return -1; - } - + CAResult_t res = CA_STATUS_FAILED; /* - * Read DTLS PSK credentials from persistent storage and - * set in the OC stack. - */ + * Read DTLS PSK credentials from persistent storage and + * set in the OC stack. + */ #ifdef __WITH_DTLS__ - res = SetCredentials(); - if (CA_STATUS_OK != res) + if (SetCredentials() == false) { printf("SetCredentials failed\n"); - return -1; + return 1; } res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials); - if (CA_STATUS_OK != res) + if(CA_STATUS_OK != res) { printf("Set credential handler fail\n"); - return -1; + return 1; } #endif + res = Initialize(); + if (CA_STATUS_OK != res) + { + printf("CAInitialize fail\n"); + return 1; + } // set handler. - CARegisterHandler(request_handler, response_handler); + CARegisterHandler(RequestHandler, ResponseHandler); - process(); + Process(); - CADestroyToken(g_last_request_token); + if (g_lastRequestToken != NULL) + { + CADestroyToken(g_lastRequestToken); + } + g_lastRequestToken = NULL; CATerminate(); #ifdef __WITH_DTLS__ - clearDtlsCredentialInfo(); + ClearDtlsCredentialInfo(); #endif return 0; } -void process() +void Process() { while (1) { - char menu = get_menu(); + char menu = toupper(PrintOptions()); switch (menu) { @@ -289,59 +240,59 @@ void process() case 'M': break; - case 'q': // quit - case 'Q': + case 'Q': // quits the sample program printf("quit..!!\n"); + g_main_loop_quit(mainloop); return; case 's': // start server - case 'S': - start_listening_server(); + case 'S': // start server + StartListeningServer(); break; case 't': // send request case 'T': - send_request_all(); + SendRequestAll(); break; case 'c': // start client case 'C': - start_discovery_server(); + StartDiscoveryServer(); break; case 'f': // find resource case 'F': - find_resource(); + FindResource(); break; case 'r': // send request case 'R': - send_request(); + SendRequest(); break; case 'a': // advertise resource case 'A': - advertise_resource(); + AdvertiseResource(); break; case 'b': // send notification case 'B': - send_notification(); + SendNotification(); break; case 'n': // select network case 'N': - select_network(); + SelectNetwork(); break; case 'x': // unselect network case 'X': - unselect_network(); + UnselectNetwork(); break; case 'h': // handle request response case 'H': - handle_request_response(); + HandleRequestResponse(); break; case 'y': @@ -349,83 +300,97 @@ void process() while (1) { g_received = 0; - find_fixed_resource(); + FindFixedResource(); while (g_received == 0) { sleep(1); - handle_request_response(); + HandleRequestResponse(); } } break; - - case 'w': - case 'W': - g_received = 0; - start_discovery_server(); - //send_secure_request(); - while (g_received == 0) - { - sleep(1); - handle_request_response(); - } - break; - case 'z': case 'Z': - start_listening_server(); + StartListeningServer(); while (1) { sleep(1); - handle_request_response(); + HandleRequestResponse(); } break; case 'g': // get network information case 'G': - get_network_info(); + GetNetworkInfo(); break; default: - printf("Not supported menu!!\n"); + printf("not supported menu!!\n"); break; } } } -void start_listening_server() +CAResult_t Initialize() +{ + CAResult_t res = CA_STATUS_FAILED; + mainloop = g_main_loop_new(NULL, FALSE); + if(!mainloop) + { + printf("g_main_loop_new failed\n"); + return res; + } + + int result = pthread_create(&thread, NULL, (void *) &pthread_func, NULL); + if (result < 0) + { + printf("pthread_create failed in initialize\n"); + return res; + } + + res = CAInitialize(); + if (res != CA_STATUS_OK) + { + printf("CAInitialize fail\n"); + } + return res; +} + +void StartListeningServer() { - printf("Start listening server!!\n"); + printf("start listening server!!\n"); CAResult_t res = CAStartListeningServer(); - if (CA_STATUS_OK != res) + if (res != CA_STATUS_OK) { - printf("Start listening server fail, error code : %d\n", res); + printf("start listening server fail\n"); } else { - printf("Start listening server success\n"); + printf("start listening server success\n"); } } -void start_discovery_server() +void StartDiscoveryServer() { - printf("Start discovery client!!\n"); + printf("start discovery client!!\n"); CAResult_t res = CAStartDiscoveryServer(); - if (CA_STATUS_OK != res) + if (res != CA_STATUS_OK) { - printf("Start discovery client fail, error code : %d\n", res); + printf("start discovery client fail\n"); } else { - printf("Start discovery client success\n"); + printf("start discovery client success\n"); } } -void find_fixed_resource() +void FindFixedResource() { + char buf[] ="/a/light"; + // create token CAToken_t token = NULL; uint8_t tokenLength = CA_MAX_TOKEN_LEN; @@ -433,23 +398,20 @@ void find_fixed_resource() CAResult_t res = CAGenerateToken(&token, tokenLength); if ((CA_STATUS_OK != res) || (!token)) { - printf("Token generate error!!"); + printf("token generate error!!"); return; } printf("Generated token %s\n", token); - char buf[MAX_BUF_LEN] = { 0 }; - strcpy(buf, "/a/light"); - res = CAFindResource(buf, token, tokenLength); - if (CA_STATUS_OK != res) + if (res != CA_STATUS_OK) { - printf("Find resource error : %d\n", res); + printf("find resource error : %d\n", res); } else { - printf("Find resource to %s URI\n", buf); + printf("find resource to %s URI\n", buf); } // delete token @@ -458,15 +420,17 @@ void find_fixed_resource() printf("=============================================\n"); } -void find_resource() +void FindResource() { + char buf[MAX_BUF_LEN] = {0}; + printf("\n=============================================\n"); printf("ex) /a/light\n"); printf("reference uri : "); - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) + if(!fgets(buf, MAX_BUF_LEN, stdin)) { + printf("fgets error\n"); return; } @@ -477,88 +441,93 @@ void find_resource() CAResult_t res = CAGenerateToken(&token, tokenLength); if ((CA_STATUS_OK != res) || (!token)) { - printf("Token generate error!!\n"); + printf("token generate error!!\n"); return; } printf("Generated token %s\n", token); res = CAFindResource(buf, token, tokenLength); - if (CA_STATUS_OK != res) + if (res != CA_STATUS_OK) { - printf("Find resource error : %d\n", res); + printf("find resource error : %d\n", res); CADestroyToken(token); } else { - printf("Find resource to %s URI\n", buf); - CADestroyToken(g_last_request_token); - g_last_request_token = token; + printf("find resource to %s URI\n", buf); + + CADestroyToken(g_lastRequestToken); + + g_lastRequestToken = token; } printf("=============================================\n"); } -void send_request() +void SendRequest() { - CAResult_t res = get_network_type(); - if (CA_STATUS_OK != res) + char secureRequest[2] = {0}; + CAResult_t res = CA_STATUS_FAILED; + char uri[MAX_BUF_LEN] = {'\0'}; + + res = GetNetworkType(); + if (res != CA_STATUS_OK) { return; } - printf("Do you want to send secure request ?.... enter (0/1): "); - - char secureRequest[MAX_BUF_LEN] = {0}; - if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN)) + printf("Do you want to send secure request ?.... enter (0/1): \n"); + if(!fgets(secureRequest, 1, stdin)) { + printf("fgets error\n"); return; } - if (strcmp(secureRequest, "1") == 0) + if ('1' == secureRequest[0]) { printf("Enter the URI like below....\n"); printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n"); + printf("uri: "); } - else if (strcmp(secureRequest, "0") == 0) + else { printf("Enter the URI like below....\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"); - } - else - { - printf("Input data is wrong value\n"); - return; + printf("uri: "); } - char uri[MAX_BUF_LEN] = {'\0'}; - if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN)) + if(!fgets(uri, MAX_BUF_LEN, stdin)) { + printf("fgets error\n"); return; } // create remote endpoint CARemoteEndpoint_t *endpoint = NULL; - res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint); - if (CA_STATUS_OK != res || !endpoint) + if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, g_selectedNwType, &endpoint) + || !endpoint) { - printf("Failed to create remote endpoint, error code : %d\n", res); + printf("Failed to create remote endpoint!\n"); + CADestroyRemoteEndpoint(endpoint); return; } + char buf[MAX_BUF_LEN]={0}; + printf("\n=============================================\n"); printf("0:CON, 1:NON\n"); printf("select message type : "); - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) + if(!fgets(buf, MAX_BUF_LEN, stdin)) { + printf("fgets error\n"); CADestroyRemoteEndpoint(endpoint); return; } - CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0; + CAMessageType_t msgType = (buf[0] == '0' || buf[0] == '1') ? buf[0] - '0' : 0; // create token CAToken_t token = NULL; @@ -567,108 +536,108 @@ void send_request() res = CAGenerateToken(&token, tokenLength); if ((CA_STATUS_OK != res) || (!token)) { - printf("Token generate error, error code : %d\n", res); - CADestroyRemoteEndpoint(endpoint); + printf("token generate error, error code : %d\n", res); return; } printf("Generated token %s\n", token); // extract relative resourceuri from give uri - printf("URI : %s\n", uri); - char resourceURI[15] = {0}; - get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH); + + printf("URI : %s\n", uri); + GetResourceUri(uri, resourceURI, 14); // create request data - CAInfo_t requestData = { 0 }; + CAInfo_t requestData = {CA_MSG_RESET}; requestData.token = token; - requestData.tokenLength = tokenLength; - - if (strcmp(secureRequest, "1") == 0) + if ('1' == secureRequest[0]) { - uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI); - requestData.payload = (CAPayload_t) calloc(length, sizeof(char)); - if (NULL == requestData.payload) + int length = strlen(g_secureInfoData) + strlen(resourceURI) + 1; + requestData.payload = (CAPayload_t) malloc(length); + if(!requestData.payload) { - printf("Memory allocation fail\n"); - CADestroyRemoteEndpoint(endpoint); + printf("Memory allocation is failed\n"); CADestroyToken(token); + CADestroyRemoteEndpoint(endpoint); return; } - snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_local_secure_port); + sprintf(requestData.payload, g_secureInfoData, resourceURI, g_localSecurePort); } else { - uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI); - requestData.payload = (CAPayload_t) calloc(length, sizeof(char)); - if (NULL == requestData.payload) + int length = strlen(g_normalInfoData) + strlen(resourceURI) + 1; + requestData.payload = (CAPayload_t) malloc(length); + if(!requestData.payload) { - printf("Memory allocation fail\n"); - CADestroyRemoteEndpoint(endpoint); + printf("Memory allocation is failed\n"); CADestroyToken(token); + CADestroyRemoteEndpoint(endpoint); return; } - snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI); + sprintf(requestData.payload, g_normalInfoData, resourceURI); } requestData.type = msgType; - CARequestInfo_t requestInfo = { 0 }; + CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}}; requestInfo.method = CA_GET; requestInfo.info = requestData; // send request - res = CASendRequest(endpoint, &requestInfo); - if (CA_STATUS_OK != res) - { - printf("Could not send request : %d\n", res); - } + CASendRequest(endpoint, &requestInfo); - //destroy token CADestroyToken(token); - // destroy remote endpoint - CADestroyRemoteEndpoint(endpoint); - free(requestData.payload); + free(requestData.payload); + // destroy remote endpoint + CADestroyRemoteEndpoint(endpoint); printf("=============================================\n"); } -void send_request_all() +void SendRequestAll() { - CAResult_t res = get_network_type(); - if (CA_STATUS_OK != res) + char buf[MAX_BUF_LEN] = {0}; + + CAResult_t res = CA_STATUS_FAILED; + + res = GetNetworkType(); + if (res != CA_STATUS_OK) { return; } printf("\n=============================================\n"); - printf("ex) /a/light\n"); - printf("resource uri : "); + printf("10.11.12.13:4545/resource_uri ( for IP )\n"); + printf("10:11:12:13:45:45/resource_uri ( for BT )\n"); + printf("uri : "); - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) + if(!fgets(buf, MAX_BUF_LEN, stdin)) { + printf("fgets error\n"); return; } // create remote endpoint CARemoteEndpoint_t *endpoint = NULL; - res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint); - if (CA_STATUS_OK != res) + res = CACreateRemoteEndpoint(buf, g_selectedNwType, &endpoint); + + if (res != CA_STATUS_OK) { - printf("Create remote endpoint error, error code: %d\n", res); + printf("create remote endpoint error!!\n"); + CADestroyRemoteEndpoint(endpoint); return; } - CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t)); - if (NULL == group) + CAGroupEndpoint_t *group = NULL; + group = (CAGroupEndpoint_t *)malloc(sizeof(CAGroupEndpoint_t)); + if (NULL == group) { printf("Memory allocation failed!\n"); CADestroyRemoteEndpoint(endpoint); return; } - group->connectivityType = endpoint->connectivityType; + group->transportType = endpoint->transportType; group->resourceUri = endpoint->resourceUri; // create token @@ -678,9 +647,7 @@ void send_request_all() res = CAGenerateToken(&token, tokenLength); if ((CA_STATUS_OK != res) || (!token)) { - printf("Token generate error!!\n"); - CADestroyRemoteEndpoint(endpoint); - free(group); + printf("token generate error!!\n"); return; } @@ -696,81 +663,61 @@ void send_request_all() requestInfo.method = CA_GET; requestInfo.info = requestData; - // send request all - res = CASendRequestToAll(group, &requestInfo); - if (CA_STATUS_OK != res) - { - printf("Could not send request to all\n"); - CADestroyToken(token); - } - else - { - CADestroyToken(g_last_request_token); - g_last_request_token = token; - } + // send request + CASendRequestToAll(group, &requestInfo); + + CADestroyToken(token); // destroy remote endpoint CADestroyRemoteEndpoint(endpoint); + free(group); printf("=============================================\n"); } -void advertise_resource() +void AdvertiseResource() { + char buf[MAX_BUF_LEN] = {0}; + printf("\n=============================================\n"); printf("uri : "); - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) + if(!fgets(buf, MAX_BUF_LEN, stdin)) { + printf("fgets error\n"); return; } - char optionNumBuf[MAX_BUF_LEN] = { 0 }; - char optionData[MAX_OPT_LEN] = { 0 } ; + int optionNum = 0; + char optionData[MAX_OPT_LEN] = {0}; printf("Option Num : "); - if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN)) - { - return; - } - int optionNum = atoi(optionNumBuf); - - CAHeaderOption_t * headerOpt = (CAHeaderOption_t *) - calloc(1, optionNum * sizeof(CAHeaderOption_t)); + scanf("%d", &optionNum); + CAHeaderOption_t *headerOpt = NULL; + headerOpt = (CAHeaderOption_t *) malloc(sizeof(CAHeaderOption_t) * optionNum); if (NULL == headerOpt) { printf("Memory allocation failed!\n"); return; } + memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum); - int i; - for (i = 0; i < optionNum; i++) + int i = 0; + for (i = 0 ; i < optionNum ; i++) { - char getOptionID[MAX_BUF_LEN] = { 0 } ; - + int optionID = 0; printf("[%d] Option ID : ", i + 1); - if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN)) - { - free(headerOpt); - return; - } - int optionID = atoi(getOptionID); - + scanf("%d", &optionID); headerOpt[i].optionID = optionID; printf("[%d] Option Data : ", i + 1); - if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN)) - { - free(headerOpt); - return; - } - - memcpy(headerOpt[i].optionData, optionData, strlen(optionData)); - printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData); + scanf("%s", optionData); + int len = strlen(optionData); + memcpy(headerOpt[i].optionData, optionData, len + 1); + printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData ); - headerOpt[i].optionLength = (uint16_t) strlen(optionData); + headerOpt[i].optionLength = (uint16_t)len; } printf("\n=============================================\n"); @@ -781,118 +728,91 @@ void advertise_resource() CAResult_t res = CAGenerateToken(&token, tokenLength); if ((CA_STATUS_OK != res) || (!token)) { - printf("Token generate error!!\n"); - free(headerOpt); + printf("token generate error!!\n"); return; } - printf("Generated token %s\n", token); + printf("generated token %s\n", token); - res = CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t) optionNum); - if (CA_STATUS_OK != res) - { - printf("Could not start advertise resource\n"); - CADestroyToken(token); - } - else - { - CADestroyToken(g_last_request_token); - g_last_request_token = token; - } + CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t)optionNum); + + // delete token + CADestroyToken(token); free(headerOpt); } -void send_notification() +void SendNotification() { - CAResult_t res = get_network_type(); - if (CA_STATUS_OK != res) + char buf[MAX_BUF_LEN] = {0}; + + CAResult_t res = CA_STATUS_FAILED; + + res = get_network_type(); + if (res != CA_STATUS_OK) { return; } printf("\n=============================================\n"); - printf("Enter the URI like below....\n"); printf("10.11.12.13:4545/resource_uri ( for IP )\n"); printf("10:11:12:13:45:45/resource_uri ( for BT )\n"); printf("uri : "); - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) - { - return; - } - - printf("\n=============================================\n"); - printf("\tselect message type\n"); - printf("CON : 0\n"); - printf("NON : 1\n"); - printf("ACK : 2\n"); - printf("RESET : 3\n"); - printf("select : "); - - char messageTypeBuf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN)) + if(!fgets(buf, MAX_BUF_LEN, stdin)) { + printf("fgets error\n"); return; } - int messageType = messageTypeBuf[0] - '0'; - // create remote endpoint CARemoteEndpoint_t *endpoint = NULL; - res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint); - if (CA_STATUS_OK != res) + res = CACreateRemoteEndpoint(buf, g_selectedNwType, &endpoint); + if (res != CA_STATUS_OK) { - printf("Create remote endpoint error, error code: %d\n", res); + printf("create remote endpoint error!!\n"); + CADestroyRemoteEndpoint(endpoint); return; } - // create token - CAToken_t token = NULL; - uint8_t tokenLength = CA_MAX_TOKEN_LEN; + CAInfo_t respondData = {CA_MSG_RESET}; + respondData.tokenLength = CA_MAX_TOKEN_LEN; - res = CAGenerateToken(&token, tokenLength); - if ((CA_STATUS_OK != res) || (!token)) + res = CAGenerateToken(&respondData.token, respondData.tokenLength); + if ((CA_STATUS_OK != res) || (!respondData.token)) { - printf("Token generate error!!\n"); - CADestroyRemoteEndpoint(endpoint); + printf("token generate error!!\n"); return; } - printf("Generated token %s\n", token); - - CAInfo_t respondData = { 0 }; - respondData.token = token; - respondData.tokenLength = tokenLength; respondData.payload = "Temp Notification Data"; - respondData.type = messageType; - CAResponseInfo_t responseInfo = { 0 }; + CAResponseInfo_t responseInfo = {0}; responseInfo.result = CA_SUCCESS; responseInfo.info = respondData; - // send notification + // send request res = CASendNotification(endpoint, &responseInfo); - if (CA_STATUS_OK != res) + if (res != CA_STATUS_OK) { - printf("Send notification error, error code: %d\n", res); + printf("send notification error, error code: %d\n", res); } else { - printf("Send notification success\n"); + printf("send notification success\n"); } - // destroy token - CADestroyToken(token); + // delete token + CADestroyToken(respondData.token); // destroy remote endpoint CADestroyRemoteEndpoint(endpoint); printf("\n=============================================\n"); } - -void select_network() +void SelectNetwork() { + char buf[MAX_BUF_LEN] = {0}; + printf("\n=============================================\n"); printf("\tselect network\n"); printf("IPv4 : 0\n"); @@ -900,74 +820,71 @@ void select_network() printf("LE : 3\n"); printf("select : "); - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) + if(!fgets(buf, MAX_BUF_LEN, stdin)) { + printf("fgets error\n"); return; } int number = buf[0] - '0'; - if (number < 0 || number > 3) - { - printf("Invalid network type\n"); - return; - } + number = (number < 0 || number > 3) ? 0 : number; CAResult_t res = CASelectNetwork(1 << number); - if (CA_STATUS_OK != res) + if (res != CA_STATUS_OK) { - printf("Select network error\n"); - g_selected_nw_type = 1 << number; + printf("select network error\n"); + g_selectedNwType = 1 << number; } else { - printf("Select network success\n"); + printf("select network success\n"); } printf("=============================================\n"); } -void unselect_network() +void UnselectNetwork() { + char buf[MAX_BUF_LEN] = {0}; + printf("\n=============================================\n"); printf("\tunselect enabled network\n"); - printf("IPv4 : 0\n"); + printf("ETHERNET : 0\n"); + printf("WIFI : 1\n"); printf("EDR : 2\n"); printf("LE : 3\n"); printf("select : "); - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) + if(!fgets(buf, MAX_BUF_LEN, stdin)) { + printf("fgets error\n"); return; } int number = buf[0] - '0'; - if (number < 0 || number > 3) - { - printf("Invalid network type\n"); - return; - } + number = (number < 0 || number > 3) ? 1 : number; CAResult_t res = CAUnSelectNetwork(1 << number); - if (CA_STATUS_OK != res) + if (res != CA_STATUS_OK) { - printf("Unselect network error\n"); + printf("unselect network error\n"); } else { - printf("Unselect network success\n"); + printf("unselect network success\n"); } - printf("=============================================\n"); } -char get_menu() +char PrintOptions() { + char buf[MAX_BUF_LEN] = {0}; + printf("\n=============================================\n"); printf("\t\tMenu\n"); + printf("\tm : show menu\n"); printf("\ts : start server\n"); printf("\tc : start client\n"); printf("\tf : find resource\n"); @@ -981,111 +898,105 @@ char get_menu() printf("\th : handle request response\n"); printf("\ty : run static client\n"); printf("\tz : run static server\n"); - printf("\tw : send secure request\n"); printf("\tq : quit\n"); printf("=============================================\n"); printf("select : "); - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) + if(!fgets(buf, MAX_BUF_LEN, stdin)) { - printf("Failed to get input data\n"); + printf("fgets error\n"); + return '\0'; } return buf[0]; } -void handle_request_response() +void HandleRequestResponse() { - printf("Handle_request_response\n"); + printf("handle_request_response\n"); CAResult_t res = CAHandleRequestResponse(); - if (CA_STATUS_OK != res) + if (res != CA_STATUS_OK) { - printf("Handle request error, error code: %d\n", res); + printf("handle request error\n"); } else { - printf("Handle request success\n"); + printf("handle request success\n"); } } -void get_network_info() +void GetNetworkInfo() { + int index = 0; CALocalConnectivity_t *tempInfo = NULL; uint32_t tempSize = 0; - CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize); - if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize) + CAGetNetworkInformation(&tempInfo, &tempSize); + if (tempInfo == NULL || tempSize <= 0) { - printf("Network not connected\n"); - free(tempInfo); + printf("network not connected\n"); return; } printf("################## Network Information #######################\n"); - printf("Network info total size is %d\n\n", tempSize); + printf("network info total size is %d\n\n", tempSize); - int index; for (index = 0; index < tempSize; index++) { printf("Type: %d\n", tempInfo[index].type); - if (CA_WIFI == tempInfo[index].type) - { - printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress); - printf("Port: %d\n", tempInfo[index].addressInfo.IP.port); - } - else if (CA_EDR == tempInfo[index].type) - { - printf("Address: %s\n", tempInfo[index].addressInfo.BT.btMacAddress); - } + printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress); + printf("Port: %d\n", tempInfo[index].addressInfo.IP.port); printf("Secured: %d\n\n", tempInfo[index].isSecured); - if (tempInfo[index].isSecured) + if (true == tempInfo[index].isSecured) + { + g_localSecurePort = tempInfo[index].addressInfo.IP.port; + } + else { - g_local_secure_port = tempInfo[index].addressInfo.IP.port; - printf("Secured: in global %d\n\n", g_local_secure_port); + g_localUnicastPort = tempInfo[index].addressInfo.IP.port; } } + // free free(tempInfo); + printf("##############################################################"); } -void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo) +void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo) { - if (NULL == object || NULL == requestInfo) + printf("##########received request from remote device #############\n"); + if (!object) { - printf("Input parameter is NULL\n"); + printf("Remote endpoint is NULL!\n"); return; } - if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token) - && (strncmp(g_last_request_token, requestInfo->info.token, - requestInfo->info.tokenLength) == 0)) + if (!requestInfo) { - printf("Token is same. received request of it's own. skip.. \n"); + printf("Request info is NULL!\n"); return; } - printf("##########received request from remote device #############\n"); printf("Uri: %s\n", object->resourceUri); - if (CA_WIFI == object->connectivityType) - { - printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress, - object->addressInfo.IP.port, object->isSecured); - } - else if (CA_EDR == object->connectivityType) + printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress, + object->addressInfo.IP.port, object->isSecured); + + printf("Data: %s\n", requestInfo->info.payload); + printf("Message type: %s\n", g_messageType[requestInfo->info.type]); + if (g_lastRequestToken != NULL && requestInfo->info.token != NULL + && (strcmp((char *)g_lastRequestToken, requestInfo->info.token) == 0)) { - printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress); + printf("token is same. received request of it's own. skip.. \n"); + return; } - printf("Data: %s\n", requestInfo->info.payload); - printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]); if (requestInfo->info.options) { uint32_t len = requestInfo->info.numOptions; - uint32_t i; + uint32_t i = 0; for (i = 0; i < len; i++) { printf("Option %d\n", i + 1); @@ -1097,29 +1008,27 @@ void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *re printf("############################################################\n"); //Check if this has secure communication information - if (requestInfo->info.payload && - (CA_WIFI == object->connectivityType)) + if (requestInfo->info.payload) { - int securePort = get_secure_information(requestInfo->info.payload); + int securePort = GetSecureInformation(requestInfo->info.payload); if (0 < securePort) //Set the remote endpoint secure details and send response { printf("This is secure resource...\n"); + char *uri = NULL; + int length = 0; - //length of "coaps://" - int length = sizeof(SECURE_COAPS_PREFIX) - 1; - - // length of "ipaddress:port" - length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH; + length = 8; //length of "coaps://" + length += strlen(object->addressInfo.IP.ipAddress) + 5; // length of "ipaddress:port" length += strlen(object->resourceUri) + 1; - char *uri = calloc(1, sizeof(char) * length); + uri = calloc(1, sizeof(char) * length); if (!uri) { printf("Failed to create new uri\n"); return; } - sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress, - object->addressInfo.IP.port, object->resourceUri); + sprintf(uri, "coaps://%s:%d/%s", object->addressInfo.IP.ipAddress, + securePort, object->resourceUri); CARemoteEndpoint_t *endpoint = NULL; if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->connectivityType, &endpoint)) @@ -1127,6 +1036,7 @@ void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *re printf("Failed to create duplicate of remote endpoint!\n"); return; } + //endpoint->connectivityType = object->connectivityType; endpoint->isSecured = true; object = endpoint; @@ -1134,33 +1044,38 @@ void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *re } } - printf("Send response with URI\n"); - send_response(object, &requestInfo->info); + printf("send response with URI\n"); + SendResponse(object, &requestInfo->info); g_received = 1; } -void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo) +void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo) { printf("##########Received response from remote device #############\n"); - printf("Uri: %s\n", object->resourceUri); - if (CA_WIFI == object->connectivityType) + if(!object) { - printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress, - object->addressInfo.IP.port, object->isSecured); + printf("response_handler object is null\n"); + return; } - else if (CA_EDR == object->connectivityType) + + if(!responseInfo) { - printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress); + printf("response_handler responseInfo is null\n"); + return; } + + printf("Uri: %s\n", object->resourceUri); + printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress, + object->addressInfo.IP.port, object->isSecured); printf("response result : %d\n", responseInfo->result); printf("Data: %s\n", responseInfo->info.payload); - printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]); + printf("Message type: %s\n", g_messageType[responseInfo->info.type]); printf("Token: %s\n", responseInfo->info.token); if (responseInfo->info.options) { uint32_t len = responseInfo->info.numOptions; - uint32_t i; + uint32_t i = 0; for (i = 0; i < len; i++) { printf("Option %d\n", i + 1); @@ -1175,7 +1090,7 @@ void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t * //Check if this has secure communication information if (responseInfo->info.payload) { - int securePort = get_secure_information(responseInfo->info.payload); + int securePort = GetSecureInformation(responseInfo->info.payload); if (0 < securePort) //Set the remote endpoint secure details and send response { printf("This is secure resource...\n"); @@ -1183,107 +1098,98 @@ void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t * } } -void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info) +void SendResponse(CARemoteEndpoint_t *endpoint, CAInfo_t *info) { printf("entering send_response\n"); - printf("\n=============================================\n"); - printf("\tselect message type\n"); - printf("CON : 0\n"); - printf("NON : 1\n"); - printf("ACK : 2\n"); - printf("RESET : 3\n"); - printf("select : "); - - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) + if(!endpoint) { + printf("endpoint is null\n"); return; } - int messageType = buf[0] - '0'; - int responseCode = 0 ; - char responseCodeBuf[MAX_BUF_LEN] = { 0 }; - if (CA_MSG_RESET != messageType) - { - printf("\n=============================================\n"); - printf("\tselect response code\n"); - printf("EMPTY : 0\n"); - printf("SUCCESS : 200\n"); - printf("CREATED : 201\n"); - printf("DELETED : 202\n"); - printf("BAD_REQ : 400\n"); - printf("BAD_OPT : 402\n"); - printf("NOT_FOUND : 404\n"); - printf("INTERNAL_SERVER_ERROR : 500\n"); - printf("RETRANSMIT_TIMEOUT : 504\n"); - printf("select : "); - - if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN)) - { - return; - } - responseCode = atoi(responseCodeBuf); + CAInfo_t responseData = {CA_MSG_RESET}; + responseData.type = + (info != NULL) ? + ((info->type == CA_MSG_CONFIRM) ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM) : + CA_MSG_NONCONFIRM; + responseData.messageId = 0; + responseData.token = ""; + if(info) + { + responseData.messageId = info->messageId; + responseData.token = info->token; + responseData.tokenLength = info->tokenLength; } - CAInfo_t responseData = { 0 }; - responseData.type = messageType; + responseData.payload = "response payload"; - responseData.messageId = (info != NULL) ? info->messageId : 0; - if(CA_MSG_RESET != messageType) + CAResponseInfo_t responseInfo = {0}; + responseInfo.result = 203; + responseInfo.info = responseData; + + if (true == endpoint->isSecured) + { + printf("Sending response on secure communication\n"); + } + else { - responseData.token = (info != NULL) ? info->token : NULL; - responseData.tokenLength = (info != NULL) ? info->tokenLength : 0; + printf("Sending response on non-secure communication\n"); + } - if (endpoint->isSecured) - { - printf("Sending response on secure communication\n"); + // send request (connectivityType from remoteEndpoint of request Info) + CAResult_t res = CASendResponse(endpoint, &responseInfo); + if (res != CA_STATUS_OK) + { + printf("send response failed\n"); + } + else + { + printf("send response success\n"); + } - uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(endpoint->resourceUri); - responseData.payload = (CAPayload_t) calloc(length, sizeof(char)); - if (NULL == responseData.payload) - { - printf("Memory allocation fail\n"); - return; - } - snprintf(responseData.payload, length, SECURE_INFO_DATA, endpoint->resourceUri, - g_local_secure_port); - } - else - { - printf("Sending response on non-secure communication\n"); + printf("=============================================\n"); +} - uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(endpoint->resourceUri); - responseData.payload = (CAPayload_t) calloc(length, sizeof(char)); - if (NULL == responseData.payload) - { - printf("Memory allocation fail\n"); - return; - } - snprintf(responseData.payload, length, NORMAL_INFO_DATA, endpoint->resourceUri); - } +void SendRequestTemp(CARemoteEndpoint_t *endpoint, CAToken_t token, uint8_t tokenLength) +{ + printf("\n=============================================\n"); + + if(!endpoint) + { + printf("endpoint is null\n"); + return; } - CAResponseInfo_t responseInfo = { 0 }; - responseInfo.result = responseCode; - responseInfo.info = responseData; + CAInfo_t requestData ={CA_MSG_RESET}; + requestData.token = token; + requestData.tokenLength = tokenLength; + requestData.payload = "Temp Json Payload"; - // send response (transportType from remoteEndpoint of request Info) - CAResult_t res = CASendResponse(endpoint, &responseInfo); - if (CA_STATUS_OK != res) + CARequestInfo_t requestInfo ={CA_GET, {CA_MSG_RESET}}; + memset(&requestInfo, 0, sizeof(CARequestInfo_t)); + requestInfo.method = CA_GET; + requestInfo.info = requestData; + + // send request + endpoint->connectivityType = CA_WIFI; + + CAResult_t res = CASendRequest(endpoint, &requestInfo); + if (res != CA_STATUS_OK) { - printf("Send response error\n"); + printf("send request failed\n"); } else { - printf("Send response success\n"); + printf("send request success\n"); } printf("=============================================\n"); + } -int get_secure_information(CAPayload_t payLoad) +int GetSecureInformation(CAPayload_t payLoad) { - printf("Entering get_secure_information\n"); + printf("entering get_secure_information\n"); if (!payLoad) { @@ -1331,7 +1237,7 @@ int get_secure_information(CAPayload_t payLoad) return atoi(portStr); } -void get_resource_uri(char *URI, char *resourceURI, int length) +void GetResourceUri(char *URI, char *resourceURI, int length) { char *startPos = URI; char *temp = NULL; @@ -1353,9 +1259,7 @@ void get_resource_uri(char *URI, char *resourceURI, int length) endPos -= 1; if (endPos - startPos <= length) - { memcpy(resourceURI, startPos + 1, endPos - startPos); - } printf("URI: %s, ResourceURI:%s\n", URI, resourceURI); } @@ -1369,24 +1273,26 @@ CAResult_t get_network_type() printf("LE : 3\n"); printf("select : "); - char buf[MAX_BUF_LEN] = { 0 }; - if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN)) + if(!fgets(buf, MAX_BUF_LEN, stdin)) { - return CA_NOT_SUPPORTED ; + printf("fgets error\n"); + return CA_STATUS_FAILED; } int number = buf[0] - '0'; + number = (number < 0 || number > 3) ? 0 : 1 << number; if (!(number & 0xf)) { return CA_NOT_SUPPORTED; } - if (number & CA_WIFI) + if (number & CA_IPV4) { - g_selected_nw_type = CA_WIFI; + g_selected_nw_type = CA_IPV4; return CA_STATUS_OK; } + if (number & CA_EDR) { g_selected_nw_type = CA_EDR; @@ -1403,19 +1309,4 @@ CAResult_t get_network_type() return CA_STATUS_FAILED; } -CAResult_t get_input_data(char *buf, int32_t length) -{ - if (!fgets(buf, length, stdin)) - { - printf("fgets error\n"); - return CA_STATUS_FAILED; - } - - char *p = NULL; - if ((p = strchr(buf, '\n')) != NULL) - { - *p = '\0'; - } - return CA_STATUS_OK; -} diff --git a/resource/csdk/connectivity/samples/tizen/scons/SConscript b/resource/csdk/connectivity/samples/tizen/scons/SConscript index dc340ef..301a366 100644 --- a/resource/csdk/connectivity/samples/tizen/scons/SConscript +++ b/resource/csdk/connectivity/samples/tizen/scons/SConscript @@ -23,7 +23,7 @@ env.Append(LIBS=[ env.Prepend(RPATH=[root_dir +'/lib/tizen/ble/libs/',]) if 'ALL' in transport: - env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER', 'NO_ETHERNET_ADAPTER','EDR_ADAPTER','LE_ADAPTER','BT_ADAPTER_TEST','BLE_ADAPTER_TEST','WIFI_ADAPTER_TEST']) + env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER','BT_ADAPTER_TEST','BLE_ADAPTER_TEST']) print "CA Transport is ALL" else: if 'BT' in transport: @@ -37,13 +37,13 @@ else: print "CA Transport is BLE" else: env.AppendUnique(CPPDEFINES = ['NO_LE_ADAPTER']) - - if 'WIFI' in transport: - env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER','WIFI_ADAPTER_TEST']) - print "CA Transport is WIFI" - else: - env.AppendUnique(CPPDEFINES = ['NO_WIFI_ADAPTER']) + if 'IP' in transport: + env.AppendUnique(CPPDEFINES = ['IP_ADAPTER']) + print "CA Transport is IP" + else: + env.AppendUnique(CPPDEFINES = ['NO_IP_ADAPTER']) + ca_sample_src = [sample_dir + '/casample.c'] diff --git a/resource/csdk/connectivity/src/SConscript b/resource/csdk/connectivity/src/SConscript index 6611ada..45db09b 100644 --- a/resource/csdk/connectivity/src/SConscript +++ b/resource/csdk/connectivity/src/SConscript @@ -83,16 +83,12 @@ env.AppendUnique(CA_SRC = ca_common_src) if 'ALL' in ca_transport: - env.SConscript(ca_path + 'ethernet_adapter/SConscript') - env.SConscript(ca_path + 'wifi_adapter/SConscript') + env.SConscript(ca_path + 'ip_adapter/SConscript') env.SConscript(ca_path + 'bt_edr_adapter/SConscript') env.SConscript(ca_path + 'bt_le_adapter/SConscript') -if 'WIFI' in ca_transport: - env.SConscript(ca_path + 'wifi_adapter/SConscript') - -if 'ETHERNET' in ca_transport: - env.SConscript(ca_path + 'ethernet_adapter/SConscript') +if 'IP' in ca_transport: + env.SConscript(ca_path + 'ip_adapter/SConscript') if 'BT' in ca_transport: env.SConscript(ca_path + 'bt_edr_adapter/SConscript') diff --git a/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c b/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c index c0ab41f..562a5fa 100644 --- a/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c +++ b/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c @@ -19,7 +19,7 @@ ******************************************************************/ #include "caadapternetdtls.h" #include "cacommon.h" -#include "cawifiinterface.h" +#include "caipinterface.h" #include "dtls.h" #include "oic_malloc.h" diff --git a/resource/csdk/connectivity/src/adapter_util/caadapterutils.c b/resource/csdk/connectivity/src/adapter_util/caadapterutils.c index 9d60453..6f85445 100644 --- a/resource/csdk/connectivity/src/adapter_util/caadapterutils.c +++ b/resource/csdk/connectivity/src/adapter_util/caadapterutils.c @@ -42,8 +42,7 @@ void CALogPDUData(coap_pdu_t *pdu) OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - token : %s", pdu->hdr->token); } -CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CAConnectivityType_t type, - const char *address) +CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CATransportType_t type, const char *address) { CALocalConnectivity_t *info = (CALocalConnectivity_t *) OICCalloc(1, sizeof(CALocalConnectivity_t)); @@ -66,11 +65,17 @@ CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CAConnectivityType_t type, strncpy(info->addressInfo.LE.leMacAddress, address, CA_MACADDR_SIZE - 1); info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0'; } - else if (CA_WIFI == type || CA_ETHERNET == type) + else if (CA_IPV4 == type) { strncpy(info->addressInfo.IP.ipAddress, address, CA_IPADDR_SIZE - 1); info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0'; } + else if (CA_IPV6 == type) + { + OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported"); + OICFree(info); + return NULL; + } else { OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!"); @@ -107,14 +112,21 @@ CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(const CALocalConnectivity_t *c CA_MACADDR_SIZE - 1); info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0'; } - else if ((CA_WIFI == info->type || CA_ETHERNET == info->type) - && strlen(connectivity->addressInfo.IP.ipAddress)) + else if ((CA_IPV4 == info->type) + + && strlen(connectivity->addressInfo.IP.ipAddress)) { strncpy(info->addressInfo.IP.ipAddress, connectivity->addressInfo.IP.ipAddress, CA_IPADDR_SIZE - 1); info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0'; info->addressInfo.IP.port = connectivity->addressInfo.IP.port; } + else if (CA_IPV6 == info->type) + { + OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported"); + OICFree(info); + return NULL; + } else { OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!"); @@ -131,9 +143,8 @@ void CAAdapterFreeLocalEndpoint(CALocalConnectivity_t *localEndpoint) OICFree(localEndpoint); } -CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CAConnectivityType_t type, - const char *address, - const char *resourceUri) +CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CATransportType_t type, const char *address, + const char *resourceUri) { CARemoteEndpoint_t *info = (CARemoteEndpoint_t *) OICCalloc(1, sizeof(CARemoteEndpoint_t)); @@ -143,7 +154,7 @@ CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CAConnectivityType_t type, return NULL; } - info->connectivityType = type; + info->transportType = type; if (address && strlen(address)) { if (CA_EDR == type) @@ -156,11 +167,17 @@ CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CAConnectivityType_t type, strncpy(info->addressInfo.LE.leMacAddress, address, CA_MACADDR_SIZE - 1); info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0'; } - else if (CA_WIFI == type || CA_ETHERNET == type) + else if (CA_IPV4 == type) { strncpy(info->addressInfo.IP.ipAddress, address, CA_IPADDR_SIZE - 1); info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0'; } + else if (CA_IPV6 == type) + { + OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported"); + OICFree(info); + return NULL; + } else { OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!"); @@ -189,27 +206,32 @@ CARemoteEndpoint_t *CAAdapterCopyRemoteEndpoint(const CARemoteEndpoint_t *remote return NULL; } - info->connectivityType = remoteEndpoint->connectivityType; - if (CA_EDR == info->connectivityType && strlen(remoteEndpoint->addressInfo.BT.btMacAddress)) + info->transportType = remoteEndpoint->transportType; + if (CA_EDR == info->transportType && ('\0' != remoteEndpoint->addressInfo.BT.btMacAddress[0])) { strncpy(info->addressInfo.BT.btMacAddress, remoteEndpoint->addressInfo.BT.btMacAddress, CA_MACADDR_SIZE - 1); info->addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0'; } - else if (CA_LE == info->connectivityType && strlen(remoteEndpoint->addressInfo.LE.leMacAddress)) + else if (CA_LE == info->transportType + && ('\0' != remoteEndpoint->addressInfo.LE.leMacAddress[0])) { strncpy(info->addressInfo.LE.leMacAddress, remoteEndpoint->addressInfo.LE.leMacAddress, CA_MACADDR_SIZE - 1); info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0'; } - else if ((CA_WIFI == info->connectivityType || CA_ETHERNET == info->connectivityType) - && strlen(remoteEndpoint->addressInfo.IP.ipAddress)) + else if ((CA_IPV4 == info->transportType) + && ('\0' != remoteEndpoint->addressInfo.IP.ipAddress[0])) { strncpy(info->addressInfo.IP.ipAddress, remoteEndpoint->addressInfo.IP.ipAddress, CA_IPADDR_SIZE - 1); info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0'; info->addressInfo.IP.port = remoteEndpoint->addressInfo.IP.port; } + else if (CA_IPV6 == info->transportType) + { + OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Currently IPV6 is not supported"); + } else { OIC_LOG(DEBUG, CA_ADAPTER_UTILS_TAG, "Its not matching. May be multicast."); @@ -344,3 +366,190 @@ bool CAAdapterIsSameSubnet(const char *ipAddress1, const char *ipAddress2, const && ((ipList1[3] & maskList[3]) == (ipList2[3] & maskList[3])); } + +bool CAIsMulticastServerStarted(const u_arraylist_t *serverInfoList, const char *ipAddress, + const char *multicastAddress, uint16_t port) +{ + VERIFY_NON_NULL_RET(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null", false); + VERIFY_NON_NULL_RET(ipAddress, CA_ADAPTER_UTILS_TAG, "ipAddress is null", false); + VERIFY_NON_NULL_RET(multicastAddress, CA_ADAPTER_UTILS_TAG, "multicastAddress is null", false); + + uint32_t listLength = u_arraylist_length(serverInfoList); + for (uint32_t listIndex = 0; listIndex < listLength; listIndex++) + { + CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex); + if (!info) + { + OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Info is NULL"); + return false; + } + + if (info->isMulticastServer && (strncmp(info->ipAddress, multicastAddress, + strlen(multicastAddress) == 0)) + && (info->port == port) && (strncmp(info->ifAddr, ipAddress, strlen(ipAddress)) == 0)) + { + return info->isServerStarted; + } + } + return false; +} + +bool CAIsUnicastServerStarted(const u_arraylist_t *serverInfoList, const char *ipAddress, + uint16_t port) +{ + VERIFY_NON_NULL_RET(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null", false); + VERIFY_NON_NULL_RET(ipAddress, CA_ADAPTER_UTILS_TAG, "ipAddress is null", false); + + uint32_t listLength = u_arraylist_length(serverInfoList); + for (uint32_t listIndex = 0; listIndex < listLength; listIndex++) + { + CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex); + if (!info) + { + continue; + } + + if (!info->isMulticastServer && (strncmp(info->ipAddress, ipAddress, + strlen(ipAddress)) == 0) + && (info->port == port)) + { + return info->isServerStarted; + } + } + return false; +} + +uint16_t CAGetServerPort(const u_arraylist_t *serverInfoList, const char *ipAddress, bool isSecured) +{ + VERIFY_NON_NULL_RET(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null", 0); + VERIFY_NON_NULL_RET(ipAddress, CA_ADAPTER_UTILS_TAG, "ipAddress is null", 0); + + uint32_t listLength = u_arraylist_length(serverInfoList); + for (uint32_t listIndex = 0; listIndex < listLength; listIndex++) + { + CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex); + if (!info) + { + continue; + } + if ((strncmp(info->ipAddress, ipAddress, strlen(ipAddress)) == 0) && + (info->isSecured == isSecured)) + { + return info->port; + } + } + + return 0; +} + +int CAGetSocketFdForUnicastServer(const u_arraylist_t *serverInfoList, const char *ipAddress, + bool isSecured, bool isMulticast, CATransportType_t type) +{ + VERIFY_NON_NULL_RET(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null", -1); + VERIFY_NON_NULL_RET(ipAddress, CA_ADAPTER_UTILS_TAG, "ipAddress is null", -1); + + uint32_t listLength = u_arraylist_length(serverInfoList); + + for (uint32_t listIndex = 0; listIndex < listLength; listIndex++) + { + CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex); + if (!info) + { + continue; + } + + if (!CAAdapterIsSameSubnet(info->ipAddress, ipAddress, info->subNetMask)) + { + continue; + } + + if (!info->isMulticastServer && (info->isSecured == isSecured)) + { + OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, + "CAGetSocketFdForServer found socket [%d]", info->socketFd); + return info->socketFd; + } + + } + + OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, + "CAGetSocketFdForServer socket fd is not found"); + return -1; +} + +CAResult_t CAAddServerInfo(u_arraylist_t *serverInfoList, CAServerInfo_t *info) +{ + VERIFY_NON_NULL(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null"); + VERIFY_NON_NULL(info, CA_ADAPTER_UTILS_TAG, "info is null"); + + CAResult_t result = u_arraylist_add(serverInfoList, (void *) info); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "u_arraylist_add failed!"); + } + return result; +} + +void CARemoveServerInfo(u_arraylist_t *serverInfoList, int sockFd) +{ + VERIFY_NON_NULL_VOID(serverInfoList, CA_ADAPTER_UTILS_TAG, "serverInfoList is null"); + + uint32_t listLength = u_arraylist_length(serverInfoList); + for (uint32_t listIndex = 0; listIndex < listLength;) + { + CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex); + if (!info) + { + listIndex++; + continue; + } + + if (info->socketFd == sockFd) + { + if (u_arraylist_remove(serverInfoList, listIndex)) + { + OICFree(info); + listLength--; + } + else + { + OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "u_arraylist_remove failed!"); + break; + } + } + else + { + listIndex++; + } + } +} + +void CAClearNetInterfaceInfoList(u_arraylist_t *infoList) +{ + uint32_t listLength = u_arraylist_length(infoList); + for (uint32_t listIndex = 0; listIndex < listLength; listIndex++) + { + CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get(infoList, listIndex); + if (!netInfo) + { + continue; + } + OICFree(netInfo); + } + u_arraylist_free(&infoList); +} + +void CAClearServerInfoList(u_arraylist_t *serverInfoList) +{ + uint32_t listLength = u_arraylist_length(serverInfoList); + for (uint32_t listIndex = 0; listIndex < listLength; listIndex++) + { + CAServerInfo_t *serverInfo = (CAServerInfo_t *) u_arraylist_get(serverInfoList, listIndex); + if (!serverInfo) + { + continue; + } + OICFree(serverInfo); + } + u_arraylist_free(&serverInfoList); +} diff --git a/resource/csdk/connectivity/src/bt_le_adapter/caleadapter_singlethread.c b/resource/csdk/connectivity/src/bt_le_adapter/caleadapter_singlethread.c index 018c9bc..7e6c1af 100644 --- a/resource/csdk/connectivity/src/bt_le_adapter/caleadapter_singlethread.c +++ b/resource/csdk/connectivity/src/bt_le_adapter/caleadapter_singlethread.c @@ -296,7 +296,7 @@ void CANotifyCallback(const void *data, int32_t dataLen, const char *senderAdrs, /* Cannot get Address as of now */ CARemoteEndpoint_t endPoint; endPoint.resourceUri = ""; // will be filled by upper layer - endPoint.connectivityType = CA_LE; + endPoint.transportType= CA_LE; g_respCallback(&endPoint, data, dataLen); } diff --git a/resource/csdk/connectivity/src/caconnectivitymanager.c b/resource/csdk/connectivity/src/caconnectivitymanager.c index ccbdac7..1eabcec 100644 --- a/resource/csdk/connectivity/src/caconnectivitymanager.c +++ b/resource/csdk/connectivity/src/caconnectivitymanager.c @@ -85,12 +85,12 @@ CAResult_t CARegisterDTLSCredentialsHandler( } #endif //__WITH_DTLS__ -CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, - const CAConnectivityType_t connectivityType,CARemoteEndpoint_t **remoteEndpoint) +CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, const CATransportType_t transportType, + CARemoteEndpoint_t **remoteEndpoint) { OIC_LOG(DEBUG, TAG, "CACreateRemoteEndpoint"); - CARemoteEndpoint_t *remote = CACreateRemoteEndpointUriInternal(uri, connectivityType); + CARemoteEndpoint_t *remote = CACreateRemoteEndpointUriInternal(uri, transportType); if (remote == NULL) { @@ -191,29 +191,24 @@ CAResult_t CASelectNetwork(const uint32_t interestedNetwork) return CA_NOT_SUPPORTED; } - CAResult_t res =CA_STATUS_OK; - if (interestedNetwork & CA_ETHERNET) - { - res = CAAddNetworkType(CA_ETHERNET); - OIC_LOG_V(DEBUG, TAG, "CAAddNetworkType(CA_ETHERNET) function returns error : %d", res); - } + CAResult_t res = CA_STATUS_OK; - if (interestedNetwork & CA_WIFI) + if (interestedNetwork & CA_IPV4) { - res = CAAddNetworkType(CA_WIFI); - OIC_LOG_V(DEBUG, TAG, "CAAddNetworkType(CA_WIFI) function returns error : %d", res); + res = CAAddNetworkType(CA_IPV4); + OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_IPV4) function returns error : %d", res); } if (interestedNetwork & CA_EDR) { res = CAAddNetworkType(CA_EDR); - OIC_LOG_V(DEBUG, TAG, "CAAddNetworkType(CA_EDR) function returns error : %d", res); + OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_EDR) function returns error : %d", res); } if (interestedNetwork & CA_LE) { res = CAAddNetworkType(CA_LE); - OIC_LOG_V(DEBUG, TAG, "CAAddNetworkType(CA_LE) function returns error : %d", res); + OIC_LOG_V(ERROR, TAG, "CAAddNetworkType(CA_LE) function returns error : %d", res); } return res; @@ -229,28 +224,23 @@ CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork) } CAResult_t res = CA_STATUS_OK; - if (nonInterestedNetwork & CA_ETHERNET) - { - res = CARemoveNetworkType(CA_ETHERNET); - OIC_LOG_V(DEBUG, TAG, "CARemoveNetworkType(CA_ETHERNET) function returns error : %d", res); - } - if (nonInterestedNetwork & CA_WIFI) + if (nonInterestedNetwork & CA_IPV4) { - res = CARemoveNetworkType(CA_WIFI); - OIC_LOG_V(DEBUG, TAG, "CARemoveNetworkType(CA_WIFI) function returns error : %d", res); + res = CARemoveNetworkType(CA_IPV4); + OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_IPV4) function returns error : %d", res); } if (nonInterestedNetwork & CA_EDR) { res = CARemoveNetworkType(CA_EDR); - OIC_LOG_V(DEBUG, TAG, "CARemoveNetworkType(CA_EDR) function returns error : %d", res); + OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_EDR) function returns error : %d", res); } if (nonInterestedNetwork & CA_LE) { res = CARemoveNetworkType(CA_LE); - OIC_LOG_V(DEBUG, TAG, "CARemoveNetworkType(CA_LE) function returns error : %d", res); + OIC_LOG_V(ERROR, TAG, "CARemoveNetworkType(CA_LE) function returns error : %d", res); } return res; diff --git a/resource/csdk/connectivity/src/caconnectivitymanager_singlethread.c b/resource/csdk/connectivity/src/caconnectivitymanager_singlethread.c index 442d1cb..8d25223 100644 --- a/resource/csdk/connectivity/src/caconnectivitymanager_singlethread.c +++ b/resource/csdk/connectivity/src/caconnectivitymanager_singlethread.c @@ -67,12 +67,12 @@ void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHand OIC_LOG(DEBUG, TAG, "OUT"); } -CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, - const CAConnectivityType_t connectivityType,CARemoteEndpoint_t **remoteEndpoint) +CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, const CATransportType_t transportType, + CARemoteEndpoint_t **remoteEndpoint) { OIC_LOG(DEBUG, TAG, "IN"); - CARemoteEndpoint_t *remote = CACreateRemoteEndpointUriInternal(uri,connectivityType); + CARemoteEndpoint_t *remote = CACreateRemoteEndpointUriInternal(uri, transportType); if (remote == NULL) { @@ -158,19 +158,9 @@ CAResult_t CASelectNetwork(const uint32_t interestedNetwork) } CAResult_t res = CA_STATUS_OK; - if (interestedNetwork & CA_ETHERNET) + if (interestedNetwork & CA_IPV4) { - res = CAAddNetworkType(CA_ETHERNET); - if (res != CA_STATUS_OK) - { - OIC_LOG(ERROR, TAG, "Failed to Add n/w type"); - return res; - } - } - - if (interestedNetwork & CA_WIFI) - { - res = CAAddNetworkType(CA_WIFI); + res = CAAddNetworkType(CA_IPV4); if (res != CA_STATUS_OK) { OIC_LOG(ERROR, TAG, "Failed to Add n/w type"); @@ -213,19 +203,9 @@ CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork) CAResult_t res = CA_STATUS_OK; - if (nonInterestedNetwork & CA_ETHERNET) - { - res = CARemoveNetworkType(CA_ETHERNET); - if (res != CA_STATUS_OK) - { - OIC_LOG(ERROR, TAG, "Failed to remove n/w type"); - return res; - } - } - - if (nonInterestedNetwork & CA_WIFI) + if (nonInterestedNetwork & CA_IPV4) { - res = CARemoveNetworkType(CA_WIFI); + res = CARemoveNetworkType(CA_IPV4); if (res != CA_STATUS_OK) { OIC_LOG(ERROR, TAG, "Failed to remove n/w type"); diff --git a/resource/csdk/connectivity/src/cainterfacecontroller.c b/resource/csdk/connectivity/src/cainterfacecontroller.c index 0c09fe4..18a8257 100644 --- a/resource/csdk/connectivity/src/cainterfacecontroller.c +++ b/resource/csdk/connectivity/src/cainterfacecontroller.c @@ -24,10 +24,9 @@ #include #include "cainterfacecontroller.h" -#include "caethernetadapter.h" +#include "caipadapter.h" #include "caedradapter.h" #include "caleadapter.h" -#include "cawifiadapter.h" #include "canetworkconfigurator.h" #include "caremotehandler.h" #include "oic_malloc.h" @@ -39,21 +38,21 @@ #define CA_MEMORY_ALLOC_CHECK(arg) {if (arg == NULL) \ {OIC_LOG(ERROR, TAG, "memory error");goto memory_error_exit;} } -#define CA_CONNECTIVITY_TYPE_NUM 4 +#define CA_TRANSPORT_TYPE_NUM 4 -static CAConnectivityHandler_t g_adapterHandler[CA_CONNECTIVITY_TYPE_NUM]; +static CAConnectivityHandler_t g_adapterHandler[CA_TRANSPORT_TYPE_NUM]; static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL; static CANetworkChangeCallback g_networkChangeCallback = NULL; -static int CAGetAdapterIndex(CAConnectivityType_t cType) +static int CAGetAdapterIndex(CATransportType_t cType) { switch (cType) { - case CA_ETHERNET: + case CA_IPV4: return 0; - case CA_WIFI: + case CA_IPV6: return 1; case CA_EDR: return 2; @@ -61,12 +60,12 @@ static int CAGetAdapterIndex(CAConnectivityType_t cType) return 3; } - OIC_LOG(DEBUG, TAG, "CA_CONNECTIVITY_TYPE_NUM is not 4"); + OIC_LOG(DEBUG, TAG, "CA_TRANSPORT_TYPE_NUM is not 4"); return -1; } -static void CARegisterCallback(CAConnectivityHandler_t handler, CAConnectivityType_t cType) +static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportType_t cType) { OIC_LOG(DEBUG, TAG, "CARegisterCallback - Entry"); @@ -134,18 +133,13 @@ void CAInitializeAdapters(ca_thread_pool_t handle) { OIC_LOG(DEBUG, TAG, "initialize adapters.."); - memset(g_adapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_CONNECTIVITY_TYPE_NUM); + memset(g_adapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_TRANSPORT_TYPE_NUM); // Initialize adapters and register callback. -#ifdef ETHERNET_ADAPTER - CAInitializeEthernet(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, +#ifdef IP_ADAPTER + CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, handle); -#endif /* ETHERNET_ADAPTER */ - -#ifdef WIFI_ADAPTER - CAInitializeWIFI(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, - handle); -#endif /* WIFI_ADAPTER */ +#endif /* IP_ADAPTER */ #ifdef EDR_ADAPTER CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, @@ -173,11 +167,11 @@ void CASetNetworkChangeCallback(CANetworkChangeCallback callback) g_networkChangeCallback = callback; } -CAResult_t CAStartAdapter(CAConnectivityType_t cType) +CAResult_t CAStartAdapter(CATransportType_t transportType) { - OIC_LOG_V(DEBUG, TAG, "Start the adapter of CAConnectivityType[%d]", cType); + OIC_LOG_V(DEBUG, TAG, "Start the adapter of CAConnectivityType[%d]", transportType); - int index = CAGetAdapterIndex(cType); + int index = CAGetAdapterIndex(transportType); if (index == -1) { @@ -193,15 +187,15 @@ CAResult_t CAStartAdapter(CAConnectivityType_t cType) return CA_STATUS_OK; } -void CAStopAdapter(CAConnectivityType_t cType) +void CAStopAdapter(CATransportType_t transportType) { - OIC_LOG_V(DEBUG, TAG, "Stop the adapter of CAConnectivityType[%d]", cType); + OIC_LOG_V(DEBUG, TAG, "Stop the adapter of CATransportType[%d]", transportType); - int index = CAGetAdapterIndex(cType); + int index = CAGetAdapterIndex(transportType); if (index == -1) { - OIC_LOG(DEBUG, TAG, "unknown connectivity type!"); + OIC_LOG(ERROR, TAG, "unknown transport type!"); return; } @@ -213,16 +207,13 @@ void CAStopAdapter(CAConnectivityType_t cType) CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size) { - CALocalConnectivity_t *tempInfo[CA_CONNECTIVITY_TYPE_NUM]; - uint32_t tempSize[CA_CONNECTIVITY_TYPE_NUM]; - - memset(tempInfo, 0, sizeof(CALocalConnectivity_t *) * CA_CONNECTIVITY_TYPE_NUM); - memset(tempSize, 0, sizeof(uint32_t) * CA_CONNECTIVITY_TYPE_NUM); + CALocalConnectivity_t *tempInfo[CA_TRANSPORT_TYPE_NUM] = { 0 }; + uint32_t tempSize[CA_TRANSPORT_TYPE_NUM] = { 0 }; // #1. get information each adapter uint8_t index = 0; CAResult_t res = CA_STATUS_FAILED; - for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++) + for (index = 0; index < CA_TRANSPORT_TYPE_NUM; index++) { if (g_adapterHandler[index].GetnetInfo != NULL) { @@ -234,7 +225,7 @@ CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size) } uint32_t resSize = 0; - for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++) + for (index = 0; index < CA_TRANSPORT_TYPE_NUM; index++) { // check information if (tempInfo[index] == NULL || tempSize[index] <= 0) @@ -265,7 +256,7 @@ CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size) CA_MEMORY_ALLOC_CHECK(resInfo); uint8_t pos = 0; - for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++) + for (index = 0; index < CA_TRANSPORT_TYPE_NUM; index++) { // check information if (tempInfo[index] == NULL || tempSize[index] <= 0) @@ -299,7 +290,7 @@ CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size) // memory error label. memory_error_exit: - for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++) + for (index = 0; index < CA_TRANSPORT_TYPE_NUM; index++) { OICFree(tempInfo[index]); @@ -321,13 +312,13 @@ CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *dat return CA_STATUS_INVALID_PARAM; } - CAConnectivityType_t type = endpoint->connectivityType; + CATransportType_t type = endpoint->transportType; int index = CAGetAdapterIndex(type); if (index == -1) { - OIC_LOG(DEBUG, TAG, "unknown connectivity type!"); + OIC_LOG(ERROR, TAG, "unknown transport type!"); return CA_STATUS_INVALID_PARAM; } @@ -368,7 +359,7 @@ CAResult_t CASendMulticastData(const void *data, uint32_t length) continue; } - CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType; + CATransportType_t connType = *(CATransportType_t *) ptrType; int index = CAGetAdapterIndex(connType); @@ -427,7 +418,7 @@ CAResult_t CAStartListeningServerAdapters() continue; } - CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType; + CATransportType_t connType = *(CATransportType_t *) ptrType; int index = CAGetAdapterIndex(connType); if (index == -1) @@ -467,7 +458,7 @@ CAResult_t CAStartDiscoveryServerAdapters() continue; } - CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType; + CATransportType_t connType = *(CATransportType_t *) ptrType; int index = CAGetAdapterIndex(connType); @@ -490,13 +481,9 @@ void CATerminateAdapters() { OIC_LOG(DEBUG, TAG, "terminate all adapters.."); - int index; - for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++) + uint32_t index; + for (index = 0; index < CA_TRANSPORT_TYPE_NUM; index++) { - if (g_adapterHandler[index].stopAdapter != NULL) - { - g_adapterHandler[index].stopAdapter(); - } if (g_adapterHandler[index].terminate != NULL) { g_adapterHandler[index].terminate(); diff --git a/resource/csdk/connectivity/src/cainterfacecontroller_singlethread.c b/resource/csdk/connectivity/src/cainterfacecontroller_singlethread.c index ab013d1..169ee7e 100644 --- a/resource/csdk/connectivity/src/cainterfacecontroller_singlethread.c +++ b/resource/csdk/connectivity/src/cainterfacecontroller_singlethread.c @@ -25,8 +25,7 @@ #include #include -#include "cawifiadapter_singlethread.h" -#include "caethernetadapter_singlethread.h" +#include "caipadapter_singlethread.h" #include "caedradapter_singlethread.h" #include "caleadapter_singlethread.h" #include "caadapterutils.h" @@ -48,13 +47,13 @@ static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL; static CANetworkChangeCallback g_networkChangeCallback = NULL; -static int CAGetAdapterIndex(CAConnectivityType_t cType) +static int CAGetAdapterIndex(CATransportType_t cType) { switch (cType) { - case CA_ETHERNET: + case CA_IPV4: return 0; - case CA_WIFI: + case CA_IPV6: return 1; case CA_EDR: return 2; @@ -67,7 +66,7 @@ static int CAGetAdapterIndex(CAConnectivityType_t cType) return -1; } -static void CARegisterCallback(CAConnectivityHandler_t handler, CAConnectivityType_t cType) +static void CARegisterCallback(CAConnectivityHandler_t handler, CATransportType_t cType) { OIC_LOG(DEBUG, TAG, "IN"); @@ -131,13 +130,9 @@ void CAInitializeAdapters() memset(g_adapterHandler, 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 IP_ADAPTER + CAInitializeIP(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback); +#endif /* IP_ADAPTER */ #ifdef EDR_ADAPTER CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback); @@ -146,8 +141,8 @@ void CAInitializeAdapters() #ifdef LE_ADAPTER CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback); #endif /* LE_ADAPTER */ - OIC_LOG(DEBUG, TAG, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); } void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback) @@ -166,11 +161,11 @@ void CASetNetworkChangeCallback(CANetworkChangeCallback callback) OIC_LOG(DEBUG, TAG, "OUT"); } -CAResult_t CAStartAdapter(CAConnectivityType_t cType) +CAResult_t CAStartAdapter(CATransportType_t transportType) { - OIC_LOG_V(DEBUG, TAG, "cType[%d]", cType); + OIC_LOG_V(DEBUG, TAG, "transportType[%d]", transportType); - int index = CAGetAdapterIndex(cType); + int index = CAGetAdapterIndex(transportType); if (index == -1) { @@ -186,11 +181,11 @@ CAResult_t CAStartAdapter(CAConnectivityType_t cType) return CA_STATUS_OK; } -void CAStopAdapter(CAConnectivityType_t cType) +void CAStopAdapter(CATransportType_t transportType) { - OIC_LOG_V(DEBUG, TAG, "cType[%d]", cType); + OIC_LOG_V(DEBUG, TAG, "transportType[%d]", transportType); - int index = CAGetAdapterIndex(cType); + int index = CAGetAdapterIndex(transportType); if (index == -1) { @@ -305,7 +300,7 @@ CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *dat return CA_STATUS_INVALID_PARAM; } - CAConnectivityType_t type = endpoint->connectivityType; + CATransportType_t type = endpoint->transportType; int index = CAGetAdapterIndex(type); @@ -350,7 +345,8 @@ CAResult_t CASendMulticastData(const void *data, uint32_t length) { continue; } - CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType; + + CATransportType_t connType = *(CATransportType_t *) ptrType; int index = CAGetAdapterIndex(connType); @@ -395,7 +391,8 @@ CAResult_t CAStartListeningServerAdapters() OIC_LOG(ERROR, TAG, "Invalid conn type"); continue; } - CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType; + + CATransportType_t connType = *(CATransportType_t *) ptrType; int index = CAGetAdapterIndex(connType); @@ -433,7 +430,8 @@ CAResult_t CAStartDiscoveryServerAdapters() { continue; } - CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType; + + CATransportType_t connType = *(CATransportType_t *) ptrType; int index = CAGetAdapterIndex(connType); @@ -492,7 +490,7 @@ CAResult_t CAReadData() return CA_STATUS_FAILED; } - CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType; + CATransportType_t connType = *(CATransportType_t *) ptrType; int index = CAGetAdapterIndex(connType); diff --git a/resource/csdk/connectivity/src/camessagehandler.c b/resource/csdk/connectivity/src/camessagehandler.c index 1fc824e..2779c54 100755 --- a/resource/csdk/connectivity/src/camessagehandler.c +++ b/resource/csdk/connectivity/src/camessagehandler.c @@ -664,7 +664,7 @@ CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object, CAAddress_t addr = {}; remoteEndpoint = CACreateRemoteEndpointInternal(object->resourceUri, addr, - object->connectivityType); + object->transportType); // clone request info requestInfo = CACloneRequestInfo(request); @@ -764,7 +764,7 @@ CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t CAAddress_t addr = {}; remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, addr, - CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE); + CA_IPV4 | CA_EDR | CA_LE); // create request info reqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t)); @@ -908,7 +908,7 @@ CAResult_t CAInitializeMessageHandler() void CATerminateMessageHandler() { OIC_LOG(DEBUG, TAG, "IN"); - CAConnectivityType_t connType; + CATransportType_t connType; u_arraylist_t *list = CAGetSelectedNetworkList(); uint32_t length = u_arraylist_length(list); @@ -922,7 +922,7 @@ void CATerminateMessageHandler() continue; } - connType = *(CAConnectivityType_t *) ptrType; + connType = *(CATransportType_t *) ptrType; CAStopAdapter(connType); } diff --git a/resource/csdk/connectivity/src/camessagehandler_singlethread.c b/resource/csdk/connectivity/src/camessagehandler_singlethread.c index 15a7623..1263505 100644 --- a/resource/csdk/connectivity/src/camessagehandler_singlethread.c +++ b/resource/csdk/connectivity/src/camessagehandler_singlethread.c @@ -427,7 +427,7 @@ CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object, CAAddress_t addr = {0}; CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(object->resourceUri, addr, - object->connectivityType); + object->transportType); // save data data->type = SEND_TYPE_MULTICAST; @@ -495,8 +495,7 @@ CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t CAAddress_t addr = {0}; CARemoteEndpoint_t *remoteEndpoint = - CACreateRemoteEndpointInternal(resourceUri, addr, - CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE); + CACreateRemoteEndpointInternal(resourceUri, addr, CA_IPV4 | CA_EDR | CA_LE); // create request info CARequestInfo_t *reqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t)); diff --git a/resource/csdk/connectivity/src/canetworkconfigurator.c b/resource/csdk/connectivity/src/canetworkconfigurator.c index e5ccede..c5a89bc 100644 --- a/resource/csdk/connectivity/src/canetworkconfigurator.c +++ b/resource/csdk/connectivity/src/canetworkconfigurator.c @@ -28,12 +28,12 @@ #define TAG "CANW" static u_arraylist_t *g_selectedNetworkList = NULL; -static uint32_t NETWORK_ETHERNET = CA_ETHERNET; -static uint32_t NETWORK_WIFI = CA_WIFI; +static uint32_t NETWORK_IP = CA_IPV4; static uint32_t NETWORK_EDR = CA_EDR; static uint32_t NETWORK_LE = CA_LE; -CAResult_t CAAddNetworkType(CAConnectivityType_t connectivityType) + +CAResult_t CAAddNetworkType(CATransportType_t transportType) { OIC_LOG(DEBUG, TAG, "IN"); if (NULL == g_selectedNetworkList) @@ -48,41 +48,29 @@ CAResult_t CAAddNetworkType(CAConnectivityType_t connectivityType) } } CAResult_t res = CA_STATUS_OK; - switch (connectivityType) + switch (transportType) { - case CA_ETHERNET: + case CA_IPV4: { -#ifndef ETHERNET_ADAPTER - OIC_LOG(DEBUG, TAG, "Add network type(ETHERNET) - Not Supported"); +#ifndef IP_ADAPTER + OIC_LOG(DEBUG, TAG, "Add network type(IP) - Not Supported"); return CA_NOT_SUPPORTED; -#endif /* ETHERNET_ADAPTER */ +#endif /* IP_ADAPTER */ - OIC_LOG(DEBUG, TAG, "Add network type(ETHERNET)"); - if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_ETHERNET)) + OIC_LOG(DEBUG, TAG, "Add network type(IP)"); + if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_IP)) { goto exit; } - res = u_arraylist_add(g_selectedNetworkList, &NETWORK_ETHERNET); + res = u_arraylist_add(g_selectedNetworkList, &NETWORK_IP); } break; - - case CA_WIFI: + case CA_IPV6: { - -#ifndef WIFI_ADAPTER - OIC_LOG(DEBUG, TAG, "Add network type(WIFI) - Not Supported"); + OIC_LOG(ERROR, TAG, "Currently IPV6 is not supported"); return CA_NOT_SUPPORTED; -#endif /* WIFI_ADAPTER */ - - OIC_LOG(DEBUG, TAG, "Add network type(WIFI)"); - if (u_arraylist_contains(g_selectedNetworkList, &NETWORK_WIFI)) - { - goto exit; - } - res = u_arraylist_add(g_selectedNetworkList, &NETWORK_WIFI); } - break; case CA_EDR: { @@ -125,9 +113,8 @@ CAResult_t CAAddNetworkType(CAConnectivityType_t connectivityType) OIC_LOG_V(ERROR, TAG, "Add arraylist failed[Err code: %d]", res); return res; } - // start selected interface adapter - res = CAStartAdapter((CAConnectivityType_t)connectivityType); + res = CAStartAdapter((CATransportType_t)transportType); OIC_LOG(DEBUG, TAG, "OUT"); return res; @@ -136,7 +123,7 @@ exit: return CA_STATUS_OK; } -CAResult_t CARemoveNetworkType(CAConnectivityType_t connectivityType) +CAResult_t CARemoveNetworkType(CATransportType_t transportType) { OIC_LOG(DEBUG, TAG, "IN"); @@ -156,35 +143,29 @@ CAResult_t CARemoveNetworkType(CAConnectivityType_t connectivityType) continue; } - CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType; + CATransportType_t connType = *(CATransportType_t *) ptrType; - if (connectivityType == connType) + if (transportType == connType) { - switch (connectivityType) + switch (transportType) { - case CA_ETHERNET: + case CA_IPV4: -#ifndef ETHERNET_ADAPTER - OIC_LOG(DEBUG, TAG, "Remove network type(ETHERNET) - Not Supported"); +#ifndef IP_ADAPTER + OIC_LOG(DEBUG, TAG, "Remove network type(IP) - Not Supported"); return CA_NOT_SUPPORTED; #else - OIC_LOG(DEBUG, TAG, "Remove network type(ETHERNET)"); + OIC_LOG(DEBUG, TAG, "Remove network type(IP)"); u_arraylist_remove(g_selectedNetworkList, index); -#endif /* ETHERNET_ADAPTER */ +#endif /* IP_ADAPTER */ break; - case CA_WIFI: - -#ifndef WIFI_ADAPTER - OIC_LOG(DEBUG, TAG, "Remove network type(WIFI) - Not Supported"); + case CA_IPV6: + { + OIC_LOG(ERROR, TAG, "Currently IPV6 is not supported"); return CA_NOT_SUPPORTED; -#else - OIC_LOG(DEBUG, TAG, "Remove network type(WIFI)"); - u_arraylist_remove(g_selectedNetworkList, index); -#endif /* WIFI_ADAPTER */ - - break; + } case CA_EDR: diff --git a/resource/csdk/connectivity/src/caremotehandler.c b/resource/csdk/connectivity/src/caremotehandler.c index dd64a33..1271fd9 100644 --- a/resource/csdk/connectivity/src/caremotehandler.c +++ b/resource/csdk/connectivity/src/caremotehandler.c @@ -130,7 +130,7 @@ static int32_t getCAAddress(const char *pAddress, CAAddress_t *outAddress) } CARemoteEndpoint_t *CACreateRemoteEndpointUriInternal(const CAURI_t uri, - const CAConnectivityType_t connectivityType) + const CATransportType_t transportType) { // support URI type // coap://10.11.12.13:4545/resource_uri @@ -217,7 +217,7 @@ CARemoteEndpoint_t *CACreateRemoteEndpointUriInternal(const CAURI_t uri, CAURI_t resourceUri = pResourceUri; CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, address, - connectivityType); + transportType); if (NULL == remoteEndpoint) { OIC_LOG(ERROR, TAG, "create remote endpoint fail"); @@ -234,7 +234,8 @@ CARemoteEndpoint_t *CACreateRemoteEndpointUriInternal(const CAURI_t uri, } CARemoteEndpoint_t *CACreateRemoteEndpointInternal(const CAURI_t resourceUri, - const CAAddress_t addr, const CAConnectivityType_t type) + const CAAddress_t addr, + const CATransportType_t type) { if (NULL == resourceUri) { @@ -273,7 +274,7 @@ CARemoteEndpoint_t *CACreateRemoteEndpointInternal(const CAURI_t resourceUri, memcpy(&(rep->addressInfo), &addr, sizeof(CAAddress_t)); // save the type - rep->connectivityType = type; + rep->transportType = type; return rep; } diff --git a/resource/csdk/connectivity/src/caretransmission.c b/resource/csdk/connectivity/src/caretransmission.c index b8c6f59..aeb2b5d 100644 --- a/resource/csdk/connectivity/src/caretransmission.c +++ b/resource/csdk/connectivity/src/caretransmission.c @@ -342,11 +342,11 @@ CAResult_t CARetransmissionSentData(CARetransmission_t *context, return CA_STATUS_INVALID_PARAM; } - // #0. check support connectivity type - if (!(context->config.supportType & endpoint->connectivityType)) + // #0. check support transport type + if (!(context->config.supportType & endpoint->transportType)) { - OIC_LOG_V(DEBUG, TAG, "not supported connectivity type for retransmission..(%d)", - endpoint->connectivityType); + OIC_LOG_V(DEBUG, TAG, "not supported transport type for retransmission..(%d)", + endpoint->transportType); return CA_NOT_SUPPORTED; } @@ -419,7 +419,7 @@ CAResult_t CARetransmissionSentData(CARetransmission_t *context, // found index if (NULL != currData->endpoint && currData->messageId == messageId - && (currData->endpoint->connectivityType == endpoint->connectivityType)) + && (currData->endpoint->transportType == endpoint->transportType)) { OIC_LOG(ERROR, TAG, "Duplicate message ID"); @@ -455,11 +455,11 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context, return CA_STATUS_INVALID_PARAM; } - // #0. check support connectivity type - if (!(context->config.supportType & endpoint->connectivityType)) + // #0. check support transport type + if (!(context->config.supportType & endpoint->transportType)) { - OIC_LOG_V(DEBUG, TAG, "not supported connectivity type for retransmission..(%d)", - endpoint->connectivityType); + OIC_LOG_V(DEBUG, TAG, "not supported transport type for retransmission..(%d)", + endpoint->transportType); return CA_STATUS_OK; } @@ -480,7 +480,8 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context, uint32_t len = u_arraylist_length(context->dataList); // find index - for (uint32_t i = 0; i < len; i++) + uint32_t i; + for (i = 0; i < len; i++) { CARetransmissionData_t *retData = (CARetransmissionData_t *) u_arraylist_get( context->dataList, i); @@ -492,7 +493,7 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context, // found index if (NULL != retData->endpoint && retData->messageId == messageId - && (retData->endpoint->connectivityType == endpoint->connectivityType)) + && (retData->endpoint->transportType == endpoint->transportType)) { // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device // if retransmission was finish..token will be unavailable. diff --git a/resource/csdk/connectivity/src/caretransmission_singlethread.c b/resource/csdk/connectivity/src/caretransmission_singlethread.c index 83d3855..e419278 100644 --- a/resource/csdk/connectivity/src/caretransmission_singlethread.c +++ b/resource/csdk/connectivity/src/caretransmission_singlethread.c @@ -196,7 +196,7 @@ CAResult_t CARetransmissionInitialize(CARetransmission_t *context, if (NULL == config) { // setDefault - cfg.supportType = (CAConnectivityType_t) DEFAULT_RETRANSMISSION_TYPE; + cfg.supportType = (CATransportType_t) DEFAULT_RETRANSMISSION_TYPE; cfg.tryingCount = DEFAULT_RETRANSMISSION_COUNT; } else @@ -228,10 +228,10 @@ CAResult_t CARetransmissionSentData(CARetransmission_t *context, const CARemoteE } // #0. check support connectivity type - if (!(context->config.supportType & endpoint->connectivityType)) + if (!(context->config.supportType & endpoint->transportType)) { OIC_LOG(ERROR, TAG, "error"); - OIC_LOG_V(ERROR, TAG, "not supported conntype=%d", endpoint->connectivityType); + OIC_LOG_V(ERROR, TAG, "not supported conntype=%d", endpoint->transportType); return CA_NOT_SUPPORTED; } @@ -307,9 +307,9 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context, } // #0. check support connectivity type - if (!(context->config.supportType & endpoint->connectivityType)) + if (!(context->config.supportType & endpoint->transportType)) { - OIC_LOG_V(DEBUG, TAG, "not supp conntype=%d", endpoint->connectivityType); + OIC_LOG_V(DEBUG, TAG, "not supp conntype=%d", endpoint->transportType); return CA_STATUS_OK; } @@ -320,7 +320,7 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context, OIC_LOG_V(DEBUG, TAG, "recv pdu, msgtype=%d,msgid=%d", type, messageId); - if ((CA_MSG_ACKNOWLEDGE != type) && (CA_MSG_RESET != type)) + if (CA_MSG_ACKNOWLEDGE != type && CA_MSG_RESET != type) { return CA_STATUS_OK; } @@ -340,7 +340,7 @@ CAResult_t CARetransmissionReceivedData(CARetransmission_t *context, // found index if (NULL != retData->endpoint && retData->messageId == messageId - && (retData->endpoint->connectivityType == endpoint->connectivityType)) + && (retData->endpoint->transportType == endpoint->transportType)) { // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device // if retransmission was finish..token will be unavailable. diff --git a/resource/csdk/connectivity/src/ethernet_adapter/SConscript b/resource/csdk/connectivity/src/ethernet_adapter/SConscript deleted file mode 100644 index 9e48b3b..0000000 --- a/resource/csdk/connectivity/src/ethernet_adapter/SConscript +++ /dev/null @@ -1,33 +0,0 @@ -####################################################### -# Building Ethernet adapter -####################################################### - -Import('env') - -print "Reading ethernet adapter script" - -target_os = env.get('TARGET_OS') -inc_files = env.get('CPPPATH') -src_dir = './ethernet_adapter/' - -#Source files to build common for all platforms -if target_os == 'arduino': - env.AppendUnique(CA_SRC=[src_dir+'caethernetadapter_singlethread.c']) - env.AppendUnique(CPPPATH=[src_dir+'arduino/']) -else: - env.AppendUnique(CA_SRC=[src_dir+'caethernetadapter.c']) - -#Source files to build in Linux platform -if target_os in ['linux','darwin']: - env.AppendUnique(CA_SRC=[src_dir+'linux/caethernetclient.c', - src_dir+'linux/caethernetserver.c', - src_dir+'linux/caethernetnwmonitor.c', - ]) - -#Source files to build in Arduino platform -if target_os == 'arduino': - env.AppendUnique(CA_SRC=[src_dir+'arduino/caethernetadapterutils.cpp', - src_dir+'arduino/caethernetclient.cpp', - src_dir+'arduino/caethernetserver.cpp', - src_dir+'arduino/caethernetnwmonitor.cpp', - ]) diff --git a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetnwmonitor.cpp b/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetnwmonitor.cpp deleted file mode 100644 index c20d073..0000000 --- a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetnwmonitor.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/****************************************************************** -* -* Copyright 2014 Samsung Electronics All Rights Reserved. -* -* -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -******************************************************************/ - -#include "caethernetinterface_singlethread.h" - -#include -#include -#include -#include -#include -#include -#include "logger.h" -#include "caadapterutils.h" -#include "caethernetadapter_singlethread.h" - -#define ETHERNET_MONITOR_TAG "ETHERNET_MONITOR" - -CAResult_t CAEthernetInitializeNetworkMonitor(void) -{ - return CA_STATUS_OK; -} - -CAResult_t CAEthernetStartNetworkMonitor(void) -{ - return CA_STATUS_OK; -} - -CAResult_t CAEthernetGetInterfaceInfo(char **interfaceName, char **ipAddress) -{ - return CA_STATUS_OK; -} - -bool CAEthernetIsConnected(void) -{ - return true; -} - -void CAEthernetSetConnectionStateChangeCallback - (CAEthernetConnectionStateChangeCallback callback) -{ - return; -} - -CAResult_t CAEthernetStopNetworkMonitor(void) -{ - return CA_STATUS_OK; -} - -void CAEthernetTerminateNetworkMonitor(void) -{ - return; -} diff --git a/resource/csdk/connectivity/src/ethernet_adapter/caethernetadapter_singlethread.c b/resource/csdk/connectivity/src/ethernet_adapter/caethernetadapter_singlethread.c deleted file mode 100644 index f6b4c13..0000000 --- a/resource/csdk/connectivity/src/ethernet_adapter/caethernetadapter_singlethread.c +++ /dev/null @@ -1,486 +0,0 @@ -/****************************************************************** - * - * Copyright 2014 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ - -#include "caethernetadapter_singlethread.h" - -#include -#include -#include "caadapterutils.h" -#include "logger.h" -#include "oic_malloc.h" -#include "caethernetinterface_singlethread.h" - -/** - * @def ETHERNET_ADAPTER_TAG - * @brief Logging tag for module name - */ -#define ETHERNET_ADAPTER_TAG "EA" - -/** - * @def CA_PORT - * @brief Unicast port number (to listen for incoming data on unicast server). - * Note :- Actual port number may differ based on result of bind() operation. - */ -#define CA_PORT 6298 - -/** - * @def CA_SECURE_PORT - * @brief Secured (unicast) port number as defined in COAP Specification, RFC-7252. - */ -#define CA_SECURE_PORT 5684 - -/** - * @def CA_MCAST_PORT - * @brief Multicast port number as defined in COAP Specification, RFC-7252. - */ -#define CA_MCAST_PORT 5683 - -/** - * @def CA_MULTICAST_IP - * @brief Multicast IP Address - */ -#define CA_MULTICAST_IP "224.0.1.187" - -/* Skip Queue */ -/** - * @var gNetworkPacketCallback - * @brief Network Packet Received Callback to CA - */ -static CANetworkPacketReceivedCallback gNetworkPacketCallback = NULL; - -/** - * @var gNetworkChangeCb - * @brief Network Changed Callback to CA - */ - -static CANetworkChangeCallback gNetworkChangeCallback = NULL; - -/** - * @var gIsMulticastServerStarted - * @brief Flag to check if multicast server is started - */ -static bool gIsMulticastServerStarted = false; - -/** - * @var gIsStartServerCalled - * @brief Flag to check if server start requested by CA. - */ -static bool gStartUnicastServerRequested = false; - -/** - * @var gUnicastServerport - * @brief port number on which unicast server is running. - */ -static uint16_t gUnicastServerport = 0; - -/** - * @var gIsStartServerCalled - * @brief Flag to check if server start requested by CA. - */ -static bool gStartMulticastServerRequested = false; - - -static void CAEthernetNotifyNetworkChange(const char *address, int16_t port, - CANetworkStatus_t status); -static void CAEthernetConnectionStateCB(const char *ipAddress, - CANetworkStatus_t status); -static void CAEthernetPacketReceivedCB(const char *ipAddress, uint32_t port, - const void *data, uint32_t dataLength); -static CAResult_t CAEthernetStopServers(); - -void CAEthernetNotifyNetworkChange(const char *address, int16_t port, - CANetworkStatus_t status) -{ - CALocalConnectivity_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_ETHERNET, address); - if (!localEndpoint) - { - OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Out of memory!"); - return; - } - localEndpoint->addressInfo.IP.port = port; - - if (NULL != gNetworkChangeCallback) - { - gNetworkChangeCallback(localEndpoint, status); - } - - CAAdapterFreeLocalEndpoint(localEndpoint); -} - -void CAEthernetConnectionStateCB(const char *ipAddr, - CANetworkStatus_t status) -{ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN"); - - CAResult_t ret = CA_STATUS_FAILED; - /* If Ethernet is connected, then get the latest IP from the Ethernet Interface - * and start unicast and multicast servers if requested earlier */ - if (CA_INTERFACE_UP == status) - { - uint16_t port = CA_PORT; - int32_t serverFd = -1; - /* Start Unicast server if requested earlier */ - if (gStartUnicastServerRequested) - { - ret = CAEthernetStartUnicastServer("0.0.0.0", &port, false, &serverFd); - if (CA_STATUS_OK == ret) - { - OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "unicast started:%d", port); - CAEthernetSetUnicastSocket(serverFd); - CAEthernetSetUnicastPort(port); - gUnicastServerport = port; - } - else - { - OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "FAILED:%d", ret); - } - } - - /* Start Multicast server if requested earlier */ - if (gStartMulticastServerRequested) - { - int16_t multicastPort = CA_MCAST_PORT; - ret = CAEthernetStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort, &serverFd); - if (CA_STATUS_OK == ret) - { - OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "multicast started:%d", multicastPort); - gIsMulticastServerStarted = true; - } - else - { - OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "strt mcast srv fail:%d", ret); - } - } - - char *ipAddress = NULL; - char *ifcName = NULL; - CAResult_t ret = CAEthernetGetInterfaceInfo(&ifcName, &ipAddress); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "get interface info fail:%d", ret); - OICFree(ipAddress); - OICFree(ifcName); - return; - } - /* Notify network change to CA */ - CAEthernetNotifyNetworkChange(ipAddress, port, status); - OICFree(ipAddress); - OICFree(ifcName); - } - else - { - CAEthernetNotifyNetworkChange("", 0, status); - /* Stop both Unicast and Multicast servers */ - ret = CAEthernetStopServers(); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "stop srv fail:%d", ret); - return; - } - } - - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT"); -} - -void CAEthernetPacketReceivedCB(const char *ipAddress, uint32_t port, - const void *data, uint32_t dataLength) -{ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN"); - OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "sddress:%s", ipAddress); - OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "port:%s", port); - OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "data:%s", data); - - /* CA is freeing this memory */ - CARemoteEndpoint_t *endPoint = CAAdapterCreateRemoteEndpoint(CA_ETHERNET, ipAddress, NULL); - if (NULL == endPoint) - { - OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Out of memory!"); - return; - } - endPoint->addressInfo.IP.port = port; - - if (gNetworkPacketCallback) - { - gNetworkPacketCallback(endPoint, data, dataLength); - } - CAAdapterFreeRemoteEndpoint(endPoint); - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT"); -} - -CAResult_t CAInitializeEthernet(CARegisterConnectivityCallback registerCallback, - CANetworkPacketReceivedCallback networkPacketCallback, - CANetworkChangeCallback netCallback) -{ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN"); - VERIFY_NON_NULL(registerCallback, ETHERNET_ADAPTER_TAG, "registerCallback"); - VERIFY_NON_NULL(networkPacketCallback, ETHERNET_ADAPTER_TAG, "networkPacketCallback"); - VERIFY_NON_NULL(netCallback, ETHERNET_ADAPTER_TAG, "netCallback"); - - gNetworkChangeCallback = netCallback; - gNetworkPacketCallback = networkPacketCallback; - - CAResult_t ret = CAEthernetInitializeNetworkMonitor(); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "init n/w fail:%d", ret); - return ret; - } - CAEthernetSetConnectionStateChangeCallback(CAEthernetConnectionStateCB); - - ret = CAEthernetInitializeServer(); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "init fail:%d", ret); - CATerminateEthernet(); - return ret; - } - CAEthernetSetPacketReceiveCallback(CAEthernetPacketReceivedCB); - - CAConnectivityHandler_t EthernetHandler; - EthernetHandler.startAdapter = CAStartEthernet; - EthernetHandler.startListenServer = CAStartEthernetListeningServer; - EthernetHandler.startDiscoveryServer = CAStartEthernetDiscoveryServer; - EthernetHandler.sendData = CASendEthernetUnicastData; - EthernetHandler.sendDataToAll = CASendEthernetMulticastData; - EthernetHandler.GetnetInfo = CAGetEthernetInterfaceInformation; - EthernetHandler.readData = CAReadEthernetData; - EthernetHandler.stopAdapter = CAStopEthernet; - EthernetHandler.terminate = CATerminateEthernet; - registerCallback(EthernetHandler, CA_ETHERNET); - - OIC_LOG(INFO, ETHERNET_ADAPTER_TAG, "success"); - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT"); - return CA_STATUS_OK; -} - -CAResult_t CAStartEthernet() -{ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN"); - - /* Start monitoring Ethernet network */ - CAResult_t ret = CAEthernetStartNetworkMonitor(); - if (CA_STATUS_OK != ret) - { - OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "strt n/w monitor fail"); - } - - gStartUnicastServerRequested = true; - bool retVal = CAEthernetIsConnected(); - if (false == retVal) - { - OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "not connected"); - return ret; - } - - uint16_t unicastPort = CA_PORT; - int32_t serverFd = 0; - // Address is hardcoded as we are using Single Interface - ret = CAEthernetStartUnicastServer("0.0.0.0", &unicastPort, false, &serverFd); - if (CA_STATUS_OK == ret) - { - OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "unicast started:%d", unicastPort); - CAEthernetSetUnicastSocket(serverFd); - CAEthernetSetUnicastPort(unicastPort); - gUnicastServerport = unicastPort; - } - - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT"); - return ret; -} - -CAResult_t CAStartEthernetListeningServer() -{ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN"); - - CAResult_t ret = CA_STATUS_OK; - int16_t multicastPort = CA_MCAST_PORT; - int32_t serverFD = 1; - if (gIsMulticastServerStarted == true) - { - OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Already Started!"); - return CA_SERVER_STARTED_ALREADY; - } - - gStartMulticastServerRequested = true; - bool retVal = CAEthernetIsConnected(); - if (false == retVal) - { - OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG,"Not connected"); - return CA_ADAPTER_NOT_ENABLED; - } - - ret = CAEthernetStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort, &serverFD); - if (CA_STATUS_OK == ret) - { - OIC_LOG(INFO, ETHERNET_ADAPTER_TAG, "multicast success"); - gIsMulticastServerStarted = true; - } - - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT"); - return ret; -} - -CAResult_t CAStartEthernetDiscoveryServer() -{ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN"); - /* Both listening and discovery server are same */ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT"); - return CAStartEthernetListeningServer(); -} - -int32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data, - uint32_t dataLength) -{ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN"); - - VERIFY_NON_NULL_RET(remoteEndpoint, ETHERNET_ADAPTER_TAG, "remoteEndpoint", -1); - VERIFY_NON_NULL_RET(data, ETHERNET_ADAPTER_TAG, "data", -1); - if (dataLength == 0) - { - OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Invalid length"); - return -1; - } - - CAEthernetSendData(remoteEndpoint->addressInfo.IP.ipAddress, - remoteEndpoint->addressInfo.IP.port, data, dataLength, false); - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT"); - return dataLength; -} - -int32_t CASendEthernetMulticastData(const void *data, uint32_t dataLength) -{ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN"); - - VERIFY_NON_NULL_RET(data, ETHERNET_ADAPTER_TAG, "data", -1); - if (dataLength == 0) - { - OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Invalid length"); - return -1; - } - - CAEthernetSendData(CA_MULTICAST_IP, CA_MCAST_PORT, data, dataLength, true); - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT"); - return dataLength; -} - -CAResult_t CAGetEthernetInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size) -{ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN"); - VERIFY_NON_NULL(info, ETHERNET_ADAPTER_TAG, "info"); - VERIFY_NON_NULL(size, ETHERNET_ADAPTER_TAG, "size"); - - bool retVal = CAEthernetIsConnected(); - if (false == retVal) - { - OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Not connected"); - return CA_ADAPTER_NOT_ENABLED; - } - - char *ipAddress = NULL; - char *ifcName = NULL; - CAResult_t ret = CAEthernetGetInterfaceInfo(&ifcName, &ipAddress); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "get interface info fail:%d", ret); - OICFree(ipAddress); - OICFree(ifcName); - return ret; - } - - // Create local endpoint using util function - (*info) = CAAdapterCreateLocalEndpoint(CA_ETHERNET, ipAddress); - if (NULL == (*info)) - { - OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "malloc fail"); - OICFree(ipAddress); - OICFree(ifcName); - return CA_MEMORY_ALLOC_FAILED; - } - - (*info)->addressInfo.IP.port = gUnicastServerport; - (*size) = 1; - - OICFree(ipAddress); - OICFree(ifcName); - - OIC_LOG(INFO, ETHERNET_ADAPTER_TAG, "success"); - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT"); - return CA_STATUS_OK; -} - -CAResult_t CAReadEthernetData() -{ - CAEthernetPullData(); - return CA_STATUS_OK; -} - -CAResult_t CAEthernetStopServers() -{ - CAResult_t result = CAEthernetStopUnicastServer(); - if (CA_STATUS_OK != result) - { - OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "stop ucast srv fail:%d", result); - return result; - } - CAEthernetSetUnicastSocket(-1); - CAEthernetSetUnicastPort(0); - gUnicastServerport = 0; - - result = CAEthernetStopMulticastServer(); - if (CA_STATUS_OK != result) - { - OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "stop mcast srv fail:%d", result); - return result; - } - gIsMulticastServerStarted = false; - - return result; -} - -CAResult_t CAStopEthernet() -{ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN"); - - gStartUnicastServerRequested = false; - gStartMulticastServerRequested = false; - CAEthernetStopNetworkMonitor(); - CAResult_t result = CAEthernetStopServers(); - if (CA_STATUS_OK != result) - { - OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "stop srv fail:%d", result); - } - - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT"); - return result; -} - -void CATerminateEthernet() -{ - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN"); - - CAEthernetSetConnectionStateChangeCallback(NULL); - CAEthernetTerminateNetworkMonitor(); - CAEthernetSetPacketReceiveCallback(NULL); - OIC_LOG(INFO, ETHERNET_ADAPTER_TAG, "Terminated Ethernet"); - OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT"); - return; -} - - diff --git a/resource/csdk/connectivity/src/ethernet_adapter/linux/caethernetclient.c b/resource/csdk/connectivity/src/ethernet_adapter/linux/caethernetclient.c deleted file mode 100644 index c34437d..0000000 --- a/resource/csdk/connectivity/src/ethernet_adapter/linux/caethernetclient.c +++ /dev/null @@ -1,146 +0,0 @@ -/****************************************************************** -* -* Copyright 2014 Samsung Electronics All Rights Reserved. -* -* -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -******************************************************************/ - -// Defining _BSD_SOURCE or _DEFAULT_SOURCE causes header files to expose -// definitions that may otherwise be skipped. Skipping can cause implicit -// declaration warnings and/or bugs and subtle problems in code execution. -// For glibc information on feature test macros, -// Refer http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html -// -// This file requires #define use due to inet_aton -// For details on compatibility support, -// Refer http://man7.org/linux/man-pages/man3/inet.3.html -#define _DEFAULT_SOURCE -#define _BSD_SOURCE - -#include "caethernetinterface.h" - -#include -#include -#include -#include -#include - -#include "caadapterutils.h" - -/** - * @def ETHERNET_CLIENT_TAG - * @brief Logging tag for module name - */ -#define ETHERNET_CLIENT_TAG "ETHERNET_CLIENT" - -/** - * @var g_unicastServerSocketDescClient - * @brief socket descriptor for unicast server - */ -static int32_t g_unicastServerSocketDescClient = -1; - -#ifdef __WITH_DTLS__ -/** - * @var g_unicastServerSecureSocketDescClient - * @brief socket descriptor for secure unicast server - */ -static int32_t g_unicastServerSecureSocketDescClient = -1; -#endif - -static uint32_t CASendData(const char *remoteAddress, const uint16_t port, - const void *data, const uint32_t dataLength, int32_t sockfd) -{ - OIC_LOG(DEBUG, ETHERNET_CLIENT_TAG, "IN"); - - VERIFY_NON_NULL_RET(remoteAddress, ETHERNET_CLIENT_TAG, "IP address is NULL", 0); - VERIFY_NON_NULL_RET(data, ETHERNET_CLIENT_TAG, "data is NULL", 0); - - if (0 == dataLength) - { - OIC_LOG(ERROR, ETHERNET_CLIENT_TAG, "Data length is 0 !"); - return 0; - } - - if (0 > sockfd) - { - OIC_LOG(ERROR, ETHERNET_CLIENT_TAG, "Unicast Server is not running !"); - return 0; - } - - struct sockaddr_in destAddr; - memset((char *)&destAddr, 0, sizeof(destAddr)); - destAddr.sin_family = AF_INET; - destAddr.sin_port = htons(port); - - // Conversion from ASCII format to Network format - if (0 == inet_aton(remoteAddress, &destAddr.sin_addr)) - { - OIC_LOG(ERROR, ETHERNET_CLIENT_TAG, "Failed to convert from ASCII to Network Address"); - return 0; - } - - int32_t sendDataLength = sendto(sockfd, data, dataLength, 0, - (struct sockaddr *)&destAddr, sizeof(destAddr)); - if (-1 == sendDataLength) - { - OIC_LOG_V(ERROR, ETHERNET_CLIENT_TAG, "Failed to Send Data, Error code: %s", - strerror(errno)); - return 0; - } - - OIC_LOG_V(INFO, ETHERNET_CLIENT_TAG, "Sending data is successful, sent bytes[%d]", - sendDataLength); - return sendDataLength; -} - -void CAEthernetSetUnicastSocket(const int32_t socketFD) -{ - OIC_LOG(DEBUG, ETHERNET_CLIENT_TAG, "IN"); - - g_unicastServerSocketDescClient = socketFD; -} - -#ifdef __WITH_DTLS__ -void CAEthernetSetSecureUnicastSocket(const int32_t socketFD) -{ - OIC_LOG(DEBUG, ETHERNET_CLIENT_TAG, "IN"); - - g_unicastServerSecureSocketDescClient = socketFD; -} -#endif - -uint32_t CAEthernetSendData(const char *remoteAddress, const uint16_t port, - const void *data, const uint32_t dataLength, - bool isMulticast, bool isSecured) -{ - uint32_t len = 0; - -#ifdef __WITH_DTLS__ - if (true == isSecured) - { - len = CASendData(remoteAddress, port, - data, dataLength, g_unicastServerSecureSocketDescClient); - } - else -#endif - { - len = CASendData(remoteAddress, port, - data, dataLength, g_unicastServerSocketDescClient); - } - - return len; -} - diff --git a/resource/csdk/connectivity/src/ip_adapter/SConscript b/resource/csdk/connectivity/src/ip_adapter/SConscript new file mode 100644 index 0000000..57ddf1b --- /dev/null +++ b/resource/csdk/connectivity/src/ip_adapter/SConscript @@ -0,0 +1,45 @@ +####################################################### +# Building IP adapter +####################################################### + +Import('env') + +print "Reading IP adapter script" + +target_os = env.get('TARGET_OS') +inc_files = env.get('CPPPATH') +src_dir = './ip_adapter/' + +#Source files to build common for all platforms +if target_os == 'arduino': + env.AppendUnique(CA_SRC=[src_dir+'caipadapter_singlethread.c']) + env.AppendUnique(CPPPATH=[src_dir+'arduino/']) +else: + env.AppendUnique(CA_SRC=[src_dir+'caipadapter.c']) + env.AppendUnique(CA_SRC=[src_dir+'caipclient.c']) + env.AppendUnique(CA_SRC=[src_dir+'caipserver.c']) + +#Source files to build in Linux platform +if target_os == 'linux': + env.AppendUnique(CA_SRC=[src_dir+'linux/caipnwmonitor.c']) + +if target_os == 'tizen': + env.AppendUnique(CA_SRC=[src_dir+'tizen/caipnwmonitor.c']) + +#Source files to build in Arduino platform +if target_os == 'arduino': + env.AppendUnique(CA_SRC=[src_dir+'arduino/caipnwmonitor.cpp']) + if env.get('SHIELD') == 'WIFI': + env.AppendUnique(CA_SRC=[src_dir+'arduino/caipclient_wifi.cpp', + src_dir+'arduino/caipserver_wifi.cpp', + ]) + else: + env.AppendUnique(CA_SRC=[src_dir+'arduino/caipadapterutils_eth.cpp', + src_dir+'arduino/caipclient_eth.cpp', + src_dir+'arduino/caipserver_eth.cpp', + ]) + +#Source files to build in android platform +if target_os == 'android': + env.AppendUnique(CA_SRC=[src_dir+'android/caipnwmonitor.c']) + env.AppendUnique(CPPPATH=[src_dir+'android/']) diff --git a/resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c b/resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c new file mode 100644 index 0000000..c6aa380 --- /dev/null +++ b/resource/csdk/connectivity/src/ip_adapter/android/caipnwmonitor.c @@ -0,0 +1,871 @@ +/****************************************************************** + * + * 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 "caipinterface.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "caadapterutils.h" +#include "umutex.h" +#include "logger.h" +#include "oic_malloc.h" +#include "oic_string.h" +#include "org_iotivity_jar_caipinterface.h" + +#define IP_MONITOR_TAG "IP_MONITOR" +#define MAX_INTERFACE_INFO_LENGTH (1024) + +/** + * @var g_stopNetworkMonitor + * @brief Used to stop the network monitor thread. + */ +static bool g_stopNetworkMonitor = false; + +/** + * @var g_stopNetworkMonitorMutex + * @brief Mutex for synchronizing access to g_stopNetworkMonitor flag. + */ +static u_mutex g_stopNetworkMonitorMutex = NULL; + +/** + * @struct CAIPNwMonitorContext + * @brief Used for storing network monitor context information. + */ +typedef struct +{ + u_arraylist_t *netInterfaceList; + u_thread_pool_t threadPool; + CANetworkStatus_t nwConnectivityStatus; + CAIPConnectionStateChangeCallback networkChangeCb; +} CAIPNetworkMonitorContext; + +/** + * @var g_networkMonitorContext + * @brief network monitor context. + */ +static CAIPNetworkMonitorContext *g_networkMonitorContext = NULL; + +/** + * @var g_networkMonitorContextMutex + * @brief Mutex for synchronizing access to cached interface and IP address information. + */ +static u_mutex g_networkMonitorContextMutex = NULL; + +/** + * @var g_jvm + * @brief pointer to store JavaVM + */ +static JavaVM *g_jvm = NULL; + +/** + * @var g_context + * @brief pointer to store Application Context + */ +static jobject g_context = NULL; + +/** + * @fn CAIPUpdateInterfaceInformation + * @brief This methods gets local interface name and IP address information. + */ +static CAResult_t CAIPUpdateInterfaceInformation(u_arraylist_t **netInterfaceList); +/** + * @fn CACreateIPJNIInterfaceObject + * @brief creates new instance of caipinterface through JNI + */ +static CAResult_t CACreateIPJNIInterfaceObject(jobject context); + +/** + * @fn CAIPSendNetworkChangeCallback + * @brief updates network status to IP adapter + */ +static void CAIPSendNetworkChangeCallback(CANetworkStatus_t currNetworkStatus); + +CAResult_t CAIPJniInit() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPJniInit"); + g_jvm = CANativeJNIGetJavaVM(); + + if (!g_jvm) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "JNI initialize error"); + return CA_STATUS_FAILED; + } + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPJniSetContext() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPJniSetContext"); + g_context = (jobject) CANativeJNIGetContext(); + + if (!g_context) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "unable to get application context"); + return CA_STATUS_FAILED; + } + + return CA_STATUS_OK; +} + +CAResult_t CACreateIPJNIInterfaceObject(jobject context) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "CACreateIPJNIInterfaceObject"); + + VERIFY_NON_NULL(context, IP_MONITOR_TAG, "context"); + + JNIEnv* env; + + if ((*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get JNIEnv pointer"); + return CA_STATUS_FAILED; + } + + //getApplicationContext + jclass contextClass = (*env)->FindClass(env, "android/content/Context"); + if (!contextClass) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get context object class"); + return CA_STATUS_FAILED; + } + + jmethodID getApplicationContextMethod = (*env)->GetMethodID(env, contextClass, + "getApplicationContext", + "()Landroid/content/Context;"); + if (!getApplicationContextMethod) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get getApplicationContext method"); + return CA_STATUS_FAILED; + } + + jobject gApplicationContext = (*env)->CallObjectMethod(env, context, + getApplicationContextMethod); + if (!getApplicationContextMethod) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get getApplicationContext"); + return CA_STATUS_FAILED; + } + + //Create caipinterface jni instance + jclass IPJniInterface = (*env)->FindClass(env, "org/iotivity/jar/caipinterface"); + if (!IPJniInterface) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get caipinterface class"); + return CA_STATUS_FAILED; + } + + jmethodID IPInterfaceConstructorMethod = (*env)->GetMethodID(env, IPJniInterface, "", + "(Landroid/content/Context;)V"); + if (!IPInterfaceConstructorMethod) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Could not get caipinterface constructor method"); + return CA_STATUS_FAILED; + } + + (*env)->NewObject(env, IPJniInterface, IPInterfaceConstructorMethod, gApplicationContext); + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Create caipinterface instance, success"); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +static CAResult_t CAIPUpdateInterfaceInformation(u_arraylist_t **netInterfaceList) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + VERIFY_NON_NULL(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null"); + + /* Get a socket handle. */ + int sck = socket(AF_INET, SOCK_DGRAM, 0); + if (sck < 0) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Error in socket creation"); + return CA_STATUS_FAILED; + } + + char buf[MAX_INTERFACE_INFO_LENGTH] = { 0 }; + struct ifconf ifc; + + /* Query available interfaces. */ + ifc.ifc_len = MAX_INTERFACE_INFO_LENGTH; + ifc.ifc_buf = buf; + + if (ioctl(sck, SIOCGIFCONF, &ifc) < 0) + { + close(sck); + OIC_LOG(ERROR, IP_MONITOR_TAG, "Failed to get interface info"); + return CA_STATUS_FAILED; + } + + /* Iterate through the list of interfaces. */ + struct ifreq* ifr = ifc.ifc_req; + int32_t interfaces = ifc.ifc_len / sizeof(struct ifreq); + + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPUpdateInterfaceInformation : %d", interfaces); + + for (int32_t i = 0; i < interfaces; i++) + { + struct ifreq temp_ifr = { 0 }; + struct ifreq* item = &ifr[i]; + + char interfaceAddress[CA_IPADDR_SIZE] = { 0 }; + char interfaceSubnetMask[CA_IPADDR_SIZE] = { 0 }; + socklen_t len = sizeof(struct sockaddr_in); + + strcpy(temp_ifr.ifr_name, item->ifr_name); + + if (ioctl(sck, SIOCGIFFLAGS, &temp_ifr)) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, + "CAIPUpdateInterfaceInformation, SIOCGIFFLAGS Failed"); + close(sck); + return CA_STATUS_FAILED; + } + + if ((temp_ifr.ifr_flags & IFF_LOOPBACK) + || !(temp_ifr.ifr_flags & IFF_UP) || !(temp_ifr.ifr_flags & IFF_RUNNING)) + { + continue; + } + + if (AF_INET != ((struct sockaddr_in*) &item->ifr_addr)->sin_family) + { + continue; + } + + //get the interface ip address + if (0 != getnameinfo(&item->ifr_addr, len, interfaceAddress, sizeof(interfaceAddress), + NULL, 0, NI_NUMERICHOST)) + { + OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get IPAddress, Error code: %s", + strerror(errno)); + close(sck); + return CA_STATUS_FAILED; + } + + if (ioctl((int) sck, SIOCGIFNETMASK, item) < 0) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, + "CAIPUpdateInterfaceInformation, SIOCGIFNETMASK Failed"); + close(sck); + return CA_STATUS_FAILED; + } + + // get the interface subnet mask + if (0 != getnameinfo(&item->ifr_netmask, len, interfaceSubnetMask, + sizeof(interfaceSubnetMask), NULL, 0, NI_NUMERICHOST)) + { + OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get subnet mask, Error code: %s", + strerror(errno)); + close(sck); + return CA_STATUS_FAILED; + } + + CANetInfo_t *netInfo = (CANetInfo_t *) OICCalloc(1, sizeof(CANetInfo_t)); + if (!netInfo) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed"); + close(sck); + return CA_MEMORY_ALLOC_FAILED; + } + + // set interface name + strncpy(netInfo->interfaceName, item->ifr_name, strlen(item->ifr_name)); + + // set local ip address + strncpy(netInfo->ipAddress, interfaceAddress, strlen(interfaceAddress)); + + // set subnet mask + strncpy(netInfo->subnetMask, interfaceSubnetMask, strlen(interfaceSubnetMask)); + + CAResult_t result = u_arraylist_add(*netInterfaceList, (void *) netInfo); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!Thread exiting."); + close(sck); + return CA_STATUS_FAILED; + } + + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "ipAddress : %s, interfaceName : %s, subnetmask : %s", + netInfo->ipAddress, netInfo->interfaceName, netInfo->subnetMask); + close(sck); + return CA_STATUS_OK; + + break; + } + + close(sck); + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_FAILED; +} + +static bool CACheckIsAnyInterfaceDown(const u_arraylist_t *netInterfaceList, + const CANetInfo_t *info) +{ + VERIFY_NON_NULL_RET(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null", false); + VERIFY_NON_NULL_RET(info, IP_MONITOR_TAG, "info is null", false); + + uint32_t list_length = u_arraylist_length(netInterfaceList); + for (uint32_t list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get(netInterfaceList, list_index); + if (!netInfo) + { + continue; + } + if (strncmp(netInfo->interfaceName, info->interfaceName, strlen(info->interfaceName)) == 0) + { + return false; + } + } + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Interface is down"); + return true; +} + +static bool CACheckIsInterfaceInfoChanged(const CANetInfo_t *info) +{ + VERIFY_NON_NULL_RET(info, IP_MONITOR_TAG, "info is null", false); + + u_mutex_lock(g_networkMonitorContextMutex); + + uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + for (uint32_t list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get( + g_networkMonitorContext->netInterfaceList, list_index); + if (!netInfo) + { + continue; + } + if (strncmp(netInfo->interfaceName, info->interfaceName, strlen(info->interfaceName)) == 0) + { + if (strncmp(netInfo->ipAddress, info->ipAddress, strlen(info->ipAddress)) == 0) + { + u_mutex_unlock(g_networkMonitorContextMutex); + return false; + } + else + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network interface info changed"); + if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, list_index)) + { + if (g_networkMonitorContext->networkChangeCb) + { + g_networkMonitorContext->networkChangeCb(netInfo->ipAddress, + CA_INTERFACE_DOWN); + } + OICFree(netInfo); + } + else + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed"); + } + break; + } + } + } + + CANetInfo_t *newNetInfo = (CANetInfo_t *) OICMalloc(sizeof(CANetInfo_t)); + if (!newNetInfo) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "newNetInfo malloc failed"); + u_mutex_unlock(g_networkMonitorContextMutex); + return false; + } + memcpy(newNetInfo, info, sizeof(*newNetInfo)); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "New Interface found"); + + CAResult_t result = u_arraylist_add(g_networkMonitorContext->netInterfaceList, + (void *) newNetInfo); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!"); + OICFree(newNetInfo); + u_mutex_unlock(g_networkMonitorContextMutex); + return false; + } + u_mutex_unlock(g_networkMonitorContextMutex); + + /*Callback will be unset only at the time of termination. By that time, all the threads will be + stopped gracefully. This callback is properly protected*/ + if (g_networkMonitorContext->networkChangeCb) + { + g_networkMonitorContext->networkChangeCb(newNetInfo->ipAddress, CA_INTERFACE_UP); + } + + return true; +} + +static CAResult_t CAInitializeNetworkMonitorMutexes() +{ + if (!g_networkMonitorContextMutex) + { + g_networkMonitorContextMutex = u_mutex_new(); + if (!g_networkMonitorContextMutex) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContextMutex Malloc failed"); + return CA_MEMORY_ALLOC_FAILED; + } + } + + if (!g_stopNetworkMonitorMutex) + { + g_stopNetworkMonitorMutex = u_mutex_new(); + if (!g_stopNetworkMonitorMutex) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_stopNetworkMonitorMutex Malloc failed"); + u_mutex_free(g_networkMonitorContextMutex); + return CA_MEMORY_ALLOC_FAILED; + } + } + return CA_STATUS_OK; +} + +static void CADestroyNetworkMonitorMutexes() +{ + u_mutex_free(g_networkMonitorContextMutex); + g_networkMonitorContextMutex = NULL; + + u_mutex_free(g_stopNetworkMonitorMutex); + g_stopNetworkMonitorMutex = NULL; +} + +CAResult_t CAIPInitializeNetworkMonitor(const u_thread_pool_t threadPool) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + VERIFY_NON_NULL(threadPool, IP_MONITOR_TAG, "threadPool is null"); + + CAResult_t ret = CAIPJniInit(); + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Initialization failed"); + return ret; + } + + ret = CAIPJniSetContext(); + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "CAIPJniSetContext failed"); + return ret; + } + + ret = CACreateIPJNIInterfaceObject(g_context); + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "unable to create caipinterface instance"); + return ret; + } + + ret = CAInitializeNetworkMonitorMutexes(); + + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "CAInitializeNetworkMonitorMutexes failed"); + return CA_STATUS_FAILED; + } + + u_mutex_lock(g_networkMonitorContextMutex); + + g_networkMonitorContext = (CAIPNetworkMonitorContext *) OICCalloc( + 1, sizeof(*g_networkMonitorContext)); + if (!g_networkMonitorContext) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext Malloc failed"); + u_mutex_unlock(g_networkMonitorContextMutex); + CADestroyNetworkMonitorMutexes(); + return CA_MEMORY_ALLOC_FAILED; + } + g_networkMonitorContext->threadPool = threadPool; + + g_networkMonitorContext->netInterfaceList = u_arraylist_create(); + if (!g_networkMonitorContext->netInterfaceList) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_create failed"); + OICFree(g_networkMonitorContext); + u_mutex_unlock(g_networkMonitorContextMutex); + CADestroyNetworkMonitorMutexes(); + return CA_MEMORY_ALLOC_FAILED; + } + + CAIPUpdateInterfaceInformation(&g_networkMonitorContext->netInterfaceList); + + if (u_arraylist_length(g_networkMonitorContext->netInterfaceList)) + { + g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_UP; + } + else + { + g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_DOWN; + } + + u_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +void CAIPTerminateNetworkMonitor() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + u_mutex_lock(g_networkMonitorContextMutex); + g_networkMonitorContext->threadPool = NULL; + + CAClearNetInterfaceInfoList(g_networkMonitorContext->netInterfaceList); + + g_networkMonitorContext->netInterfaceList = NULL; + g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_DOWN; + g_networkMonitorContext->networkChangeCb = NULL; + g_networkMonitorContext->threadPool = NULL; + + OICFree(g_networkMonitorContext); + g_networkMonitorContext = NULL; + + u_mutex_unlock(g_networkMonitorContextMutex); + + u_mutex_lock(g_stopNetworkMonitorMutex); + g_stopNetworkMonitor = true; + u_mutex_unlock(g_stopNetworkMonitorMutex); + + CADestroyNetworkMonitorMutexes(); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); +} + +CAResult_t CAIPStartNetworkMonitor() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + u_mutex_lock(g_stopNetworkMonitorMutex); + g_stopNetworkMonitor = false; + u_mutex_unlock(g_stopNetworkMonitorMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPStopNetworkMonitor() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + u_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext is null"); + u_mutex_unlock(g_networkMonitorContextMutex); + return CA_STATUS_FAILED; + } + + u_mutex_unlock(g_networkMonitorContextMutex); + + u_mutex_lock(g_stopNetworkMonitorMutex); + if (!g_stopNetworkMonitor) + { + g_stopNetworkMonitor = true; + } + else + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPStopNetworkMonitor, already stopped!"); + } + u_mutex_unlock(g_stopNetworkMonitorMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + VERIFY_NON_NULL(netInterfaceList, IP_MONITOR_TAG, "u_array_list is null"); + VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG, "g_networkMonitorContext is null"); + VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG, + "g_networkMonitorContextMutex is null"); + + // Get the interface and ipaddress information from cache + u_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext->netInterfaceList + || !(u_arraylist_length(g_networkMonitorContext->netInterfaceList))) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Network not enabled"); + u_mutex_unlock(g_networkMonitorContextMutex); + return CA_ADAPTER_NOT_ENABLED; + } + + uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo list length [%d]", + list_length); + for (uint32_t list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *info = (CANetInfo_t *) u_arraylist_get( + g_networkMonitorContext->netInterfaceList, list_index); + if (!info) + { + continue; + } + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo ip [%s]", + info->ipAddress); + CANetInfo_t *newNetinfo = (CANetInfo_t *) OICMalloc(sizeof(CANetInfo_t)); + if (!newNetinfo) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed!"); + u_mutex_unlock(g_networkMonitorContextMutex); + return CA_MEMORY_ALLOC_FAILED; + } + + memcpy(newNetinfo, info, sizeof(*info)); + + CAResult_t result = u_arraylist_add(*netInterfaceList, (void *) newNetinfo); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!"); + u_mutex_unlock(g_networkMonitorContextMutex); + return CA_STATUS_FAILED; + } + } + + u_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPGetInterfaceSubnetMask(const char *ipAddress, char **subnetMask) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + VERIFY_NON_NULL(subnetMask, IP_MONITOR_TAG, "subnet mask"); + VERIFY_NON_NULL(ipAddress, IP_MONITOR_TAG, "ipAddress is null"); + VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG, "g_networkMonitorContext is null"); + VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG, + "g_networkMonitorContextMutex is null"); + + // Get the interface and ipaddress information from cache + u_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext->netInterfaceList + || (0 == u_arraylist_length(g_networkMonitorContext->netInterfaceList))) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network not enabled"); + u_mutex_unlock(g_networkMonitorContextMutex); + return CA_ADAPTER_NOT_ENABLED; + } + + uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "list lenght [%d]", list_length); + for (uint32_t list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *info = (CANetInfo_t *) u_arraylist_get( + g_networkMonitorContext->netInterfaceList, list_index); + if (!info) + { + continue; + } + + if (strncmp(info->ipAddress, ipAddress, strlen(ipAddress)) == 0) + { + if (!info->subnetMask) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, + "CAIPGetInterfaceSubnetMask subnetmask is null"); + } + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, + "CAIPGetInterfaceSubnetMask subnetmask is %s", info->subnetMask); + *subnetMask = info->subnetMask ? OICStrdup(info->subnetMask) : NULL; + break; + } + } + u_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +bool CAIPIsConnected() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + if (!g_networkMonitorContextMutex || !g_networkMonitorContext) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "IP is not connected"); + return false; + } + + u_mutex_lock(g_networkMonitorContextMutex); + if (0 == u_arraylist_length(g_networkMonitorContext->netInterfaceList)) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "IP is not connected"); + u_mutex_unlock(g_networkMonitorContextMutex); + return false; + } + u_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return true; +} + +void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + if (!g_networkMonitorContextMutex || !g_networkMonitorContext) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "CAIPSetConnectionStateChangeCallback failed"); + return; + } + u_mutex_lock(g_networkMonitorContextMutex); + + g_networkMonitorContext->networkChangeCb = callback; + + u_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); +} + +void CAIPSendNetworkChangeCallback(CANetworkStatus_t currNetworkStatus) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + u_mutex_lock(g_stopNetworkMonitorMutex); + if (g_stopNetworkMonitor) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Stop Network Monitor Thread is called"); + u_mutex_unlock(g_stopNetworkMonitorMutex); + return; + } + u_mutex_unlock(g_stopNetworkMonitorMutex); + + u_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext->networkChangeCb) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkChangeCb is NULL"); + u_mutex_unlock(g_networkMonitorContextMutex); + return; + } + u_mutex_unlock(g_networkMonitorContextMutex); + + u_arraylist_t *netInterfaceList = u_arraylist_create(); + + VERIFY_NON_NULL_VOID(netInterfaceList, IP_MONITOR_TAG, + "memory allocation failed for netInterfaceList"); + + // if network status is changed + CAResult_t ret = CAIPUpdateInterfaceInformation(&netInterfaceList); + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "could not update interface information"); + } + + u_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext->netInterfaceList) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, + "u_arraylist_create failed. Network Monitor thread stopped"); + CAClearNetInterfaceInfoList(netInterfaceList); + u_mutex_unlock(g_networkMonitorContextMutex); + return; + } + + uint32_t listLength = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + for (uint32_t listIndex = 0; listIndex < listLength;) + { + CANetInfo_t *info = (CANetInfo_t *) u_arraylist_get( + g_networkMonitorContext->netInterfaceList, listIndex); + if (!info) + { + listIndex++; + continue; + } + + bool ret = CACheckIsAnyInterfaceDown(netInterfaceList, info); + if (ret) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Interface is down"); + if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, listIndex)) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "u_arraylist_remove success"); + if (g_networkMonitorContext->networkChangeCb) + { + g_networkMonitorContext->networkChangeCb(info->ipAddress, CA_INTERFACE_DOWN); + } + OICFree(info); + listLength--; + } + else + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed"); + break; + } + } + else + { + listIndex++; + } + } + + u_mutex_unlock(g_networkMonitorContextMutex); + + listLength = u_arraylist_length(netInterfaceList); + for (uint32_t listIndex = 0; listIndex < listLength; listIndex++) + { + CANetInfo_t *info = (CANetInfo_t *) u_arraylist_get(netInterfaceList, listIndex); + if (!info) + { + continue; + } + bool ret = CACheckIsInterfaceInfoChanged(info); + if (ret) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "CACheckIsInterfaceInfoChanged true"); + } + } + CAClearNetInterfaceInfoList(netInterfaceList); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); +} + +JNIEXPORT void JNICALL +Java_org_iotivity_jar_caipinterface_CAIPStateEnabled(JNIEnv *env, jclass class) +{ + CANetworkStatus_t currNetworkStatus = CA_INTERFACE_UP; + OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPStateEnabled"); + + CAIPSendNetworkChangeCallback(currNetworkStatus); +} + +JNIEXPORT void JNICALL +Java_org_iotivity_jar_caipinterface_CAIPStateDisabled(JNIEnv *env, jclass class) +{ + CANetworkStatus_t currNetworkStatus = CA_INTERFACE_DOWN; + OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPStateDisabled"); + + CAIPSendNetworkChangeCallback(currNetworkStatus); +} + diff --git a/resource/csdk/connectivity/src/ip_adapter/android/org_iotivity_jar_caipinterface.h b/resource/csdk/connectivity/src/ip_adapter/android/org_iotivity_jar_caipinterface.h new file mode 100644 index 0000000..b66bad4 --- /dev/null +++ b/resource/csdk/connectivity/src/ip_adapter/android/org_iotivity_jar_caipinterface.h @@ -0,0 +1,30 @@ +#include +/* Header for class org_iotivity_jar_caipinterface */ + +#ifndef _Included_org_iotivity_jar_caipinterface +#define _Included_org_iotivity_jar_caipinterface +#ifdef __cplusplus +extern "C" +{ +#endif +/* + * Class: org_iotivity_jar_caipinterface + * Method: CAIPStateEnabled + * Signature: ()V + */ +JNIEXPORT void JNICALL +Java_org_iotivity_jar_caipinterface_CAIPStateEnabled(JNIEnv *, jclass); + +/* + * Class: org_iotivity_jar_caipinterface + * Method: CAIPStateDisabled + * Signature: ()V + */ +JNIEXPORT +void JNICALL Java_org_iotivity_jar_caipinterface_CAIPStateDisabled +(JNIEnv *, jclass); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.cpp similarity index 76% rename from resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.cpp rename to resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.cpp index e9f1ab5..534d3a4 100644 --- a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.cpp +++ b/resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.cpp @@ -17,7 +17,7 @@ * limitations under the License. * ******************************************************************/ -#include "caethernetadapterutils.h" +#include "caipadapterutils_eth.h" #include #include @@ -29,14 +29,14 @@ #include "logger.h" #include "cacommon.h" #include "caadapterinterface.h" -#include "caethernetadapter_singlethread.h" +#include "caipadapter_singlethread.h" #include "caadapterutils.h" -#define MOD_NAME "EU" +#define TAG "IPU" CAResult_t CAArduinoGetAvailableSocket(int *sockID) { - VERIFY_NON_NULL(sockID, MOD_NAME, "sockID"); + VERIFY_NON_NULL(sockID, TAG, "sockID"); uint8_t state; //Is any socket available to work with ? *sockID = 0; @@ -52,7 +52,7 @@ CAResult_t CAArduinoGetAvailableSocket(int *sockID) if (*sockID == 0) { - OIC_LOG(ERROR, MOD_NAME, "sockID 0"); + OIC_LOG(ERROR, TAG, "sockID 0"); return CA_SOCKET_OPERATION_FAILED; } @@ -61,26 +61,26 @@ CAResult_t CAArduinoGetAvailableSocket(int *sockID) CAResult_t CAArduinoInitUdpSocket(uint16_t *port, int *socketID) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); - VERIFY_NON_NULL(port, MOD_NAME, "port"); - VERIFY_NON_NULL(socketID, MOD_NAME, "socketID"); + OIC_LOG(DEBUG, TAG, "IN"); + VERIFY_NON_NULL(port, TAG, "port"); + VERIFY_NON_NULL(socketID, TAG, "socketID"); CAResult_t ret = CAArduinoGetAvailableSocket(socketID); if (ret != CA_STATUS_OK) { - OIC_LOG(ERROR, MOD_NAME, "get sock fail"); + OIC_LOG(ERROR, TAG, "get sock fail"); return ret; } //Create a datagram socket on which to recv/send. if (!socket(*socketID, SnMR::UDP, *port, 0)) { - OIC_LOG(ERROR, MOD_NAME, "sock fail"); + OIC_LOG(ERROR, TAG, "sock fail"); return CA_STATUS_FAILED; } - OIC_LOG_V(DEBUG, MOD_NAME, "socketId:%d", *socketID); - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG_V(DEBUG, TAG, "socketId:%d", *socketID); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } @@ -88,9 +88,9 @@ CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress, uint16_t mport, uint16_t lport, int *socketID) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); - VERIFY_NON_NULL(mcastAddress, MOD_NAME, "address"); - VERIFY_NON_NULL(socketID, MOD_NAME, "socket"); + OIC_LOG(DEBUG, TAG, "IN"); + VERIFY_NON_NULL(mcastAddress, TAG, "address"); + VERIFY_NON_NULL(socketID, TAG, "socket"); uint8_t mcastMacAddr[] = { 0x01, 0x00, 0x5E, 0x00, 0x00, 0x00}; uint8_t ipAddr[4] = { 0 }; @@ -98,7 +98,7 @@ CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress, if (CAParseIPv4AddressInternal(mcastAddress, ipAddr, sizeof(ipAddr), &parsedPort) != CA_STATUS_OK) { - OIC_LOG(ERROR, MOD_NAME, "parse fail"); + OIC_LOG(ERROR, TAG, "parse fail"); return CA_STATUS_FAILED; } @@ -106,7 +106,7 @@ CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress, CAResult_t ret = CAArduinoGetAvailableSocket(socketID); if (ret != CA_STATUS_OK) { - OIC_LOG(ERROR, MOD_NAME, "sock fail"); + OIC_LOG(ERROR, TAG, "sock fail"); return ret; } @@ -121,12 +121,12 @@ CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress, //Create a datagram socket on which to recv/send. if (!socket(*socketID, SnMR::UDP, lport, SnMR::MULTI)) { - OIC_LOG(ERROR, MOD_NAME, "sock fail"); + OIC_LOG(ERROR, TAG, "sock fail"); return CA_SOCKET_OPERATION_FAILED; } - OIC_LOG_V(DEBUG, MOD_NAME, "socketId:%d", *socketID); - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG_V(DEBUG, TAG, "socketId:%d", *socketID); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } diff --git a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.h b/resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.h similarity index 86% rename from resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.h rename to resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.h index 72a7ec7..dd02d31 100644 --- a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.h +++ b/resource/csdk/connectivity/src/ip_adapter/arduino/caipadapterutils_eth.h @@ -1,4 +1,4 @@ -/* **************************************************************** +/****************************************************************** * * Copyright 2014 Samsung Electronics All Rights Reserved. * @@ -19,13 +19,12 @@ ******************************************************************/ /** - * @file - * - * This file provides APIs ethernet client/server/network monitor modules. + * @file caethernetadapterutils.h + * @brief This file provides APIs ethernet client/server/network monitor modules */ -#ifndef _CA_ETHERNET_ADAPTER_UTILS_ -#define _CA_ETHERNET_ADAPTER_UTILS_ +#ifndef CA_ETHERNET_ADAPTER_UTILS_ +#define CA_ETHERNET_ADAPTER_UTILS_ #include #include @@ -37,7 +36,7 @@ #include "logger.h" #include "cacommon.h" #include "caadapterinterface.h" -#include "caethernetadapter_singlethread.h" +#include "caipadapter_singlethread.h" #include "caadapterutils.h" #ifdef __cplusplus @@ -76,6 +75,6 @@ CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress, } #endif -#endif //_CA_ETHERNET_ADAPTER_UTILS_ +#endif //CA_ETHERNET_ADAPTER_UTILS_ diff --git a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetclient.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_eth.cpp similarity index 67% rename from resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetclient.cpp rename to resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_eth.cpp index b8d9392..95b9334 100644 --- a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetclient.cpp +++ b/resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_eth.cpp @@ -17,7 +17,7 @@ * limitations under the License. * ******************************************************************/ -#include "caethernetinterface_singlethread.h" +#include "caipinterface_singlethread.h" #include #include @@ -29,12 +29,12 @@ #include "logger.h" #include "cacommon.h" #include "caadapterinterface.h" -#include "caethernetadapter_singlethread.h" -#include "caethernetadapterutils.h" +#include "caipadapter_singlethread.h" +#include "caipadapterutils_eth.h" #include "caadapterutils.h" #include "oic_malloc.h" -#define MOD_NAME "EC" +#define TAG "IPC" static int g_sockID = 0; @@ -44,41 +44,41 @@ static int g_sockID = 0; */ static uint16_t g_unicastPort = 0; -void CAEthernetSetUnicastSocket(int socketID) +void CAIPSetUnicastSocket(int socketID) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); if (0 < socketID) { g_sockID = socketID; } else { - OIC_LOG(ERROR, MOD_NAME, "sock err"); + OIC_LOG(ERROR, TAG, "sock err"); } - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); return; } -void CAEthernetSetUnicastPort(uint16_t port) +void CAIPSetUnicastPort(uint16_t port) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); g_unicastPort = port; - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); return; } -uint32_t CAEthernetSendData(const char *remoteAddress, uint16_t port, - const char *buf, uint32_t bufLen, bool isMulticast) +uint32_t CAIPSendData(const char *remoteAddress, uint16_t port, + const char *buf, uint32_t bufLen, bool isMulticast) { if (!isMulticast && 0 == g_unicastPort) { - OIC_LOG(ERROR, MOD_NAME, "port 0"); + OIC_LOG(ERROR, TAG, "port 0"); return 0; } - VERIFY_NON_NULL(buf, MOD_NAME, "buf"); - VERIFY_NON_NULL(remoteAddress, MOD_NAME, "address"); + VERIFY_NON_NULL(buf, TAG, "buf"); + VERIFY_NON_NULL(remoteAddress, TAG, "address"); int socketID = 0; if (isMulticast) @@ -86,12 +86,12 @@ uint32_t CAEthernetSendData(const char *remoteAddress, uint16_t port, if (CAArduinoInitMulticastUdpSocket(remoteAddress, port, g_unicastPort, &socketID) != CA_STATUS_OK) { - OIC_LOG(ERROR, MOD_NAME, "init mcast err"); + OIC_LOG(ERROR, TAG, "init mcast err"); return 0; } - OIC_LOG_V(DEBUG, MOD_NAME, "MPORT:%d", port); - OIC_LOG_V(DEBUG, MOD_NAME, "LPORT:%d", g_unicastPort); - OIC_LOG_V(DEBUG, MOD_NAME, "SOCKET ID:%d", socketID); + OIC_LOG_V(DEBUG, TAG, "MPORT:%d", port); + OIC_LOG_V(DEBUG, TAG, "LPORT:%d", g_unicastPort); + OIC_LOG_V(DEBUG, TAG, "SOCKET ID:%d", socketID); } else { @@ -99,7 +99,7 @@ uint32_t CAEthernetSendData(const char *remoteAddress, uint16_t port, { if (CAArduinoInitUdpSocket(&port, &socketID) != CA_STATUS_OK) { - OIC_LOG(ERROR, MOD_NAME, "init ucast err"); + OIC_LOG(ERROR, TAG, "init ucast err"); return 0; } } @@ -115,14 +115,14 @@ uint32_t CAEthernetSendData(const char *remoteAddress, uint16_t port, if (CAParseIPv4AddressInternal(remoteAddress, ipAddr, sizeof(ipAddr), &parsedPort) != CA_STATUS_OK) { - OIC_LOG(ERROR, MOD_NAME, "parse fail"); + OIC_LOG(ERROR, TAG, "parse fail"); return 0; } if (bufLen > 65535) // Max value for uint16_t { // This will never happen as max buffer size we are dealing with is COAP_MAX_PDU_SIZE - OIC_LOG(ERROR, MOD_NAME, "Size exceeded"); + OIC_LOG(ERROR, TAG, "Size exceeded"); return 0; } @@ -132,7 +132,7 @@ uint32_t CAEthernetSendData(const char *remoteAddress, uint16_t port, close(socketID); } - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); return ret; } diff --git a/resource/csdk/connectivity/src/wifi_adapter/arduino/cawificlient.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_wifi.cpp similarity index 66% rename from resource/csdk/connectivity/src/wifi_adapter/arduino/cawificlient.cpp rename to resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_wifi.cpp index db67cfe..38acd84 100644 --- a/resource/csdk/connectivity/src/wifi_adapter/arduino/cawificlient.cpp +++ b/resource/csdk/connectivity/src/ip_adapter/arduino/caipclient_wifi.cpp @@ -17,7 +17,7 @@ * limitations under the License. * ******************************************************************/ -#include "cawifiinterface_singlethread.h" +#include "caipinterface_singlethread.h" #include #include @@ -30,31 +30,35 @@ #include "logger.h" #include "cacommon.h" #include "caadapterinterface.h" -#include "cawifiadapter_singlethread.h" +#include "caipadapter_singlethread.h" #include "caadapterutils.h" /// This is the max buffer size between Arduino and WiFi Shield -#define ARDUINO_WIFI_BUFFERSIZE (90) - -#define MOD_NAME "WC" +#define ARDUINO_IP_BUFFERSIZE (90) +#define TAG "IPC" static WiFiUDP Udp; -void CAWiFiSetUnicastSocket(int socketID) +void CAIPSetUnicastSocket(int socketID) +{ + +} + +void CAIPSetUnicastPort(uint16_t port) { } -uint32_t CAWiFiSendData(const char *remoteAddress, uint32_t port, - const void *data, uint32_t dataLength, bool isMulticast) +uint32_t CAIPSendData(const char *remoteAddress, uint16_t port, + const char *data, uint32_t dataLength, bool isMulticast) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); - VERIFY_NON_NULL_RET(data, MOD_NAME, "data", 0); - VERIFY_NON_NULL_RET(remoteAddress, MOD_NAME, "address", 0); + VERIFY_NON_NULL_RET(data, TAG, "data", 0); + VERIFY_NON_NULL_RET(remoteAddress, TAG, "address", 0); - OIC_LOG_V(DEBUG, MOD_NAME, "remoteip: %s", remoteAddress); - OIC_LOG_V(DEBUG, MOD_NAME, "port: %d", port); + OIC_LOG_V(DEBUG, TAG, "remoteip: %s", remoteAddress); + OIC_LOG_V(DEBUG, TAG, "port: %d", port); uint8_t ip[4] = {0}; uint16_t parsedPort = 0; @@ -62,7 +66,7 @@ uint32_t CAWiFiSendData(const char *remoteAddress, uint32_t port, &parsedPort); if (res != CA_STATUS_OK) { - OIC_LOG_V(ERROR, MOD_NAME, "Remote adrs parse fail %d", res); + OIC_LOG_V(ERROR, TAG, "Remote adrs parse fail %d", res); return 0; } @@ -76,12 +80,12 @@ uint32_t CAWiFiSendData(const char *remoteAddress, uint32_t port, size_t writeCount = dataLength - bytesWritten; // write upto max ARDUINO_WIFI_BUFFERSIZE bytes writeCount = Udp.write((uint8_t *)data + bytesWritten, - (writeCount > ARDUINO_WIFI_BUFFERSIZE ? - ARDUINO_WIFI_BUFFERSIZE : writeCount)); + (writeCount > ARDUINO_IP_BUFFERSIZE ? + ARDUINO_IP_BUFFERSIZE:writeCount)); if(writeCount == 0) { // write failed - OIC_LOG_V(ERROR, MOD_NAME, "Failed after %u", bytesWritten); + OIC_LOG_V(ERROR, TAG, "Failed after %u", bytesWritten); break; } bytesWritten += writeCount; @@ -89,10 +93,10 @@ uint32_t CAWiFiSendData(const char *remoteAddress, uint32_t port, if (Udp.endPacket() == 0) { - OIC_LOG(ERROR, MOD_NAME, "Failed to send"); + OIC_LOG(ERROR, TAG, "Failed to send"); return 0; } - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); return bytesWritten; } diff --git a/resource/csdk/connectivity/src/wifi_adapter/arduino/cawifinwmonitor.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipnwmonitor.cpp similarity index 57% rename from resource/csdk/connectivity/src/wifi_adapter/arduino/cawifinwmonitor.cpp rename to resource/csdk/connectivity/src/ip_adapter/arduino/caipnwmonitor.cpp index e98ea62..a64142a 100644 --- a/resource/csdk/connectivity/src/wifi_adapter/arduino/cawifinwmonitor.cpp +++ b/resource/csdk/connectivity/src/ip_adapter/arduino/caipnwmonitor.cpp @@ -1,4 +1,4 @@ -/* **************************************************************** +/****************************************************************** * * Copyright 2014 Samsung Electronics All Rights Reserved. * @@ -17,49 +17,47 @@ * limitations under the License. * ******************************************************************/ - /** - * @file - * - * This file is to keep design in sync with other platforms. Right now - * there is no api for network monitioring in arduino. + * @file caipnwmonitor.cpp + * @brief This file is to keep design in sync with other platforms. Right now there is no + * api for network monitioring in arduino. */ -#include "cawifiinterface_singlethread.h" +#include "caipinterface_singlethread.h" -#define WIFI_MONITOR_TAG "WIFI_MONITOR" +#define TAG "IPNW" -CAResult_t CAWiFiInitializeNetworkMonitor(void) +CAResult_t CAIPInitializeNetworkMonitor(void) { return CA_STATUS_OK; } -CAResult_t CAWiFiStartNetworkMonitor(void) +CAResult_t CAIPStartNetworkMonitor(void) { return CA_STATUS_OK; } -CAResult_t CAWiFiGetInterfaceInfo(char **interfaceName, char **ipAddress) +CAResult_t CAIPGetInterfaceInfo(char **ipAddress, char **interfaceName) { return CA_STATUS_OK; } -bool CAWiFiIsConnected(void) +bool CAIPIsConnected(void) { return true; } -void CAWiFiSetConnectionStateChangeCallback(CAWiFiConnectionStateChangeCallback callback) +void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback) { return; } -CAResult_t CAWiFiStopNetworkMonitor(void) +CAResult_t CAIPStopNetworkMonitor(void) { return CA_STATUS_OK; } -void CAWiFiTerminateNetworkMonitor(void) +void CAIPTerminateNetworkMonitor(void) { return; } diff --git a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetserver.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_eth.cpp similarity index 66% rename from resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetserver.cpp rename to resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_eth.cpp index ab5a2d6..0b7f3df 100644 --- a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetserver.cpp +++ b/resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_eth.cpp @@ -18,7 +18,7 @@ * ******************************************************************/ -#include "caethernetinterface_singlethread.h" +#include "caipinterface_singlethread.h" #include #include @@ -31,25 +31,25 @@ #include "cacommon.h" #include "cainterface.h" #include "caadapterinterface.h" -#include "caethernetadapter_singlethread.h" -#include "caethernetadapterutils.h" +#include "caipadapter_singlethread.h" +#include "caipadapterutils_eth.h" #include "caadapterutils.h" #include "oic_malloc.h" -#define MOD_NAME "ES" +#define TAG "IPS" // Length of the IP address decimal notation string #define IPNAMESIZE (16) -CAResult_t CAEthernetStartUnicastServer(const char *localAddress, uint16_t *port, +CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port, const bool forceStart, int32_t *serverFD); static CAResult_t CAArduinoRecvData(int32_t sockFd); static CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen); static void CAArduinoCheckData(); -static void CAPacketReceivedCallback(const char *ipAddress, const uint32_t port, +static void CAPacketReceivedCallback(const char *ipAddress, const uint16_t port, const void *data, const uint32_t dataLength); -static CAEthernetPacketReceivedCallback g_packetReceivedCallback = NULL; +static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL; static int g_unicastSocket = 0; static int g_multicastSocket = 0; @@ -59,93 +59,93 @@ static int g_multicastSocket = 0; */ static uint16_t g_unicastPort = 0; -CAResult_t CAEthernetInitializeServer(void) +CAResult_t CAIPInitializeServer(void) { return CA_STATUS_OK; } -void CAEthernetTerminateServer(void) +void CAIPTerminateServer(void) { return; } -CAResult_t CAEthernetGetUnicastServerInfo(char **ipAddress, uint16_t *port, +CAResult_t CAIPGetUnicastServerInfo(char **ipAddress, uint16_t *port, int *serverID) { return CA_STATUS_OK; } -CAResult_t CAEthernetStartUnicastServer(const char *localAddress, uint16_t *port, +CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port, const bool forceStart, int *serverFD) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); - VERIFY_NON_NULL(port, MOD_NAME, "port"); + OIC_LOG(DEBUG, TAG, "IN"); + VERIFY_NON_NULL(port, TAG, "port"); uint8_t rawIPAddr[4]; char address[16]; W5100.getIPAddress(rawIPAddr); sprintf(address, "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2], rawIPAddr[3]); - OIC_LOG_V(DEBUG, MOD_NAME, "address:%s", address); + OIC_LOG_V(DEBUG, TAG, "address:%s", address); if (CAArduinoInitUdpSocket(port, serverFD) != CA_STATUS_OK) { - OIC_LOG(DEBUG, MOD_NAME, "failed"); + OIC_LOG(DEBUG, TAG, "failed"); return CA_STATUS_FAILED; } g_unicastPort = *port; g_unicastSocket = *serverFD; - OIC_LOG_V(DEBUG, MOD_NAME, "g_unicastPort: %d", g_unicastPort); - OIC_LOG_V(DEBUG, MOD_NAME, "g_unicastSocket: %d", g_unicastSocket); - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG_V(DEBUG, TAG, "g_unicastPort: %d", g_unicastPort); + OIC_LOG_V(DEBUG, TAG, "g_unicastSocket: %d", g_unicastSocket); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } -CAResult_t CAEthernetStartMulticastServer(const char *localAddress, const char *multicastAddress, - uint16_t multicastPort, int *serverFD) +CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress, + uint16_t multicastPort, int *serverFD) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); if (CAArduinoInitMulticastUdpSocket(multicastAddress, multicastPort, multicastPort, serverFD) != CA_STATUS_OK) { - OIC_LOG(DEBUG, MOD_NAME, "failed"); + OIC_LOG(DEBUG, TAG, "failed"); return CA_STATUS_FAILED; } g_multicastSocket = *serverFD; - OIC_LOG_V(DEBUG, MOD_NAME, "gMulticastPort: %d", multicastPort); - OIC_LOG_V(DEBUG, MOD_NAME, "g_multicastSocket: %d", g_multicastSocket); - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG_V(DEBUG, TAG, "gMulticastPort: %d", multicastPort); + OIC_LOG_V(DEBUG, TAG, "g_multicastSocket: %d", g_multicastSocket); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } -CAResult_t CAEthernetStopUnicastServer() +CAResult_t CAIPStopUnicastServer() { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); close(g_unicastSocket); g_unicastSocket = 0; - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } -CAResult_t CAEthernetStopMulticastServer() +CAResult_t CAIPStopMulticastServer() { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); close(g_multicastSocket); g_multicastSocket = 0; - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } -void CAPacketReceivedCallback(const char *ipAddress, const uint32_t port, +void CAPacketReceivedCallback(const char *ipAddress, const uint16_t port, const void *data, const uint32_t dataLength) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); if (g_packetReceivedCallback) { g_packetReceivedCallback(ipAddress, port, data, dataLength); } - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); } void CAArduinoCheckData() @@ -154,8 +154,8 @@ void CAArduinoCheckData() { if (CAArduinoRecvData(g_unicastSocket) != CA_STATUS_OK) { - OIC_LOG(ERROR, MOD_NAME, "rcv fail"); - CAEthernetStopUnicastServer(); + OIC_LOG(ERROR, TAG, "rcv fail"); + CAIPStopUnicastServer(); } } @@ -163,8 +163,8 @@ void CAArduinoCheckData() { if (CAArduinoRecvData(g_multicastSocket) != CA_STATUS_OK) { - OIC_LOG(ERROR, MOD_NAME, "rcv fail"); - CAEthernetStopMulticastServer(); + OIC_LOG(ERROR, TAG, "rcv fail"); + CAIPStopMulticastServer(); } } } @@ -191,13 +191,13 @@ CAResult_t CAArduinoRecvData(int32_t sockFd) return CA_STATUS_OK; } - OIC_LOG_V(DEBUG, MOD_NAME, "rcvd %d", recvLen); + OIC_LOG_V(DEBUG, TAG, "rcvd %d", recvLen); recvLen = recvLen > COAP_MAX_PDU_SIZE ? COAP_MAX_PDU_SIZE:recvLen; data = OICCalloc(recvLen + 1, 1); if (NULL == data) { - OIC_LOG(DEBUG, MOD_NAME, "Out of memory!"); + OIC_LOG(DEBUG, TAG, "Out of memory!"); return CA_MEMORY_ALLOC_FAILED; } @@ -205,13 +205,13 @@ CAResult_t CAArduinoRecvData(int32_t sockFd) int32_t ret = recvfrom(sockFd, (uint8_t *)data, recvLen + 1, senderAddr, &senderPort); if (ret < 0) { - OIC_LOG(ERROR, MOD_NAME, "rcv fail"); + OIC_LOG(ERROR, TAG, "rcv fail"); OICFree(data); return CA_STATUS_FAILED; } else if (ret > 0) { - OIC_LOG(DEBUG, MOD_NAME, "data recvd"); + OIC_LOG(DEBUG, TAG, "data recvd"); snprintf(addr, sizeof(addr), "%d.%d.%d.%d", senderAddr[0], senderAddr[1], senderAddr[2], senderAddr[3]); CAPacketReceivedCallback(addr, senderPort, data, ret); @@ -219,23 +219,23 @@ CAResult_t CAArduinoRecvData(int32_t sockFd) OICFree(data); - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } -void CAEthernetSetPacketReceiveCallback(CAEthernetPacketReceivedCallback callback) +void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); g_packetReceivedCallback = callback; - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); } -void CAEthernetSetExceptionCallback(CAEthernetExceptionCallback callback) +void CAIPSetExceptionCallback(CAIPExceptionCallback callback) { // TODO } -void CAEthernetPullData() +void CAIPPullData() { CAArduinoCheckData(); } @@ -243,14 +243,14 @@ void CAEthernetPullData() /// Retrieves the IP address assigned to Arduino Ethernet shield CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); - VERIFY_NON_NULL(address, MOD_NAME, "address"); + OIC_LOG(DEBUG, TAG, "IN"); + VERIFY_NON_NULL(address, TAG, "address"); //TODO : Fix this for scenarios when this API is invoked when device is not connected uint8_t rawIPAddr[4]; if (addrLen < IPNAMESIZE) { - OIC_LOG(ERROR, MOD_NAME, "Invalid addrLen"); + OIC_LOG(ERROR, TAG, "Invalid addrLen"); return CA_STATUS_FAILED; } @@ -258,8 +258,8 @@ CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen) snprintf(address, sizeof(address), "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2], rawIPAddr[3]); - OIC_LOG_V(DEBUG, MOD_NAME, "address:%s", address); - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG_V(DEBUG, TAG, "address:%s", address); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } diff --git a/resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiserver.cpp b/resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_wifi.cpp similarity index 60% rename from resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiserver.cpp rename to resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_wifi.cpp index 44b55fb..97dd582 100644 --- a/resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiserver.cpp +++ b/resource/csdk/connectivity/src/ip_adapter/arduino/caipserver_wifi.cpp @@ -18,7 +18,7 @@ * ******************************************************************/ -#include "cawifiinterface_singlethread.h" +#include "caipinterface_singlethread.h" #include #include @@ -32,34 +32,34 @@ #include "cacommon.h" #include "cainterface.h" #include "caadapterinterface.h" -#include "cawifiadapter_singlethread.h" +#include "caipadapter_singlethread.h" #include "caadapterutils.h" #include "oic_malloc.h" -#define MOD_NAME "WS" +#define TAG "IPS" // Length of the IP address decimal notation string #define IPNAMESIZE (16) // Start offsets based on end of received data buffer -#define WIFI_RECBUF_IPADDR_OFFSET (6) -#define WIFI_RECBUF_PORT_OFFSET (2) +#define IP_RECBUF_IPADDR_OFFSET (6) +#define IP_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) +#define IP_RECBUF_IPADDR_SIZE (IP_RECBUF_IPADDR_OFFSET - IP_RECBUF_PORT_OFFSET) +#define IP_RECBUF_PORT_SIZE (IP_RECBUF_PORT_OFFSET - 0) +#define IP_RECBUF_FOOTER_SIZE (IP_RECBUF_IPADDR_SIZE + IP_RECBUF_PORT_SIZE) static CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen); static void CAArduinoCheckData(); -static void CAPacketReceivedCallback(const char *ipAddress, const uint32_t port, - const void *data, const uint32_t dataLength); +static void CAPacketReceivedCallback(const char *ipAddress, const uint16_t port, + const void *data, const uint32_t dataLength); -static CAWiFiPacketReceivedCallback gPacketReceivedCallback = NULL; +static CAIPPacketReceivedCallback gPacketReceivedCallback = NULL; static int32_t gUnicastSocket = 0; static bool gServerRunning = false; static WiFiUDP Udp; -CAResult_t CAWiFiInitializeServer(void) +CAResult_t CAIPInitializeServer(void) { /** * This API is to keep design in sync with other platforms. @@ -68,7 +68,7 @@ CAResult_t CAWiFiInitializeServer(void) return CA_STATUS_OK; } -void CAWiFiTerminateServer(void) +void CAIPTerminateServer(void) { /** * This API is to keep design in sync with other platforms. @@ -76,7 +76,7 @@ void CAWiFiTerminateServer(void) */ } -CAResult_t CAWiFiGetUnicastServerInfo(char **ipAddress, int *port, int *serverID) +CAResult_t CAIPGetUnicastServerInfo(char **ipAddress, uint16_t *port, int *serverID) { /* * This API is to keep design in sync with other platforms. @@ -85,81 +85,81 @@ CAResult_t CAWiFiGetUnicastServerInfo(char **ipAddress, int *port, int *serverID return CA_STATUS_OK; } -CAResult_t CAWiFiStartUnicastServer(const char *localAddress, int16_t *port, - bool forceStart, int *serverFD) +CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port, + bool forceStart, int *serverFD) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); - VERIFY_NON_NULL(port, MOD_NAME, "port"); + OIC_LOG(DEBUG, TAG, "IN"); + VERIFY_NON_NULL(port, TAG, "port"); if (gServerRunning) { // already running - OIC_LOG(DEBUG, MOD_NAME, "Error"); + OIC_LOG(DEBUG, TAG, "Error"); return CA_STATUS_FAILED; } if (WiFi.status() != WL_CONNECTED) { - OIC_LOG(ERROR, MOD_NAME, "ERROR:No WIFI"); + OIC_LOG(ERROR, TAG, "ERROR:No WIFI"); return CA_STATUS_FAILED; } char localIpAddress[CA_IPADDR_SIZE]; int32_t localIpAddressLen = sizeof(localIpAddress); CAArduinoGetInterfaceAddress(localIpAddress, localIpAddressLen); - OIC_LOG_V(DEBUG, MOD_NAME, "address: %s", localIpAddress); - OIC_LOG_V(DEBUG, MOD_NAME, "port: %d", *port); + OIC_LOG_V(DEBUG, TAG, "address: %s", localIpAddress); + OIC_LOG_V(DEBUG, TAG, "port: %d", *port); Udp.begin((uint16_t ) *port); gServerRunning = true; - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } -CAResult_t CAWiFiStartMulticastServer(const char *localAddress, const char *multicastAddress, - int16_t multicastPort, int *serverFD) +CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress, + uint16_t multicastPort, int *serverFD) { // wifi shield does not support multicast - OIC_LOG(DEBUG, MOD_NAME, "IN"); - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "IN"); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_NOT_SUPPORTED; } -CAResult_t CAWiFiStopUnicastServer() +CAResult_t CAIPStopUnicastServer() { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); Udp.stop(); gServerRunning = false; - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } -CAResult_t CAWiFiStopMulticastServer() +CAResult_t CAIPStopMulticastServer() { - return CAWiFiStopUnicastServer(); + return CAIPStopUnicastServer(); } -void CAPacketReceivedCallback(const char *ipAddress, const uint32_t port, +void CAPacketReceivedCallback(const char *ipAddress, const uint16_t port, const void *data, const uint32_t dataLength) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); if (gPacketReceivedCallback) { gPacketReceivedCallback(ipAddress, port, data, dataLength); - OIC_LOG(DEBUG, MOD_NAME, "Notified network packet"); + OIC_LOG(DEBUG, TAG, "Notified network packet"); } - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); } void CAArduinoCheckData() { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); char addr[IPNAMESIZE] = {0}; uint16_t senderPort = 0; int16_t packetSize = Udp.parsePacket(); - OIC_LOG_V(DEBUG, MOD_NAME, "Rcv packet of size:%d ", packetSize); + OIC_LOG_V(DEBUG, TAG, "Rcv packet of size:%d ", packetSize); if (packetSize) { packetSize = packetSize > COAP_MAX_PDU_SIZE ? COAP_MAX_PDU_SIZE:packetSize; @@ -171,7 +171,7 @@ void CAArduinoCheckData() IPAddress remoteIp = Udp.remoteIP(); senderPort = Udp.remotePort(); sprintf(addr, "%d.%d.%d.%d", remoteIp[0], remoteIp[1], remoteIp[2], remoteIp[3]); - OIC_LOG_V(DEBUG, MOD_NAME, "remoteip: %s, port: %d", addr, senderPort); + OIC_LOG_V(DEBUG, TAG, "remoteip: %s, port: %d", addr, senderPort); // read the packet into packetBufffer int32_t dataLen = Udp.read(data, COAP_MAX_PDU_SIZE); if (dataLen > 0) @@ -181,22 +181,22 @@ void CAArduinoCheckData() CAPacketReceivedCallback(addr, senderPort, data, dataLen); OICFree(data); } - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); } -void CAWiFiSetPacketReceiveCallback(CAWiFiPacketReceivedCallback callback) +void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); gPacketReceivedCallback = callback; - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG(DEBUG, TAG, "OUT"); } -void CAWiFiSetExceptionCallback(CAWiFiExceptionCallback callback) +void CAIPSetExceptionCallback(CAIPExceptionCallback callback) { // TODO } -void CAWiFiPullData() +void CAIPPullData() { CAArduinoCheckData(); } @@ -204,25 +204,25 @@ void CAWiFiPullData() /// Retrieves the IP address assigned to Arduino WiFi shield CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen) { - OIC_LOG(DEBUG, MOD_NAME, "IN"); + OIC_LOG(DEBUG, TAG, "IN"); if (WiFi.status() != WL_CONNECTED) { - OIC_LOG(DEBUG, MOD_NAME, "No WIFI"); + OIC_LOG(DEBUG, TAG, "No WIFI"); return CA_STATUS_FAILED; } - VERIFY_NON_NULL(address, MOD_NAME, "Invalid address"); + VERIFY_NON_NULL(address, TAG, "Invalid address"); if (addrLen < IPNAMESIZE) { - OIC_LOG_V(ERROR, MOD_NAME, "AddrLen MUST be atleast %d", IPNAMESIZE); + OIC_LOG_V(ERROR, TAG, "AddrLen MUST be atleast %d", IPNAMESIZE); return CA_STATUS_FAILED; } IPAddress ip = WiFi.localIP(); sprintf((char *)address, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); - OIC_LOG_V(DEBUG, MOD_NAME, "Wifi shield address is: %s", address); - OIC_LOG(DEBUG, MOD_NAME, "OUT"); + OIC_LOG_V(DEBUG, TAG, "Wifi shield address is: %s", address); + OIC_LOG(DEBUG, TAG, "OUT"); return CA_STATUS_OK; } diff --git a/resource/csdk/connectivity/src/ip_adapter/caipadapter.c b/resource/csdk/connectivity/src/ip_adapter/caipadapter.c new file mode 100644 index 0000000..667f958 --- /dev/null +++ b/resource/csdk/connectivity/src/ip_adapter/caipadapter.c @@ -0,0 +1,818 @@ +/****************************************************************** + * + * 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 "caipadapter.h" + +#include +#include +#include +#include + +#include "caipinterface.h" +#include "caqueueingthread.h" +#include "caadapterutils.h" +#ifdef __WITH_DTLS__ +#include "caadapternetdtls.h" +#endif +#include "camutex.h" +#include "uarraylist.h" +#include "logger.h" +#include "oic_malloc.h" + +/** + * @def IP_ADAPTER_TAG + * @brief Logging tag for module name + */ +#define IP_ADAPTER_TAG "IP_ADAP" + +/** + * @def CA_PORT + * @brief Port to listen for incoming data + */ +#define CA_PORT 6298 + +/** + * @def CA_SECURE_PORT + * @brief Secured (unicast) port number as defined in COAP Specification, RFC-7252. + */ +#define CA_SECURE_PORT 5684 + +/** + * @def CA_MCAST_PORT + * @brief Multicast port number as defined in COAP Specification, RFC-7252. + */ +#define CA_MCAST_PORT 5683 + +/** + * @def CA_MULTICAST_IP + * @brief Multicast IP Address as defined in COAP Specification, RFC-7252. + */ +#define CA_MULTICAST_IP "224.0.1.187" + +/** + * @var CAIPData + * @brief Holds inter thread ip data information. + */ +typedef struct +{ + CARemoteEndpoint_t *remoteEndpoint; + void *data; + uint32_t dataLen; +} CAIPData; + +/** + * @var g_networkPacketCallback + * @brief Network Packet Received Callback to CA + */ +static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL; + +/** + * @var g_networkChangeCallback + * @brief Network Changed Callback to CA + */ +static CANetworkChangeCallback g_networkChangeCallback = NULL; + +/** + * @var g_sendQueueHandle + * @brief Queue handle for Send Data + */ +static CAQueueingThread_t *g_sendQueueHandle = NULL; + +/** + * @var g_threadPool + * @brief ThreadPool for storing ca_thread_pool_t handle passed from CA + */ +static ca_thread_pool_t g_threadPool = NULL; + +static CAResult_t CAIPInitializeQueueHandles(); + +static void CAIPDeinitializeQueueHandles(); + +static void CAIPNotifyNetworkChange(const char *address, uint16_t port, + CANetworkStatus_t status); + +static void CAIPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status); + +static void CAIPPacketReceivedCB(const char *ipAddress, uint16_t port, const void *data, + uint32_t dataLength, bool isSecured); +#ifdef __WITH_DTLS__ +static uint32_t CAIPPacketSendCB(const char *ipAddress, uint16_t port, + const void *data, uint32_t dataLength); +#endif + +static CAResult_t CAIPStopServers(); + +static void CAIPSendDataThread(void *threadData); + +static CAIPData *CACreateIPData(const CARemoteEndpoint_t *remoteEndpoint, + const void *data, uint32_t dataLength); +void CAFreeIPData(CAIPData *ipData); + +static void CADataDestroyer(void *data, uint32_t size); + +CAResult_t CAIPInitializeQueueHandles() +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + // Check if the message queue is already initialized + if (g_sendQueueHandle) + { + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "send queue handle is already initialized!"); + return CA_STATUS_OK; + } + + // Create send message queue + g_sendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t)); + if (!g_sendQueueHandle) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Memory allocation failed!"); + return CA_MEMORY_ALLOC_FAILED; + } + + if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle, g_threadPool, + CAIPSendDataThread, CADataDestroyer)) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to Initialize send queue thread"); + OICFree(g_sendQueueHandle); + g_sendQueueHandle = NULL; + return CA_STATUS_FAILED; + } + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +void CAIPDeinitializeQueueHandles() +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + CAQueueingThreadDestroy(g_sendQueueHandle); + OICFree(g_sendQueueHandle); + g_sendQueueHandle = NULL; + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); +} + +void CAIPNotifyNetworkChange(const char *address, uint16_t port, CANetworkStatus_t status) +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + VERIFY_NON_NULL_VOID(address, IP_ADAPTER_TAG, "address is NULL"); + + CALocalConnectivity_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_IPV4, address); + if (!localEndpoint) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "localEndpoint creation failed!"); + return; + } + + localEndpoint->addressInfo.IP.port = port; + + if (g_networkChangeCallback) + { + g_networkChangeCallback(localEndpoint, status); + } + else + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "g_networkChangeCallback is NULL"); + } + + CAAdapterFreeLocalEndpoint(localEndpoint); + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); +} + +void CAIPConnectionStateCB(const char *ipAddress, CANetworkStatus_t status) +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + VERIFY_NON_NULL_VOID(ipAddress, IP_ADAPTER_TAG, "ipAddress is NULL"); + + if (CA_INTERFACE_UP == status) + { + uint16_t port = CA_PORT; + CAResult_t ret = CAIPStartUnicastServer(ipAddress, &port, false, false); + if (CA_STATUS_OK == ret) + { + OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Unicast server started on %d port", port); + } + else + { + OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to start Unicast server port[%d]", ret); + } + +#ifdef __WITH_DTLS__ + port = CA_SECURE_PORT; + ret = CAIPStartUnicastServer(ipAddress, &port, false, true); + if (CA_STATUS_OK == ret) + { + OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Secure Unicast server started on %d", port); + } + else + { + OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to start secure Unicast server [%d]", + ret); + } +#endif + ret = CAIPStartMulticastServer(ipAddress, CA_MULTICAST_IP, CA_MCAST_PORT); + if (CA_STATUS_OK == ret) + { + OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Multicast server started on port[%d]", + CA_MCAST_PORT); + } + else + { + OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to start Multicast server port[%d]", + ret); + } + + // Notify network change to CA + CAIPNotifyNetworkChange(ipAddress, port, status); + } + else + { + CAIPNotifyNetworkChange(ipAddress, 0, status); + + // Stop Unicast, Secured unicast and Multicast servers + CAIPStopServer(ipAddress); + } + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); +} + +#ifdef __WITH_DTLS__ +uint32_t CAIPPacketSendCB(const char *ipAddress, uint16_t port, + const void *data, uint32_t dataLength) +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + VERIFY_NON_NULL_RET(ipAddress, IP_ADAPTER_TAG, "ipAddress is NULL", 0); + + VERIFY_NON_NULL_RET(data, IP_ADAPTER_TAG, "data is NULL", 0); + + uint32_t sentLength = CAIPSendData(ipAddress, port, data, dataLength, false, true); + + OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Successfully sent %d of encrypted data!", sentLength); + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); + + return sentLength; +} +#endif + +void CAIPPacketReceivedCB(const char *ipAddress, uint16_t port, const void *data, + uint32_t dataLength, bool isSecured) +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + VERIFY_NON_NULL_VOID(ipAddress, IP_ADAPTER_TAG, "ipAddress is NULL"); + + VERIFY_NON_NULL_VOID(data, IP_ADAPTER_TAG, "data is NULL"); + + OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Address: %s, port:%d", ipAddress, port); + + // CA is freeing this memory + CARemoteEndpoint_t *endPoint = CAAdapterCreateRemoteEndpoint(CA_IPV4, ipAddress, NULL ); + if (!endPoint) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "EndPoint creation failed!"); + return; + } + endPoint->addressInfo.IP.port = port; + endPoint->isSecured = isSecured; + + void *buf = OICCalloc(dataLength + 1, sizeof(char)); + if (!buf) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Memory Allocation failed!"); + CAAdapterFreeRemoteEndpoint(endPoint); + return; + } + memcpy(buf, data, dataLength); + if (g_networkPacketCallback) + { + g_networkPacketCallback(endPoint, buf, dataLength); + } + else + { + OICFree(buf); + CAAdapterFreeRemoteEndpoint(endPoint); + } + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); +} + +CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback networkPacketCallback, + CANetworkChangeCallback netCallback, ca_thread_pool_t handle) +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + VERIFY_NON_NULL(registerCallback, IP_ADAPTER_TAG, "registerCallback"); + VERIFY_NON_NULL(networkPacketCallback, IP_ADAPTER_TAG, "networkPacketCallback"); + VERIFY_NON_NULL(netCallback, IP_ADAPTER_TAG, "netCallback"); + VERIFY_NON_NULL(handle, IP_ADAPTER_TAG, "thread pool handle"); + + g_threadPool = handle; + g_networkChangeCallback = netCallback; + g_networkPacketCallback = networkPacketCallback; + + CAResult_t ret = CAIPInitializeNetworkMonitor(g_threadPool); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to initialize n/w monitor![%d]", ret); + return ret; + } + CAIPSetConnectionStateChangeCallback(CAIPConnectionStateCB); + + ret = CAIPInitializeServer(g_threadPool); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to initialize server![%d]", ret); + CATerminateIP(); + return ret; + } + + CAIPSetPacketReceiveCallback(CAIPPacketReceivedCB); +#ifdef __WITH_DTLS__ + CAAdapterNetDtlsInit(); + + CADTLSSetAdapterCallbacks(CAIPPacketReceivedCB, CAIPPacketSendCB, DTLS_IP); +#endif + + CAConnectivityHandler_t ipHandler; + ipHandler.startAdapter = CAStartIP; + ipHandler.startListenServer = CAStartIPListeningServer; + ipHandler.startDiscoveryServer = CAStartIPDiscoveryServer; + ipHandler.sendData = CASendIPUnicastData; + ipHandler.sendDataToAll = CASendIPMulticastData; + ipHandler.GetnetInfo = CAGetIPInterfaceInformation; + ipHandler.readData = CAReadIPData; + ipHandler.stopAdapter = CAStopIP; + ipHandler.terminate = CATerminateIP; + registerCallback(ipHandler, CA_IPV4); + + if (CA_STATUS_OK != CAIPInitializeQueueHandles()) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to Initialize Queue Handle"); + CATerminateIP(); + return CA_STATUS_FAILED; + } + + OIC_LOG(INFO, IP_ADAPTER_TAG, "OUT IntializeIP is Success"); + return CA_STATUS_OK; +} + +CAResult_t CAStartIP() +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + // Start monitoring IP network + CAResult_t ret = CAIPStartNetworkMonitor(); + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to Start n/w monitor"); + return ret; + } + + // Start send queue thread + if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle)) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to Start Send Data Thread"); + return CA_STATUS_FAILED; + } + + bool retVal = CAIPIsConnected(); + if (false == retVal) + { + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IP is not Connected"); + return CA_STATUS_OK; + } + + u_arraylist_t *netInterfaceList = u_arraylist_create(); + + VERIFY_NON_NULL(netInterfaceList, IP_ADAPTER_TAG, "netInterfaceList is NULL"); + + ret = CAIPGetInterfaceInfo(&netInterfaceList); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to get IP interface info [%d]", ret); + CAClearNetInterfaceInfoList(netInterfaceList); + return ret; + } + + uint32_t listIndex = 0; + uint32_t listLength = u_arraylist_length(netInterfaceList); + for (listIndex = 0; listIndex < listLength; listIndex++) + { + CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get(netInterfaceList, listIndex); + if (!netInfo || !netInfo->ipAddress) + { + continue; + } + uint16_t unicastPort = CA_PORT; + ret = CAIPStartUnicastServer(netInfo->ipAddress, &unicastPort, false, false); + if (CA_STATUS_OK == ret) + { + OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Unicast server started on %d port", + unicastPort); + } + +#ifdef __WITH_DTLS__ + unicastPort = CA_SECURE_PORT; + ret = CAIPStartUnicastServer(netInfo->ipAddress, &unicastPort, false, true); + + if (CA_STATUS_OK == ret) + { + OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, + "Secure Unicast server started on %d port", unicastPort); + } +#endif + } + CAClearNetInterfaceInfoList(netInterfaceList); + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); + return ret; +} + +CAResult_t CAStartIPListeningServer() +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + bool retVal = CAIPIsConnected(); + if (false == retVal) + { + OIC_LOG(DEBUG, IP_ADAPTER_TAG, + "IP not Connected. Couldn't start multicast server"); + return CA_STATUS_OK; + } + + u_arraylist_t *netInterfaceList = u_arraylist_create(); + + VERIFY_NON_NULL(netInterfaceList, IP_ADAPTER_TAG, "netInterfaceList is NULL"); + + CAResult_t ret = CAIPGetInterfaceInfo(&netInterfaceList); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "Failed to get IP interface info [%d]", ret); + CAClearNetInterfaceInfoList(netInterfaceList); + return ret; + } + + uint32_t listIndex = 0; + uint32_t listLength = u_arraylist_length(netInterfaceList); + for (listIndex = 0; listIndex < listLength; listIndex++) + { + + CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get(netInterfaceList, listIndex); + if (!netInfo || !netInfo->ipAddress) + { + continue; + } + + OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, "Ip address for multicast interface %s", + netInfo->ipAddress); + ret = CAIPStartMulticastServer(netInfo->ipAddress, CA_MULTICAST_IP, CA_MCAST_PORT); + if (CA_STATUS_OK == ret) + { + OIC_LOG(INFO, IP_ADAPTER_TAG, "Multicast Server is Started Successfully"); + } + } + + CAClearNetInterfaceInfoList(netInterfaceList); + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); + return ret; +} + +CAResult_t CAStartIPDiscoveryServer() +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + return CAStartIPListeningServer(); +} + +int32_t CASendIPUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data, + uint32_t dataLength) +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + VERIFY_NON_NULL_RET(remoteEndpoint, IP_ADAPTER_TAG, "remoteEndpoint", -1); + VERIFY_NON_NULL_RET(data, IP_ADAPTER_TAG, "data", -1); + VERIFY_NON_NULL_RET(g_sendQueueHandle, IP_ADAPTER_TAG, "sendQueueHandle", -1); + + if (0 == dataLength) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Invalid Data Length"); + return -1; + } + + // Create IPData to add to queue + CAIPData *ipData = CACreateIPData(remoteEndpoint, data, dataLength); + if (!ipData) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to create ipData!"); + return -1; + } + else + { + // Add message to send queue + CAQueueingThreadAddData(g_sendQueueHandle, ipData, sizeof(CAIPData)); + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); + return dataLength; + } +} + +int32_t CASendIPMulticastData(const void *data, uint32_t dataLength) +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + VERIFY_NON_NULL_RET(data, IP_ADAPTER_TAG, "data", -1); + VERIFY_NON_NULL_RET(g_sendQueueHandle, IP_ADAPTER_TAG, "sendQueueHandle", -1); + + if (0 == dataLength) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Invalid Data Length"); + return -1; + } + + // Create IPData to add to queue + CAIPData *ipData = CACreateIPData(NULL, data, dataLength); + if (!ipData) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Failed to create ipData!"); + return -1; + } + else + { + // Add message to send queue + CAQueueingThreadAddData(g_sendQueueHandle, ipData, sizeof(CAIPData)); + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); + return dataLength; + } +} + +CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size) +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + VERIFY_NON_NULL(info, IP_ADAPTER_TAG, "info is NULL"); + VERIFY_NON_NULL(size, IP_ADAPTER_TAG, "size is NULL"); + + bool retVal = CAIPIsConnected(); + if (false == retVal) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, + "Failed to get interface address, IP not Connected"); + return CA_ADAPTER_NOT_ENABLED; + } + + u_arraylist_t *netInterfaceList = u_arraylist_create(); + + VERIFY_NON_NULL(netInterfaceList, IP_ADAPTER_TAG, "netInterfaceList is NULL"); + + CAResult_t ret = CAIPGetInterfaceInfo(&netInterfaceList); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, IP_ADAPTER_TAG, "CAIPGetInterfaceInfo failed:%d", ret); + CAClearNetInterfaceInfoList(netInterfaceList); + return ret; + } + + uint32_t listLength = u_arraylist_length(netInterfaceList); + uint32_t netInfoSize = listLength; + +#ifdef __WITH_DTLS__ + if (listLength) + { + netInfoSize = listLength * 2; + } +#endif + + CALocalConnectivity_t *conInfo = (CALocalConnectivity_t *) OICCalloc( + netInfoSize, sizeof(CALocalConnectivity_t)); + if (!conInfo) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Malloc Failed"); + CAClearNetInterfaceInfoList(netInterfaceList); + return CA_MEMORY_ALLOC_FAILED; + } + + uint32_t listIndex = 0; + uint32_t count = 0; + for (listIndex = 0; listIndex < listLength; listIndex++) + { + CANetInfo_t *netInfo = (CANetInfo_t *) u_arraylist_get(netInterfaceList, listIndex); + if (!netInfo || !netInfo->ipAddress) + { + continue; + } + + conInfo[count].type = CA_IPV4; + conInfo[count].isSecured = false; + conInfo[count].addressInfo.IP.port = CAGetServerPortNum(netInfo->ipAddress, false); + strncpy(conInfo[count].addressInfo.IP.ipAddress, netInfo->ipAddress, + strlen(netInfo->ipAddress)); + +#ifdef __WITH_DTLS__ + // copy secure unicast server information + { + count ++; + conInfo[count].type = CA_IPV4; + conInfo[count].isSecured = true; + conInfo[count].addressInfo.IP.port = CAGetServerPortNum(netInfo->ipAddress, true); + strncpy(conInfo[count].addressInfo.IP.ipAddress, netInfo->ipAddress, + strlen(netInfo->ipAddress)); + } +#endif + count ++; + } + *size = count; + *info = conInfo; + CAClearNetInterfaceInfoList(netInterfaceList); + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAReadIPData() +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPStopServers() +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + // Stop all unicast and multicast servers. + if (CA_STATUS_OK == CAIPStopAllServers()) + { + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "CAIPStopAllServers success"); + } + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAStopIP() +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + // Stop IP network monitor + CAIPStopNetworkMonitor(); + + // Stop send queue thread + if (g_sendQueueHandle) + { + CAQueueingThreadStop(g_sendQueueHandle); + } + + // Stop Unicast, Secured unicast and Multicast servers running + CAIPStopServers(); + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +void CATerminateIP() +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + +#ifdef __WITH_DTLS__ + CADTLSSetAdapterCallbacks(NULL, NULL, DTLS_IP); + CAAdapterNetDtlsDeInit(); +#endif + + CAIPSetPacketReceiveCallback(NULL); + // Stop IP adapter + CAStopIP(); + + // Terminate IP server + CAIPTerminateServer(); + + // Terminate network monitor + CAIPSetConnectionStateChangeCallback(NULL); + CAIPTerminateNetworkMonitor(); + + // Terminate message queue handler + CAIPDeinitializeQueueHandles(); + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); +} + +void CAIPSendDataThread(void *threadData) +{ + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "IN"); + + CAIPData *ipData = (CAIPData *) threadData; + if (!ipData) + { + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Invalid ip data!"); + return; + } + + //If remoteEndpoint is NULL, its Multicast, else its Unicast. + if (ipData->remoteEndpoint) + { + //Processing for sending unicast + char *address = ipData->remoteEndpoint->addressInfo.IP.ipAddress; + uint16_t port = ipData->remoteEndpoint->addressInfo.IP.port; + +#ifdef __WITH_DTLS__ + if (!ipData->remoteEndpoint->isSecured) + { + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Unicast Data is called"); + CAIPSendData(address, port, ipData->data, ipData->dataLen, false, + ipData->remoteEndpoint->isSecured); + } + else + { + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt called!"); + uint8_t cacheFlag = 0; + CAResult_t result = CAAdapterNetDtlsEncrypt(address, port, ipData->data, + ipData->dataLen, &cacheFlag, + DTLS_IP); + + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt failed!"); + } + OIC_LOG_V(DEBUG, IP_ADAPTER_TAG, + "CAAdapterNetDtlsEncrypt returned with cache[%d]", cacheFlag); + } +#else + CAIPSendData(address, port, ipData->data, ipData->dataLen, false, + ipData->remoteEndpoint->isSecured); +#endif + } + else + { + //Processing for sending multicast + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "Send Multicast Data is called"); + CAIPSendData(CA_MULTICAST_IP, CA_MCAST_PORT, ipData->data, + ipData->dataLen, true, false); + } + + OIC_LOG(DEBUG, IP_ADAPTER_TAG, "OUT"); +} + +CAIPData *CACreateIPData(const CARemoteEndpoint_t *remoteEndpoint, const void *data, + uint32_t dataLength) +{ + VERIFY_NON_NULL_RET(data, IP_ADAPTER_TAG, "IPData is NULL", NULL); + + CAIPData *ipData = (CAIPData *) OICMalloc(sizeof(CAIPData)); + if (!ipData) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Memory allocation failed!"); + return NULL; + } + + ipData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint); + ipData->data = (void *) OICMalloc(dataLength); + if (!ipData->data) + { + OIC_LOG(ERROR, IP_ADAPTER_TAG, "Memory allocation failed!"); + CAFreeIPData(ipData); + return NULL; + } + + memcpy(ipData->data, data, dataLength); + ipData->dataLen = dataLength; + + return ipData; +} + +void CAFreeIPData(CAIPData *ipData) +{ + VERIFY_NON_NULL_VOID(ipData, IP_ADAPTER_TAG, "ipData is NULL"); + + CAAdapterFreeRemoteEndpoint(ipData->remoteEndpoint); + OICFree(ipData->data); + OICFree(ipData); +} + +void CADataDestroyer(void *data, uint32_t size) +{ + CAIPData *etdata = (CAIPData *) data; + + CAFreeIPData(etdata); +} + diff --git a/resource/csdk/connectivity/src/ip_adapter/caipadapter_singlethread.c b/resource/csdk/connectivity/src/ip_adapter/caipadapter_singlethread.c new file mode 100644 index 0000000..9a36455 --- /dev/null +++ b/resource/csdk/connectivity/src/ip_adapter/caipadapter_singlethread.c @@ -0,0 +1,487 @@ +/****************************************************************** + * + * 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 "caipadapter_singlethread.h" + +#include +#include +#include +#include +#include "caadapterutils.h" +#include "logger.h" +#include "oic_malloc.h" +#include "caipinterface_singlethread.h" + +/** + * @def TAG + * @brief Logging tag for module name + */ +#define TAG "IPAD" + +/** + * @def CA_PORT + * @brief Unicast port number (to listen for incoming data on unicast server). + * Note :- Actual port number may differ based on result of bind() operation. + */ +#define CA_PORT 6298 + +/** + * @def CA_SECURE_PORT + * @brief Secured (unicast) port number as defined in COAP Specification, RFC-7252. + */ +#define CA_SECURE_PORT 5684 + +/** + * @def CA_MCAST_PORT + * @brief Multicast port number as defined in COAP Specification, RFC-7252. + */ +#define CA_MCAST_PORT 5683 + +/** + * @def CA_MULTICAST_IP + * @brief Multicast IP Address + */ +#define CA_MULTICAST_IP "224.0.1.187" + +/* Skip Queue */ +/** + * @var g_networkPacketCallback + * @brief Network Packet Received Callback to CA + */ +static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL; + +/** + * @var g_networkChangeCallback + * @brief Network Changed Callback to CA + */ + +static CANetworkChangeCallback g_networkChangeCallback = NULL; + +/** + * @var g_isMulticastServerStarted + * @brief Flag to check if multicast server is started + */ +static bool g_isMulticastServerStarted = false; + +/** + * @var g_startUnicastServerRequested + * @brief Flag to check if server start requested by CA. + */ +static bool g_startUnicastServerRequested = false; + +/** + * @var g_unicastServerport + * @brief port number on which unicast server is running. + */ +static uint16_t g_unicastServerport = 0; + +/** + * @var g_startMulticastServerRequested + * @brief Flag to check if server start requested by CA. + */ +static bool g_startMulticastServerRequested = false; + + +static void CAIPNotifyNetworkChange(const char *address, uint16_t port, + CANetworkStatus_t status); +static void CAIPConnectionStateCB(const char *ipAddress, + CANetworkStatus_t status); +static void CAIPPacketReceivedCB(const char *ipAddress, uint16_t port, + const void *data, uint32_t dataLength); +static CAResult_t CAIPStopServers(); + +void CAIPNotifyNetworkChange(const char *address, uint16_t port, CANetworkStatus_t status) +{ + CALocalConnectivity_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_IPV4, address); + if (!localEndpoint) + { + OIC_LOG(ERROR, TAG, "Out of memory!"); + return; + } + localEndpoint->addressInfo.IP.port = port; + + if (NULL != g_networkChangeCallback) + { + g_networkChangeCallback(localEndpoint, status); + } + + CAAdapterFreeLocalEndpoint(localEndpoint); +} + +void CAIPConnectionStateCB(const char *ipAddr, + CANetworkStatus_t status) +{ + OIC_LOG(DEBUG, TAG, "IN"); + + CAResult_t ret = CA_STATUS_FAILED; + /* If IP is connected, then get the latest IP from the IP Interface + * and start unicast and multicast servers if requested earlier */ + if (CA_INTERFACE_UP == status) + { + uint16_t port = CA_PORT; + int32_t serverFd = -1; + /* Start Unicast server if requested earlier */ + if (g_startUnicastServerRequested) + { + ret = CAIPStartUnicastServer("0.0.0.0", &port, false, &serverFd); + if (CA_STATUS_OK == ret) + { + OIC_LOG_V(DEBUG, TAG, "unicast started:%d", port); + CAIPSetUnicastSocket(serverFd); + CAIPSetUnicastPort(port); + g_unicastServerport = port; + } + else + { + OIC_LOG_V(ERROR, TAG, "FAILED:%d", ret); + } + } + + /* Start Multicast server if requested earlier */ + if (g_startMulticastServerRequested) + { + uint16_t multicastPort = CA_MCAST_PORT; + ret = CAIPStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort, &serverFd); + if (CA_STATUS_OK == ret) + { + OIC_LOG_V(DEBUG, TAG, "multicast started:%d", multicastPort); + g_isMulticastServerStarted = true; + } + else + { + OIC_LOG_V(ERROR, TAG, "strt mcast srv fail:%d", ret); + } + } + + char *ipAddress = NULL; + char *ifcName = NULL; + CAResult_t ret = CAIPGetInterfaceInfo(&ifcName, &ipAddress); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, TAG, "get interface info fail:%d", ret); + OICFree(ipAddress); + OICFree(ifcName); + return; + } + /* Notify network change to CA */ + CAIPNotifyNetworkChange(ipAddress, port, status); + OICFree(ipAddress); + OICFree(ifcName); + } + else + { + CAIPNotifyNetworkChange("", 0, status); + /* Stop both Unicast and Multicast servers */ + ret = CAIPStopServers(); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, TAG, "stop srv fail:%d", ret); + return; + } + } + + OIC_LOG(DEBUG, TAG, "OUT"); +} + +void CAIPPacketReceivedCB(const char *ipAddress, uint16_t port, + const void *data, uint32_t dataLength) +{ + OIC_LOG(DEBUG, TAG, "IN"); + OIC_LOG_V(DEBUG, TAG, "sddress:%s", ipAddress); + OIC_LOG_V(DEBUG, TAG, "port:%d", port); + OIC_LOG_V(DEBUG, TAG, "data:%s", data); + + /* CA is freeing this memory */ + CARemoteEndpoint_t *endPoint = CAAdapterCreateRemoteEndpoint(CA_IPV4, ipAddress, NULL); + if (NULL == endPoint) + { + OIC_LOG(ERROR, TAG, "Out of memory!"); + return; + } + endPoint->addressInfo.IP.port = port; + + if (g_networkPacketCallback) + { + g_networkPacketCallback(endPoint, data, dataLength); + } + CAAdapterFreeRemoteEndpoint(endPoint); + OIC_LOG(DEBUG, TAG, "OUT"); +} + +CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback networkPacketCallback, + CANetworkChangeCallback netCallback) +{ + OIC_LOG(DEBUG, TAG, "IN"); + VERIFY_NON_NULL(registerCallback, TAG, "registerCallback"); + VERIFY_NON_NULL(networkPacketCallback, TAG, "networkPacketCallback"); + VERIFY_NON_NULL(netCallback, TAG, "netCallback"); + + g_networkChangeCallback = netCallback; + g_networkPacketCallback = networkPacketCallback; + + CAResult_t ret = CAIPInitializeNetworkMonitor(); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, TAG, "init n/w fail:%d", ret); + return ret; + } + CAIPSetConnectionStateChangeCallback(CAIPConnectionStateCB); + + ret = CAIPInitializeServer(); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, TAG, "init fail:%d", ret); + CATerminateIP(); + return ret; + } + CAIPSetPacketReceiveCallback(CAIPPacketReceivedCB); + + CAConnectivityHandler_t IPHandler; + IPHandler.startAdapter = CAStartIP; + IPHandler.startListenServer = CAStartIPListeningServer; + IPHandler.startDiscoveryServer = CAStartIPDiscoveryServer; + IPHandler.sendData = CASendIPUnicastData; + IPHandler.sendDataToAll = CASendIPMulticastData; + IPHandler.GetnetInfo = CAGetIPInterfaceInformation; + IPHandler.readData = CAReadIPData; + IPHandler.stopAdapter = CAStopIP; + IPHandler.terminate = CATerminateIP; + registerCallback(IPHandler, CA_IPV4); + + OIC_LOG(INFO, TAG, "success"); + OIC_LOG(DEBUG, TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAStartIP() +{ + OIC_LOG(DEBUG, TAG, "IN"); + + /* Start monitoring IP network */ + CAResult_t ret = CAIPStartNetworkMonitor(); + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, TAG, "strt n/w monitor fail"); + } + + g_startUnicastServerRequested = true; + bool retVal = CAIPIsConnected(); + if (false == retVal) + { + OIC_LOG(ERROR, TAG, "not connected"); + return ret; + } + + uint16_t unicastPort = CA_PORT; + int32_t serverFd = 0; + // Address is hardcoded as we are using Single Interface + ret = CAIPStartUnicastServer("0.0.0.0", &unicastPort, false, &serverFd); + if (CA_STATUS_OK == ret) + { + OIC_LOG_V(DEBUG, TAG, "unicast started:%d", unicastPort); + CAIPSetUnicastSocket(serverFd); + CAIPSetUnicastPort(unicastPort); + g_unicastServerport = unicastPort; + } + + OIC_LOG(DEBUG, TAG, "OUT"); + return ret; +} + +CAResult_t CAStartIPListeningServer() +{ + OIC_LOG(DEBUG, TAG, "IN"); + + CAResult_t ret = CA_STATUS_OK; + uint16_t multicastPort = CA_MCAST_PORT; + int32_t serverFD = 1; + if (g_isMulticastServerStarted == true) + { + OIC_LOG(ERROR, TAG, "Already Started!"); + return CA_SERVER_STARTED_ALREADY; + } + + g_startMulticastServerRequested = true; + bool retVal = CAIPIsConnected(); + if (false == retVal) + { + OIC_LOG(ERROR, TAG,"Not connected"); + return CA_ADAPTER_NOT_ENABLED; + } + + ret = CAIPStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort, &serverFD); + if (CA_STATUS_OK == ret) + { + OIC_LOG(INFO, TAG, "multicast success"); + g_isMulticastServerStarted = true; + } + + OIC_LOG(DEBUG, TAG, "OUT"); + return ret; +} + +CAResult_t CAStartIPDiscoveryServer() +{ + OIC_LOG(DEBUG, TAG, "IN"); + /* Both listening and discovery server are same */ + OIC_LOG(DEBUG, TAG, "OUT"); + return CAStartIPListeningServer(); +} + +int32_t CASendIPUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data, + uint32_t dataLength) +{ + OIC_LOG(DEBUG, TAG, "IN"); + + VERIFY_NON_NULL_RET(remoteEndpoint, TAG, "remoteEndpoint", -1); + VERIFY_NON_NULL_RET(data, TAG, "data", -1); + if (dataLength == 0) + { + OIC_LOG(ERROR, TAG, "Invalid length"); + return -1; + } + + CAIPSendData(remoteEndpoint->addressInfo.IP.ipAddress, + remoteEndpoint->addressInfo.IP.port, data, dataLength, false); + OIC_LOG(DEBUG, TAG, "OUT"); + return dataLength; +} + +int32_t CASendIPMulticastData(const void *data, uint32_t dataLength) +{ + OIC_LOG(DEBUG, TAG, "IN"); + + VERIFY_NON_NULL_RET(data, TAG, "data", -1); + if (dataLength == 0) + { + OIC_LOG(ERROR, TAG, "Invalid length"); + return -1; + } + + CAIPSendData(CA_MULTICAST_IP, CA_MCAST_PORT, data, dataLength, true); + OIC_LOG(DEBUG, TAG, "OUT"); + return dataLength; +} + +CAResult_t CAGetIPInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size) +{ + OIC_LOG(DEBUG, TAG, "IN"); + VERIFY_NON_NULL(info, TAG, "info"); + VERIFY_NON_NULL(size, TAG, "size"); + + bool retVal = CAIPIsConnected(); + if (false == retVal) + { + OIC_LOG(ERROR, TAG, "Not connected"); + return CA_ADAPTER_NOT_ENABLED; + } + + char *ipAddress = NULL; + char *ifcName = NULL; + CAResult_t ret = CAIPGetInterfaceInfo(&ipAddress, &ifcName); + if (CA_STATUS_OK != ret) + { + OIC_LOG_V(ERROR, TAG, "get interface info fail:%d", ret); + OICFree(ipAddress); + OICFree(ifcName); + return ret; + } + + // Create local endpoint using util function + (*info) = CAAdapterCreateLocalEndpoint(CA_IPV4, ipAddress); + if (NULL == (*info)) + { + OIC_LOG(ERROR, TAG, "malloc fail"); + OICFree(ipAddress); + OICFree(ifcName); + return CA_MEMORY_ALLOC_FAILED; + } + + (*info)->addressInfo.IP.port = g_unicastServerport; + (*size) = 1; + + OICFree(ipAddress); + OICFree(ifcName); + + OIC_LOG(INFO, TAG, "success"); + OIC_LOG(DEBUG, TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAReadIPData() +{ + CAIPPullData(); + return CA_STATUS_OK; +} + +CAResult_t CAIPStopServers() +{ + CAResult_t result = CAIPStopUnicastServer(); + if (CA_STATUS_OK != result) + { + OIC_LOG_V(ERROR, TAG, "stop ucast srv fail:%d", result); + return result; + } + CAIPSetUnicastSocket(-1); + CAIPSetUnicastPort(0); + g_unicastServerport = 0; + + result = CAIPStopMulticastServer(); + if (CA_STATUS_OK != result) + { + OIC_LOG_V(ERROR, TAG, "stop mcast srv fail:%d", result); + return result; + } + g_isMulticastServerStarted = false; + + return result; +} + +CAResult_t CAStopIP() +{ + OIC_LOG(DEBUG, TAG, "IN"); + + g_startUnicastServerRequested = false; + g_startMulticastServerRequested = false; + CAIPStopNetworkMonitor(); + CAResult_t result = CAIPStopServers(); + if (CA_STATUS_OK != result) + { + OIC_LOG_V(ERROR, TAG, "stop srv fail:%d", result); + } + + OIC_LOG(DEBUG, TAG, "OUT"); + return result; +} + +void CATerminateIP() +{ + OIC_LOG(DEBUG, TAG, "IN"); + + CAIPSetConnectionStateChangeCallback(NULL); + CAIPTerminateNetworkMonitor(); + CAIPSetPacketReceiveCallback(NULL); + OIC_LOG(INFO, TAG, "Terminated Ethernet"); + OIC_LOG(DEBUG, TAG, "OUT"); + return; +} + + diff --git a/resource/csdk/connectivity/src/ip_adapter/caipclient.c b/resource/csdk/connectivity/src/ip_adapter/caipclient.c new file mode 100644 index 0000000..7cb40df --- /dev/null +++ b/resource/csdk/connectivity/src/ip_adapter/caipclient.c @@ -0,0 +1,146 @@ +/****************************************************************** + * + * 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 "caipinterface.h" + +#include +#include +#include +#include +#include + +#include "caadapterutils.h" + +/** + * @def IP_CLIENT_TAG + * @brief Logging tag for module name + */ +#define IP_CLIENT_TAG "IP_CLIENT" + +static uint32_t CASendData(const char *remoteAddress, uint16_t port, const void *data, + uint32_t dataLength, int sockfd) +{ + OIC_LOG(DEBUG, IP_CLIENT_TAG, "IN"); + + VERIFY_NON_NULL_RET(remoteAddress, IP_CLIENT_TAG, "IP address is NULL", 0); + VERIFY_NON_NULL_RET(data, IP_CLIENT_TAG, "data is NULL", 0); + + if (0 == dataLength) + { + OIC_LOG(ERROR, IP_CLIENT_TAG, "Data length is 0!"); + return 0; + } + + if (0 > sockfd) + { + OIC_LOG(ERROR, IP_CLIENT_TAG, "Unicast Server is not running!"); + return 0; + } + + struct sockaddr_in destAddr = { 0 }; + destAddr.sin_family = AF_INET; + destAddr.sin_port = htons(port); + + int ret = inet_pton(AF_INET, remoteAddress, &(destAddr.sin_addr)); + if (1 != ret) + { + OIC_LOG(ERROR, IP_CLIENT_TAG, "inet_pton failed!"); + return 0; + } + + ssize_t sendDataLength = sendto(sockfd, data, dataLength, 0, (struct sockaddr *) &destAddr, + sizeof(destAddr)); + if (-1 == sendDataLength) + { + OIC_LOG_V(ERROR, IP_CLIENT_TAG, "sendto failed, Error code: %s", + strerror(errno)); + return 0; + } + + OIC_LOG_V(INFO, IP_CLIENT_TAG, "Sending data is successful, sent bytes[%d] to ip[%s:%d]", + sendDataLength, remoteAddress, port); + OIC_LOG(DEBUG, IP_CLIENT_TAG, "OUT"); + return sendDataLength; +} + +uint32_t CAIPSendData(const char *remoteAddress, uint16_t remotePort, const void *data, + uint32_t dataLength, bool isMulticast, bool isSecured) +{ + u_arraylist_t *tempServerInfoList = u_arraylist_create(); + if (!tempServerInfoList) + { + OIC_LOG(ERROR, IP_CLIENT_TAG, "u_arraylist_create failed"); + return 0; + } + + CAResult_t res = CAGetIPServerInfoList(&tempServerInfoList); + if (CA_STATUS_OK != res) + { + OIC_LOG(ERROR, IP_CLIENT_TAG, "CAGetIPServerInfoList failed"); + CAClearServerInfoList(tempServerInfoList); + return 0; + } + + uint32_t len = 0; + if (isMulticast) + { + uint32_t listIndex = 0; + uint32_t listLength = u_arraylist_length(tempServerInfoList); + for (listIndex = 0; listIndex < listLength; listIndex++) + { + CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(tempServerInfoList, + listIndex); + if (!info || info->isMulticastServer || info->isSecured) + { + continue; + } + + if (info->socketFd < 0) + { + OIC_LOG(ERROR, IP_CLIENT_TAG, "Invalid Socket Fd"); + continue; + } + + OIC_LOG_V(DEBUG, IP_CLIENT_TAG, + "CA IP Multicast SendData with src ip %s port %d sockFd %d", + info->ipAddress, info->port, info->socketFd); + len = CASendData(remoteAddress, remotePort, data, dataLength, info->socketFd); + } + } + else + { + int sockFd = CAGetSocketFdForUnicastServer(tempServerInfoList, remoteAddress, isSecured, + isMulticast, CA_IPV4); + + if (sockFd < 0) + { + OIC_LOG(ERROR, IP_CLIENT_TAG, "Invalid Socket Fd"); + CAClearServerInfoList(tempServerInfoList); + return len; + } + + OIC_LOG_V(DEBUG, IP_CLIENT_TAG, "IP unicast SendData sockFd %d", sockFd); + + len = CASendData(remoteAddress, remotePort, data, dataLength, sockFd); + + } + CAClearServerInfoList(tempServerInfoList); + return len; +} + diff --git a/resource/csdk/connectivity/src/ip_adapter/caipserver.c b/resource/csdk/connectivity/src/ip_adapter/caipserver.c new file mode 100644 index 0000000..997e5e3 --- /dev/null +++ b/resource/csdk/connectivity/src/ip_adapter/caipserver.c @@ -0,0 +1,975 @@ +/****************************************************************** + * + * 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 "caipinterface.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "pdu.h" +#include "caadapterutils.h" +#ifdef __WITH_DTLS__ +#include "caadapternetdtls.h" +#endif +#include "camutex.h" +#include "oic_malloc.h" + +/** + * @def IP_SERVER_TAG + * @brief Logging tag for module name + */ +#define IP_SERVER_TAG "IP_SERVER" + +/** + * @def CA_UDP_BIND_RETRY_COUNT + * @brief Retry count in case of socket bind failure. + */ +#define CA_UDP_BIND_RETRY_COUNT 10 + +/** + * @def IPNAMESIZE + * @brief Max length for ip address. + */ +#define IPNAMESIZE 16 + +/** + * @def SOCKETOPTION + * @brief Socket option. + */ +#define SOCKETOPTION 1 + +/** + * @var g_packetHandlerStopFlag + * @brief Flag for stopping packet handler thread. + */ +static bool g_packetHandlerStopFlag = false; + +/** + * @var CAAdapterIPServerContext_t + * @brief Thread context information for callbacks and threadpool. + */ +typedef struct +{ + ca_thread_pool_t threadPool; + CAIPPacketReceivedCallback packetReceivedCallback; + CAIPExceptionCallback exceptionCallback; +} CAAdapterIPServerContext_t; + +/** + * @var g_serverInfoList + * @brief Mutex to synchronize ethenet adapter context. + */ +static u_arraylist_t *g_serverInfoList = NULL; + +/** + * @var g_mutexServerInfoList + * @brief Mutex to synchronize Server Information. + */ +static ca_mutex g_mutexServerInfoList = NULL; + +/** + * @var g_adapterEthServerContext + * @brief Mutex to synchronize ethenet adapter context. + */ +static CAAdapterIPServerContext_t *g_adapterEthServerContext = NULL; + +/** + * @var g_mutexAdapterServerContext + * @brief Mutex to synchronize unicast server + */ +static ca_mutex g_mutexAdapterServerContext = NULL; + +static void CAReceiveHandler(void *data) +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + + fd_set readFds; + int maxSd = 0; + struct timeval timeout; + char recvBuffer[COAP_MAX_PDU_SIZE] = { 0 }; + + while (true != g_packetHandlerStopFlag) + { + timeout.tv_sec = 1; + timeout.tv_usec = 0; + FD_ZERO(&readFds); + + ca_mutex_lock(g_mutexServerInfoList); + uint32_t listIndex = 0; + uint32_t listLength = u_arraylist_length(g_serverInfoList); + + u_arraylist_t *tempServerInfoList = u_arraylist_create(); + if (!tempServerInfoList) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_create failed"); + ca_mutex_unlock(g_mutexServerInfoList); + return; + } + + for (listIndex = 0; listIndex < listLength; listIndex++) + { + CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, listIndex); + if (!info) + { + listIndex++; + continue; + } + + int sd = info->socketFd; + //if valid socket descriptor then add to read list + if (sd > 0) + { + FD_SET(sd, &readFds); + } + + //highest file descriptor number, need it for the select function + if (sd > maxSd) + { + maxSd = sd; + } + + CAServerInfo_t *newInfo = (CAServerInfo_t *) OICMalloc(sizeof(CAServerInfo_t)); + if (!newInfo) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed"); + CAClearServerInfoList(tempServerInfoList); + ca_mutex_unlock(g_mutexServerInfoList); + return; + } + + memcpy(newInfo, info, sizeof(CAServerInfo_t)); + + CAResult_t result = u_arraylist_add(tempServerInfoList, (void *) newInfo); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_add failed!Thread exit"); + CAClearServerInfoList(tempServerInfoList); + ca_mutex_unlock(g_mutexServerInfoList); + return; + } + } + + ca_mutex_unlock(g_mutexServerInfoList); + + int ret = select(maxSd + 1, &readFds, NULL, NULL, &timeout); + if (g_packetHandlerStopFlag) + { + OIC_LOG_V(DEBUG, IP_SERVER_TAG, + "Packet receiver handler Stop request received. Thread exited"); + CAClearServerInfoList(tempServerInfoList); + break; + } + if (ret < 0) + { + OIC_LOG_V(FATAL, IP_SERVER_TAG, "select returned error %s", strerror(errno)); + CAClearServerInfoList(tempServerInfoList); + continue; + } + + listLength = u_arraylist_length(tempServerInfoList); + for (listIndex = 0; listIndex < listLength; listIndex++) + { + CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(tempServerInfoList, + listIndex); + if (!info) + { + continue; + } + + int sd = info->socketFd; + if (FD_ISSET(sd , &readFds)) + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, + "data Received server information ip %s, port %d socket %d", + info->ipAddress, info->port, sd); + memset(recvBuffer, 0, sizeof(recvBuffer)); + + struct sockaddr_in srcSockAddress = { 0 }; + socklen_t srcAddressLen = sizeof(srcSockAddress); + + //Reading from socket + ssize_t recvLen = recvfrom(sd, recvBuffer, sizeof(recvBuffer), 0, + (struct sockaddr *) &srcSockAddress, &srcAddressLen); + if (-1 == recvLen) + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, "Recvfrom failed %s", strerror(errno)); + continue; + } + else if (0 == recvLen) + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, "Server socket shutdown sock fd[%d]", sd); + ca_mutex_lock(g_mutexAdapterServerContext); + // Notify upper layer this exception + if (g_adapterEthServerContext->exceptionCallback) + { + // need to make proper exception callback. + //g_adapterEthServerContext->exceptionCallback(ctx->type); + } + ca_mutex_unlock(g_mutexAdapterServerContext); + } + + char srcIPAddress[CA_IPADDR_SIZE] = { 0 }; + if (!inet_ntop(AF_INET, &srcSockAddress.sin_addr.s_addr, srcIPAddress, + sizeof(srcIPAddress))) + { + + OIC_LOG(ERROR, IP_SERVER_TAG, "inet_ntop is failed!"); + continue; + } + + uint16_t srcPort = ntohs(srcSockAddress.sin_port); + + OIC_LOG_V(DEBUG, IP_SERVER_TAG, "Received packet from %s:%d len %d", + srcIPAddress, srcPort, recvLen); + + char *netMask = NULL; + if (CA_STATUS_OK != CAIPGetInterfaceSubnetMask(info->ifAddr, &netMask)) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to get IP subnet"); + continue; + } + + if (!CAAdapterIsSameSubnet(info->ifAddr, srcIPAddress, netMask)) + { + OIC_LOG(DEBUG, IP_SERVER_TAG, + "Packet received from different subnet, Ignore!"); + OICFree(netMask); + continue; + } + OICFree(netMask); + + if (info->isSecured) + { +#ifdef __WITH_DTLS__ + CAResult_t ret = CAAdapterNetDtlsDecrypt(srcIPAddress, srcPort, + (uint8_t *)recvBuffer, recvLen, + DTLS_IP); + OIC_LOG_V(DEBUG, IP_SERVER_TAG, + "CAAdapterNetDtlsDecrypt returns [%d]", ret); +#endif + } + else //both multicast and unicast + { + ca_mutex_lock(g_mutexAdapterServerContext); + + if (g_adapterEthServerContext->packetReceivedCallback) + { + g_adapterEthServerContext->packetReceivedCallback(srcIPAddress, srcPort, + recvBuffer, recvLen, + false); + } + + ca_mutex_unlock(g_mutexAdapterServerContext); + } + } + } + CAClearServerInfoList(tempServerInfoList); + } + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); +} + +static CAResult_t CACreateSocket(int *socketFD, const char *localIp, uint16_t *port, + bool forceBindStart) +{ + VERIFY_NON_NULL(socketFD, IP_SERVER_TAG, "socketFD is NULL"); + VERIFY_NON_NULL(localIp, IP_SERVER_TAG, "localIp is NULL"); + VERIFY_NON_NULL(port, IP_SERVER_TAG, "port is NULL"); + // Create a UDP socket + int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (-1 == sock) + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to create Socket, Error code: %s", + strerror(errno)); + return CA_STATUS_FAILED; + } + + // Make the socket non-blocking + if (-1 == fcntl(sock, F_SETFL, O_NONBLOCK)) + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to set non-block mode, Error code: %s", + strerror(errno)); + + close(sock); + return CA_STATUS_FAILED; + } + + if (true == forceBindStart) + { + int setOptionOn = SOCKETOPTION; + if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &setOptionOn, + sizeof(setOptionOn))) + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to set SO_REUSEADDR! Error code: %s", + strerror(errno)); + close(sock); + return CA_STATUS_FAILED; + } + } + + struct sockaddr_in sockAddr = { 0 }; + uint16_t serverPort = *port; + sockAddr.sin_family = AF_INET; + sockAddr.sin_port = htons(serverPort); + if (localIp) + { + sockAddr.sin_addr.s_addr = inet_addr(localIp); + } + else + { + sockAddr.sin_addr.s_addr = htonl(INADDR_ANY); + } + + int16_t i = 0; + bool isBound = false; + for (i = 0; i < CA_UDP_BIND_RETRY_COUNT; i++) + { + if (-1 == bind(sock, (struct sockaddr *) &sockAddr, sizeof(sockAddr))) + { + if (false == forceBindStart) + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to bind socket[%s]. Trying again..", + strerror(errno)); + + //Set the port to next one + serverPort += 1; + sockAddr.sin_port = htons(serverPort); + continue; + } + else + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to bind socket[%s]!", + strerror(errno)); + break; + } + } + + isBound = true; + break; + } + + if (false == isBound) + { + close(sock); + return CA_STATUS_FAILED; + } + + *port = serverPort; + *socketFD = sock; + return CA_STATUS_OK; +} + +static void CACloseSocket(int socketFD) +{ + if (-1 == socketFD) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Invalid Socket Fd"); + return; + } + + // close the socket + if (-1 == close(socketFD)) + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, "Failed to close the socket, Error code: %s\n", + strerror(errno)); + } +} + +static CAResult_t CAStartUnicastServer(const char *localAddress, uint16_t *port, + bool forceBindStart, bool isSecured, int *serverFD) +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + + VERIFY_NON_NULL(serverFD, IP_SERVER_TAG, "serverFD"); + VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress"); + VERIFY_NON_NULL(port, IP_SERVER_TAG, "port"); + + CAResult_t ret = CACreateSocket(serverFD, localAddress, port, forceBindStart); + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create unicast socket"); + } + + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); + return ret; +} + +static CAResult_t CAIPStartPacketReceiverHandler() +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + + ca_mutex_lock(g_mutexServerInfoList); + + uint32_t listLength = u_arraylist_length(g_serverInfoList); + + ca_mutex_unlock(g_mutexServerInfoList); + + ca_mutex_lock(g_mutexAdapterServerContext); + + if (!g_adapterEthServerContext) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL"); + ca_mutex_unlock(g_mutexAdapterServerContext); + return CA_STATUS_FAILED; + } + + if (1 == listLength) //Its first time. + { + if (CA_STATUS_OK != ca_thread_pool_add_task(g_adapterEthServerContext->threadPool, + CAReceiveHandler, NULL )) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "thread_pool_add_task failed!"); + ca_mutex_unlock(g_mutexAdapterServerContext); + return CA_STATUS_FAILED; + } + OIC_LOG(DEBUG, IP_SERVER_TAG, "CAReceiveHandler thread started successfully."); + } + else + { + OIC_LOG(DEBUG, IP_SERVER_TAG, "CAReceiveHandler thread already is running"); + } + ca_mutex_unlock(g_mutexAdapterServerContext); + + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); + + return CA_STATUS_OK; +} + +static void CAIPServerDestroyMutex(void) +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + + if (g_mutexServerInfoList) + { + ca_mutex_free(g_mutexServerInfoList); + g_mutexServerInfoList = NULL; + } + + if (g_mutexAdapterServerContext) + { + ca_mutex_free(g_mutexAdapterServerContext); + g_mutexAdapterServerContext = NULL; + } + + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); +} + +static CAResult_t CAIPServerCreateMutex(void) +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + + g_mutexServerInfoList = ca_mutex_new(); + if (!g_mutexServerInfoList) + { + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); + return CA_MEMORY_ALLOC_FAILED; + } + + g_mutexAdapterServerContext = ca_mutex_new(); + if (!g_mutexAdapterServerContext) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to created mutex!"); + ca_mutex_free(g_mutexServerInfoList); + g_mutexServerInfoList = NULL; + return CA_MEMORY_ALLOC_FAILED; + } + + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPInitializeServer(const ca_thread_pool_t threadPool) +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + + // Input validation + VERIFY_NON_NULL(threadPool, IP_SERVER_TAG, "Thread pool handle is NULL"); + + // Initialize mutex + if (CA_STATUS_OK != CAIPServerCreateMutex()) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create mutex!"); + return CA_STATUS_FAILED; + } + + ca_mutex_lock(g_mutexAdapterServerContext); + g_adapterEthServerContext = (CAAdapterIPServerContext_t *) OICCalloc(1, + sizeof(CAAdapterIPServerContext_t)); + + if (!g_adapterEthServerContext) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed"); + ca_mutex_unlock(g_mutexAdapterServerContext); + return CA_MEMORY_ALLOC_FAILED; + } + + g_adapterEthServerContext->threadPool = threadPool; + + ca_mutex_unlock(g_mutexAdapterServerContext); + + ca_mutex_lock(g_mutexServerInfoList); + + g_serverInfoList = u_arraylist_create(); + if (!g_serverInfoList) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_create failed"); + ca_mutex_unlock(g_mutexServerInfoList); + return CA_MEMORY_ALLOC_FAILED; + } + ca_mutex_unlock(g_mutexServerInfoList); + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); + return CA_STATUS_OK; +} + +void CAIPTerminateServer() +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + ca_mutex_lock(g_mutexAdapterServerContext); + if (!g_adapterEthServerContext) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL"); + ca_mutex_unlock(g_adapterEthServerContext); + return; + } + + OICFree(g_adapterEthServerContext); + g_adapterEthServerContext = NULL; + + ca_mutex_unlock(g_mutexAdapterServerContext); + + ca_mutex_lock(g_mutexAdapterServerContext); + + CAClearServerInfoList(g_serverInfoList); + g_serverInfoList = NULL; + + ca_mutex_unlock(g_mutexAdapterServerContext); + // Destroy mutex + CAIPServerDestroyMutex(); + + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); + +} + +CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port, + bool forceBindStart, bool isSecured) +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + + // Input validation + VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress"); + VERIFY_NON_NULL(port, IP_SERVER_TAG, "port"); + + if (0 >= *port) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Invalid input: port is invalid!"); + return CA_STATUS_INVALID_PARAM; + } + + ca_mutex_lock(g_mutexServerInfoList); + bool isUnicastServerStarted = CAIsUnicastServerStarted(g_serverInfoList, localAddress, *port); + if (!isUnicastServerStarted) + { + int unicastServerFd = -1; + if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceBindStart, isSecured, + &unicastServerFd)) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to start unicast server!"); + ca_mutex_unlock(g_mutexServerInfoList); + return CA_STATUS_FAILED; + } + + CAServerInfo_t *info = (CAServerInfo_t *) OICCalloc(1, sizeof(CAServerInfo_t)); + if (!info) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed"); + close(unicastServerFd); + ca_mutex_unlock(g_mutexServerInfoList); + return CA_MEMORY_ALLOC_FAILED; + } + + char *netMask = NULL; + if (CA_STATUS_OK != CAIPGetInterfaceSubnetMask(localAddress, &netMask)) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to get IP subnet"); + } + if (netMask) + { + strncpy(info->subNetMask, netMask, strlen(netMask)); + OICFree(netMask); + } + strncpy(info->ipAddress, localAddress, strlen(localAddress)); + info->port = *port; + info->socketFd = unicastServerFd; + info->isSecured = isSecured; + info->isServerStarted = true; + info->isMulticastServer = false; + strncpy(info->ifAddr, localAddress, strlen(localAddress)); + + CAResult_t res = CAAddServerInfo(g_serverInfoList, info); + if (CA_STATUS_OK != res) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "CAAddServerInfo failed!"); + close(unicastServerFd); + ca_mutex_unlock(g_mutexServerInfoList); + return res; + } + ca_mutex_unlock(g_mutexServerInfoList); + + res = CAIPStartPacketReceiverHandler(); + if (CA_STATUS_OK != res) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "CAIPStartPacketReceiverHandler failed!"); + close(unicastServerFd); + return res; + } + } + else + { + OIC_LOG_V(DEBUG, IP_SERVER_TAG, "Already Unicast Server Started ip [%s] port [%d]", + localAddress, *port); + ca_mutex_unlock(g_mutexServerInfoList); + } + + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPStartMulticastServer(const char *localAddress, const char *multicastAddress, + uint16_t multicastPort) +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + + // Input validation + VERIFY_NON_NULL(localAddress, IP_SERVER_TAG, "localAddress"); + VERIFY_NON_NULL(multicastAddress, IP_SERVER_TAG, "port"); + + uint16_t port = multicastPort; + if (0 >= port) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Invalid input: Multicast port is invalid!"); + return CA_STATUS_INVALID_PARAM; + } + + ca_mutex_lock(g_mutexServerInfoList); + bool isMulticastServerStarted = CAIsMulticastServerStarted(g_serverInfoList, localAddress, + multicastAddress, port); + if (!isMulticastServerStarted) + { + int mulicastServerFd = -1; + CAResult_t ret = CACreateSocket(&mulicastServerFd, multicastAddress, &port, true); + if (ret != CA_STATUS_OK) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to create multicast socket"); + ca_mutex_unlock(g_mutexServerInfoList); + return ret; + } + + struct ip_mreq multicastMemberReq = {.imr_interface.s_addr = inet_addr(localAddress)}; + inet_aton(multicastAddress, &multicastMemberReq.imr_multiaddr); + + if (-1 == setsockopt(mulicastServerFd, IPPROTO_IP, IP_ADD_MEMBERSHIP, + (char *) &multicastMemberReq, sizeof(struct ip_mreq))) + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, + "Failed to add to multicast group, Error code: %s\n", strerror(errno)); + close(mulicastServerFd); + ca_mutex_unlock(g_mutexServerInfoList); + return CA_STATUS_FAILED; + } + + CAServerInfo_t *info = (CAServerInfo_t *) OICCalloc(1, sizeof(CAServerInfo_t)); + if (!info) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed"); + close(mulicastServerFd); + ca_mutex_unlock(g_mutexServerInfoList); + return CA_MEMORY_ALLOC_FAILED; + } + + char *netMask = NULL; + if (CA_STATUS_OK != CAIPGetInterfaceSubnetMask(localAddress, &netMask)) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Failed to get IP subnet"); + } + if (netMask) + { + strncpy(info->subNetMask, netMask, strlen(netMask)); + OICFree(netMask); + } + + strncpy(info->ipAddress, multicastAddress, strlen(multicastAddress)); + info->port = multicastPort; + info->socketFd = mulicastServerFd; + info->isSecured = false; + info->isServerStarted = true; + info->isMulticastServer = true; + strncpy(info->ifAddr, localAddress, strlen(localAddress)); + + ret = CAAddServerInfo(g_serverInfoList, info); + + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "CAAddServerInfo failed!"); + close(mulicastServerFd); + ca_mutex_unlock(g_mutexServerInfoList); + return ret; + } + ca_mutex_unlock(g_mutexServerInfoList); + + ret = CAIPStartPacketReceiverHandler(); + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "CAIPStartPacketReceiverHandler failed!"); + close(mulicastServerFd); + return ret; + } + } + else + { + OIC_LOG_V(DEBUG, IP_SERVER_TAG, + "Multicast Server is already started on interface addr[%s]", localAddress); + ca_mutex_unlock(g_mutexServerInfoList); + } + + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPStopServer(const char *interfaceAddress) +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + + VERIFY_NON_NULL(interfaceAddress, IP_SERVER_TAG, "interfaceAddress is NULL"); + + ca_mutex_lock(g_mutexServerInfoList); + uint32_t listIndex = 0; + uint32_t listLength = u_arraylist_length(g_serverInfoList); + + for (listIndex = 0; listIndex < listLength;) + { + CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, listIndex); + if (!info) + { + listIndex++; + continue; + } + + if (info->isMulticastServer && strncmp(interfaceAddress, info->ifAddr, strlen(info->ifAddr)) + == 0) + { + if (u_arraylist_remove(g_serverInfoList, listIndex)) + { + struct ip_mreq multicastMemberReq = { { 0 }, { 0 } }; + + multicastMemberReq.imr_interface.s_addr = inet_addr(info->ifAddr); + inet_aton(info->ipAddress, &multicastMemberReq.imr_multiaddr); + if (-1 == setsockopt(info->socketFd, IPPROTO_IP, IP_DROP_MEMBERSHIP, + (char *) &multicastMemberReq, sizeof(struct ip_mreq))) + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, + "Failed to leave multicast group, Error code: %s", strerror(errno)); + } + CACloseSocket(info->socketFd); + OICFree(info); + OIC_LOG_V(DEBUG, IP_SERVER_TAG, + "Multicast server is stopped successfully on IF [%s]", info->ifAddr); + // Reduce list length by 1 as we removed one element. + listLength--; + } + else + { + OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed."); + ca_mutex_unlock(g_mutexServerInfoList); + return CA_STATUS_FAILED; + } + } + else if (strncmp(interfaceAddress, info->ipAddress, strlen(info->ipAddress)) == 0) + { + if (u_arraylist_remove(g_serverInfoList, listIndex)) + { + CACloseSocket(info->socketFd); + OICFree(info); + OIC_LOG_V(DEBUG, IP_SERVER_TAG, + "Unicast server is stopped successfully on IF [%s]", info->ifAddr); + // Reduce list length by 1 as we removed one element. + listLength--; + } + else + { + OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed."); + ca_mutex_unlock(g_mutexServerInfoList); + return CA_STATUS_FAILED; + } + } + else + { + listIndex++; + } + } + + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); + ca_mutex_unlock(g_mutexServerInfoList); + return CA_STATUS_OK; +} + +CAResult_t CAIPStopAllServers() +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + + g_packetHandlerStopFlag = true; + + ca_mutex_lock(g_mutexServerInfoList); + + uint32_t listIndex = 0; + uint32_t listLength = u_arraylist_length(g_serverInfoList); + for (listIndex = 0; listIndex < listLength;) + { + CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, listIndex); + if (!info) + { + listIndex++; + continue; + } + if (u_arraylist_remove(g_serverInfoList, listIndex)) + { + if (info->isMulticastServer) + { + struct ip_mreq multicastMemberReq = { { 0 }, { 0 } }; + + multicastMemberReq.imr_interface.s_addr = inet_addr(info->ifAddr); + inet_aton(info->ipAddress, &multicastMemberReq.imr_multiaddr); + if (-1 == setsockopt(info->socketFd, IPPROTO_IP, IP_DROP_MEMBERSHIP, + (char *) &multicastMemberReq, sizeof(struct ip_mreq))) + { + OIC_LOG_V(ERROR, IP_SERVER_TAG, + "Failed to leave multicast group, Error code: %s", strerror(errno)); + } + } + CACloseSocket(info->socketFd); + //Freeing server info. + OICFree(info); + // Reduce list length by 1 as we removed one element. + listLength--; + } + else + { + OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_remove failed."); + ca_mutex_unlock(g_mutexServerInfoList); + return CA_STATUS_FAILED; + } + } + + ca_mutex_unlock(g_mutexServerInfoList); + + OIC_LOG(DEBUG, IP_SERVER_TAG, "All Server stopped successfully. OUT"); + return CA_STATUS_OK; +} + +uint16_t CAGetServerPortNum(const char *ipAddress, bool isSecured) +{ + ca_mutex_lock(g_mutexServerInfoList); + + uint16_t port = CAGetServerPort(g_serverInfoList, ipAddress, isSecured); + + ca_mutex_unlock(g_mutexServerInfoList); + + return port; +} + +CAResult_t CAGetIPServerInfoList(u_arraylist_t **serverInfoList) +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + ca_mutex_lock(g_mutexServerInfoList); + + uint32_t list_index = 0; + uint32_t list_length = u_arraylist_length(g_serverInfoList); + for (list_index = 0; list_index < list_length; list_index++) + { + CAServerInfo_t *info = (CAServerInfo_t *) u_arraylist_get(g_serverInfoList, list_index); + if (!info) + { + continue; + } + + CAServerInfo_t *newNetinfo = (CAServerInfo_t *) OICMalloc(sizeof(CAServerInfo_t)); + if (!newNetinfo) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "Malloc failed!"); + ca_mutex_unlock(g_mutexServerInfoList); + return CA_MEMORY_ALLOC_FAILED; + } + + memcpy(newNetinfo, info, sizeof(*info)); + + CAResult_t result = u_arraylist_add(*serverInfoList, (void *) newNetinfo); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "u_arraylist_add failed!"); + ca_mutex_unlock(g_mutexServerInfoList); + return CA_STATUS_FAILED; + } + } + ca_mutex_unlock(g_mutexServerInfoList); + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); + return CA_STATUS_OK; +} + +void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback) +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + + ca_mutex_lock(g_mutexAdapterServerContext); + + if (!g_adapterEthServerContext) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL"); + ca_mutex_unlock(g_mutexAdapterServerContext); + return; + } + g_adapterEthServerContext->packetReceivedCallback = callback; + + ca_mutex_unlock(g_mutexAdapterServerContext); + + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); +} + +void CAIPSetExceptionCallback(CAIPExceptionCallback callback) +{ + OIC_LOG(DEBUG, IP_SERVER_TAG, "IN"); + ca_mutex_lock(g_mutexAdapterServerContext); + + if (!g_adapterEthServerContext) + { + OIC_LOG(ERROR, IP_SERVER_TAG, "g_adapterEthServerContext NULL"); + ca_mutex_unlock(g_mutexAdapterServerContext); + return; + } + g_adapterEthServerContext->exceptionCallback = callback; + + ca_mutex_unlock(g_mutexAdapterServerContext); + + OIC_LOG(DEBUG, IP_SERVER_TAG, "OUT"); +} + diff --git a/resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c b/resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c new file mode 100644 index 0000000..8c7653e --- /dev/null +++ b/resource/csdk/connectivity/src/ip_adapter/linux/caipnwmonitor.c @@ -0,0 +1,668 @@ +/****************************************************************** +* +* 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 "caipinterface.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "caadapterutils.h" +#include "camutex.h" +#include "logger.h" +#include "oic_malloc.h" +#include "oic_string.h" + +#define IP_MONITOR_TAG "IP_MONITOR" + +/** + * @var g_networkMonitorContextMutex + * @brief Mutex for synchronizing access to cached interface and IP address information. + */ +static ca_mutex g_networkMonitorContextMutex = NULL; + +/** + * @var g_stopNetworkMonitor + * @brief Used to stop the network monitor thread. + */ +static bool g_stopNetworkMonitor = false; + +/** + * @var g_stopNetworkMonitorMutex + * @brief Mutex for synchronizing access to g_stopNetworkMonitor flag. + */ +static ca_mutex g_stopNetworkMonitorMutex = NULL; + +/** + * @struct CAIPNwMonitorContext + * @brief Used for storing network monitor context information. + */ +typedef struct +{ + u_arraylist_t *netInterfaceList; + ca_thread_pool_t threadPool; + CANetworkStatus_t nwConnectivityStatus; + CAIPConnectionStateChangeCallback networkChangeCb; +} CAIPNetworkMonitorContext; + +/** + * @var g_networkMonitorContext + * @brief network monitor context. + */ +static CAIPNetworkMonitorContext *g_networkMonitorContext = NULL; + +static void CAIPGetInterfaceInformation(u_arraylist_t **netInterfaceList) +{ + + VERIFY_NON_NULL_VOID(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null"); + + struct ifaddrs *ifp = NULL; + if (-1 == getifaddrs(&ifp)) + { + OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get interface list!, Error code: %s", + strerror(errno)); + return; + } + + struct ifaddrs *ifa = NULL; + for (ifa = ifp; ifa; ifa = ifa->ifa_next) + { + char interfaceAddress[CA_IPADDR_SIZE] = {0}; + char interfaceSubnetMask[CA_IPADDR_SIZE] = {0}; + socklen_t len = sizeof(struct sockaddr_in); + + if (!ifa->ifa_addr) + { + continue; + } + + int type = ifa->ifa_addr->sa_family; + if (ifa->ifa_flags & IFF_LOOPBACK + || !((ifa->ifa_flags & IFF_UP) && (ifa->ifa_flags & IFF_RUNNING))) + { + continue; + } + + if (AF_INET != type) + { + continue; + } + + // get the interface ip address + if (0 != getnameinfo(ifa->ifa_addr, len, interfaceAddress, + sizeof(interfaceAddress), NULL, 0, NI_NUMERICHOST)) + { + OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get IPAddress, Error code: %s", + strerror(errno)); + continue; + } + + // get the interface subnet mask + if (0 != getnameinfo(ifa->ifa_netmask, len, interfaceSubnetMask, + sizeof(interfaceSubnetMask), NULL, 0, NI_NUMERICHOST)) + { + OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get subnet mask, Error code: %s", + strerror(errno)); + continue; + } + + CANetInfo_t *netInfo = (CANetInfo_t *)OICCalloc(1, sizeof(CANetInfo_t)); + if (!netInfo) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed"); + freeifaddrs(ifp); + return; + } + // set interface name + strncpy(netInfo->interfaceName, ifa->ifa_name, strlen(ifa->ifa_name)); + + // set local ip address + strncpy(netInfo->ipAddress, interfaceAddress, strlen(interfaceAddress)); + + // set subnet mask + strncpy(netInfo->subnetMask, interfaceSubnetMask, strlen(interfaceSubnetMask)); + + CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)netInfo); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!Thread exiting."); + freeifaddrs(ifp); + return; + } + } + + freeifaddrs(ifp); +} + +static bool CACheckIsAnyInterfaceDown(const u_arraylist_t *netInterfaceList, + const CANetInfo_t *info) +{ + VERIFY_NON_NULL_RET(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null", false); + VERIFY_NON_NULL_RET(info, IP_MONITOR_TAG, "info is null", false); + + uint32_t list_index = 0; + uint32_t list_length = u_arraylist_length(netInterfaceList); + for (list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *netInfo = (CANetInfo_t *)u_arraylist_get(netInterfaceList, + list_index); + if (!netInfo) + { + continue; + } + if (strncmp(netInfo->interfaceName, info->interfaceName, strlen(info->interfaceName)) == 0) + { + return false; + } + } + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Interface is down"); + return true; +} + +static bool CACheckIsInterfaceInfoChanged(const CANetInfo_t *info) +{ + VERIFY_NON_NULL_RET(info, IP_MONITOR_TAG, "info is null", false); + + ca_mutex_lock(g_networkMonitorContextMutex); + uint32_t list_index = 0; + uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + for (list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *netInfo = (CANetInfo_t *)u_arraylist_get( + g_networkMonitorContext->netInterfaceList, list_index); + if (!netInfo) + { + continue; + } + if (strncmp(netInfo->interfaceName, info->interfaceName, strlen(info->interfaceName)) == 0) + { + if (strncmp(netInfo->ipAddress, info->ipAddress, strlen(info->ipAddress)) == 0) + { + ca_mutex_unlock(g_networkMonitorContextMutex); + return false; + } + else + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network interface info changed"); + if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, list_index)) + { + if (g_networkMonitorContext->networkChangeCb) + { + g_networkMonitorContext->networkChangeCb(netInfo->ipAddress, + CA_INTERFACE_DOWN); + } + OICFree(netInfo); + } + else + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed"); + } + break; + } + } + } + + CANetInfo_t *newNetInfo = (CANetInfo_t *)OICMalloc(sizeof(CANetInfo_t)); + if (!newNetInfo) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "newNetInfo malloc failed"); + ca_mutex_unlock(g_networkMonitorContextMutex); + return false; + } + memcpy(newNetInfo, info, sizeof(*newNetInfo)); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "New Interface found"); + + CAResult_t result = u_arraylist_add(g_networkMonitorContext->netInterfaceList, + (void *)newNetInfo); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!"); + OICFree(newNetInfo); + ca_mutex_unlock(g_networkMonitorContextMutex); + return false; + } + ca_mutex_unlock(g_networkMonitorContextMutex); + + /*Callback will be unset only at the time of termination. By that time, all the threads will be + stopped gracefully. This callback is properly protected*/ + if (g_networkMonitorContext->networkChangeCb) + { + g_networkMonitorContext->networkChangeCb(newNetInfo->ipAddress, CA_INTERFACE_UP); + } + + return true; +} + +static void CANetworkMonitorThread(void *threadData) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + while (!g_stopNetworkMonitor) + { + u_arraylist_t *netInterfaceList = u_arraylist_create(); + + VERIFY_NON_NULL_VOID(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null"); + + CAIPGetInterfaceInformation(&netInterfaceList); + + ca_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext->netInterfaceList) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, + "u_arraylist_create failed. Network Monitor thread stopped"); + CAClearNetInterfaceInfoList(netInterfaceList); + ca_mutex_unlock(g_networkMonitorContextMutex); + return; + } + + uint32_t listIndex = 0; + uint32_t listLength = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + for (listIndex = 0; listIndex < listLength;) + { + CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get( + g_networkMonitorContext->netInterfaceList, listIndex); + if (!info) + { + listIndex++; + continue; + } + + bool ret = CACheckIsAnyInterfaceDown(netInterfaceList, info); + if (ret) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Interface is down"); + if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, listIndex)) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "u_arraylist_remove success"); + if (g_networkMonitorContext->networkChangeCb) + { + g_networkMonitorContext->networkChangeCb(info->ipAddress, + CA_INTERFACE_DOWN); + } + OICFree(info); + listLength--; + } + else + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed"); + break; + } + } + else + { + listIndex++; + } + } + ca_mutex_unlock(g_networkMonitorContextMutex); + + listLength = u_arraylist_length(netInterfaceList); + for (listIndex = 0; listIndex < listLength; listIndex++) + { + CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get(netInterfaceList, listIndex); + if (!info) + { + continue; + } + bool ret = CACheckIsInterfaceInfoChanged(info); + if (ret) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "CACheckIsInterfaceInfoChanged true"); + } + } + CAClearNetInterfaceInfoList(netInterfaceList); + sleep(2); // To avoid maximum cpu usage. + } + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); +} + +static CAResult_t CAInitializeNetworkMonitorMutexes() +{ + if (!g_networkMonitorContextMutex) + { + g_networkMonitorContextMutex = ca_mutex_new(); + if (!g_networkMonitorContextMutex) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContextMutex Malloc failed"); + return CA_MEMORY_ALLOC_FAILED; + } + } + + if (!g_stopNetworkMonitorMutex) + { + g_stopNetworkMonitorMutex = ca_mutex_new(); + if (!g_stopNetworkMonitorMutex) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_stopNetworkMonitorMutex Malloc failed"); + ca_mutex_free(g_networkMonitorContextMutex); + return CA_MEMORY_ALLOC_FAILED; + } + } + return CA_STATUS_OK; +} +static void CADestroyNetworkMonitorMutexes() +{ + ca_mutex_free(g_networkMonitorContextMutex); + g_networkMonitorContextMutex = NULL; + + ca_mutex_free(g_stopNetworkMonitorMutex); + g_stopNetworkMonitorMutex = NULL; +} + +CAResult_t CAIPInitializeNetworkMonitor(const ca_thread_pool_t threadPool) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + VERIFY_NON_NULL(threadPool, IP_MONITOR_TAG, "threadPool is null"); + + CAResult_t ret = CAInitializeNetworkMonitorMutexes(); + + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "CAInitializeNetworkMonitorMutexes failed"); + return CA_STATUS_FAILED; + } + + ca_mutex_lock(g_networkMonitorContextMutex); + + g_networkMonitorContext = (CAIPNetworkMonitorContext *)OICCalloc(1, + sizeof(*g_networkMonitorContext)); + if (!g_networkMonitorContext) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext Malloc failed"); + ca_mutex_unlock(g_networkMonitorContextMutex); + CADestroyNetworkMonitorMutexes(); + return CA_MEMORY_ALLOC_FAILED; + } + g_networkMonitorContext->threadPool = threadPool; + + g_networkMonitorContext->netInterfaceList = u_arraylist_create(); + if (!g_networkMonitorContext->netInterfaceList) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_create failed"); + OICFree(g_networkMonitorContext); + ca_mutex_unlock(g_networkMonitorContextMutex); + CADestroyNetworkMonitorMutexes(); + return CA_MEMORY_ALLOC_FAILED; + } + + CAIPGetInterfaceInformation(&g_networkMonitorContext->netInterfaceList); + + + if (u_arraylist_length(g_networkMonitorContext->netInterfaceList)) + { + g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_UP; + } + else + { + g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_DOWN; + } + + ca_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +void CAIPTerminateNetworkMonitor() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + ca_mutex_lock(g_networkMonitorContextMutex); + g_networkMonitorContext->threadPool = NULL; + + CAClearNetInterfaceInfoList(g_networkMonitorContext->netInterfaceList); + + g_networkMonitorContext->netInterfaceList = NULL; + g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_DOWN; + g_networkMonitorContext->networkChangeCb = NULL; + g_networkMonitorContext->threadPool = NULL; + + OICFree(g_networkMonitorContext); + g_networkMonitorContext = NULL; + + ca_mutex_unlock(g_networkMonitorContextMutex); + + ca_mutex_lock(g_stopNetworkMonitorMutex); + g_stopNetworkMonitor = true; + ca_mutex_unlock(g_stopNetworkMonitorMutex); + + CADestroyNetworkMonitorMutexes(); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); +} + +CAResult_t CAIPStartNetworkMonitor() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + ca_mutex_lock(g_stopNetworkMonitorMutex); + + g_stopNetworkMonitor = false; + + ca_mutex_unlock(g_stopNetworkMonitorMutex); + + ca_mutex_lock(g_networkMonitorContextMutex); + + if (!g_networkMonitorContext) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext is null"); + ca_mutex_unlock(g_networkMonitorContextMutex); + return CA_STATUS_FAILED; + } + + if (CA_STATUS_OK != ca_thread_pool_add_task(g_networkMonitorContext->threadPool, + CANetworkMonitorThread, NULL)) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "[ThreadPool] thread_pool_add_task failed!"); + ca_mutex_unlock(g_networkMonitorContextMutex); + return CA_STATUS_FAILED; + } + ca_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPStopNetworkMonitor() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + ca_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext is null"); + ca_mutex_unlock(g_networkMonitorContextMutex); + return CA_STATUS_FAILED; + } + + ca_mutex_unlock(g_networkMonitorContextMutex); + + ca_mutex_lock(g_stopNetworkMonitorMutex); + if (!g_stopNetworkMonitor) + { + g_stopNetworkMonitor = true; + } + else + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "CAIPStopNetworkMonitor, already stopped!"); + } + ca_mutex_unlock(g_stopNetworkMonitorMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + VERIFY_NON_NULL(netInterfaceList, IP_MONITOR_TAG, "u_array_list is null"); + VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG, + "g_networkMonitorContext is null"); + VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG, + "g_networkMonitorContextMutex is null"); + + // Get the interface and ipaddress information from cache + ca_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext->netInterfaceList + || !(u_arraylist_length(g_networkMonitorContext->netInterfaceList))) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Network not enabled"); + ca_mutex_unlock(g_networkMonitorContextMutex); + return CA_ADAPTER_NOT_ENABLED; + } + + uint32_t list_index = 0; + uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo list length [%d]", + list_length); + for (list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get( + g_networkMonitorContext->netInterfaceList, list_index); + if (!info) + { + continue; + } + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo ip [%s]", + info->ipAddress); + CANetInfo_t *newNetinfo = (CANetInfo_t *) OICMalloc(sizeof(CANetInfo_t)); + if (!newNetinfo) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed!"); + ca_mutex_unlock(g_networkMonitorContextMutex); + return CA_MEMORY_ALLOC_FAILED; + } + + memcpy(newNetinfo, info, sizeof(*info)); + + CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)newNetinfo); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!"); + ca_mutex_unlock(g_networkMonitorContextMutex); + return CA_STATUS_FAILED; + } + } + + ca_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPGetInterfaceSubnetMask(const char *ipAddress, char **subnetMask) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + VERIFY_NON_NULL(subnetMask, IP_MONITOR_TAG, "subnet mask"); + VERIFY_NON_NULL(ipAddress, IP_MONITOR_TAG, "ipAddress is null"); + VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG, + "g_networkMonitorContext is null"); + VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG, + "g_networkMonitorContextMutex is null"); + + // Get the interface and ipaddress information from cache + ca_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext->netInterfaceList + || (0 == u_arraylist_length(g_networkMonitorContext->netInterfaceList))) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network not enabled"); + ca_mutex_unlock(g_networkMonitorContextMutex); + return CA_ADAPTER_NOT_ENABLED; + } + + uint32_t list_index = 0; + uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "list lenght [%d]", list_length); + for (list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get( + g_networkMonitorContext->netInterfaceList, list_index); + if (!info) + { + continue; + } + + if (strncmp(info->ipAddress, ipAddress, strlen(ipAddress)) == 0) + { + if (!info->subnetMask) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, + "CAIPGetInterfaceSubnetMask subnetmask is null"); + } + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, + "CAIPGetInterfaceSubnetMask subnetmask is %s", info->subnetMask); + *subnetMask = info->subnetMask ? OICStrdup(info->subnetMask) : NULL; + break; + } + } + ca_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +bool CAIPIsConnected() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + if (!g_networkMonitorContextMutex || !g_networkMonitorContext) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "IP is not connected"); + return false; + } + + ca_mutex_lock(g_networkMonitorContextMutex); + if (0 == u_arraylist_length(g_networkMonitorContext->netInterfaceList)) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "IP is not connected"); + ca_mutex_unlock(g_networkMonitorContextMutex); + return false; + } + ca_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return true; +} + +void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + if (!g_networkMonitorContextMutex || !g_networkMonitorContext) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "CAIPSetConnectionStateChangeCallback failed"); + return; + } + ca_mutex_lock(g_networkMonitorContextMutex); + + g_networkMonitorContext->networkChangeCb = callback; + + ca_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); +} + diff --git a/resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c b/resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c new file mode 100644 index 0000000..7f0cc7c --- /dev/null +++ b/resource/csdk/connectivity/src/ip_adapter/tizen/caipnwmonitor.c @@ -0,0 +1,650 @@ +/****************************************************************** +* +* 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 "caipinterface.h" + +#include + +#include "caadapterutils.h" +#include "umutex.h" +#include "logger.h" +#include "oic_malloc.h" +#include "oic_string.h" + +#define IP_MONITOR_TAG "IP_MONITOR" + +/** + * @var g_networkMonitorContextMutex + * @brief Mutex for synchronizing access to cached interface and IP address information. + */ +static u_mutex g_networkMonitorContextMutex = NULL; + +/** + * @struct CAIPNwMonitorContext + * @brief Used for storing network monitor context information. + */ +typedef struct +{ + u_arraylist_t *netInterfaceList; + ca_thread_pool_t threadPool; + CANetworkStatus_t nwConnectivityStatus; + CAIPConnectionStateChangeCallback networkChangeCb; +} CAIPNetworkMonitorContext; + +/** + * @var g_networkMonitorContext + * @brief network monitor context. + */ +static CAIPNetworkMonitorContext *g_networkMonitorContext = NULL; + +static void CARemoveInterfaceInfo() +{ + u_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext->netInterfaceList) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, + "netInterfaceList is empty"); + u_mutex_unlock(g_networkMonitorContextMutex); + return; + } + + uint32_t list_index = 0; + uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + for (list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *netInfo = (CANetInfo_t *)u_arraylist_get( + g_networkMonitorContext->netInterfaceList, list_index); + if (!netInfo) + { + continue; + } + + if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, list_index)) + { + if (g_networkMonitorContext->networkChangeCb) + { + g_networkMonitorContext->networkChangeCb(netInfo->ipAddress, + CA_INTERFACE_DOWN); + } + } + else + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed"); + } + + OICFree(netInfo); + } + + u_arraylist_free(&g_networkMonitorContext->netInterfaceList); + + u_mutex_unlock(g_networkMonitorContextMutex); +} + +static bool CACheckIsInterfaceInfoChanged(const CANetInfo_t *info) +{ + VERIFY_NON_NULL_RET(info, IP_MONITOR_TAG, "info is null", false); + + u_mutex_lock(g_networkMonitorContextMutex); + uint32_t list_index = 0; + uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + for (list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *netInfo = (CANetInfo_t *)u_arraylist_get( + g_networkMonitorContext->netInterfaceList, list_index); + if (!netInfo) + { + continue; + } + + if (strncmp(netInfo->interfaceName, info->interfaceName, strlen(info->interfaceName)) == 0) + { + if (strncmp(netInfo->ipAddress, info->ipAddress, strlen(info->ipAddress)) == 0) + { + u_mutex_unlock(g_networkMonitorContextMutex); + return false; + } + else + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network interface info changed"); + if (u_arraylist_remove(g_networkMonitorContext->netInterfaceList, list_index)) + { + if (g_networkMonitorContext->networkChangeCb) + { + g_networkMonitorContext->networkChangeCb(netInfo->ipAddress, + CA_INTERFACE_DOWN); + } + OICFree(netInfo); + } + else + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_remove failed"); + } + break; + } + } + } + + CANetInfo_t *newNetInfo = (CANetInfo_t *)OICMalloc(sizeof(CANetInfo_t)); + if (!newNetInfo) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "newNetInfo malloc failed"); + u_mutex_unlock(g_networkMonitorContextMutex); + return false; + } + memcpy(newNetInfo, info, sizeof(*newNetInfo)); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "New Interface found"); + + CAResult_t result = u_arraylist_add(g_networkMonitorContext->netInterfaceList, + (void *)newNetInfo); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!"); + OICFree(newNetInfo); + u_mutex_unlock(g_networkMonitorContextMutex); + return false; + } + u_mutex_unlock(g_networkMonitorContextMutex); + + /*Callback will be unset only at the time of termination. By that time, all the threads will be + stopped gracefully. This callback is properly protected*/ + if (g_networkMonitorContext->networkChangeCb) + { + g_networkMonitorContext->networkChangeCb(newNetInfo->ipAddress, CA_INTERFACE_UP); + } + + return true; +} + +void CAWiFiGetInterfaceInformation(char **interfaceName, char **ipAddress, char **subnetMask) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + int ret = WIFI_ERROR_NONE; + + if (!interfaceName || !ipAddress || !subnetMask) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Invalid input: interface/ipaddress holder is NULL!"); + return; + } + + // Get wifi interface name + if (WIFI_ERROR_NONE != (ret = wifi_get_network_interface_name(interfaceName))) + { + OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get interface name! error num [%d]", ret); + return; + } + + // Get wifi connected IP address + wifi_ap_h accessPoint = NULL; + if (WIFI_ERROR_NONE != (ret = wifi_get_connected_ap(&accessPoint))) + { + OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get access point! error num [%d]", + ret); + + OICFree(*interfaceName); + *interfaceName = NULL; + return; + } + + if (WIFI_ERROR_NONE != (ret = wifi_ap_get_ip_address(accessPoint, WIFI_ADDRESS_FAMILY_IPV4, + ipAddress))) + { + OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get interface address! error num [%d]", + ret); + OICFree(*interfaceName); + *interfaceName = NULL; + return; + } + + if (WIFI_ERROR_NONE != (ret = wifi_ap_get_subnet_mask(accessPoint, WIFI_ADDRESS_FAMILY_IPV4, + subnetMask))) + { + OIC_LOG_V(ERROR, IP_MONITOR_TAG, "Failed to get interface address! error num [%d]", + ret); + OICFree(*ipAddress); + OICFree(*interfaceName); + *ipAddress = NULL; + *interfaceName = NULL; + return; + } + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); +} + +static void CAIPGetInterfaceInformation(u_arraylist_t **netInterfaceList) +{ + VERIFY_NON_NULL_VOID(netInterfaceList, IP_MONITOR_TAG, "netInterfaceList is null"); + + // Get wifi network information + char *interfaceName = NULL; + char *ipAddress = NULL; + char *subnetMask = NULL; + ///TODO: currently we are filling single interface. Once found the proper tizen apis for + // getting multiple interfaces, then this function will be updated. + CAWiFiGetInterfaceInformation(&interfaceName, &ipAddress, &subnetMask); + + if (!interfaceName || !ipAddress || !subnetMask) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "interface/ipaddress/subnetmask is NULL!"); + return; + } + + CANetInfo_t *netInfo = (CANetInfo_t *)OICCalloc(1, sizeof(CANetInfo_t)); + if (!netInfo) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed"); + OICFree(interfaceName); + OICFree(ipAddress); + OICFree(subnetMask); + return; + } + + // set interface name + strncpy(netInfo->interfaceName, interfaceName, strlen(interfaceName)); + + // set local ip address + strncpy(netInfo->ipAddress, ipAddress, strlen(ipAddress)); + + // set subnet mask + strncpy(netInfo->subnetMask, subnetMask, strlen(subnetMask)); + + CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)netInfo); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!"); + } + OICFree(interfaceName); + OICFree(ipAddress); + OICFree(subnetMask); +} + + +void CAWIFIConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap, + void *userData) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + if (WIFI_CONNECTION_STATE_ASSOCIATION == state + || WIFI_CONNECTION_STATE_CONFIGURATION == state) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Connection is in Association State"); + return; + } + + // If Wifi is connected, then get the latest IP from the WIFI Interface + if (WIFI_CONNECTION_STATE_CONNECTED == state) + { + // Get network information + char *interfaceName = NULL; + char *ipAddress = NULL; + char *subnetMask = NULL; + CAWiFiGetInterfaceInformation(&interfaceName, &ipAddress, &subnetMask); + + CANetInfo_t *netInfo = (CANetInfo_t *)OICCalloc(1, sizeof(CANetInfo_t)); + if (!netInfo) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed"); + OICFree(interfaceName); + OICFree(ipAddress); + OICFree(subnetMask); + return; + } + + // set interface name + strncpy(netInfo->interfaceName, interfaceName, strlen(interfaceName)); + + // set local ip address + strncpy(netInfo->ipAddress, ipAddress, strlen(ipAddress)); + + // set subnet mask + strncpy(netInfo->subnetMask, subnetMask, strlen(subnetMask)); + + bool ret = CACheckIsInterfaceInfoChanged(netInfo); + if (ret) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "CACheckIsInterfaceInfoChanged true"); + } + + OICFree(interfaceName); + OICFree(ipAddress); + OICFree(subnetMask); + } + else + { + CARemoveInterfaceInfo(); + } + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); +} + +void CAWIFIDeviceStateChangedCb(wifi_device_state_e state, void *userData) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + if (WIFI_DEVICE_STATE_ACTIVATED == state) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Wifi is in Activated State"); + } + else + { + CAWIFIConnectionStateChangedCb(WIFI_CONNECTION_STATE_DISCONNECTED, NULL, NULL); + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Wifi is in Deactivated State"); + } + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); +} + +static CAResult_t CAInitializeNetworkMonitorMutexes() +{ + if (!g_networkMonitorContextMutex) + { + g_networkMonitorContextMutex = u_mutex_new(); + if (!g_networkMonitorContextMutex) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContextMutex Malloc failed"); + return CA_MEMORY_ALLOC_FAILED; + } + } + + return CA_STATUS_OK; +} + +static void CADestroyNetworkMonitorMutexes() +{ + u_mutex_free(g_networkMonitorContextMutex); + g_networkMonitorContextMutex = NULL; +} + +CAResult_t CAIPInitializeNetworkMonitor(const ca_thread_pool_t threadPool) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + VERIFY_NON_NULL(threadPool, IP_MONITOR_TAG, "threadPool is null"); + + CAResult_t ret = CAInitializeNetworkMonitorMutexes(); + + if (CA_STATUS_OK != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "CAInitializeNetworkMonitorMutexes failed"); + return CA_STATUS_FAILED; + } + u_mutex_lock(g_networkMonitorContextMutex); + + // Initialize Wifi service + wifi_error_e retValue = wifi_initialize(); + if (WIFI_ERROR_NONE != retValue) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_initialize failed"); + return CA_STATUS_FAILED; + } + + g_networkMonitorContext = (CAIPNetworkMonitorContext *)OICCalloc(1, + sizeof(*g_networkMonitorContext)); + if (!g_networkMonitorContext) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "g_networkMonitorContext Malloc failed"); + u_mutex_unlock(g_networkMonitorContextMutex); + CADestroyNetworkMonitorMutexes(); + return CA_MEMORY_ALLOC_FAILED; + } + + g_networkMonitorContext->netInterfaceList = u_arraylist_create(); + if (!g_networkMonitorContext->netInterfaceList) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_create failed"); + OICFree(g_networkMonitorContext); + u_mutex_unlock(g_networkMonitorContextMutex); + CADestroyNetworkMonitorMutexes(); + return CA_MEMORY_ALLOC_FAILED; + } + + CAIPGetInterfaceInformation(&g_networkMonitorContext->netInterfaceList); + + u_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +void CAIPTerminateNetworkMonitor() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + u_mutex_lock(g_networkMonitorContextMutex); + + // Deinitialize Wifi service + wifi_error_e ret = wifi_deinitialize(); + if (WIFI_ERROR_NONE != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_deinitialize failed"); + } + + CAClearNetInterfaceInfoList(g_networkMonitorContext->netInterfaceList); + + g_networkMonitorContext->netInterfaceList = NULL; + g_networkMonitorContext->nwConnectivityStatus = CA_INTERFACE_DOWN; + g_networkMonitorContext->networkChangeCb = NULL; + + OICFree(g_networkMonitorContext); + g_networkMonitorContext = NULL; + + u_mutex_unlock(g_networkMonitorContextMutex); + + CADestroyNetworkMonitorMutexes(); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); +} + +CAResult_t CAIPStartNetworkMonitor() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + // Set callback for receiving state changes + wifi_error_e ret = wifi_set_device_state_changed_cb(CAWIFIDeviceStateChangedCb, NULL); + if (WIFI_ERROR_NONE != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_set_device_state_changed_cb failed"); + return CA_STATUS_FAILED; + } + + // Set callback for receiving connection state changes + ret = wifi_set_connection_state_changed_cb(CAWIFIConnectionStateChangedCb, NULL); + if (WIFI_ERROR_NONE != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_set_connection_state_changed_cb failed"); + return CA_STATUS_FAILED; + } + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPStopNetworkMonitor() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + // Reset callback for receiving state changes + wifi_error_e ret = wifi_unset_device_state_changed_cb(); + if (WIFI_ERROR_NONE != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_unset_device_state_changed_cb failed"); + } + + // Reset callback for receiving connection state changes + ret = wifi_unset_connection_state_changed_cb(); + if (WIFI_ERROR_NONE != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "wifi_unset_connection_state_changed_cb failed"); + } + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPGetInterfaceInfo(u_arraylist_t **netInterfaceList) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + VERIFY_NON_NULL(netInterfaceList, IP_MONITOR_TAG, "u_array_list is null"); + VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG, + "g_networkMonitorContext is null"); + VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG, + "g_networkMonitorContextMutex is null"); + + // Get the interface and ipaddress information from cache + u_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext->netInterfaceList + || !(u_arraylist_length(g_networkMonitorContext->netInterfaceList))) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Network not enabled"); + u_mutex_unlock(g_networkMonitorContextMutex); + return CA_ADAPTER_NOT_ENABLED; + } + + uint32_t list_index = 0; + uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo list length [%d]", + list_length); + for (list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get( + g_networkMonitorContext->netInterfaceList, list_index); + if (!info) + { + continue; + } + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "CAIPGetInterfaceInfo ip [%s]", + info->ipAddress); + CANetInfo_t *newNetinfo = (CANetInfo_t *) OICMalloc(sizeof(CANetInfo_t)); + if (!newNetinfo) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Malloc failed!"); + u_mutex_unlock(g_networkMonitorContextMutex); + return CA_MEMORY_ALLOC_FAILED; + } + + memcpy(newNetinfo, info, sizeof(*info)); + + CAResult_t result = u_arraylist_add(*netInterfaceList, (void *)newNetinfo); + if (CA_STATUS_OK != result) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "u_arraylist_add failed!"); + u_mutex_unlock(g_networkMonitorContextMutex); + return CA_STATUS_FAILED; + } + } + + u_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAIPGetInterfaceSubnetMask(const char *ipAddress, char **subnetMask) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + VERIFY_NON_NULL(subnetMask, IP_MONITOR_TAG, "subnet mask"); + VERIFY_NON_NULL(ipAddress, IP_MONITOR_TAG, "ipAddress is null"); + VERIFY_NON_NULL(g_networkMonitorContext, IP_MONITOR_TAG, + "g_networkMonitorContext is null"); + VERIFY_NON_NULL(g_networkMonitorContextMutex, IP_MONITOR_TAG, + "g_networkMonitorContextMutex is null"); + + // Get the interface and ipaddress information from cache + u_mutex_lock(g_networkMonitorContextMutex); + if (!g_networkMonitorContext->netInterfaceList + || !(u_arraylist_length(g_networkMonitorContext->netInterfaceList))) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "Network not enabled"); + u_mutex_unlock(g_networkMonitorContextMutex); + return CA_ADAPTER_NOT_ENABLED; + } + + uint32_t list_index = 0; + uint32_t list_length = u_arraylist_length(g_networkMonitorContext->netInterfaceList); + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, "list lenght [%d]", list_length); + for (list_index = 0; list_index < list_length; list_index++) + { + CANetInfo_t *info = (CANetInfo_t *)u_arraylist_get( + g_networkMonitorContext->netInterfaceList, list_index); + if (!info) + { + continue; + } + + if (strncmp(info->ipAddress, ipAddress, strlen(ipAddress)) == 0) + { + if (!info->subnetMask) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, + "CAIPGetInterfaceSubnetMask subnetmask is null"); + } + OIC_LOG_V(DEBUG, IP_MONITOR_TAG, + "CAIPGetInterfaceSubnetMask subnetmask is %s", info->subnetMask); + *subnetMask = info->subnetMask ? OICStrdup(info->subnetMask) : NULL; + break; + } + } + u_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return CA_STATUS_OK; +} + +bool CAIPIsConnected() +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + + wifi_connection_state_e connection_state; + wifi_error_e ret = wifi_get_connection_state(&connection_state); + if (WIFI_ERROR_NONE != ret) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "Failed to get the Connection State"); + return false; + } + + if (WIFI_CONNECTION_STATE_DISCONNECTED == connection_state) + { + OIC_LOG(DEBUG, IP_MONITOR_TAG, "WIFI is not Connected"); + return false; + } + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); + return true; +} + +void CAIPSetConnectionStateChangeCallback(CAIPConnectionStateChangeCallback callback) +{ + OIC_LOG(DEBUG, IP_MONITOR_TAG, "IN"); + if (!g_networkMonitorContextMutex || !g_networkMonitorContext) + { + OIC_LOG(ERROR, IP_MONITOR_TAG, "CAIPSetConnectionStateChangeCallback failed"); + return; + } + u_mutex_lock(g_networkMonitorContextMutex); + + g_networkMonitorContext->networkChangeCb = callback; + + u_mutex_unlock(g_networkMonitorContextMutex); + + OIC_LOG(DEBUG, IP_MONITOR_TAG, "OUT"); +} diff --git a/resource/csdk/connectivity/src/wifi_adapter/SConscript b/resource/csdk/connectivity/src/wifi_adapter/SConscript deleted file mode 100644 index 7d0ceab..0000000 --- a/resource/csdk/connectivity/src/wifi_adapter/SConscript +++ /dev/null @@ -1,44 +0,0 @@ -####################################################### -# Building wifi adapter -####################################################### - -Import('env') - -print"Reading wifi adapter script" - -target_os = env.get('TARGET_OS') -src_dir = './wifi_adapter/' - -if target_os == 'tizen': - env.ParseConfig("pkg-config --cflags --libs capi-network-wifi") - -#Source files to build common for all platforms -if target_os != 'arduino': - env.AppendUnique(CA_SRC=[src_dir+'cawifiadapter.c']) -else: - env.AppendUnique(CA_SRC=[src_dir+'cawifiadapter_singlethread.c']) - -#Source files to build in Linux platform -if target_os == 'linux': - env.AppendUnique(CA_SRC=[src_dir+ 'linux/cawificlient.c', - src_dir+'linux/cawifinwmonitor.c', - src_dir+'linux/cawifiserver.c',]) - -#Source files to build in Tizen platform -if target_os == 'tizen': - env.AppendUnique(CA_SRC=[src_dir+ 'tizen/cawificlient.c', - src_dir+'tizen/cawifinwmonitor.c', - src_dir+'tizen/cawifiserver.c',]) - -#Source files to build in Arduino platform -if target_os == 'arduino': - env.AppendUnique(CA_SRC=[src_dir+ 'arduino/cawificlient.cpp', - src_dir+'arduino/cawifinwmonitor.cpp', - src_dir+'arduino/cawifiserver.cpp',]) - -#Source files to build in Android platform -if target_os == 'android': - env.AppendUnique(CA_SRC=[src_dir+'android/cawificlient.c', - src_dir+'android/cawifiserver.c', - src_dir+'android/cawifinwmonitor.c', - ]) diff --git a/resource/csdk/connectivity/src/wifi_adapter/android/cawificlient.c b/resource/csdk/connectivity/src/wifi_adapter/android/cawificlient.c deleted file mode 100644 index 21cc9ef..0000000 --- a/resource/csdk/connectivity/src/wifi_adapter/android/cawificlient.c +++ /dev/null @@ -1,138 +0,0 @@ -/****************************************************************** -* -* Copyright 2014 Samsung Electronics All Rights Reserved. -* -* -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -******************************************************************/ -#include "cawifiinterface.h" - -#include -#include -#include -#include -#include - -#include "caadapterutils.h" - -/** - * @def WIFI_CLIENT_TAG - * @brief Logging tag for module name - */ -#define WIFI_CLIENT_TAG "WIFI_CLIENT" - -/** - * @var g_unicastServerSocket - * @brief socket descriptor for unicast server - */ -static int32_t g_unicastServerSocket = -1; - -#ifdef __WITH_DTLS__ -/** - * @var g_unicastServerSecureSocket - * @brief socket descriptor for secure unicast server - */ -static int32_t g_unicastServerSecureSocket = -1; -#endif - -static uint32_t CASendData(const char *remoteAddress, uint16_t port, - const void *data, uint32_t dataLength, int sockfd) -{ - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN"); - - VERIFY_NON_NULL_RET(remoteAddress, WIFI_CLIENT_TAG, "IP address is NULL", 0); - VERIFY_NON_NULL_RET(data, WIFI_CLIENT_TAG, "data is NULL", 0); - - if (dataLength == 0) - { - OIC_LOG(ERROR, WIFI_CLIENT_TAG, "Data length is 0 !"); - return 0; - } - - if (0 > sockfd) - { - OIC_LOG(ERROR, WIFI_CLIENT_TAG, "Unicast Server is not running !"); - return 0; - } - - struct sockaddr_in destAddr = {}; - destAddr.sin_family = AF_INET; - destAddr.sin_port = htons(port); - - // Conversion from ASCII format to Network format - if (inet_aton(remoteAddress, &destAddr.sin_addr) == 0) - { - OIC_LOG(ERROR, WIFI_CLIENT_TAG, "Failed to convert from ASCII to Network Address"); - return 0; - } - - int32_t sendDataLength = sendto(sockfd, data, dataLength, 0, - (struct sockaddr *)&destAddr, sizeof(destAddr)); - if (sendDataLength == -1) - { - OIC_LOG_V(ERROR, WIFI_CLIENT_TAG, "Failed to Send Data, Error code: %s", strerror(errno)); - return 0; - } - - OIC_LOG_V(INFO, WIFI_CLIENT_TAG, "Sending data is successful, sent bytes[%d]", sendDataLength); - - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT"); - return sendDataLength; -} - -void CAWiFiSetUnicastSocket(int socketFD) -{ - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN"); - - g_unicastServerSocket = socketFD; - - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT"); -} - -#ifdef __WITH_DTLS__ -void CAWiFiSetSecureUnicastSocket(int socketFD) -{ - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN"); - - g_unicastServerSecureSocket = socketFD; - - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT"); -} -#endif -uint32_t CAWiFiSendData(const char *remoteAddress, uint16_t port, - const void *data, uint32_t dataLength, - bool isMulticast, bool isSecured) -{ - uint32_t len = 0; - -#ifdef __WITH_DTLS__ - if (true == isSecured) - { - len = CASendData(remoteAddress, port, - data, dataLength, g_unicastServerSecureSocket); - } - else - { -#endif - len = CASendData(remoteAddress, port, - data, dataLength, g_unicastServerSocket); -#ifdef __WITH_DTLS__ - } -#endif - return len; -} - - - diff --git a/resource/csdk/connectivity/src/wifi_adapter/android/com_iotivity_jar_cawifiinterface.h b/resource/csdk/connectivity/src/wifi_adapter/android/com_iotivity_jar_cawifiinterface.h deleted file mode 100644 index 6cb6874..0000000 --- a/resource/csdk/connectivity/src/wifi_adapter/android/com_iotivity_jar_cawifiinterface.h +++ /dev/null @@ -1,31 +0,0 @@ -#include -/* Header for class com_iotivity_jar_cawifiinterface */ - -#ifndef _Included_com_iotivity_jar_cawifiinterface -#define _Included_com_iotivity_jar_cawifiinterface -#ifdef __cplusplus -extern "C" { -#endif -/* - * Class: com_iotivity_jar_cawifiinterface - * Method: CAWiFiStateEnabled - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_com_iotivity_jar_cawifiinterface_CAWiFiStateEnabled -(JNIEnv *, jclass); - -/* - * Class: com_iotivity_jar_cawifiinterface - * Method: CAWiFiStateDisabled - * Signature: ()V - */ -JNIEXPORT void JNICALL -Java_com_iotivity_jar_cawifiinterface_CAWiFiStateDisabled -(JNIEnv *, jclass); - -#ifdef __cplusplus -} -#endif -#endif - diff --git a/resource/csdk/connectivity/src/wifi_adapter/cawifiadapter_singlethread.c b/resource/csdk/connectivity/src/wifi_adapter/cawifiadapter_singlethread.c deleted file mode 100644 index 3a5aacc..0000000 --- a/resource/csdk/connectivity/src/wifi_adapter/cawifiadapter_singlethread.c +++ /dev/null @@ -1,475 +0,0 @@ -/****************************************************************** - * - * Copyright 2014 Samsung Electronics All Rights Reserved. - * - * - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************/ -#include "cawifiadapter_singlethread.h" - -#include -#include -#include -#include - -#include "caadapterutils.h" -#include "logger.h" -#include "oic_malloc.h" -#include "cawifiinterface_singlethread.h" - -/** - * @def WIFI_ETHERNET_ADAPTER_TAG - * @brief Logging tag for module name - */ -#define WIFI_ADAPTER_TAG "WAST" - -/** - * @def CA_PORT - * @brief Port to listen for incoming data. Port 5683 is as per COAP RFC. - * Note :- Actual port number may differ based on result of bind() operation. - */ -#define CA_PORT 6298 - -/** - * @def CA_SECURE_PORT - * @brief Secured (unicast) port number as defined in COAP Specification, RFC-7252. - */ -#define CA_SECURE_PORT 5684 - -/** - * @def CA_MCAST_PORT - * @brief Multicast port number as defined in COAP Specification, RFC-7252. - */ -#define CA_MCAST_PORT 5683 - -/** - * @def CA_MULTICAST_IP - * @brief Multicast IP Address - */ -#define CA_MULTICAST_IP "224.0.1.187" - -/* Skip Queue */ -/** - * @var g_networkPacketCallback - * @brief Network Packet Received Callback to CA - */ -static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL; - -/** - * @var g_networkChangeCallback - * @brief Network Changed Callback to CA - */ - -static CANetworkChangeCallback g_networkChangeCallback = NULL; - -/** - * @var g_isMulticastServerStarted - * @brief Flag to check if multicast server is started - */ -static bool g_isMulticastServerStarted = false; - -/** - * @var g_startUnicastServerRequested - * @brief Flag to check if server start requested by CA. - */ -static bool g_startUnicastServerRequested = false; - -/** - * @var g_unicastServerport - * @brief port number on which unicast server is running. - */ -static int16_t g_unicastServerport = 0; - -/** - * @var g_startMulticastServerRequested - * @brief Flag to check if server start requested by CA. - */ -static bool g_startMulticastServerRequested = false; - - -static void CAWiFiNotifyNetworkChange(const char *address, int16_t port, - CANetworkStatus_t status); -static void CAWiFiConnectionStateCB(const char *ipAddress, - CANetworkStatus_t status); -static void CAWiFiPacketReceivedCB(const char *ipAddress, uint32_t port, - const void *data, uint32_t dataLength); -static CAResult_t CAWiFiStopServers(); - -void CAWiFiNotifyNetworkChange(const char *address, int16_t port, - CANetworkStatus_t status) -{ - CALocalConnectivity_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_WIFI, address); - if (!localEndpoint) - { - OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Out of memory"); - return; - } - localEndpoint->addressInfo.IP.port = port; - - if (NULL != g_networkChangeCallback) - { - g_networkChangeCallback(localEndpoint, status); - } - - CAAdapterFreeLocalEndpoint(localEndpoint); -} - -void CAWiFiConnectionStateCB(const char *ipAddr, - CANetworkStatus_t status) -{ - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN"); - - CAResult_t ret = CA_STATUS_FAILED; - /* If Wifi is connected, then get the latest IP from the WIFI Interface - * and start unicast and multicast servers if requested earlier */ - if (CA_INTERFACE_UP == status) - { - int16_t port = CA_PORT; - int32_t serverFd = -1; - /* Start Unicast server if requested earlier */ - if (g_startUnicastServerRequested) - { - ret = CAWiFiStartUnicastServer("0.0.0.0", &port, false, &serverFd); - if (CA_STATUS_OK == ret) - { - OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Unicast server started on %d port", port); - CAWiFiSetUnicastSocket(serverFd); - g_unicastServerport = port; - } - else - { - OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "strt ucast fail:%d", ret); - } - } - - /* Start Multicast server if requested earlier */ - if (g_startMulticastServerRequested) - { - int16_t multicastPort = CA_MCAST_PORT; - ret = CAWiFiStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort, &serverFd); - if (CA_STATUS_OK == ret) - { - OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Multicast server started on %d port", multicastPort); - g_isMulticastServerStarted = true; - } - else - { - OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "strt mcast fail:%d", ret); - } - } - - /* Notify network change to CA */ - CAWiFiNotifyNetworkChange(ipAddr, port, status); - } - else - { - CAWiFiNotifyNetworkChange("", 0, status); - /* Stop both Unicast and Multicast servers */ - ret = CAWiFiStopServers(); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to Stop Servers![%d]", ret); - return; - } - } - - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT"); -} - -void CAWiFiPacketReceivedCB(const char *ipAddress, uint32_t port, - const void *data, uint32_t dataLength) -{ - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN"); - OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Address: %s, port:%d ", ipAddress, port); - OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Data:%s", data); - - /* CA is freeing this memory */ - CARemoteEndpoint_t *endPoint = CAAdapterCreateRemoteEndpoint(CA_WIFI, ipAddress, NULL); - if (NULL == endPoint) - { - OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Out of memory"); - return; - } - endPoint->addressInfo.IP.port = port; - - if (g_networkPacketCallback) - { - g_networkPacketCallback(endPoint, data, dataLength); - } - CAAdapterFreeRemoteEndpoint(endPoint); - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT"); -} - -CAResult_t CAInitializeWIFI(CARegisterConnectivityCallback registerCallback, - CANetworkPacketReceivedCallback networkPacketCallback, - CANetworkChangeCallback netCallback) -{ - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN"); - VERIFY_NON_NULL(registerCallback, WIFI_ADAPTER_TAG, "registerCallback"); - VERIFY_NON_NULL(networkPacketCallback, WIFI_ADAPTER_TAG, "networkPacketCallback"); - VERIFY_NON_NULL(netCallback, WIFI_ADAPTER_TAG, "netCallback"); - - g_networkChangeCallback = netCallback; - g_networkPacketCallback = networkPacketCallback; - - CAResult_t ret = CAWiFiInitializeNetworkMonitor(); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to initialize n/w monitor![%d]", ret); - return ret; - } - CAWiFiSetConnectionStateChangeCallback(CAWiFiConnectionStateCB); - - // network monitor is yet to be implemented - ret = CAWiFiInitializeServer(); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to initialize server![%d]", ret); - CATerminateWIFI(); - return ret; - } - CAWiFiSetPacketReceiveCallback(CAWiFiPacketReceivedCB); - - CAConnectivityHandler_t wifiHandler; - wifiHandler.startAdapter = CAStartWIFI; - wifiHandler.startListenServer = CAStartWIFIListeningServer; - wifiHandler.startDiscoveryServer = CAStartWIFIDiscoveryServer; - wifiHandler.sendData = CASendWIFIUnicastData; - wifiHandler.sendDataToAll = CASendWIFIMulticastData; - wifiHandler.GetnetInfo = CAGetWIFIInterfaceInformation; - wifiHandler.readData = CAReadWIFIData; - wifiHandler.stopAdapter = CAStopWIFI; - wifiHandler.terminate = CATerminateWIFI; - registerCallback(wifiHandler, CA_WIFI); - - OIC_LOG(INFO, WIFI_ADAPTER_TAG, "Intialize WIFI Success"); - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT"); - return CA_STATUS_OK; -} - -CAResult_t CAStartWIFI() -{ - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN"); - - // Start monitoring wifi network - // network monitor is yet to be implemented - CAResult_t ret = CAWiFiStartNetworkMonitor(); - if (CA_STATUS_OK != ret) - { - OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Failed to Start n/w monitor"); - } - - g_startUnicastServerRequested = true; - bool retVal = CAWiFiIsConnected(); - if (false == retVal) - { - OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "WIFI is not Connected"); - return ret; - } - - int16_t unicastPort = CA_PORT; - int32_t serverFd = 0; - // Address is hardcoded as we are using Single Interface - ret = CAWiFiStartUnicastServer("0.0.0.0", &unicastPort, false, &serverFd); - if (CA_STATUS_OK == ret) - { - OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Unicast server started on %d port", unicastPort); - CAWiFiSetUnicastSocket(serverFd); - g_unicastServerport = unicastPort; - } - - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT"); - return ret; -} - -CAResult_t CAStartWIFIListeningServer() -{ - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN"); - - CAResult_t ret = CA_STATUS_OK; - int16_t multicastPort = CA_MCAST_PORT; - - if (g_isMulticastServerStarted == true) - { - OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Multicast Server, Already Started!"); - return CA_SERVER_STARTED_ALREADY; - } - - g_startMulticastServerRequested = true; - // network monitor is yet to be implemented - bool retVal = CAWiFiIsConnected(); - if (false == retVal) - { - OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Failed : WIFI not Connected"); - return CA_ADAPTER_NOT_ENABLED; - } - - ret = CAWiFiStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort, NULL); - if (CA_STATUS_OK == ret) - { - OIC_LOG(INFO, WIFI_ADAPTER_TAG, "Multicast Server Started Successfully"); - // iff wifi shield firmware upgrade allows multicast - g_isMulticastServerStarted = true; - } - - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT"); - return ret; -} - -CAResult_t CAStartWIFIDiscoveryServer() -{ - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN"); - // Both listening and discovery server are same - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT"); - return CAStartWIFIListeningServer(); -} - -int32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data, - uint32_t dataLength) -{ - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN"); - - VERIFY_NON_NULL_RET(remoteEndpoint, WIFI_ADAPTER_TAG, "remoteEndpoint", -1); - VERIFY_NON_NULL_RET(data, WIFI_ADAPTER_TAG, "data", -1); - if (dataLength == 0) - { - OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Invalid Data Length"); - return -1; - } - - CAWiFiSendData(remoteEndpoint->addressInfo.IP.ipAddress, - remoteEndpoint->addressInfo.IP.port, data, dataLength, false); - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT"); - return dataLength; -} - -int32_t CASendWIFIMulticastData(const void *data, uint32_t dataLength) -{ - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN"); - - VERIFY_NON_NULL_RET(data, WIFI_ADAPTER_TAG, "data", -1); - if (dataLength == 0) - { - OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Invalid Data Length"); - return -1; - } - - CAWiFiSendData(CA_MULTICAST_IP, CA_MCAST_PORT, data, dataLength, true); - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT"); - return dataLength; -} - -CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size) -{ - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN"); - VERIFY_NON_NULL(info, WIFI_ADAPTER_TAG, "info"); - VERIFY_NON_NULL(size, WIFI_ADAPTER_TAG, "size"); - - bool retVal = CAWiFiIsConnected(); - if (false == retVal) - { - OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, - "Failed to get interface address, Error Code: %d", CA_ADAPTER_NOT_ENABLED); - return CA_ADAPTER_NOT_ENABLED; - } - - char *ipAddress = NULL; - char *ifcName = NULL; - CAResult_t ret = CAWiFiGetInterfaceInfo(&ipAddress, &ifcName); - if (CA_STATUS_OK != ret) - { - OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to get interface info [%d]", ret); - OICFree(ipAddress); - OICFree(ifcName); - return ret; - } - - // Create local endpoint using util function - (*info) = CAAdapterCreateLocalEndpoint(CA_WIFI, ipAddress); - if (NULL == (*info)) - { - OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to create Local Endpoint, Error Code:%d", - CA_MEMORY_ALLOC_FAILED); - OICFree(ipAddress); - OICFree(ifcName); - return CA_MEMORY_ALLOC_FAILED; - } - - (*info)->addressInfo.IP.port = g_unicastServerport; - (*size) = 1; - - OICFree(ipAddress); - OICFree(ifcName); - - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT"); - return CA_STATUS_OK; -} - -CAResult_t CAReadWIFIData() -{ - CAWiFiPullData(); - return CA_STATUS_OK; -} - -CAResult_t CAWiFiStopServers() -{ - CAResult_t result = CAWiFiStopUnicastServer(); - if (CA_STATUS_OK != result) - { - OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to Stop Unicast Server![%d]", result); - return result; - } - CAWiFiSetUnicastSocket(-1); - g_unicastServerport = -1; - - result = CAWiFiStopMulticastServer(); - if (CA_STATUS_OK != result) - { - OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to Stop Multicast Server![%d]", result); - return result; - } - g_isMulticastServerStarted = false; - - return result; -} - -CAResult_t CAStopWIFI() -{ - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN"); - - g_startUnicastServerRequested = false; - g_startMulticastServerRequested = false; - CAWiFiStopNetworkMonitor(); - CAResult_t result = CAWiFiStopServers(); - if (CA_STATUS_OK != result) - { - OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to Stop Servers![%d]", result); - } - - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT"); - return result; -} - -void CATerminateWIFI() -{ - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN"); - - CAWiFiSetConnectionStateChangeCallback(NULL); - CAWiFiTerminateNetworkMonitor(); - OIC_LOG(INFO, WIFI_ADAPTER_TAG, "nw monitor terminated"); - CAWiFiSetPacketReceiveCallback(NULL); - OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT"); - return; -} diff --git a/resource/csdk/connectivity/src/wifi_adapter/linux/cawificlient.c b/resource/csdk/connectivity/src/wifi_adapter/linux/cawificlient.c deleted file mode 100644 index ac115fb..0000000 --- a/resource/csdk/connectivity/src/wifi_adapter/linux/cawificlient.c +++ /dev/null @@ -1,153 +0,0 @@ -/****************************************************************** -* -* Copyright 2014 Samsung Electronics All Rights Reserved. -* -* -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -******************************************************************/ - -// Defining _BSD_SOURCE or _DEFAULT_SOURCE causes header files to expose -// definitions that may otherwise be skipped. Skipping can cause implicit -// declaration warnings and/or bugs and subtle problems in code execution. -// For glibc information on feature test macros, -// Refer http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html -// -// This file requires #define use due to random() and inet_aton() -// For details on compatibility and glibc support, -// Refer http://man7.org/linux/man-pages/man3/inet.3.html -// Refer http://man7.org/linux/man-pages/man3/random.3.html -#define _DEFAULT_SOURCE -#define _BSD_SOURCE - -#include "cawifiinterface.h" - -#include -#include -#include -#include -#include - -#include "caadapterutils.h" - -/** - * @def WIFI_CLIENT_TAG - * @brief Logging tag for module name - */ -#define WIFI_CLIENT_TAG "WIFI_CLIENT" - -/** - * @var g_unicastServerSocketDescClient - * @brief socket descriptor for unicast server - */ -static int32_t g_unicastServerSocketDescClient = -1; - -#ifdef __WITH_DTLS__ -/** - * @var g_unicastServerSecureSocketDescClient - * @brief socket descriptor for secure unicast server - */ -static int32_t g_unicastServerSecureSocketDescClient = -1; -#endif - -static uint32_t CASendData(const char *remoteAddress, const uint16_t port, - const void *data, const uint32_t dataLength, int32_t sockfd) -{ - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN"); - - VERIFY_NON_NULL_RET(remoteAddress, WIFI_CLIENT_TAG, "IP address is NULL", 0); - VERIFY_NON_NULL_RET(data, WIFI_CLIENT_TAG, "data is NULL", 0); - - if (dataLength == 0) - { - OIC_LOG(ERROR, WIFI_CLIENT_TAG, "Data length is 0 !"); - return 0; - } - - if (0 > sockfd) - { - OIC_LOG(ERROR, WIFI_CLIENT_TAG, "Unicast Server is not running !"); - return 0; - } - - struct sockaddr_in destAddr; - memset((char *)&destAddr, 0, sizeof(destAddr)); - destAddr.sin_family = AF_INET; - destAddr.sin_port = htons(port); - - // Conversion from ASCII format to Network format - if (inet_aton(remoteAddress, &destAddr.sin_addr) == 0) - { - OIC_LOG(ERROR, WIFI_CLIENT_TAG, "Failed to convert from ASCII to Network Address"); - return 0; - } - - int32_t sendDataLength = sendto(sockfd, data, dataLength, 0, - (struct sockaddr *)&destAddr, sizeof(destAddr)); - if (sendDataLength == -1) - { - OIC_LOG_V(ERROR, WIFI_CLIENT_TAG, "Failed to Send Data, Error code: %s", strerror(errno)); - return 0; - } - - OIC_LOG_V(INFO, WIFI_CLIENT_TAG, "Sending data is successful, sent bytes[%d]", sendDataLength); - - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT"); - return sendDataLength; -} - -void CAWiFiSetUnicastSocket(const int32_t socketFD) -{ - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN"); - - g_unicastServerSocketDescClient = socketFD; - - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT"); -} - -#ifdef __WITH_DTLS__ -void CAWiFiSetSecureUnicastSocket(const int32_t socketFD) -{ - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN"); - - g_unicastServerSecureSocketDescClient = socketFD; - - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT"); -} -#endif -uint32_t CAWiFiSendData(const char *remoteAddress, const uint16_t port, - const void *data, const uint32_t dataLength, - bool isMulticast, bool isSecured) -{ - uint32_t len = 0; - -#ifdef __WITH_DTLS__ - if (true == isSecured) - { - len = CASendData(remoteAddress, port, - data, dataLength, g_unicastServerSecureSocketDescClient); - } - else - { -#endif - len = CASendData(remoteAddress, port, - data, dataLength, g_unicastServerSocketDescClient); -#ifdef __WITH_DTLS__ - } -#endif - return len; -} - - - diff --git a/resource/csdk/connectivity/src/wifi_adapter/tizen/cawificlient.c b/resource/csdk/connectivity/src/wifi_adapter/tizen/cawificlient.c deleted file mode 100644 index 66ff31a..0000000 --- a/resource/csdk/connectivity/src/wifi_adapter/tizen/cawificlient.c +++ /dev/null @@ -1,138 +0,0 @@ -/****************************************************************** -* -* Copyright 2014 Samsung Electronics All Rights Reserved. -* -* -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* -******************************************************************/ -#include "cawifiinterface.h" - -#include -#include -#include -#include -#include - -#include "caadapterutils.h" - -/** - * @def WIFI_CLIENT_TAG - * @brief Logging tag for module name - */ -#define WIFI_CLIENT_TAG "WIFI_CLIENT" - -/** - * @var g_unicastServerSocketDescClient - * @brief socket descriptor for unicast server - */ -static int g_unicastServerSocketDescClient = -1; - -#ifdef __WITH_DTLS__ -/** - * @var g_unicastServerSocketDescClient - * @brief socket descriptor for secure unicast server - */ -static int g_unicastServerSecureSocketDescClient = -1; -#endif - -static uint32_t CASendData(const char *remoteAddress, uint16_t port, - const void *data, uint32_t dataLength, int sockfd) -{ - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN"); - - VERIFY_NON_NULL_RET(remoteAddress, WIFI_CLIENT_TAG, "IP address is NULL", 0); - VERIFY_NON_NULL_RET(data, WIFI_CLIENT_TAG, "data is NULL", 0); - - if (dataLength == 0) - { - OIC_LOG(ERROR, WIFI_CLIENT_TAG, "Data length is 0 !"); - return 0; - } - - if (0 > sockfd) - { - OIC_LOG(ERROR, WIFI_CLIENT_TAG, "Unicast Server is not running !"); - return 0; - } - - struct sockaddr_in destAddr = {0}; - destAddr.sin_family = AF_INET; - destAddr.sin_port = htons(port); - - // Conversion from ASCII format to Network format - if (inet_aton(remoteAddress, &destAddr.sin_addr) == 0) - { - OIC_LOG(ERROR, WIFI_CLIENT_TAG, "Failed to convert from ASCII to Network Address"); - return 0; - } - - int sendDataLength = sendto(sockfd, data, dataLength, 0, - (struct sockaddr *)&destAddr, sizeof(destAddr)); - if (sendDataLength == -1) - { - OIC_LOG_V(ERROR, WIFI_CLIENT_TAG, "Failed to Send Data, Error code: %s", strerror(errno)); - return 0; - } - - OIC_LOG_V(INFO, WIFI_CLIENT_TAG, "Sending data is successful, sent bytes[%d]", sendDataLength); - - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT"); - return sendDataLength; -} - -void CAWiFiSetUnicastSocket(int socketFD) -{ - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN"); - - g_unicastServerSocketDescClient = socketFD; - - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT"); -} - -#ifdef __WITH_DTLS__ -void CAWiFiSetSecureUnicastSocket(int socketFD) -{ - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN"); - - g_unicastServerSecureSocketDescClient = socketFD; - - OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT"); -} -#endif -uint32_t CAWiFiSendData(const char *remoteAddress, uint16_t port, - const void *data, uint32_t dataLength, - bool isMulticast, bool isSecured) -{ - uint32_t len = 0; - -#ifdef __WITH_DTLS__ - if (true == isSecured) - { - len = CASendData(remoteAddress, port, - data, dataLength, g_unicastServerSecureSocketDescClient); - } - else - { -#endif - len = CASendData(remoteAddress, port, - data, dataLength, g_unicastServerSocketDescClient); -#ifdef __WITH_DTLS__ - } -#endif - return len; -} - - - diff --git a/resource/csdk/connectivity/test/ca_api_unittest.cpp b/resource/csdk/connectivity/test/ca_api_unittest.cpp index 40f81ad..55edd55 100755 --- a/resource/csdk/connectivity/test/ca_api_unittest.cpp +++ b/resource/csdk/connectivity/test/ca_api_unittest.cpp @@ -161,7 +161,7 @@ TEST_F(CATests, TerminateTest) // check return value TEST(StartListeningServerTest, DISABLED_TC_03_Positive_01) { - CASelectNetwork(CA_ETHERNET); + CASelectNetwork(CA_IPV4); EXPECT_EQ(CA_STATUS_OK, CAStartListeningServer()); } @@ -187,7 +187,7 @@ TEST_F(CATests, CreateRemoteEndpointTestGood) { uri = (char *) URI; - EXPECT_EQ(CA_STATUS_OK, CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep)); + EXPECT_EQ(CA_STATUS_OK, CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep)); if (tempRep != NULL) { @@ -201,7 +201,7 @@ TEST_F(CATests, CreateRemoteEndpointTestValues) { uri = (char *) URI; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); EXPECT_TRUE(tempRep != NULL); @@ -222,7 +222,7 @@ TEST_F(CATests, CreateRemoteEndpointTestBad) { uri = NULL; - EXPECT_EQ(CA_STATUS_FAILED, CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep)); + EXPECT_EQ(CA_STATUS_FAILED, CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep)); if (tempRep != NULL) { @@ -235,7 +235,7 @@ TEST_F(CATests, CreateRemoteEndpointTestBad) TEST_F(CATests, CreateRemoteEndpointTestWithNullUri) { uri = NULL; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); if (tempRep != NULL) { @@ -255,7 +255,7 @@ TEST_F(CATests, CreateRemoteEndpointTestWithNullUri) TEST_F(CATests, DestroyRemoteEndpointTest) { uri = (char *) URI; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); CADestroyRemoteEndpoint(tempRep); tempRep = NULL; @@ -315,7 +315,7 @@ TEST_F(CATests, FindResourceTest) TEST(SendRequestTest, DISABLED_TC_16_Positive_01) { uri = (char *) URI; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); memset(&requestData, 0, sizeof(CAInfo_t)); CAGenerateToken(&tempToken, tokenLength); @@ -346,7 +346,7 @@ TEST(SendRequestTest, DISABLED_TC_16_Positive_01) TEST_F(CATests, SendRequestTestWithNullURI) { uri = NULL; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); memset(&requestData, 0, sizeof(CAInfo_t)); CAGenerateToken(&tempToken, tokenLength); @@ -379,7 +379,7 @@ TEST_F(CATests, SendRequestTestWithNullURI) TEST_F(CATests, SendRequestTestWithNullAddr) { uri = (char *) URI; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendRequest(tempRep, NULL)); @@ -395,7 +395,7 @@ TEST_F(CATests, SendRequestTestWithNullAddr) TEST(SendResponseTest, DISABLED_TC_19_Positive_01) { uri = (char *) URI; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); memset(&responseData, 0, sizeof(CAInfo_t)); responseData.type = CA_MSG_NONCONFIRM; @@ -421,7 +421,7 @@ TEST(SendResponseTest, DISABLED_TC_19_Positive_01) TEST(SendResponseTest, DISABLED_TC_20_Negative_01) { uri = NULL; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); memset(&responseData, 0, sizeof(CAInfo_t)); responseData.type = CA_MSG_NONCONFIRM; @@ -450,7 +450,7 @@ TEST(SendResponseTest, DISABLED_TC_20_Negative_01) TEST_F(CATests, SendResponseTest) { uri = (char *) URI; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendResponse(tempRep, NULL)); @@ -466,7 +466,7 @@ TEST_F(CATests, SendResponseTest) TEST(SendNotificationTest, DISABLED_TC_22_Positive_01) { uri = (char *) URI; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); memset(&responseData, 0, sizeof(CAInfo_t)); responseData.type = CA_MSG_NONCONFIRM; @@ -494,7 +494,7 @@ TEST(SendNotificationTest, DISABLED_TC_22_Positive_01) TEST_F(CATests, SendNotificationTest) { uri = NULL; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); memset(&responseData, 0, sizeof(CAInfo_t)); responseData.type = CA_MSG_NONCONFIRM; @@ -595,16 +595,16 @@ TEST_F(CATests, SelectNetworkTestGood) CAResult_t checkSelectNetwork() { - CAResult_t res = CASelectNetwork(CA_ETHERNET); + CAResult_t res = CASelectNetwork(CA_IPV4); if (CA_STATUS_OK == res) { - EXPECT_EQ(CA_STATUS_OK, CAUnSelectNetwork(CA_ETHERNET)); + EXPECT_EQ(CA_STATUS_OK, CAUnSelectNetwork(CA_IPV4)); return CA_STATUS_OK; } if (CA_NOT_SUPPORTED == res) { - EXPECT_EQ(CA_STATUS_FAILED, CAUnSelectNetwork(CA_ETHERNET)); + EXPECT_EQ(CA_STATUS_FAILED, CAUnSelectNetwork(CA_IPV4)); return CA_STATUS_OK; } @@ -636,13 +636,13 @@ TEST_F(CATests, HandlerRequestResponseTest) // check return value TEST(SendRequestToAllTest, DISABLED_TC_31_Positive_01) { - CASelectNetwork(CA_ETHERNET); + CASelectNetwork(CA_IPV4); uri = (char *) RESOURCE_URI; - CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep); + CACreateRemoteEndpoint(uri, CA_IPV4, &tempRep); CAGroupEndpoint_t *group = NULL; group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t)); - group->connectivityType = tempRep->connectivityType; + group->transportType = tempRep->transportType; group->resourceUri = tempRep->resourceUri; memset(&requestData, 0, sizeof(CAInfo_t)); diff --git a/resource/csdk/stack/include/internal/ocobserve.h b/resource/csdk/stack/include/internal/ocobserve.h index 712a936..fc76777 100644 --- a/resource/csdk/stack/include/internal/ocobserve.h +++ b/resource/csdk/stack/include/internal/ocobserve.h @@ -49,7 +49,7 @@ typedef struct ResourceObserver /** Remote Endpoint address **/ CAAddress_t addressInfo; /** Connectivity of the endpoint**/ - CAConnectivityType_t connectivityType; + CATransportType_t connectivityType; // Quality of service of the request OCQualityOfService qos; // number of times the server failed to reach the observer @@ -140,7 +140,7 @@ OCStackResult AddObserver (const char *resUri, OCResource *resHandle, OCQualityOfService qos, const CAAddress_t *addressInfo, - CAConnectivityType_t connectivityType); + CATransportType_t connectivityType); /** * Delete observer with specified token from list of observers. diff --git a/resource/csdk/stack/include/internal/ocresourcehandler.h b/resource/csdk/stack/include/internal/ocresourcehandler.h index aecc032..a2fec0c 100644 --- a/resource/csdk/stack/include/internal/ocresourcehandler.h +++ b/resource/csdk/stack/include/internal/ocresourcehandler.h @@ -160,7 +160,7 @@ OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr, const char *filterValue, char * out, uint16_t *remaining, - CAConnectivityType_t connType); + CATransportType_t connType); /** * A helper function that Maps an @ref OCEntityHandlerResult type to an diff --git a/resource/csdk/stack/include/internal/ocserverrequest.h b/resource/csdk/stack/include/internal/ocserverrequest.h index f8e1d1d..7909399 100644 --- a/resource/csdk/stack/include/internal/ocserverrequest.h +++ b/resource/csdk/stack/include/internal/ocserverrequest.h @@ -48,7 +48,7 @@ typedef struct OCServerRequest /** Remote Endpoint address **/ CAAddress_t addressInfo; /** Connectivity of the endpoint**/ - CAConnectivityType_t connectivityType; + CATransportType_t connectivityType; // token for the request CAToken_t requestToken; // token length the request @@ -166,7 +166,7 @@ OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID, char * reqJSONPayload, CAToken_t requestToken, uint8_t tokenLength, char * resourceUrl, size_t reqTotalSize, - CAAddress_t *addressInfo, CAConnectivityType_t connectivityType); + CAAddress_t *addressInfo, CATransportType_t connectivityType); /** * Form the OCEntityHandlerRequest struct that is passed to a resource's entity handler diff --git a/resource/csdk/stack/include/internal/ocstackinternal.h b/resource/csdk/stack/include/internal/ocstackinternal.h index e9f732e..176dd41 100644 --- a/resource/csdk/stack/include/internal/ocstackinternal.h +++ b/resource/csdk/stack/include/internal/ocstackinternal.h @@ -80,7 +80,7 @@ typedef struct // TODO: bundle this up as endpoint CAAddress_t addressInfo; /** Connectivity of the endpoint**/ - CAConnectivityType_t connectivityType; + CATransportType_t connectivityType; //token for the observe request CAToken_t requestToken; diff --git a/resource/csdk/stack/src/occollection.c b/resource/csdk/stack/src/occollection.c index 3ee6de9..3ac8af0 100644 --- a/resource/csdk/stack/src/occollection.c +++ b/resource/csdk/stack/src/occollection.c @@ -302,7 +302,7 @@ HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest, // Function will return error if not enough space in buffer. ret = BuildVirtualResourceResponse(temp, filterOn, filterValue, - (char*)ptr, &remaining, CA_WIFI ); + (char*)ptr, &remaining, CA_IPV4 ); if (ret != OC_STACK_OK) { break; diff --git a/resource/csdk/stack/src/ocobserve.c b/resource/csdk/stack/src/ocobserve.c index 2eb4dd2..c5648b7 100644 --- a/resource/csdk/stack/src/ocobserve.c +++ b/resource/csdk/stack/src/ocobserve.c @@ -342,7 +342,7 @@ OCStackResult AddObserver (const char *resUri, OCResource *resHandle, OCQualityOfService qos, const CAAddress_t *addressInfo, - CAConnectivityType_t connectivityType) + CATransportType_t connectivityType) { // Check if resource exists and is observable. if (!resHandle) diff --git a/resource/csdk/stack/src/ocresource.c b/resource/csdk/stack/src/ocresource.c index 18c39cd..420aa42 100644 --- a/resource/csdk/stack/src/ocresource.c +++ b/resource/csdk/stack/src/ocresource.c @@ -75,7 +75,7 @@ OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag, } /* This method will retrieve the port at which the secure resource is hosted */ -static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint16_t *port) +static OCStackResult GetSecurePortInfo(CATransportType_t connType, uint16_t *port) { CALocalConnectivity_t* info = NULL; uint32_t size = 0; @@ -88,8 +88,7 @@ static OCStackResult GetSecurePortInfo(CAConnectivityType_t connType, uint16_t * { if (info[size].isSecured && info[size].type == connType) { - if (info[size].type == CA_ETHERNET || - info[size].type == CA_WIFI) + if (info[size].type == CA_IPV4) { *port = info[size].addressInfo.IP.port; ret = OC_STACK_OK; @@ -181,7 +180,7 @@ static OCStackResult ValidateUrlQuery (char *url, char *query, OCStackResult BuildVirtualResourceResponse(const OCResource *resourcePtr, uint8_t filterOn, const char *filterValue, char *out, uint16_t *remaining, - CAConnectivityType_t connType ) + CATransportType_t connType ) { if(!resourcePtr || !out || !remaining) { diff --git a/resource/csdk/stack/src/ocserverrequest.c b/resource/csdk/stack/src/ocserverrequest.c index 9ea8023..99611d7 100644 --- a/resource/csdk/stack/src/ocserverrequest.c +++ b/resource/csdk/stack/src/ocserverrequest.c @@ -244,7 +244,7 @@ OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID, char * reqJSONPayload, CAToken_t requestToken, uint8_t tokenLength, char * resourceUrl, size_t reqTotalSize, - CAAddress_t *addressInfo, CAConnectivityType_t connectivityType) + CAAddress_t *addressInfo, CATransportType_t connectivityType) { OCServerRequest * serverRequest = NULL; @@ -460,7 +460,7 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse) // Copy the address responseEndpoint.resourceUri = (CAURI_t) serverRequest->resourceUrl; responseEndpoint.addressInfo = serverRequest->addressInfo; - responseEndpoint.connectivityType = serverRequest->connectivityType; + responseEndpoint.transportType = serverRequest->connectivityType; responseEndpoint.isSecured = serverRequest->secured; responseInfo.result = ConvertEHResultToCAResult(ehResponse->ehResult); @@ -558,18 +558,18 @@ OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse) #ifdef WITH_PRESENCE //TODO: Add other connectivity types to CAConnTypes[] when enabled - CAConnectivityType_t CAConnTypes[] = {CA_ETHERNET, CA_WIFI}; - const char * connTypes[] = {"ethernet", "wifi"}; - int size = sizeof(CAConnTypes)/ sizeof(CAConnectivityType_t); - CAConnectivityType_t connType = responseEndpoint.connectivityType; + CATransportType_t CAConnTypes[] = {CA_IPV4}; + const char * connTypes[] = {"ip transport"}; + int size = sizeof(CAConnTypes)/ sizeof(CATransportType_t); + CATransportType_t connType = responseEndpoint.transportType; CAResult_t caResult = CA_STATUS_FAILED; result = OC_STACK_OK; //Sending response on all n/w interfaces for(int i = 0; i < size; i++ ) { - responseEndpoint.connectivityType = (CAConnectivityType_t)(connType & CAConnTypes[i]); - if(responseEndpoint.connectivityType) + responseEndpoint.transportType = (CATransportType_t)(connType & CAConnTypes[i]); + if(responseEndpoint.transportType) { //The result is set to OC_STACK_OK only if CASendResponse succeeds in sending the //response on all the n/w interfaces else it is set to OC_STACK_ERROR diff --git a/resource/csdk/stack/src/ocstack.c b/resource/csdk/stack/src/ocstack.c index ef84d11..f709623 100644 --- a/resource/csdk/stack/src/ocstack.c +++ b/resource/csdk/stack/src/ocstack.c @@ -346,23 +346,23 @@ static OCStackResult CAToOCStackResult(CAResponseResult_t caCode); static CAResponseResult_t OCToCAStackResult(OCStackResult ocCode); /** - * Convert OCConnectivityType to CAConnectivityType_t. + * Convert OCConnectivityType to CATransportType_t. * * @param ocConType OCConnectivityType input. - * @param caConType CAConnectivityType_t output. + * @param caConType CATransportType_t output. * @return ::OC_STACK_OK on success, some other value upon failure. */ -static OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, - CAConnectivityType_t* caConType); +static OCStackResult OCToCATransportType(OCConnectivityType ocConType, + CATransportType_t* caConType); /** - * Convert CAConnectivityType_t to CAConnectivityType_t. + * Convert CATransportType_t to OCConnectivityType. * - * @param caConType CAConnectivityType_t input. + * @param caConType CATransportType_t input. * @param ocConType OCConnectivityType output. * @return ::OC_STACK_OK on success, some other value upon failure. */ -static OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, +static OCStackResult CAToOCConnectivityType(CATransportType_t caConType, OCConnectivityType *ocConType); /** @@ -648,17 +648,17 @@ CAResponseResult_t OCToCAStackResult(OCStackResult ocCode) return ret; } -OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivityType_t* caConType) +OCStackResult OCToCATransportType(OCConnectivityType ocConType, CATransportType_t* caConType) { OCStackResult ret = OC_STACK_OK; switch(ocConType) { case OC_ETHERNET: - *caConType = CA_ETHERNET; + *caConType = CA_IPV4; break; case OC_WIFI: - *caConType = CA_WIFI; + *caConType = CA_IPV4; break; case OC_EDR: *caConType = CA_EDR; @@ -669,7 +669,7 @@ OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivit case OC_ALL: // Currently OC_ALL represents WIFI and ETHERNET // Add other connectivity types as they are enabled in future - *caConType = (CAConnectivityType_t) (CA_WIFI|CA_ETHERNET); + *caConType = (CATransportType_t) (CA_IPV4); break; default: ret = OC_STACK_INVALID_PARAM; @@ -678,18 +678,15 @@ OCStackResult OCToCAConnectivityType(OCConnectivityType ocConType, CAConnectivit return ret; } -OCStackResult CAToOCConnectivityType(CAConnectivityType_t caConType, OCConnectivityType *ocConType) +OCStackResult CAToOCConnectivityType(CATransportType_t caConType, OCConnectivityType *ocConType) { OCStackResult ret = OC_STACK_OK; switch(caConType) { - case CA_ETHERNET: + case CA_IPV4: *ocConType = OC_ETHERNET; break; - case CA_WIFI: - *ocConType = OC_WIFI; - break; case CA_EDR: *ocConType = OC_EDR; break; @@ -927,7 +924,7 @@ static OCStackResult HandlePresenceResponse(const CARemoteEndpoint_t* endPoint, response.addr = &address; - result = CAToOCConnectivityType(endPoint->connectivityType, &(response.connType)); + result = CAToOCConnectivityType(endPoint->transportType, &(response.connType)); if(result != OC_STACK_OK) { OC_LOG(ERROR, TAG, PCF("Invalid connectivity type in endpoint")); @@ -1172,7 +1169,7 @@ void HandleCAResponses(const CARemoteEndpoint_t* endPoint, const CAResponseInfo_ // Populate the connectivity type. If this is a discovery response, // the resource that will be constructed from this response will make // further API calls from this interface. - result = CAToOCConnectivityType(endPoint->connectivityType, + result = CAToOCConnectivityType(endPoint->transportType, &(response.connType)); if(result != OC_STACK_OK) { @@ -1495,7 +1492,7 @@ void HandleCARequests(const CARemoteEndpoint_t* endPoint, const CARequestInfo_t* // copy the address serverRequest.addressInfo = endPoint->addressInfo; - serverRequest.connectivityType = endPoint->connectivityType; + serverRequest.connectivityType = endPoint->transportType; // copy vendor specific header options uint8_t tempNum = (requestInfo->info.numOptions); @@ -2013,9 +2010,9 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ requestInfo.info = requestData; - CAConnectivityType_t caConType; + CATransportType_t caConType; - result = OCToCAConnectivityType((OCConnectivityType) conType, &caConType); + result = OCToCATransportType((OCConnectivityType) conType, &caConType); if (result != OC_STACK_OK) { OC_LOG(ERROR, TAG, PCF("Invalid Connectivity Type")); @@ -2025,7 +2022,7 @@ OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requ // send request if(conType == OC_ALL) { - grpEnd.connectivityType = caConType; + grpEnd.transportType = caConType; grpEnd.resourceUri = (CAURI_t) OCMalloc(uriLen + 1); if(!grpEnd.resourceUri) @@ -2155,8 +2152,8 @@ OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption requestInfo.method = CA_GET; requestInfo.info = requestData; - CAConnectivityType_t caConType; - ret = OCToCAConnectivityType(clientCB->conType, &caConType); + CATransportType_t caConType; + ret = OCToCATransportType(clientCB->conType, &caConType); if(ret != OC_STACK_OK) { goto Error; @@ -2283,8 +2280,8 @@ OCStackResult OCProcessPresence() OC_LOG(DEBUG, TAG, PCF("time to test server presence")); - CAConnectivityType_t caConType; - result = OCToCAConnectivityType(cbNode->conType, &caConType); + CATransportType_t caConType; + result = OCToCATransportType(cbNode->conType, &caConType); caResult = CACreateRemoteEndpoint((char *)cbNode->requestUri, caConType, &endpoint); if (caResult != CA_STATUS_OK || result != OC_STACK_OK) @@ -2375,8 +2372,8 @@ OCStackResult OCStartPresence(const uint32_t ttl) return OC_STACK_ERROR; } - CAConnectivityType_t connType; - OCToCAConnectivityType(OC_ALL, &connType ); + CATransportType_t connType; + OCToCATransportType(OC_ALL, &connType ); AddObserver(OC_PRESENCE_URI, NULL, 0, caToken, tokenLength, (OCResource *)presenceResource.handle, OC_LOW_QOS, &addressInfo, connType); @@ -3827,8 +3824,10 @@ CAResult_t OCSelectNetwork() CAResult_t retResult = CA_STATUS_FAILED; CAResult_t caResult = CA_STATUS_OK; - CAConnectivityType_t connTypes[] = {CA_ETHERNET, CA_WIFI, CA_EDR, CA_LE}; - + CATransportType_t connTypes[] = { + CA_IPV4, + CA_EDR, + CA_LE}; int numConnTypes = sizeof(connTypes)/sizeof(connTypes[0]); for(int i = 0; i