diff options
author | Susheel Yadagiri <syadagir@codeaurora.org> | 2011-11-16 13:51:02 -0800 |
---|---|---|
committer | Susheel Yadagiri <syadagir@codeaurora.org> | 2011-11-16 13:54:22 -0800 |
commit | cd20ec712b4f59ae7a7ce5a88eb00d0c04add114 (patch) | |
tree | 81e6ed853058a2eecfb485ef2565ae0476569d2c /cnd | |
parent | a7cef34477dbe5fb47c9955801bcefa6b0adffe2 (diff) | |
download | android_external_connectivity-cd20ec712b4f59ae7a7ce5a88eb00d0c04add114.tar.gz android_external_connectivity-cd20ec712b4f59ae7a7ce5a88eb00d0c04add114.tar.bz2 android_external_connectivity-cd20ec712b4f59ae7a7ce5a88eb00d0c04add114.zip |
cnd: Remove cnd and reference cne as it's no longer needed
Change-Id: Ieed840bf8f561aced0af8e53d1674c20573f5d49
Diffstat (limited to 'cnd')
-rw-r--r-- | cnd/inc/cnd.h | 70 | ||||
-rw-r--r-- | cnd/inc/cnd_commands.h | 38 | ||||
-rw-r--r-- | cnd/inc/cnd_event.h | 60 | ||||
-rw-r--r-- | cnd/inc/cnd_iproute2.h | 268 | ||||
-rw-r--r-- | cnd/inc/cnd_unsol_messages.h | 31 | ||||
-rw-r--r-- | cnd/src/Android.mk | 31 | ||||
-rw-r--r-- | cnd/src/cnd.c | 47 | ||||
-rw-r--r-- | cnd/src/cnd_event.cpp | 308 | ||||
-rw-r--r-- | cnd/src/cnd_iproute2.cpp | 1802 | ||||
-rwxr-xr-x | cnd/src/cnd_process.cpp | 1306 |
10 files changed, 0 insertions, 3961 deletions
diff --git a/cnd/inc/cnd.h b/cnd/inc/cnd.h deleted file mode 100644 index fff057b..0000000 --- a/cnd/inc/cnd.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -** Copyright 2006, The Android Open Source Project -** Copyright (c) 2010, 2011 Code Aurora Forum. All rights reserved. -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ -#ifndef CND_H -#define CND_H - -#include <stdlib.h> -#include <sys/time.h> -#include <utils/Log.h> -#include "cne.h" - -#define CNE_DEBUG_LOGGING 0 - -#define CNE_LOGE(...) LOGE(__VA_ARGS__) -#define CNE_LOGW(...) LOGW(__VA_ARGS__) -#define CNE_LOGI(...) \ - ( (CONDITION(CNE_DEBUG_LOGGING)) \ - ? (void)LOG(LOG_INFO, LOCAL_TAG, __VA_ARGS__) \ - : (void)0 ) -#define CNE_LOGD(...) \ - ( (CONDITION(CNE_DEBUG_LOGGING)) \ - ? (void)LOG(LOG_DEBUG, LOCAL_TAG, __VA_ARGS__) \ - : (void)0 ) -#define CNE_LOGV(...) \ - ( (CONDITION(CNE_DEBUG_LOGGING)) \ - ? (void)LOG(LOG_VERBOSE, LOCAL_TAG, __VA_ARGS__) \ - : (void)0 ) - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef void * CND_Token; - -typedef enum { - CND_E_SUCCESS = 0, - CND_E_RADIO_NOT_AVAILABLE = 1, /* If radio did not start or is resetting */ - CND_E_GENERIC_FAILURE = 2, - CND_E_INVALID_RESPONSE - -} CND_Errno; - - - - -void cnd_init(void); -void cnd_startEventLoop(void); - - - -#ifdef __cplusplus -} -#endif - -#endif /* CND_H */ - diff --git a/cnd/inc/cnd_commands.h b/cnd/inc/cnd_commands.h deleted file mode 100644 index 4e8c968..0000000 --- a/cnd/inc/cnd_commands.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -** Copyright 2006, The Android Open Source Project -** Copyright (c) 2010, 2011 Code Aurora Forum. All rights reserved. -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ - {0, NULL, NULL}, //none - {CNE_REQUEST_INIT_CMD, dispatchVoid, responseVoid}, - {CNE_REQUEST_REG_ROLE_CMD, dispatchInts, responseInts}, - {CNE_REQUEST_GET_COMPATIBLE_NWS_CMD, dispatchInts, responseInts}, - {CNE_REQUEST_CONFIRM_NW_CMD, dispatchInts, responseInts}, - {CNE_REQUEST_DEREG_ROLE_CMD, dispatchInts, responseInts}, - {CNE_REQUEST_REG_NOTIFICATIONS_CMD, dispatchInts, responseInts}, - {CNE_REQUEST_UPDATE_BATTERY_INFO_CMD, dispatchInts, responseVoid}, - {CNE_REQUEST_UPDATE_WLAN_INFO_CMD, dispatchWlanInfo, responseVoid}, - {CNE_REQUEST_UPDATE_WWAN_INFO_CMD, dispatchWwanInfo, responseVoid}, - {CNE_NOTIFY_RAT_CONNECT_STATUS_CMD, dispatchRatStatus, responseVoid}, - {CNE_NOTIFY_DEFAULT_NW_PREF_CMD, dispatchInts, responseVoid}, - {CNE_REQUEST_UPDATE_WLAN_SCAN_RESULTS_CMD, dispatchWlanScanResults, responseVoid}, - {CNE_NOTIFY_SENSOR_EVENT_CMD, dispatchVoid, responseVoid}, - {CNE_REQUEST_CONFIG_IPROUTE2_CMD, dispatchIproute2Cmd, responseVoid}, - {CNE_NOTIFY_TIMER_EXPIRED_CMD, dispatchVoid, responseVoid}, - {CNE_REQUEST_START_FMC_CMD, dispatchString, responseVoid}, - {CNE_REQUEST_STOP_FMC_CMD, dispatchVoid, responseVoid}, - {CNE_REQUEST_UPDATE_WWAN_DORMANCY_INFO_CMD, dispatchInt, responseVoid}, - {CNE_REQUEST_UPDATE_DEFAULT_NETWORK_INFO_CMD, dispatchInt, responseVoid}, - {CNE_NOTIFY_SOCKET_CLOSED_CMD, dispatchVoid, responseVoid}, - {CNE_REQUEST_VENDOR_CMD, dispatchRaw, responseVoid} diff --git a/cnd/inc/cnd_event.h b/cnd/inc/cnd_event.h deleted file mode 100644 index 07b4fff..0000000 --- a/cnd/inc/cnd_event.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef CNE_EVENT_H -#define CNE_EVENT_H -/* -** Copyright 2006, The Android Open Source Project -** Copyright (c) 2010, 2011 Code Aurora Forum. All rights reserved. -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT 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 "cne.h" - -// Max number of fd's we watch at any one time. Increase if necessary. -#define MAX_FD_EVENTS 128 - -typedef void (*cnd_event_cb)(int fd, void *userdata); -typedef int (*cneIntFnType)(void); -typedef void (*cneProcessCmdFnType)(int, int, void*,size_t); -typedef void (*cneRegMsgCbFnType)(cne_messageCbType); - -struct cnd_event { - struct cnd_event *next; - struct cnd_event *prev; - - int fd; - int index; - int persist; - cnd_event_cb func; - void *param; -}; - -// Initialize internal data structs -int cnd_event_init(); - -// Initialize an event -void cnd_event_set(struct cnd_event * ev, int fd, int persist, cnd_event_cb func, void * param); - -// Add event to watch list -void cnd_event_add(struct cnd_event * ev); - - -// Remove event from watch list -void cnd_event_del(struct cnd_event * ev); - -// Event loop -void cnd_event_loop(); - - -// Dump watch table for debugging -void cnd_dump_watch_table(); - -#endif /* CNE_EVENT_H */ diff --git a/cnd/inc/cnd_iproute2.h b/cnd/inc/cnd_iproute2.h deleted file mode 100644 index 24b8080..0000000 --- a/cnd/inc/cnd_iproute2.h +++ /dev/null @@ -1,268 +0,0 @@ -/* Copyright (c) 2010, Code Aurora Forum. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Code Aurora nor - * the names of its contributors may be used to endorse or promote - * products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -#ifndef CND_IPROUTE2_H -#define CND_IPROUTE2_H - -/**---------------------------------------------------------------------------- - @file cnd_iproute2.h - - cnd_iproute2 is an interface to make the necessary calls to iproute2 - in order to set up and take down routing tables. Defines APIs so that - a routing table associated with a network interface can be added or - deleted. Also allows the user to change the default routing table when - a given source address is not already associated with a network - interface. ------------------------------------------------------------------------------*/ - - -/*---------------------------------------------------------------------------- - * Include Files - * -------------------------------------------------------------------------*/ -#include <sys/types.h> - -/*---------------------------------------------------------------------------- - * Preprocessor Definitions and Constants - * -------------------------------------------------------------------------*/ - -/*---------------------------------------------------------------------------- - * Type Declarations - * -------------------------------------------------------------------------*/ - -/*---------------------------------------------------------------------------- - * Class Definitions - * -------------------------------------------------------------------------*/ - -class cnd_iproute2 -{ - public: - /** - * @brief Returns an instance of the Cnd_iproute2 class. - * - * The user of this class will call this function to get an - * instance of the class. All other public functions will be - * called on this instance - * - * @param None - * @see None - * @return An instance of the Cnd_iproute2 class is returned. - */ - static cnd_iproute2* getInstance - ( - void - ); - - /** - * @brief Creates a custom route in the main table using iproute2 - * - * The user of this function passes in the name of the network - * interface that matches the name already defined in the Android - * system. This radio will handle any packets that are sent to - * the inputted destination address of a host. Optionally, a user - * can pass the gateway address of the device. - * - * @param destinationAddress The destination address of the - * custom entry in the main table that - * will be added - * @param deviceName The name of the device that will - * handle packets to the host - * @param gatewayAddress The gateway address of the device - * (optional) - * @return True if function is successful. - * False otherwise. - */ - bool addCustomEntryInMainTable - ( - uint8_t *destinationAddress, - uint8_t *deviceName, - uint8_t *gatewayAddress - ); - - /** - * @brief Create a routing table for a network interface using - * iproute2 - * - * The user of this function passes in the name of the network - * interface that matches the name already defined in the Android - * system. The user also needs to locate the source prefix, and, - * optionally, the gateway address assocated with that radio. If - * a table is added when no another tables exist, it will - * automatically become the default table. - * - * @param deviceName The name of the device whose table - * will be added - * @param sourcePrefix The source network prefix or address - * that will be routed to the device - * (Such as 37.214.21/24 or 10.156.45.1) - * @param gatewayAddress The gateway address of the device - * (optional) - * @return True if function is successful. False - * otherwise. - */ - bool addRoutingTable - ( - uint8_t *deviceName, - uint8_t *sourcePrefix, - uint8_t *gatewayAddress - ); - - /** - * @brief Deletes the custom route to the inputted destination - * address in the main table using iproute2 - * - * The custom route being deleted should have been added via - * addCustomEntryToMainTable() - * - * @param destinationAddress The destination address of the - * custom entry in the main table that - * will be removed - * @return True if function is successful. - * False otherwise. - */ - bool deleteCustomEntryInMainTable - ( - uint8_t *destinationAddress - ); - - /** - * @brief Deletes all custom routes in the main table that route - * through a specific interface name - * - * The custom routes being deleted should have been added via - * addCustomEntryToMainTable() - * - * @param deviceName The name of the device whose custom - * entries in the main table will be - * removed - * @return True if function is successful. False - * otherwise. - */ - bool deleteDeviceCustomEntriesInMainTable - ( - uint8_t *deviceName - ); - - /** - * @brief Deletes a default entry from the main table. - * - * @param deviceName The name of the device whose default - * entry in the main table will be - * deleted - * @return True if function is successful. False - * otherwise. - */ - bool deleteDefaultEntryInMainTable - ( - uint8_t *deviceName - ); - - /** - * @brief Deletes a routing table from the system along with the - * rule corresponding to that table. - * - * The table being deleted should have been added via - * addRoutingTable() - * - * @param deviceName The name of the device whose table will be - * deleted - * @return True if function is successful. False - * otherwise. - */ - bool deleteRoutingTable - ( - uint8_t *deviceName - ); - - /** - * @brief Change the default routing table that is associated - * with any source addresses not bound to another table. - * - * The user of this function passes in the name of the network - * interface that matches the name already defined in the Android - * system. That device will become the new default. If this radio - * is already the default, this function simply returns true. - * - * @param deviceName The name of the device whose table - * will be added - * @return True if function is successful. False - * otherwise. - */ - bool replaceDefaultEntryInMainTable - ( - uint8_t *deviceName, - uint8_t *gatewayAddress - ); - - /** - * Displays the contents of all routing tables for debugging - * purposes. - * - * @return True if function is successful. False - * otherwise. - */ - bool showAllRoutingTables - ( - void - ); - - /** - * Displays the contents of the routing table associated with - * the inputted device name. - * - * @param deviceName The name of the device to be displayed - * @return True if function is successful. False - * otherwise. - */ - bool showRoutingTable - ( - uint8_t *deviceName - ); - - /** - * Displays the rules associated with all tables for debugging - * purposes. - * - * @return True if function is successful. False - * otherwise. - */ - bool showRules - ( - void - ); - - private: - /* constructor */ - cnd_iproute2(){}; - /* destructor */ - ~cnd_iproute2(){}; - - static cnd_iproute2* instancePtr; -}; - - -#endif /* CND_IPROUTE2_H*/ diff --git a/cnd/inc/cnd_unsol_messages.h b/cnd/inc/cnd_unsol_messages.h deleted file mode 100644 index 6d41074..0000000 --- a/cnd/inc/cnd_unsol_messages.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -** Copyright 2006, The Android Open Source Project -** Copyright (c) 2010, 2011 Code Aurora Forum. All rights reserved. -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ - - {0, NULL}, //none - {CNE_RESPONSE_REG_ROLE_MSG, responseInts}, - {CNE_RESPONSE_GET_COMPATIBLE_NWS_MSG, rspCompatibleNws}, - {CNE_RESPONSE_CONFIRM_NW_MSG, responseInts}, - {CNE_RESPONSE_DEREG_ROLE_MSG, responseInts}, - {CNE_REQUEST_BRING_RAT_DOWN_MSG, eventRatChange}, - {CNE_REQUEST_BRING_RAT_UP_MSG, eventRatChange}, - {CNE_NOTIFY_MORE_PREFERED_RAT_AVAIL_MSG, evtMorePrefNw}, - {CNE_NOTIFY_RAT_LOST_MSG, responseInts}, - {CNE_REQUEST_START_SCAN_WLAN_MSG, responseVoid}, - {CNE_NOTIFY_INFLIGHT_STATUS_MSG, responseInts}, - {CNE_NOTIFY_FMC_STATUS_MSG, responseInts}, - {CNE_NOTIFY_HOST_ROUTING_IP_MSG, responseString}, - {CNE_NOTIFY_VENDOR_MSG, responseRaw} diff --git a/cnd/src/Android.mk b/cnd/src/Android.mk deleted file mode 100644 index 4548773..0000000 --- a/cnd/src/Android.mk +++ /dev/null @@ -1,31 +0,0 @@ -# For cnd binary -# ======================= -LOCAL_PATH:= $(call my-dir) - -include $(CLEAR_VARS) - -LOCAL_SRC_FILES:= \ - cnd.c \ - cnd_event.cpp \ - cnd_process.cpp \ - cnd_iproute2.cpp - -LOCAL_MODULE:= cnd - -LOCAL_MODULE_TAGS := optional - -LOCAL_SHARED_LIBRARIES := \ - libutils \ - libbinder \ - libcutils \ - libdl \ - libhardware_legacy \ - -LOCAL_C_INCLUDES := \ - external/connectivity/cnd/inc \ - external/connectivity/include/cne - -include external/connectivity/stlport/libstlport.mk - -include $(BUILD_EXECUTABLE) -# vim: et diff --git a/cnd/src/cnd.c b/cnd/src/cnd.c deleted file mode 100644 index b8783df..0000000 --- a/cnd/src/cnd.c +++ /dev/null @@ -1,47 +0,0 @@ -/* -** Copyright 2006, The Android Open Source Project -** Copyright (c) 2010, Code Aurora Forum. All rights reserved. -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ - -#define LOG_TAG "CND" - -#include <stdio.h> -#include <assert.h> -#include <sys/types.h> -#include <fcntl.h> -#include <cnd.h> -#include "cutils/properties.h" - -int main (int argc, char **argv) -{ - char prop_value[PROPERTY_VALUE_MAX] = {'\0'}; - int len = property_get("persist.cne.UseCne", prop_value, "none"); - prop_value[len] = '\0'; - if((strcasecmp(prop_value, "vendor") == 0) || - (strcasecmp(prop_value, "reference") == 0)) - { - cnd_init(); - cnd_cap_init(); - cnd_startEventLoop(); - while(1) - { - // sleep(UINT32_MAX) seems to return immediately on bionic - sleep(0x00ffffff); - } - } - return 0; -} - - diff --git a/cnd/src/cnd_event.cpp b/cnd/src/cnd_event.cpp deleted file mode 100644 index e6a7823..0000000 --- a/cnd/src/cnd_event.cpp +++ /dev/null @@ -1,308 +0,0 @@ -/* -** Copyright 2006, The Android Open Source Project -** Copyright (c) 2010, 2011 Code Aurora Forum. All rights reserved. -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ - -#define LOG_TAG "CND_EVENT" -#define LOCAL_TAG "CND_EVENT_DEBUG" - -#define LOG_NDEBUG 0 -#define LOG_NDDEBUG 0 -#define LOG_NIDEBUG 0 - -#include <stdlib.h> -#include <unistd.h> -#include <errno.h> -#include <fcntl.h> -#include <utils/Log.h> -#include <cnd_event.h> -#include <string.h> -#include <sys/time.h> -#include <time.h> -#include <pthread.h> -#include <dlfcn.h> -#include "cutils/properties.h" -#include "cne.h" -#include "cnd.h" - -static pthread_mutex_t listMutex; -#define MUTEX_ACQUIRE() pthread_mutex_lock(&listMutex) -#define MUTEX_RELEASE() pthread_mutex_unlock(&listMutex) -#define MUTEX_INIT() pthread_mutex_init(&listMutex, NULL) -#define MUTEX_DESTROY() pthread_mutex_destroy(&listMutex) - -cneProcessCmdFnType cne_processCommand; -cneRegMsgCbFnType cne_regMessageCb; - -static fd_set readFds; -static int nfds = 0; - -static struct cnd_event * watch_table[MAX_FD_EVENTS]; -static struct cnd_event pending_list; - -static void init_list(struct cnd_event * list) -{ - memset(list, 0, sizeof(struct cnd_event)); - list->next = list; - list->prev = list; - list->fd = -1; -} - -static void addToList(struct cnd_event * ev, struct cnd_event * list) -{ - ev->next = list; - ev->prev = list->prev; - ev->prev->next = ev; - list->prev = ev; - -} - -static void removeFromList(struct cnd_event * ev) -{ - - ev->next->prev = ev->prev; - ev->prev->next = ev->next; - ev->next = NULL; - ev->prev = NULL; -} - - -static void removeWatch(struct cnd_event * ev, int index) -{ - - CNE_LOGV("removeWatch: fd=%d, index=%d", ev->fd, index); - - watch_table[index] = NULL; - ev->index = -1; - - FD_CLR(ev->fd, &readFds); - - if (ev->fd+1 == nfds) { - int n = 0; - - for (int i = 0; i < MAX_FD_EVENTS; i++) { - struct cnd_event * rev = watch_table[i]; - - if ((rev != NULL) && (rev->fd > n)) { - n = rev->fd; - } - } - nfds = n + 1; - - } -} - -static void processReadReadyEvent(fd_set * rfds, int n) -{ - - CNE_LOGV("processReadReadyEvent: num of fd set=%d, rfds0=%ld", n, rfds->fds_bits[0]); - - MUTEX_ACQUIRE(); - - for (int i = 0; (i < MAX_FD_EVENTS) && (n > 0); i++) { - struct cnd_event * rev = watch_table[i]; - CNE_LOGD("processReadReadyEvent: watch_table index=%d", i); - if (rev == NULL) { - CNE_LOGD("processReadReadyEvent: REV is NULL at i=%d", i); - } - if (rev != NULL && FD_ISSET(rev->fd, rfds)) { - addToList(rev, &pending_list); - CNE_LOGV("processReadReadyEvent: add to pendingList at watch_table" - "index=%d, fd=%d", i, rev->fd); - if (rev->persist == 0) { - CNE_LOGV("processReadReadyEvent: Should not get here, fd=%d", rev->fd); - removeWatch(rev, i); - } - n--; - } - } - - MUTEX_RELEASE(); - -} - -static void firePendingEvent(void) -{ - - struct cnd_event * ev = pending_list.next; - while (ev != &pending_list) { - struct cnd_event * next = ev->next; - removeFromList(ev); - ev->func(ev->fd, ev->param); - ev = next; - } - -} - -// Initialize internal data structs -int cnd_event_init() -{ - - MUTEX_INIT(); - FD_ZERO(&readFds); - init_list(&pending_list); - memset(watch_table, 0, sizeof(watch_table)); - - void* cneLibHandle; - cneIntFnType cne_svc_init = NULL; - char prop_value[PROPERTY_VALUE_MAX] = {'\0'}; - int len = property_get("persist.cne.UseCne", prop_value, "none"); - prop_value[len] = '\0'; - if(strcasecmp(prop_value, "vendor") == 0) - { - CNE_LOGV("loading vendor cne library"); - cneLibHandle = dlopen("/system/lib/libcne.so",RTLD_NOW); - } - else - { - CNE_LOGV("loading refcne library"); - cneLibHandle = dlopen("/system/lib/librefcne.so",RTLD_NOW); - } - - if(cneLibHandle != NULL) - { - cne_svc_init = (cneIntFnType)dlsym(cneLibHandle, "cne_svc_init"); - cne_processCommand = (cneProcessCmdFnType)dlsym(cneLibHandle, - "cne_processCommand"); - cne_regMessageCb = (cneRegMsgCbFnType)dlsym(cneLibHandle, - "cne_regMessageCb"); - } - else - { - CNE_LOGV("cne library load failed."); - } - if(cne_svc_init == NULL || cne_processCommand == NULL || - cne_regMessageCb == NULL) - { - CNE_LOGD("dlsym ret'd cne_svc_init=%x cne_processCommand=%x cne_regMessageCb=%x", - (unsigned int)cne_svc_init, - (unsigned int)cne_processCommand, - (unsigned int)cne_regMessageCb); - } - else - { - return(cne_svc_init()); - } - - return CNE_SERVICE_DISABLED; -} - -// Initialize an event -void cnd_event_set(struct cnd_event * ev, int fd, int persist, cnd_event_cb func, void * param) -{ - memset(ev, 0, sizeof(struct cnd_event)); - - ev->fd = fd; - ev->index = -1; - ev->persist = persist; - ev->func = func; - ev->param = param; - - fcntl(fd, F_SETFL, O_NONBLOCK); - -} - -// Add event to watch list -void cnd_event_add(struct cnd_event * ev) -{ - - CNE_LOGV("cnd_event_add-called:fd=%d, readFds0=%ld", ev->fd, readFds.fds_bits[0]); - - MUTEX_ACQUIRE(); - - for (int i = 0; i < MAX_FD_EVENTS; i++) { - if (watch_table[i] == NULL) { - watch_table[i] = ev; - ev->index = i; - CNE_LOGV("cnd_event_add-before: add at index=%d for fd=%d, readFds0=%ld", - i, ev->fd, readFds.fds_bits[0]); - FD_SET(ev->fd, &readFds); - if (ev->fd >= nfds) - nfds = ev->fd+1; - CNE_LOGV("cnd_event_add-after: add at index=%d for fd=%d, readFds0=%ld", - i, ev->fd, readFds.fds_bits[0]); - break; - } - } - MUTEX_RELEASE(); - - -} - - -// Remove event from watch or timer list -void cnd_event_del(struct cnd_event * ev) -{ - - CNE_LOGV("cnd_event_del: index=%d", ev->index); - MUTEX_ACQUIRE(); - - if (ev->index < 0 || ev->index >= MAX_FD_EVENTS) { - return; - } - - removeWatch(ev, ev->index); - - MUTEX_RELEASE(); - -} - - -void cnd_dump_watch_table(void) -{ - struct cnd_event * ev; - for (int i = 0; i < MAX_FD_EVENTS; i++) { - if (watch_table[i] != NULL) { - ev = watch_table[i]; - CNE_LOGV("cnd_dump_watch_table: at i=%d , fd=%d", i, ev->fd); - } - } - - return; -} - -void cnd_event_loop(void) -{ - int n; - fd_set rfds; - int s_fdCommand; - - CNE_LOGV("cnd_event_loop: started, nfds=%d",nfds); - - for (;;) { - // make local copy of read fd_set - memcpy(&rfds, &readFds, sizeof(fd_set)); - - CNE_LOGV("cnd_event_loop: waiting for select nfds=%d, rfds0=%ld", nfds, rfds.fds_bits[0]); - - n = select(nfds, &rfds, NULL, NULL, NULL); - if (n < 0) { - if (errno == EINTR) - continue; - CNE_LOGD("cnd_event_loop: select error (%d)", errno); - return; - } - - if (n == 0) - CNE_LOGV("cnd_event_loop: select timedout"); - else if (n > 0) - CNE_LOGV("cnd_event_loop: select ok,n=%d, rfds0=%ld",n, rfds.fds_bits[0]); - - // Check for read-ready events - processReadReadyEvent(&rfds, n); - // Fire pending event - firePendingEvent(); - } -} diff --git a/cnd/src/cnd_iproute2.cpp b/cnd/src/cnd_iproute2.cpp deleted file mode 100644 index 311f682..0000000 --- a/cnd/src/cnd_iproute2.cpp +++ /dev/null @@ -1,1802 +0,0 @@ -/* Copyright (c) 2010, Code Aurora Forum. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of Code Aurora nor - * the names of its contributors may be used to endorse or promote - * products derived from this software without specific prior written - * permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR - * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -/*============================================================================ - FILE: cnd_iproute2.cpp - - OVERVIEW: This program is an interface to make the necessary calls to - iproute2 in order to set up and take down routing tables. - These calls are made indirectly over the command line by using - a call to the C++ system() function. For each routing device - visible to the kernel, cnd_iproute2 allows one table. Each - table contains one entry, a default path to the inputted - routing device. A source address or network prefix is also - required in order to instantiate a table, so that packets from - that ip address are routed through the device. A gateway - address can also be inputted optionally for a newly added - routing table. - - DEPENDENCIES: None -============================================================================*/ - -/*---------------------------------------------------------------------------- - * Include Files - * -------------------------------------------------------------------------*/ -#include "cnd_iproute2.h" -#include <utils/Log.h> -#include <sys/types.h> -#include <cstdarg> -#include <map> -#include <set> -#include <cnd.h> - -using namespace std; - -/*---------------------------------------------------------------------------- - * Preprocessor Definitions and Constants - * -------------------------------------------------------------------------*/ -#undef LOG_TAG -#define LOG_TAG "CND_IPROUTE2" -#define LOCAL_TAG "CND_IPROUTE2_DEBUG" - -/*---------------------------------------------------------------------------- - * Type Declarations - * -------------------------------------------------------------------------*/ -// List of all actions supported from iproute2. Should match defintions -// defined below prefixed with ACTIONS -enum Cmd_line_actions -{ - ACTIONS_ADD_ENUM, - ACTIONS_DELETE_ENUM, - ACTIONS_FLUSH_ENUM, - ACTIONS_REPLACE_ENUM, - ACTIONS_SHOW_ENUM -}; - -// Comparator function for use in the map of active interfaces. -struct routingTableMapComparator { - bool operator() (const uint8_t *string1, const uint8_t *string2) const - { - if (string1 && string2) { - return (strcmp((char *)string1, (char *)string2) < 0); - } - return false; - } -}; - -class CustomRouteInfo; -class RoutingTableInfo; - -/*---------------------------------------------------------------------------- - * Static Variable Definitions - * -------------------------------------------------------------------------*/ -// Commands to begin the command line string -static const uint8_t *ROUTING_CMD = (uint8_t *)"ip route"; -static const uint8_t *RULE_CMD = (uint8_t *)"ip rule"; - -// List of all actions supported from iproute2. These should match values in -// above enumeration 'Cmd_line_actions' -static const uint8_t *ACTIONS_ADD_STR = (uint8_t *)"add"; -static const uint8_t *ACTIONS_DELETE_STR = (uint8_t *)"delete"; -static const uint8_t *ACTIONS_FLUSH_STR = (uint8_t *)"flush"; -static const uint8_t *ACTIONS_REPLACE_STR = (uint8_t *)"replace"; -static const uint8_t *ACTIONS_SHOW_STR = (uint8_t *)"show"; - -// Keywords used to refine calls to iproute2 -static const uint8_t *CMD_LINE_DEVICE_NAME = (uint8_t *)"dev"; -static const uint8_t *CMD_LINE_GATEWAY_ADDRESS = (uint8_t *)"via"; -static const uint8_t *CMD_LINE_PRIORITY_NUMBER = (uint8_t *)"priority"; -static const uint8_t *CMD_LINE_SOURCE_PREFIX = (uint8_t *)"from"; -static const uint8_t *CMD_LINE_TABLE_NUMBER = (uint8_t *)"table"; - -// Keywords that refer to specific routes or tables -static const uint8_t *ALL_TABLES = (uint8_t *)"all"; -static const uint8_t *CACHED_ENTRIES = (uint8_t *)"cache"; -static const uint8_t *DEFAULT_ADDRESS = (uint8_t *)"default"; -static const uint8_t *SCOPE_GLOBAL = (uint8_t *)"global"; -static const uint8_t *SCOPE_KEYWORD = (uint8_t *)"scope"; -static const uint8_t *SCOPE_LINK = (uint8_t *)"link"; - -// Table #1 is the first usable routing table -static const int32_t MIN_TABLE_NUMBER = 1; - -// Table #253 is the 'defined' default routing table, which should not -// be overwritten -static const int32_t MAX_TABLE_NUMBER = 252; - -// Priority number 32766 diverts packets to the main table (Table #254) -static const int32_t MAX_PRIORITY_NUMBER = 32765; - -// Max number of digits in a table number is 3 -static const int32_t MAX_DIGITS_TABLE_NUMBER = 3; - -// Max number of digits in a priority number is 5 -static const int32_t MAX_DIGITS_PRIORITY_NUMBER = 5; - -cnd_iproute2* cnd_iproute2::instancePtr = NULL; - -/*---------------------------------------------------------------------------- - * Global Data Definitions - * -------------------------------------------------------------------------*/ -// Set of all table numbers currently being used. Cannot contain more than -// MAX_TABLE_NUMBER - MIN_TABLE_NUMBER elements -set<int32_t> tableNumberSet; - -// Maps the name of a device to its corresponding routing characteristics -map<uint8_t*, RoutingTableInfo*, routingTableMapComparator> routingTableMap; - -// Maps destination address of any custom entries created in the main table with -// its corresponding routing table characteristics. -map<uint8_t*, CustomRouteInfo*, routingTableMapComparator> customRouteMap; - -// If a packet does not have an associated rule, it will go to the main -// routing table and be routed to the following device by default -uint8_t *defaultDevice; - -/*------------------------------------------------------------------------- - * Declaration for a non-member method. - *-----------------------------------------------------------------------*/ -void flushCache -( - void -); - -uint8_t *cmdLineActionEnumToString -( - Cmd_line_actions commandAction -); - -uint8_t *storeRoutingInformation -( - uint8_t *parameterPtr -); - -bool modifyCustomRouteInMainTable -( - uint8_t *destinationAddress, - uint8_t *deviceName, - uint8_t *gatewayAddress, - Cmd_line_actions commandAction -); - -bool modifyDefaultRoute -( - uint8_t *deviceName, - uint8_t *gatewayAddress, - Cmd_line_actions commandAction -); - -bool modifyRoutingTable -( - uint8_t *deviceName, - uint8_t *sourcePrefix, - uint8_t *gatewayAddress, - Cmd_line_actions commandAction -); - -bool modifyRule -( - RoutingTableInfo *currentDevice, - Cmd_line_actions commandAction -); - -bool cmdLineCaller -( - const uint8_t* cmdLineFirstWord, - ... -); - -/*------------------------------------------------------------------------- - * Class Definitions - *-----------------------------------------------------------------------*/ -/** Stores information needed to create a custom entry in the - * main table. This allows the calling class to delete that - * entry without needing to keep track of any characteristics - * of the device other than its name. - */ -class CustomRouteInfo -{ - private: - uint8_t *deviceName; - uint8_t *gatewayAddress; - uint8_t *destinationAddress; - - public: - CustomRouteInfo - ( - uint8_t *deviceName, - uint8_t *gatewayAddress, - uint8_t *destinationAddress - ) - { - CustomRouteInfo::deviceName = storeRoutingInformation(deviceName); - - if (NULL != gatewayAddress) - { - CustomRouteInfo::gatewayAddress = - storeRoutingInformation(gatewayAddress); - } - - else - { - CustomRouteInfo::gatewayAddress = NULL; - } - - CustomRouteInfo::destinationAddress = - storeRoutingInformation(destinationAddress); - } - - ~CustomRouteInfo() - { - delete [] CustomRouteInfo::deviceName; - if (NULL != CustomRouteInfo::gatewayAddress) - { - delete [] CustomRouteInfo::gatewayAddress; - } - if (NULL != CustomRouteInfo::destinationAddress) - { - delete [] CustomRouteInfo::destinationAddress; - } - } - - uint8_t* getDestinationAddress(void) - { - return destinationAddress; - } - - uint8_t* getDeviceName(void) - { - return deviceName; - } - - uint8_t* getGatewayAddress(void) - { - return gatewayAddress; - } - - void setDeviceName(uint8_t *deviceName) - { - if (NULL != CustomRouteInfo::deviceName) - { - delete [] CustomRouteInfo::deviceName; - } - - CustomRouteInfo::deviceName = storeRoutingInformation(deviceName); - } - - void setGatewayAddress(uint8_t *gatewayAddress) - { - if (NULL != CustomRouteInfo::gatewayAddress) - { - delete [] CustomRouteInfo::gatewayAddress; - } - - CustomRouteInfo::gatewayAddress = storeRoutingInformation(gatewayAddress); - } -}; - -/** Stores information needed to create a routing table and a rule. This - * allows the calling class to delete that table without needing to - * keep track of any characteristics of the device other than its name. - * Assumes that there can only be 1 rule associated with any defined - * table. - */ -class RoutingTableInfo -{ - private: - // Variables relating to the routing table - int32_t tableNumber; - uint8_t *deviceName; - uint8_t *gatewayAddress; - - // Variables relating to the corresponding rule. - uint8_t *sourcePrefix; - int32_t priorityNumber; - - public: - RoutingTableInfo - ( - uint8_t *deviceName, - int32_t tableNumber, - uint8_t *gatewayAddress, - uint8_t *sourcePrefix, - int32_t priorityNumber - ) - { - RoutingTableInfo::deviceName = storeRoutingInformation(deviceName); - RoutingTableInfo::tableNumber = tableNumber; - if (NULL != gatewayAddress) - { - RoutingTableInfo::gatewayAddress = storeRoutingInformation(gatewayAddress); - } - - else - { - RoutingTableInfo::gatewayAddress = NULL; - } - - RoutingTableInfo::sourcePrefix = storeRoutingInformation(sourcePrefix); - RoutingTableInfo::priorityNumber = priorityNumber; - } - - ~RoutingTableInfo() - { - delete [] RoutingTableInfo::deviceName; - delete [] RoutingTableInfo::sourcePrefix; - if (NULL != RoutingTableInfo::gatewayAddress) - { - delete [] RoutingTableInfo::gatewayAddress; - } - } - - uint8_t* getDeviceName(void) - { - return deviceName; - } - - uint8_t* getGatewayAddress(void) - { - return gatewayAddress; - } - - int32_t getPriorityNumber(void) - { - return priorityNumber; - } - - uint8_t* getSourcePrefix(void) - { - return sourcePrefix; - } - - int32_t getTableNumber(void) - { - return tableNumber; - } - - void setGatewayAddress(uint8_t *gatewayAddress) - { - if (NULL != RoutingTableInfo::gatewayAddress) - { - delete [] RoutingTableInfo::gatewayAddress; - } - - RoutingTableInfo::gatewayAddress = storeRoutingInformation(gatewayAddress); - } - - void setSourcePrefix(uint8_t *sourcePrefix) - { - delete [] RoutingTableInfo::sourcePrefix; - RoutingTableInfo::sourcePrefix = storeRoutingInformation(sourcePrefix); - } -}; - -/*---------------------------------------------------------------------------- - * FUNCTION getInstance - - DESCRIPTION Returns a pointer to an instance of the cnd_iproute2 such - that only 1 instance can be open at a time. - - * DEPENDENCIES None - - * RETURN VALUE cnd_iproute2* - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -cnd_iproute2* cnd_iproute2::getInstance -( - void -) -{ - if(NULL == instancePtr) - { - instancePtr = new cnd_iproute2; - } - - return instancePtr; -} - -/*---------------------------------------------------------------------------- - * FUNCTION cmdLineActionEnumToString - - * DESCRIPTION Helper function to converts values of Cmd_line_actions enum - to a string. - - * DEPENDENCIES None - - * RETURN VALUE uint8_t* - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -uint8_t *cmdLineActionEnumToString -( - Cmd_line_actions commandAction -) -{ - switch(commandAction) - { - case ACTIONS_ADD_ENUM: - return (uint8_t *)ACTIONS_ADD_STR; - break; - case ACTIONS_DELETE_ENUM: - return (uint8_t *)ACTIONS_DELETE_STR; - break; - case ACTIONS_FLUSH_ENUM: - return (uint8_t *)ACTIONS_FLUSH_STR; - break; - case ACTIONS_REPLACE_ENUM: - return (uint8_t *)ACTIONS_REPLACE_STR; - break; - case ACTIONS_SHOW_ENUM: - return (uint8_t *)ACTIONS_SHOW_STR; - break; - default: - CNE_LOGD("Unsupported conversion of command action to string"); - return NULL; - } -} -/*---------------------------------------------------------------------------- - * FUNCTION flushCache - - * DESCRIPTION Flushes the cache after routing table entries are changed - - * DEPENDENCIES None - - * RETURN VALUE None - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -void flushCache -( - void -) -{ - if (!cmdLineCaller(ROUTING_CMD, - cmdLineActionEnumToString(ACTIONS_FLUSH_ENUM), - CACHED_ENTRIES, - NULL)) - { - CNE_LOGD("Attempt to flush the routing cache failed."); - } -} - -/*---------------------------------------------------------------------------- - * FUNCTION storeRoutingInformation - - * DESCRIPTION Copies inputted pointer to permanent storage, returning a - pointer to the newly allocated space. - - * DEPENDENCIES None - - * RETURN VALUE Returns pointer to newly allocated memory in heap. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -uint8_t *storeRoutingInformation -( - uint8_t *parameterPtr -) -{ - if(NULL == parameterPtr) - { - CNE_LOGD("storeRoutingInformation: Parameter is null."); - return NULL; - } - - uint8_t *memCopyPtr = new (nothrow) uint8_t[strlen((char*)parameterPtr) + 1]; - - if (NULL == memCopyPtr) - { - CNE_LOGW("storeRoutingInformation: unable to allocate memory"); - return NULL; - } - - int newByteLength = strlen((char *)parameterPtr) * sizeof(uint8_t); - - memcpy(memCopyPtr, parameterPtr, newByteLength + 1); - memCopyPtr[newByteLength] = '\0'; - - return memCopyPtr; -} - -/*---------------------------------------------------------------------------- - * FUNCTION modifyCustomRouteInMainTable - - * DESCRIPTION Adds or deletes a custom route in the main table given the name - of the device associated with this route. This custom route - will route all packets to an inputted destination address of a - host through the inputted device name, possibly using an - optional gateway address. - - * DEPENDENCIES commandAction should be either ADD OR DELETE - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool modifyCustomRouteInMainTable -( - uint8_t *destinationAddress, - uint8_t *deviceName, - uint8_t *gatewayAddress, - Cmd_line_actions commandAction -) -{ - CustomRouteInfo *currentDevice = NULL; - map<uint8_t*, RoutingTableInfo*>::iterator routingTableMapIter; - map<uint8_t*, CustomRouteInfo*>::iterator customRouteMapIter; - - if (NULL == destinationAddress) - { - CNE_LOGD("Null destination address was passed while modifying a custom route " \ - "in the main table"); - return false; - } - - switch(commandAction) - { - case ACTIONS_ADD_ENUM: - { - CNE_LOGV("Adding a custom route in the main table to destination %s", - destinationAddress); - - if (NULL == deviceName) - { - CNE_LOGD("Null device name was passed when adding a custom route"); - return false; - } - - if (NULL == gatewayAddress) - { - CNE_LOGV("A null gateway address was passed when adding the entry to %s", - destinationAddress); - } - - routingTableMapIter = routingTableMap.find(deviceName); - - if ((routingTableMapIter != routingTableMap.end()) && - (NULL == routingTableMapIter->second)) - { - CNE_LOGD("Routing table information has been corrupted for %s table", - deviceName); - } - - else if (routingTableMapIter != routingTableMap.end()) - { - CNE_LOGV("A separate routing table exists for %s. This table will not be " \ - "updated.", deviceName); - } - - customRouteMapIter = customRouteMap.find(destinationAddress); - - if ((customRouteMapIter != customRouteMap.end()) && - (NULL == customRouteMapIter->second)) - { - CNE_LOGD("Custom route in main table information has been corrupted for %s", - destinationAddress); - } - - else if (customRouteMapIter != customRouteMap.end()) - { - CustomRouteInfo *existingDevice = customRouteMapIter->second; - - uint8_t *existingGateway = existingDevice->getGatewayAddress(); - - // If interface name has changed for a particular destination, must - // delete and add back the custom entry. A simple 'replace' command - // will not remove the old entry. Any changes to the gateway address - // will be picked up when a new entry is added - if (0 != strcmp((char *)existingDevice->getDeviceName(), - (char *)deviceName)) - { - commandAction = ACTIONS_REPLACE_ENUM; - - existingDevice->setDeviceName(deviceName); - existingDevice->setGatewayAddress(gatewayAddress); - - break; - } - - // Because the gateway address is an optional parameter, must account - // for cases where the gateway address changes from null to non-null or - // vice-versa - else if ( !((NULL == existingGateway) && (NULL == gatewayAddress)) && - ((NULL == gatewayAddress) || (NULL == existingGateway) || - (0 != strcmp((char *)existingGateway, - (char *)gatewayAddress))) ) - { - commandAction = ACTIONS_REPLACE_ENUM; - - existingDevice->setGatewayAddress(gatewayAddress); - - break; - } - - else { - if (NULL == gatewayAddress) - { - CNE_LOGV("Adding duplicate custom route in main table with device %s," \ - "destination address %s.", deviceName, destinationAddress); - return true; - } - - else { - CNE_LOGV("Adding duplicate custom route in main table with device %s," \ - "destination %s, gateway %s", - deviceName, destinationAddress, gatewayAddress); - return true; - } - } - } - else { - CNE_LOGV("Device '%s' not found in a custom entry to main table", - deviceName); - } - - currentDevice = new CustomRouteInfo(deviceName, - gatewayAddress, - destinationAddress); - - if ((NULL == currentDevice) || - (NULL == currentDevice->getDeviceName()) || - (NULL == currentDevice->getDestinationAddress())) - { - CNE_LOGD("Failed to allocate new device information while adding custom " \ - "entry over interface %s to main table.", deviceName); - return false; - } - - break; - } - - case ACTIONS_DELETE_ENUM: - { - CNE_LOGV("Deleting a custom route in the main table with destination %s", - destinationAddress); - - if (customRouteMap.empty()) - { - CNE_LOGD("Deleting a custom route in the main table when no route exists."); - return false; - } - - customRouteMapIter = customRouteMap.find(destinationAddress); - - if (customRouteMapIter == customRouteMap.end()) - { - CNE_LOGD("Cannot delete custom route over %s that has not been created.", - destinationAddress); - return false; - } - - currentDevice = customRouteMapIter->second; - if (NULL == currentDevice) - { - CNE_LOGD("Deleting custom route over %s with a stored name and null value", - destinationAddress); - return false; - } - - gatewayAddress = currentDevice->getGatewayAddress(); - deviceName = currentDevice->getDeviceName(); - break; - } - - default: - { - CNE_LOGD("Unsupported command action found while modifying a custom route"); - return false; - } - } - - if (NULL == gatewayAddress) - { - cmdLineCaller(ROUTING_CMD, - cmdLineActionEnumToString(commandAction), - destinationAddress, - CMD_LINE_DEVICE_NAME, - deviceName, - SCOPE_KEYWORD, - SCOPE_LINK, - NULL); - } - - else - { - cmdLineCaller(ROUTING_CMD, - cmdLineActionEnumToString(commandAction), - destinationAddress, - CMD_LINE_GATEWAY_ADDRESS, - gatewayAddress, - CMD_LINE_DEVICE_NAME, - deviceName, - SCOPE_KEYWORD, - SCOPE_GLOBAL, - NULL); - } - - switch(commandAction) - { - case ACTIONS_ADD_ENUM: - { - customRouteMap.insert(make_pair(currentDevice->getDestinationAddress(), - currentDevice)); - break; - } - - case ACTIONS_DELETE_ENUM: - { - customRouteMap.erase(destinationAddress); - delete currentDevice; - - break; - } - - default: - break; - } - - flushCache(); - - return true; -} -/*---------------------------------------------------------------------------- - * FUNCTION modifyDefaultRoute - - * DESCRIPTION Changes the default route given the name of the device that - will be the new default. The default case occurs if a packet - is sent from some source address not associated with a defined - table. When this occurs, the main table will route these - undefined source addresses to the gateway of the defined - default device. This function will add or delete that default - route in the main table. If a default route is being deleted, - no input is required for deviceName. The 'replace' command - will change the default entry already existing in the main - routing table, or add the entry if it does not exist. - - * DEPENDENCIES commandAction should be either REPLACE OR DELETE - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool modifyDefaultRoute -( - uint8_t *deviceName, - uint8_t *cmdGatewayAddress, - Cmd_line_actions commandAction -) -{ - uint8_t *gatewayAddress = NULL; - - CNE_LOGV("modifyDefaultRoute: devName:%s, cmdGateway:%s, action:%d", - deviceName, cmdGatewayAddress, commandAction); - - switch(commandAction) - { - case ACTIONS_REPLACE_ENUM: - { - if (NULL == deviceName) - { - CNE_LOGD("A null device name was passed while replacing the default table"); - return false; - } - - // Case where the default device known by cnd is the same as the new - // device that is replacing it. - if ((NULL != defaultDevice) && - (0 == strcmp((char *)defaultDevice, (char *)deviceName))) - { - CNE_LOGV("The new default interface %s is the same as the one known by cnd", - deviceName); - } - - CNE_LOGV("Replacing default routing table with %s", deviceName); - - bool foundMatchingEntry = false; - map<uint8_t*, RoutingTableInfo*>::iterator routingTableMapIter; - map<uint8_t*, CustomRouteInfo*>::iterator customRouteMapIter; - - routingTableMapIter = routingTableMap.find(deviceName); - customRouteMapIter = customRouteMap.begin(); - - if (routingTableMapIter != routingTableMap.end()) - { - if (NULL == routingTableMapIter->second) - { - CNE_LOGD("Routing table for new default %s has corrupt stored values", - deviceName); - } - - else - { - CNE_LOGV("Routing table for new default %s found", deviceName); - foundMatchingEntry = true; - gatewayAddress = routingTableMapIter->second->getGatewayAddress(); - } - } - - else - { - while (customRouteMapIter != customRouteMap.end()) - { - uint8_t *destinationAddress = customRouteMapIter->first; - CustomRouteInfo *currentDevice = customRouteMapIter->second; - - ++customRouteMapIter; - - if (NULL == destinationAddress) - { - CNE_LOGD("Entry in custom route map is corrupted"); - continue; - } - - if (NULL == currentDevice) - { - CNE_LOGD("Value in custom route map with destination %s is corrupted", - destinationAddress); - continue; - } - - if (0 == strcmp((char *)currentDevice->getDeviceName(), - (char *)deviceName)) - { - CNE_LOGV("Custom route for new default %s found", deviceName); - foundMatchingEntry = true; - gatewayAddress = currentDevice->getGatewayAddress(); - break; - } - } - } - - if (!foundMatchingEntry) - { - CNE_LOGV("No routing tables or entries found for new default device %s", - deviceName); - } - - defaultDevice = storeRoutingInformation(deviceName); - - break; - } - - case ACTIONS_DELETE_ENUM: - { - // The following case should only be entered if the default table is - // being deleted when no tables exist - if (NULL == defaultDevice) - { - CNE_LOGD("No stored default device; use deleteDefaultEntryFromMainTable."); - return false; - } - - CNE_LOGV("Deleting default routing table"); - - break; - } - - default: - { - CNE_LOGD("Unsupported command action found while changing the default table"); - return false; - } - } - - // These commands may fail if the kernel has already executed an operation on - // its own. Treat a call to modify the main table as if was successful. - if (NULL == gatewayAddress) - gatewayAddress = cmdGatewayAddress; - - if (NULL == gatewayAddress) - { - cmdLineCaller(ROUTING_CMD, - cmdLineActionEnumToString(commandAction), - DEFAULT_ADDRESS, - CMD_LINE_DEVICE_NAME, - defaultDevice, - NULL); - } - else - { - cmdLineCaller(ROUTING_CMD, - cmdLineActionEnumToString(commandAction), - DEFAULT_ADDRESS, - CMD_LINE_GATEWAY_ADDRESS, - gatewayAddress, - CMD_LINE_DEVICE_NAME, - defaultDevice, - NULL); - } - - if (ACTIONS_DELETE_ENUM == commandAction) - { - // After a deletion, there should be no default device defined in the main - // routing table - if (NULL != defaultDevice) - { - delete [] defaultDevice; - defaultDevice = NULL; - } - } - - flushCache(); - - return true; -} - -/*---------------------------------------------------------------------------- - * FUNCTION modifyRoutingTable - - * DESCRIPTION Adds or deletes a routing table given the name of the device - This routing table has one route, which will route all packets - to the device with the inputted name. This route can - optionally be set up to send packets through an inputted - gateway address. Once the table has been modified, - modifyRoutingTable will call another function to create or - delete a rule that maps some source address' packets to this - table. - - * DEPENDENCIES commandAction should be either ADD OR DELETE - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool modifyRoutingTable -( - uint8_t *deviceName, - uint8_t *sourcePrefix, - uint8_t *gatewayAddress, - Cmd_line_actions commandAction -) -{ - int32_t tableNumber; - int32_t priorityNumber; - - RoutingTableInfo *currentDevice = NULL; - map<uint8_t*, RoutingTableInfo*>::iterator routingTableMapIter; - set<int32_t>::iterator tableNumberSetIter; - - if (NULL == deviceName) - { - CNE_LOGD("A null device name was passed while modifying a routing table"); - return false; - } - switch(commandAction) - { - case ACTIONS_ADD_ENUM: - { - CNE_LOGV("Adding a routing table for interface %s", deviceName); - - if (NULL == sourcePrefix) - { - CNE_LOGD("A null source prefix was passed when adding the %s table", - deviceName); - return false; - } - - if (NULL == gatewayAddress) - { - CNE_LOGV("A null gateway address was passed when adding the %s table", - deviceName); - } - - routingTableMapIter = routingTableMap.find(deviceName); - - if ((routingTableMapIter != routingTableMap.end()) && - (NULL == routingTableMapIter->second)) - { - CNE_LOGD("Adding duplicate routing table with corrupt device information"); - routingTableMap.erase(deviceName); - } - - // If a call to add a routing table overwrites an existing table, the - // new source and gateway addresses will overwrite the old ones. - // However, calls to add a duplicate table, where the source and - // gateway addresses do not change, are ignored and will simply return - // true. - else if (routingTableMapIter != routingTableMap.end()) - { - RoutingTableInfo *existingDevice = routingTableMapIter->second; - - int isNewSourcePrefix = strcmp((char *)existingDevice->getSourcePrefix(), - (char *)sourcePrefix); - - uint8_t *existingGateway = existingDevice->getGatewayAddress(); - - // Because the gateway address is an optional parameter, must account - // for cases where the gateway address changes from null to non-null or - // vice-versa - if ( !((NULL == existingGateway) && (NULL == gatewayAddress)) && - ((NULL == gatewayAddress) || (NULL == existingGateway) || - (0 != strcmp((char *)existingGateway, - (char *)gatewayAddress))) ) - { - // Replace active table and rule with changes to gateway address and - // possibly the source prefix, if it has changed. - commandAction = ACTIONS_REPLACE_ENUM; - - modifyRule(existingDevice, ACTIONS_DELETE_ENUM); - - existingDevice->setGatewayAddress(gatewayAddress); - - if (0 != isNewSourcePrefix) - { - existingDevice->setSourcePrefix(sourcePrefix); - } - - tableNumber = existingDevice->getTableNumber(); - - break; - } - - // Check for differences between source addresses. If a change in the - // gateway address has already been detected, this step of modifying the - // rule will be done implicitly. - else if (0 != isNewSourcePrefix) - { - modifyRule(existingDevice, ACTIONS_DELETE_ENUM); - existingDevice->setSourcePrefix(sourcePrefix); - modifyRule(existingDevice, ACTIONS_ADD_ENUM); - - return true; - } - - else { - if (NULL == gatewayAddress) - { - CNE_LOGV("Adding a duplicate %s table with source %s.", - deviceName, sourcePrefix); - return true; - } - - else { - CNE_LOGV("Adding a duplicate %s table with gateway %s and source %s.", - deviceName, sourcePrefix, gatewayAddress); - return true; - } - } - } - - else { - CNE_LOGV("Device '%s' not found as an active interface", deviceName); - } - - // Instantiating more than 252 tables simultaneously is an error - if (MAX_TABLE_NUMBER - MIN_TABLE_NUMBER < tableNumberSet.size()) - { - CNE_LOGD("Too many tables exist to add %s. %d tables are defined", - deviceName, tableNumberSet.size()); - return false; - } - - // Locate next available table number. If the previous check passed, - // there must be a table number available - for (int32_t nextTableNumber = MIN_TABLE_NUMBER; - nextTableNumber < MAX_TABLE_NUMBER; nextTableNumber++) - { - tableNumberSetIter = tableNumberSet.find(nextTableNumber); - if (tableNumberSetIter == tableNumberSet.end()) - { - tableNumber = nextTableNumber; - break; - } - } - - // Always map the same rule to the same table number. This allows the - // reuse of priority numbers. - priorityNumber = MAX_PRIORITY_NUMBER - tableNumber + 1; - - currentDevice = new RoutingTableInfo(deviceName, - tableNumber, - gatewayAddress, - sourcePrefix, - priorityNumber); - - if ((NULL == currentDevice) || - (NULL == currentDevice->getDeviceName()) || - (NULL == currentDevice->getSourcePrefix())) - { - CNE_LOGD("Failed to allocate new device information while adding table %s.", - deviceName); - return false; - } - - break; - } - - case ACTIONS_DELETE_ENUM: - { - CNE_LOGV("Deleting routing table for interface %s", deviceName); - - if (routingTableMap.empty()) - { - CNE_LOGD("Deleting a table when no table exists."); - return false; - } - - routingTableMapIter = routingTableMap.find(deviceName); - - if (routingTableMapIter == routingTableMap.end()) - { - CNE_LOGD("Cannot delete table %s that has not been created.", deviceName); - return false; - } - - currentDevice = routingTableMapIter->second; - if (NULL == currentDevice) - { - CNE_LOGD("Deleting table with a stored name and null value"); - return false; - } - - gatewayAddress = currentDevice->getGatewayAddress(); - tableNumber = currentDevice->getTableNumber(); - break; - } - - default: - { - CNE_LOGD("Unsupported command action found while modifying a table"); - return false; - } - } - - // Convert table number int to string, null-terminating the result - char tableNumberString[MAX_DIGITS_TABLE_NUMBER+1]; - int32_t numberOfDigits = snprintf(tableNumberString, - MAX_DIGITS_TABLE_NUMBER+1, - "%d", - tableNumber); - tableNumberString[numberOfDigits] = '\0'; - - if (NULL == gatewayAddress) - { - cmdLineCaller(ROUTING_CMD, - cmdLineActionEnumToString(commandAction), - DEFAULT_ADDRESS, - CMD_LINE_DEVICE_NAME, - deviceName, - CMD_LINE_TABLE_NUMBER, - (uint8_t *)tableNumberString, - NULL); - } - else - { - cmdLineCaller(ROUTING_CMD, - cmdLineActionEnumToString(commandAction), - DEFAULT_ADDRESS, - CMD_LINE_GATEWAY_ADDRESS, - gatewayAddress, - CMD_LINE_DEVICE_NAME, - deviceName, - CMD_LINE_TABLE_NUMBER, - (uint8_t *)tableNumberString, - NULL); - } - - switch(commandAction) - { - // This case should not break to account for common code with the replace - // command. - case ACTIONS_ADD_ENUM: - { - routingTableMap.insert(make_pair(currentDevice->getDeviceName(),currentDevice)); - tableNumberSet.insert(tableNumber); - } - - case ACTIONS_REPLACE_ENUM: - { - // If there is no default entry, the new device should be the default. - if (NULL == defaultDevice) - { - CNE_LOGV("Routing table added when no default exists. Adding new default."); - modifyDefaultRoute(deviceName, gatewayAddress, ACTIONS_REPLACE_ENUM); - } - - break; - } - - case ACTIONS_DELETE_ENUM: - { - routingTableMap.erase(deviceName); - tableNumberSet.erase(tableNumber); - - // If there are no more tables, then there should be no default device. - // There is a scenarios where iproute2 is recorded having no table since - // iproute2 not adding it, but there is default entry in main table - // created by system when network comes up, and if the default entry is - // removed, then there will be no default. Need to revisit iproute2. - if (0 == tableNumberSet.size()) - { - CNE_LOGW("Warning: There are no tables"); - } - - // If the default table has been deleted and another device is available, - // set an arbitrary new device as the new default. - else if (0 == strcmp((char *)defaultDevice, - (char *)currentDevice->getDeviceName())) - { - uint8_t *newDefaultName = routingTableMap.begin()->first; - - CNE_LOGV("Replacing old default device with %s", newDefaultName); - modifyDefaultRoute(newDefaultName, gatewayAddress, ACTIONS_REPLACE_ENUM); - } - - break; - } - - default: - break; - } - - // There is no 'ip rule replace' command. When a gateway address is changed, - // must delete the rule and add it back. - if (ACTIONS_REPLACE_ENUM == commandAction) { - commandAction = ACTIONS_ADD_ENUM; - } - - bool modifyRuleRetValue = modifyRule(currentDevice, commandAction); - - // Delete device information that will no longer be used, if it is not - // being stored elsewhere - if (ACTIONS_DELETE_ENUM == commandAction) - { - delete currentDevice; - } - - return modifyRuleRetValue; -} - -/*---------------------------------------------------------------------------- - * FUNCTION modifyRule - - * DESCRIPTION Adds or deletes a rule given the actual device object of the - table associated with that rule. Every defined routing table - requires some rule to map packets from some given source - address to that routing table. This function takes an object - so that after a routing table has been removed, the source - prefix, table number, and priority number associated with that - table can still be accessed. This allows a call to be made to - iproute2 to delete the corresponding rule. - - * DEPENDENCIES commandAction should be either ADD OR DELETE - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool modifyRule -( - RoutingTableInfo *currentDevice, - Cmd_line_actions commandAction -) -{ - if (NULL == currentDevice) - { - CNE_LOGD("A null device was passed while modifying a rule"); - return false; - } - - uint8_t* deviceName = currentDevice->getDeviceName(); - map<uint8_t*, RoutingTableInfo*>::iterator routingTableMapIter; - routingTableMapIter = routingTableMap.find(deviceName); - - // If a rule is being added, its corresponding table should exist in the map - // of all routing tables. - if ((ACTIONS_ADD_ENUM == commandAction) && - (routingTableMapIter == routingTableMap.end())) - { - CNE_LOGD("Cannot %s a rule for nonexistant table %s", - cmdLineActionEnumToString(commandAction), - deviceName); - return false; - } - - int32_t tableNumber = currentDevice->getTableNumber(); - int32_t priorityNumber = currentDevice->getPriorityNumber(); - uint8_t *sourcePrefix = currentDevice->getSourcePrefix(); - - // Convert table number & priority number ints to string, null-terminating - // the results - char tableNumberString[MAX_DIGITS_TABLE_NUMBER+1]; - char priorityNumberString[MAX_DIGITS_PRIORITY_NUMBER+1]; - - int32_t numberOfDigits = snprintf(tableNumberString, - MAX_DIGITS_TABLE_NUMBER+1, - "%d", - tableNumber); - tableNumberString[numberOfDigits] = '\0'; - - numberOfDigits = snprintf(priorityNumberString, - MAX_DIGITS_PRIORITY_NUMBER+1, - "%d", - priorityNumber); - priorityNumberString[numberOfDigits] = '\0'; - - cmdLineCaller(RULE_CMD, - cmdLineActionEnumToString(commandAction), - CMD_LINE_SOURCE_PREFIX, - sourcePrefix, - CMD_LINE_TABLE_NUMBER, - (uint8_t *)tableNumberString, - CMD_LINE_PRIORITY_NUMBER, - (uint8_t *)priorityNumberString, - NULL); - - flushCache(); - - return true; -} - -/*---------------------------------------------------------------------------- - * FUNCTION cmdLineCaller - - * DESCRIPTION Sends a call to iproute2 over the command line. This function - takes in a list of an arbitrary number of words, which is - parsed together into one final string. This string is sent - over the command line using the C routine 'system'. To see - the standard output of a failed command in the ADB logs, the - 'logwrapper' utility must be used while instantiating the cnd - process. - - * DEPENDENCIES Should not be any spaces in any inputted argument - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool cmdLineCaller -( - const uint8_t* cmdLineFirstWord, - ... -) -{ - size_t byteLength = 0; - size_t memLength; - int32_t numberOfSpaces = 0; - va_list cmdLineWordList; - uint8_t *nextWord; - char *cmdLineString; - - if (NULL == cmdLineFirstWord) - { - CNE_LOGD("No actual command passed to build a command line."); - return false; - } - - // Find length of overall command line string to determine how much - // space to allocate for it - byteLength = strlen((char *)cmdLineFirstWord); - va_start(cmdLineWordList, cmdLineFirstWord); - - while((nextWord = va_arg(cmdLineWordList,uint8_t*)) != NULL) - { - byteLength += strlen((char *)nextWord); - numberOfSpaces++; - } - - va_end(cmdLineWordList); - - // Allocate command line string, which is number of bytes in inputted words - // plus the null character, plus the number of white spaces. - cmdLineString = new (nothrow) char[byteLength + numberOfSpaces + 1]; - - if (NULL == cmdLineString) - { - CNE_LOGW("Could not allocate memory to build command line string."); - return false; - } - - memLength = strlcpy(cmdLineString, - (char *)cmdLineFirstWord, - strlen((char *)cmdLineFirstWord) * sizeof(uint8_t) + 1); - if (memLength > strlen((char *)cmdLineFirstWord) * sizeof(uint8_t) + 1) - { - CNE_LOGD("Failure building first word of command line string."); - delete [] cmdLineString; - return false; - } - - // Build command line string containing each inputted word. - va_start(cmdLineWordList, cmdLineFirstWord); - - while((nextWord = va_arg(cmdLineWordList,uint8_t*)) != NULL) - { - // Add white space - memLength = strlcat(cmdLineString, - " ", - strlen(cmdLineString) * sizeof(char) + - sizeof(uint8_t) + 1); - if (memLength > strlen(cmdLineString) * sizeof(char) + sizeof(uint8_t) + 1) - { - CNE_LOGD("Failure adding whitespace to command line string."); - delete [] cmdLineString; - va_end(cmdLineWordList); - return false; - } - - // Add next word - memLength = strlcat(cmdLineString, - (char *)nextWord, - strlen(cmdLineString) * sizeof(char) + - strlen((char *)nextWord) * sizeof(uint8_t) + 1); - if (memLength > strlen(cmdLineString) * sizeof(char) + - strlen((char *)nextWord) * sizeof(uint8_t) + 1) - { - CNE_LOGD("Failure adding next word to command line string."); - delete [] cmdLineString; - va_end(cmdLineWordList); - return false; - } - } - - va_end(cmdLineWordList); - - cmdLineString[byteLength + numberOfSpaces] = '\0'; - - CNE_LOGV("Iproute2 will be called with: %s", cmdLineString); - - int cmdLineExitValue = system(cmdLineString); - - delete [] cmdLineString; - - if (0 != cmdLineExitValue) - { - CNE_LOGD("Command line call to iproute2 failed with exitvalue %d.", - cmdLineExitValue); - return false; - } - - CNE_LOGV("Iproute2 successfully called."); - - return true; -} - - -/*---------------------------------------------------------------------------- - * FUNCTION addCustomEntryInMainTable - - * DESCRIPTION Adds a custom entry to the main table to a specific destination - address over the given interface name - - * DEPENDENCIES None - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool cnd_iproute2::addCustomEntryInMainTable -( - uint8_t *destinationAddress, - uint8_t *deviceName, - uint8_t *gatewayAddress -) -{ - return (modifyCustomRouteInMainTable(destinationAddress, - deviceName, - gatewayAddress, - ACTIONS_ADD_ENUM)); -} - -/*---------------------------------------------------------------------------- - * FUNCTION addRoutingTable - - * DESCRIPTION Adds a routing table to the system that contains a single - default entry, a route to the device with the inputted name, - which will optionally route through an inputted gateway - address. It also adds a rule to route a given source network - prefix or address to the new table. - - The parameter deviceName refers to the name of the device - whose table will be added (Such as wlan or wwan) - The parameter sourcePrefix refers to the source network prefix - or address that will be routed to the device (Such as - 37.214.21/24 or 10.156.45.1) - - * DEPENDENCIES None - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool cnd_iproute2::addRoutingTable -( - uint8_t *deviceName, - uint8_t *sourcePrefix, - uint8_t *gatewayAddress -) -{ - return (modifyRoutingTable(deviceName, - sourcePrefix, - gatewayAddress, - ACTIONS_ADD_ENUM)); -} - -/*---------------------------------------------------------------------------- - * FUNCTION deleteRoutingTable - - * DESCRIPTION Deletes a routing table from the system along with the rule - corresponding to that table. - - * DEPENDENCIES The table must have already been added via the addRoutingTable - API. - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool cnd_iproute2::deleteRoutingTable -( - uint8_t *deviceName -) -{ - return (modifyRoutingTable(deviceName, NULL, NULL, ACTIONS_DELETE_ENUM)); -} - -/*---------------------------------------------------------------------------- - * FUNCTION deleteCustomEntryInMainTable - - * DESCRIPTION Deletes a custom entry from the main table that has already - been added via addCustomEntryToMainTable - - * DEPENDENCIES None - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool cnd_iproute2::deleteCustomEntryInMainTable -( - uint8_t *destinationAddress -) -{ - return (modifyCustomRouteInMainTable(destinationAddress, - NULL, - NULL, - ACTIONS_DELETE_ENUM)); -} - -/*---------------------------------------------------------------------------- - * FUNCTION deleteDeviceCustomEntriesInMainTable - - * DESCRIPTION Deletes all custom entries from the main table that route - through the inputted interface name. These routes must have - already been added via addCustomEntryToMainTable - - * DEPENDENCIES None - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool cnd_iproute2::deleteDeviceCustomEntriesInMainTable -( - uint8_t *deviceName -) -{ - if (NULL == deviceName) - { - CNE_LOGD("Null device name was passed when adding a custom route"); - return false; - } - - CNE_LOGV("Deleting custom routes in the main table through interface %s", - deviceName); - - if (customRouteMap.empty()) - { - CNE_LOGD("Deleting a custom route in the main table when no route exists."); - return false; - } - - bool returnValue = true; - bool foundMatchingEntry = false; - - map<uint8_t*, CustomRouteInfo*>::iterator customRouteMapIter; - - customRouteMapIter = customRouteMap.begin(); - - while (customRouteMapIter != customRouteMap.end()) - { - uint8_t *destinationAddress = customRouteMapIter->first; - CustomRouteInfo *currentDevice = customRouteMapIter->second; - - ++customRouteMapIter; - - if (NULL == destinationAddress) - { - CNE_LOGD("Entry in currentDevice is corrupted."); - continue; - } - - if (NULL == currentDevice) - { - CNE_LOGD("Entry in currentDevice with destination %s is corrupted", - destinationAddress); - continue; - } - - if (0 == strcmp((char *)currentDevice->getDeviceName(), (char *)deviceName)) - { - foundMatchingEntry = true; - returnValue = modifyCustomRouteInMainTable(destinationAddress, - NULL, - NULL, - ACTIONS_DELETE_ENUM); - } - } - - if (!foundMatchingEntry) - { - CNE_LOGD("No entry was found with interface name %s.", deviceName); - return false; - } - - return returnValue; -} - -/*---------------------------------------------------------------------------- - * FUNCTION deleteDefaultEntryInMainTable - - * DESCRIPTION Deletes the default entry in the main table for the inputted - interface name. - - * DEPENDENCIES None - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool cnd_iproute2::deleteDefaultEntryInMainTable -( - uint8_t *deviceName -) -{ - CNE_LOGV("Deleting %s interface from main table.", deviceName); - - if (!cmdLineCaller(ROUTING_CMD, - cmdLineActionEnumToString(ACTIONS_DELETE_ENUM), - DEFAULT_ADDRESS, - CMD_LINE_DEVICE_NAME, - deviceName, - NULL)) - { - return false; - } - - flushCache(); - - return true; -} - -/*---------------------------------------------------------------------------- - * FUNCTION replaceDefaultEntryInMainTable - - * DESCRIPTION Changes the default device where packets are routed to. If - some source address does not match an already defined rule, - packets from that source address will be routed through the - main table to some default device. This function replaces the - default route to direct traffic to an inputted, already - defined device. A routing table associated with this device - must have been added through addRoutingTable() before it can - be the default. - - * DEPENDENCIES The new default table must have already been added via the - addRoutingTable API. - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool cnd_iproute2::replaceDefaultEntryInMainTable -( - uint8_t *deviceName, - uint8_t *gatewayAddress -) -{ - CNE_LOGV("replaceDefaultEntryInMainTable: devName:%s, gatewayAddress:%s", - deviceName, gatewayAddress); - return (modifyDefaultRoute(deviceName, gatewayAddress, ACTIONS_REPLACE_ENUM)); -} - -/*---------------------------------------------------------------------------- - * FUNCTION showAllRoutingTables - - * DESCRIPTION Displays the contents of all routing tables for debugging - purposes. - - * DEPENDENCIES None - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool cnd_iproute2::showAllRoutingTables -( - void -) -{ - return cmdLineCaller(ROUTING_CMD, - cmdLineActionEnumToString(ACTIONS_SHOW_ENUM), - CMD_LINE_TABLE_NUMBER, - ALL_TABLES, - NULL); -} - -/*---------------------------------------------------------------------------- - * FUNCTION showRoutingTable - - * DESCRIPTION Displays the contents of the routing table associated with - the inputted device name. - - * DEPENDENCIES None - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool cnd_iproute2::showRoutingTable -( - uint8_t *deviceName -) -{ - if (NULL == deviceName) - { - CNE_LOGD("A null device name was passed while displaying a table."); - return false; - } - - return cmdLineCaller(ROUTING_CMD, - cmdLineActionEnumToString(ACTIONS_SHOW_ENUM), - CMD_LINE_TABLE_NUMBER, - deviceName, - NULL); -} - -/*---------------------------------------------------------------------------- - * FUNCTION showRoutingTable - - * DESCRIPTION Displays the rules associated with all tables for debugging - purposes. - - * DEPENDENCIES None - - * RETURN VALUE bool - True if function is successful. False otherwise. - - * SIDE EFFECTS None - *--------------------------------------------------------------------------*/ -bool cnd_iproute2::showRules -( - void -) -{ - return cmdLineCaller(RULE_CMD, - cmdLineActionEnumToString(ACTIONS_SHOW_ENUM), - NULL); -} diff --git a/cnd/src/cnd_process.cpp b/cnd/src/cnd_process.cpp deleted file mode 100755 index 006c0a4..0000000 --- a/cnd/src/cnd_process.cpp +++ /dev/null @@ -1,1306 +0,0 @@ -/* -** Copyright 2006, The Android Open Source Project -** Copyright (c) 2010, 2011 Code Aurora Forum. All rights reserved. -** -** Licensed under the Apache License, Version 2.0 (the "License"); -** you may not use this file except in compliance with the License. -** You may obtain a copy of the License at -** -** http://www.apache.org/licenses/LICENSE-2.0 -** -** Unless required by applicable law or agreed to in writing, software -** distributed under the License is distributed on an "AS IS" BASIS, -** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -** See the License for the specific language governing permissions and -** limitations under the License. -*/ -#define LOG_TAG "CND_PROCESS" -#define LOCAL_TAG "CND_PROCESS_DEBUG" -#define LOG_NDEBUG 0 -#define LOG_NDDEBUG 0 -#define LOG_NIDEBUG 0 - -#include <cutils/sockets.h> -#include <cutils/jstring.h> -#include <cutils/record_stream.h> -#include <utils/Log.h> -#include <utils/SystemClock.h> -#include <pthread.h> -#include <binder/Parcel.h> -#include <cutils/jstring.h> - -#include <linux/capability.h> -#include <linux/prctl.h> -#include <sys/types.h> -#include <pwd.h> - -#include <stdio.h> -#include <stdlib.h> -#include <stdarg.h> -#include <string.h> -#include <unistd.h> -#include <fcntl.h> -#include <time.h> -#include <errno.h> -#include <assert.h> -#include <ctype.h> -#include <alloca.h> -#include <sys/un.h> -#include <assert.h> -#include <netinet/in.h> -#include <cutils/properties.h> -#include <dirent.h> -#include <cnd_event.h> -#include <cnd.h> -#include <cne.h> -#include <cnd_iproute2.h> - - -namespace android { - -#define SOCKET_NAME_CND "cnd" -#define RUN_LEVEL_CND "radio" - -// match with constant in .java -#define MAX_COMMAND_BYTES (8 * 1024) - -// Basically: memset buffers that the client library -// shouldn't be using anymore in an attempt to find -// memory usage issues sooner. -#define MEMSET_FREED 1 - -#define NUM_ELEMS(a) (sizeof (a) / sizeof (a)[0]) - -/* Constants for response types */ -#define SOLICITED_RESPONSE 0 -#define UNSOLICITED_MESSAGE 1 - -typedef struct { - int commandNumber; - void (*dispatchFunction) (Parcel &p, struct RequestInfo *pRI); - int(*responseFunction) (Parcel &p, void *response, size_t responselen); -} CommandInfo; - -typedef struct { - int messageNumber; - int (*responseFunction) (Parcel &p, void *response, size_t responselen); -} UnsolMessageInfo; - -typedef struct RequestInfo { - int32_t token; //this is not CND_Token - int fd; - CommandInfo *pCI; - struct RequestInfo *p_next; - char cancelled; -} RequestInfo; - - -/*******************************************************************/ - -static int s_registerCalled = 0; - -static pthread_t s_tid_dispatch; - -static int s_started = 0; - -static int s_fdListen = -1; - -static struct cnd_event s_commands_event[MAX_FD_EVENTS]; -static struct cnd_event s_listen_event; -static int command_index = 0; -static int cneServiceEnabled = 0; - -static pthread_mutex_t s_pendingRequestsMutex = PTHREAD_MUTEX_INITIALIZER; -static pthread_mutex_t s_writeMutex = PTHREAD_MUTEX_INITIALIZER; -static pthread_mutex_t s_startupMutex = PTHREAD_MUTEX_INITIALIZER; -static pthread_cond_t s_startupCond = PTHREAD_COND_INITIALIZER; - -static pthread_mutex_t s_dispatchMutex = PTHREAD_MUTEX_INITIALIZER; -static pthread_cond_t s_dispatchCond = PTHREAD_COND_INITIALIZER; - -static RequestInfo *s_pendingRequests = NULL; - -static RequestInfo *s_toDispatchHead = NULL; -static RequestInfo *s_toDispatchTail = NULL; - - -/*******************************************************************/ -static void dispatchVoid (Parcel& p, RequestInfo *pRI); -static void dispatchString (Parcel& p, RequestInfo *pRI); -static void dispatchStrings (Parcel& p, RequestInfo *pRI); -static void dispatchInt (Parcel& p, RequestInfo *pRI); -static void dispatchInts (Parcel& p, RequestInfo *pRI); -static void dispatchWlanInfo(Parcel &p, RequestInfo *pRI); -static void dispatchWwanInfo(Parcel &p, RequestInfo *pRI); -static void dispatchWlanScanResults(Parcel &p, RequestInfo *pRI); -static void dispatchRaw(Parcel& p, RequestInfo *pRI); -static void dispatchRatStatus(Parcel &p, RequestInfo *pRI); -static void dispatchIproute2Cmd(Parcel &p, RequestInfo *pRI); -static int responseInts(Parcel &p, void *response, size_t responselen); -static int responseStrings(Parcel &p, void *response, size_t responselen); -static int responseString(Parcel &p, void *response, size_t responselen); -static int responseVoid(Parcel &p, void *response, size_t responselen); -static int responseRaw(Parcel &p, void *response, size_t responselen); -static int responseStartTrans(Parcel &p, void *response, size_t responselen); -static int sendResponseRaw (const void *data, size_t dataSize, int fdCommand); -static int sendResponse (Parcel &p, int fd); -static int rspCompatibleNws(Parcel &p, void *response, size_t responselen); -static int evtMorePrefNw(Parcel &p, void *response, size_t responselen); -static int eventRatChange (Parcel &p, void *response, size_t responselen); -static char *strdupReadString(Parcel &p); -static void writeStringToParcel(Parcel &p, const char *s); -static void memsetString (char *s); -static int writeData(int fd, const void *buffer, size_t len); -static void unsolicitedMessage(int unsolMessage, void *data, size_t datalen, int fd); -static void processCommand (int command, void *data, size_t datalen, CND_Token t); -static int processCommandBuffer(void *buffer, size_t buflen, int fd); -static void onCommandsSocketClosed(void); -static void processCommandsCallback(int fd, void *param); -static void listenCallback (int fd, void *param); -static void *eventLoop(void *param); -static int checkAndDequeueRequestInfo(struct RequestInfo *pRI); -static void cnd_commandComplete(CND_Token t, CND_Errno e, void *response, size_t responselen); - -extern "C" const char * requestToString(int request); -extern "C" cneProcessCmdFnType cne_processCommand; -extern "C" cneRegMsgCbFnType cne_regMessageCb; - -/** Index == commandNumber */ -static CommandInfo s_commands[] = { -#include "cnd_commands.h" -}; - -static UnsolMessageInfo s_unsolMessages[] = { -#include "cnd_unsol_messages.h" -}; - -#define TEMP_BUFFER_SIZE (80) - - -void cnd_sendUnsolicitedMsg(int targetFd, int msgType, int dataLen, void *data) -{ - int fd; - - CNE_LOGV ("cnd_sendUnsolicitedMsg: Fd=%d, msgType=%d, datalen=%d\n", - targetFd, msgType, dataLen); - - //unsolicitedMessage(msgType, data, dataLen, fd); - unsolicitedMessage(msgType, data, dataLen, targetFd); - - -} - -static void -processCommand (int command, void *data, size_t datalen, CND_Token t) -{ - - - RequestInfo *reqInfo = (RequestInfo *)t; - CNE_LOGV ("processCommand: command=%d, datalen=%d, fd=%d", command, datalen, reqInfo->fd); - - - /* Special handling for iproute2 command to setup iproute2 table */ - if ((command == CNE_REQUEST_CONFIG_IPROUTE2_CMD) && (cneServiceEnabled)) - { - - int cmd = 0; - unsigned char *ipAddr = NULL; - unsigned char *gatewayAddr = NULL; - unsigned char *ifName = NULL; - - if ((data == NULL) || (datalen ==0)) { - CNE_LOGD ("processCommand: invalid data"); - return; - } - - cmd = ((int *)data)[0]; - ifName = ((unsigned char **)data)[1]; - ipAddr = ((unsigned char **)data)[2]; - gatewayAddr = ((unsigned char **)data)[3]; - - CNE_LOGV ("processCommand: iproute2cmd=%d, ipAddr=%s, gatewayAddr=%s, " - "ifName=%s", cmd, ipAddr, gatewayAddr, ifName); - - cnd_iproute2* cnd_iproute2_ptr = cnd_iproute2::getInstance(); - if (cnd_iproute2_ptr != NULL) { - // Call iproute2 API - switch(cmd) - { - case CNE_IPROUTE2_ADD_ROUTING: - cnd_iproute2::getInstance()->addRoutingTable(ifName, ipAddr, gatewayAddr); - break; - case CNE_IPROUTE2_DELETE_ROUTING: - case CNE_IPROUTE2_DELETE_HOST_ROUTING: - cnd_iproute2::getInstance()->deleteRoutingTable(ifName); - break; - case CNE_IPROUTE2_DELETE_DEFAULT_IN_MAIN: - case CNE_IPROUTE2_DELETE_HOST_DEFAULT_IN_MAIN: - cnd_iproute2::getInstance()->deleteDefaultEntryInMainTable(ifName); - break; - case CNE_IPROUTE2_REPLACE_DEFAULT_ENTRY_IN_MAIN: - case CNE_IPROUTE2_REPLACE_HOST_DEFAULT_ENTRY_IN_MAIN: - cnd_iproute2::getInstance()->replaceDefaultEntryInMainTable(ifName, gatewayAddr); - break; - case CNE_IPROUTE2_ADD_HOST_IN_MAIN: - cnd_iproute2::getInstance()->addCustomEntryInMainTable(ipAddr, ifName, gatewayAddr); - break; - case CNE_IPROUTE2_DELETE_HOST_IN_MAIN: - cnd_iproute2::getInstance()->deleteDeviceCustomEntriesInMainTable(ifName); - break; - default: - CNE_LOGD ("processCommand: not iproute2 command=%d", command); - break; - } - } - - return; - - } - - if(cne_processCommand != NULL) - { - cne_processCommand(reqInfo->fd, command, data, datalen); - } - else - { - CNE_LOGD("cne_processCommand is NULL"); - } - cnd_commandComplete(t, CND_E_SUCCESS, NULL, 0); - return; -} - -static char * -strdupReadString(Parcel &p) -{ - size_t stringlen; - const char16_t *s16; - - s16 = p.readString16Inplace(&stringlen); - - return strndup16to8(s16, stringlen); -} - -static void writeStringToParcel(Parcel &p, const char *s) -{ - char16_t *s16; - size_t s16_len; - s16 = strdup8to16(s, &s16_len); - p.writeString16(s16, s16_len); - free(s16); -} - -static void -memsetString (char *s) -{ - if (s != NULL) { - memset (s, 0, strlen(s)); - } -} - -/** Callee expects NULL */ -static void -dispatchVoid (Parcel& p, RequestInfo *pRI) -{ - - processCommand(pRI->pCI->commandNumber, NULL, 0, pRI); -} - -/** Callee expects const char * */ -static void -dispatchString (Parcel& p, RequestInfo *pRI) -{ - status_t status; - size_t datalen; - size_t stringlen; - char *string8 = NULL; - - string8 = strdupReadString(p); - - CNE_LOGV ("dispatchString: strlen=%d", strlen(string8)); - processCommand(pRI->pCI->commandNumber, string8, strlen(string8), pRI); - - -#ifdef MEMSET_FREED - memsetString(string8); -#endif - - free(string8); - return; -} - -/** Callee expects const char ** */ -static void -dispatchStrings (Parcel &p, RequestInfo *pRI) -{ - int32_t countStrings; - status_t status; - size_t datalen; - char **pStrings; - - status = p.readInt32 (&countStrings); - - if (status != NO_ERROR){ - CNE_LOGD ("dispatchStrings: invalid block"); - return; - } - - if (countStrings == 0) { - // just some non-null pointer - pStrings = (char **)alloca(sizeof(char *)); - datalen = 0; - } else if (((int)countStrings) == -1) { - pStrings = NULL; - datalen = 0; - } else { - datalen = sizeof(char *) * countStrings; - - pStrings = (char **)alloca(datalen); - - for (int i = 0 ; i < countStrings ; i++) { - pStrings[i] = strdupReadString(p); - - } - } - - processCommand(pRI->pCI->commandNumber, pStrings, datalen, pRI); - - if (pStrings != NULL) { - for (int i = 0 ; i < countStrings ; i++) { -#ifdef MEMSET_FREED - memsetString (pStrings[i]); -#endif - free(pStrings[i]); - } - -#ifdef MEMSET_FREED - memset(pStrings, 0, datalen); -#endif - } - - return; -} - -/** Callee expects const int * */ -static void -dispatchInt (Parcel &p, RequestInfo *pRI) -{ - status_t status; - int32_t value; - - status = p.readInt32 (&value); - if (status != NO_ERROR) { - CNE_LOGD ("dispatchInt: invalid block"); - return; - } - - CNE_LOGV ("dispatchInt: int32_t=%d", value); - - processCommand(pRI->pCI->commandNumber, const_cast<int *>(&value), sizeof(int32_t), pRI); -} - -/** Callee expects const int * */ -static void -dispatchInts (Parcel &p, RequestInfo *pRI) -{ - int32_t count; - status_t status; - size_t datalen; - int *pInts; - - status = p.readInt32 (&count); - - if (status != NO_ERROR || count == 0) { - CNE_LOGD ("dispatchInts: invalid block"); - return; - } - - datalen = sizeof(int) * count; - pInts = (int *)alloca(datalen); - - if (pInts == NULL) { - CNE_LOGW ("dispatchInts: alloc failed"); - return; - } - - for (int i = 0 ; i < count ; i++) { - int32_t t; - - status = p.readInt32(&t); - pInts[i] = (int)t; - - if (status != NO_ERROR) { - CNE_LOGD ("dispatchInts: invalid block"); - return; - } - } - - processCommand(pRI->pCI->commandNumber, const_cast<int *>(pInts), - datalen, pRI); - -#ifdef MEMSET_FREED - memset(pInts, 0, datalen); -#endif - - return; - -} - - -static void -dispatchWlanInfo(Parcel &p, RequestInfo *pRI) -{ - int32_t t; - status_t status; - CneWlanInfoType args; - - memset(&args, 0, sizeof(args)); - - status = p.readInt32 (&t); - args.type = (int)t; - status = p.readInt32 (&t); - args.status = (int)t; - status = p.readInt32 (&t); - args.rssi = (int)t; - args.ssid = strdupReadString(p); - args.ipAddr = strdupReadString(p); - args.iface = strdupReadString(p); - args.timeStamp = strdupReadString(p); - - if (status != NO_ERROR){ - CNE_LOGD ("dispatchWlanInfo: invalid block"); - return; - } - - - CNE_LOGV ("dispatchWlanInfo: state=%d, rssi=%d, ssid=%s, ipAddr=%s, " - "timeStamp=%s", - args.status, args.rssi, args.ssid, args.ipAddr, args.timeStamp); - - processCommand(pRI->pCI->commandNumber, &args, sizeof(args), pRI); - - return; -} - -static void -dispatchWlanScanResults(Parcel &p, RequestInfo *pRI) -{ - int32_t t; - status_t status; - CneWlanScanResultsType args; - int32_t numItems; - - status = p.readInt32 (&t); - - if (status != NO_ERROR){ - CNE_LOGD ("dispatchWlanScanResults: invalid block"); - return; - } - - args.numItems = (int)t; - int max = (t < CNE_MAX_SCANLIST_SIZE)? t:CNE_MAX_SCANLIST_SIZE; - - for (int i = 0; i < max; i++) - { - args.numItems = max; - status = p.readInt32 (&t); - args.scanList[i].level = (int)t; - status = p.readInt32 (&t); - args.scanList[i].frequency = (int)t; - args.scanList[i].ssid = strdupReadString(p); - args.scanList[i].bssid = strdupReadString(p); - args.scanList[i].capabilities = strdupReadString(p); - - if (status != NO_ERROR){ - CNE_LOGD ("dispatchWlanScanResults: invalid block"); - return; - } - } - - - processCommand(pRI->pCI->commandNumber, &args, sizeof(args), pRI); - - return; -} - -static void -dispatchWwanInfo(Parcel &p, RequestInfo *pRI) -{ - int32_t t; - status_t status; - CneWwanInfoType args; - - memset(&args, 0, sizeof(args)); - - status = p.readInt32 (&t); - args.type = (int)t; - status = p.readInt32 (&t); - args.status = (int)t; - status = p.readInt32 (&t); - args.rssi = (int)t; - status = p.readInt32 (&t); - args.roaming = (int)t; - args.ipAddr = strdupReadString(p); - args.iface = strdupReadString(p); - args.timeStamp = strdupReadString(p); - - if (status != NO_ERROR){ - CNE_LOGD ("dispatchWwanInfo: invalid block"); - return; - } - - CNE_LOGV ("dispatchWwanInfo: type=%d, state=%d, rssi=%d, roaming=%d, " - "ipAddr=%s, timeStamp=%s", args.type, args.status, args.rssi, - args.roaming, args.ipAddr, args.timeStamp); - - processCommand(pRI->pCI->commandNumber, &args, sizeof(args), pRI); - - return; -} - -static void -dispatchRatStatus(Parcel &p, RequestInfo *pRI) -{ - int32_t t; - status_t status; - CneRatStatusType args; - - memset(&args, 0, sizeof(args)); - - status = p.readInt32 (&t); - args.rat = (cne_rat_type)t; - status = p.readInt32 (&t); - args.ratStatus = (cne_network_state_enum_type)t; - args.ipAddr = strdupReadString(p); - - if (status != NO_ERROR){ - CNE_LOGD ("dispatchRatStatus: invalid block"); - return; - } - - CNE_LOGV ("dispatchRatStatus: type=%d, ratStatus=%d, ipAddr=%s", - args.rat, args.ratStatus, args.ipAddr); - - - processCommand(pRI->pCI->commandNumber, &args, sizeof(args), pRI); - - return; -} - -static void -dispatchIproute2Cmd(Parcel &p, RequestInfo *pRI) -{ - int32_t t; - status_t status; - CneIpRoute2CmdType args; - - memset(&args, 0, sizeof(args)); - - status = p.readInt32 (&t); - args.cmd = t; - args.ifName = strdupReadString(p); - args.ipAddr = strdupReadString(p); - args.gatewayAddr = strdupReadString(p); - - if ((status != NO_ERROR) || (args.ifName == NULL)) { - CNE_LOGD ("dispatchIproute2Cmd: invalid block"); - return; - } - - - CNE_LOGV ("dispatchIproute2Cmd: cmd=%d, ifName=%s, ipAddr=%s, gatewayAddr=%s", - args.cmd, args.ifName, args.ipAddr, args.gatewayAddr); - - processCommand(pRI->pCI->commandNumber, &args, sizeof(args), pRI); - - if (args.ifName != NULL) { - free(args.ifName); - } - if (args.ipAddr != NULL) { - free(args.ipAddr); - } - if (args.gatewayAddr != NULL) { - free(args.gatewayAddr); - } - return; -} - -static void -dispatchRaw(Parcel &p, RequestInfo *pRI) -{ - int32_t len; - status_t status; - const void *data; - - status = p.readInt32(&len); - - if (status != NO_ERROR){ - CNE_LOGD ("dispatchRaw: invalid block"); - return; - } - - // The java code writes -1 for null arrays - if (((int)len) == -1) { - data = NULL; - len = 0; - } - - data = p.readInplace(len); - - processCommand(pRI->pCI->commandNumber, const_cast<void *>(data), len, pRI); - - return; -} - -static int -writeData(int fd, const void *buffer, size_t len) -{ - size_t writeOffset = 0; - const uint8_t *toWrite; - - toWrite = (const uint8_t *)buffer; - - CNE_LOGV ("writeData: fd=%d, len=%d, offset=%d", fd, len, writeOffset); - while (writeOffset < len) { - CNE_LOGV ("writeData in loop: fd=%d, len=%d, offset=%d", fd, len, writeOffset); - ssize_t written; - do { - written = write (fd, toWrite + writeOffset, - len - writeOffset); - } while (written < 0 && errno == EINTR); - - if (written >= 0) { - writeOffset += written; - } else { // written < 0 - CNE_LOGD ("writeData: unexpected error on write errno:%d", errno); - close(fd); - return -1; - } - } - - return 0; -} - -static int -sendResponseRaw (const void *data, size_t dataSize, int fdCommand) -{ - int ret; - uint32_t header; - - if (fdCommand < 0) { - return -1; - } - - if (dataSize > MAX_COMMAND_BYTES) { - CNE_LOGD("sendResponseRaw: packet larger than %u (%u)", - MAX_COMMAND_BYTES, (unsigned int )dataSize); - - return -1; - } - - pthread_mutex_lock(&s_writeMutex); - - header = htonl(dataSize); - - - CNE_LOGD("sendResponseRaw: fd=%d, datasize=%d, header=%d", - fdCommand, dataSize, header); - ret = writeData(fdCommand, (void *)&header, sizeof(header)); - - if (ret < 0) { - return ret; - } - - writeData(fdCommand, data, dataSize); - - if (ret < 0) { - pthread_mutex_unlock(&s_writeMutex); - return ret; - } - - pthread_mutex_unlock(&s_writeMutex); - - return 0; -} - -static int -sendResponse (Parcel &p, int fd) -{ - - return sendResponseRaw(p.data(), p.dataSize(), fd); -} - -/** response is an int* pointing to an array of ints*/ - -static int -responseInts(Parcel &p, void *response, size_t responselen) -{ - int numInts; - - if (response == NULL && responselen != 0) { - CNE_LOGD("invalid response: NULL"); - return CND_E_INVALID_RESPONSE; - } - if (responselen % sizeof(int) != 0) { - CNE_LOGD("invalid response length %d expected multiple of %d\n", - (int)responselen, (int)sizeof(int)); - return CND_E_INVALID_RESPONSE; - } - - int *p_int = (int *) response; - - numInts = responselen / sizeof(int *); - p.writeInt32 (numInts); - - /* each int*/ - for (int i = 0 ; i < numInts ; i++) { - - p.writeInt32(p_int[i]); - } - - - - return 0; -} - -/** response is a char **, pointing to an array of char *'s */ -static int responseStrings(Parcel &p, void *response, size_t responselen) -{ - int numStrings; - - if (response == NULL && responselen != 0) { - CNE_LOGD("invalid response: NULL"); - return CND_E_INVALID_RESPONSE; - } - if (responselen % sizeof(char *) != 0) { - CNE_LOGD("invalid response length %d expected multiple of %d\n", - (int)responselen, (int)sizeof(char *)); - return CND_E_INVALID_RESPONSE; - } - - if (response == NULL) { - p.writeInt32 (0); - } else { - char **p_cur = (char **) response; - - numStrings = responselen / sizeof(char *); - p.writeInt32 (numStrings); - - /* each string*/ - for (int i = 0 ; i < numStrings ; i++) { - - writeStringToParcel (p, p_cur[i]); - } - - } - return 0; -} - - -/** - * NULL strings are accepted - * FIXME currently ignores responselen - */ -static int responseString(Parcel &p, void *response, size_t responselen) -{ - - CNE_LOGV("responseString called"); - /* one string only */ - writeStringToParcel(p, (const char *)response); - - return 0; -} - -static int responseVoid(Parcel &p, void *response, size_t responselen) -{ - return 0; -} - -static int responseRaw(Parcel &p, void *response, size_t responselen) -{ - if (response == NULL && responselen != 0) { - CNE_LOGD("invalid response: NULL with responselen != 0"); - return CND_E_INVALID_RESPONSE; - } - - // The java code reads -1 size as null byte array - if (response == NULL) { - p.writeInt32(-1); - } else { - CNE_LOGD("responseRaw len=%d\n", responselen); - p.writeInt32(responselen); - p.write(response, responselen); - } - - return 0; -} - - -static int rspCompatibleNws(Parcel &p, void *response, size_t responselen) -{ - if (response == NULL && responselen != 0) - { - CNE_LOGD("invalid response: NULL"); - return CND_E_INVALID_RESPONSE; - } - - cne_get_compatible_nws_evt_rsp_data_type *p_cur = - ((cne_get_compatible_nws_evt_rsp_data_type *) response); - - p.writeInt32((int)p_cur->reg_id); - p.writeInt32((int)p_cur->is_success); - p.writeInt32((int)p_cur->best_rat); - for(int index = 0; index<CNE_RAT_MAX; index++) - { - p.writeInt32((int)p_cur->rat_pref_order[index]); - } - writeStringToParcel(p,p_cur->ip_addr); - p.writeInt32((int)p_cur->fl_bw_est); - p.writeInt32((int)p_cur->rl_bw_est); - return 0; -} - -static int evtMorePrefNw(Parcel &p, void *response, size_t responselen) -{ - if (response == NULL && responselen != 0) - { - CNE_LOGD("invalid response: NULL"); - return CND_E_INVALID_RESPONSE; - } - - cne_pref_rat_avail_evt_data_type *p_cur = - ((cne_pref_rat_avail_evt_data_type *) response); - - p.writeInt32((int)p_cur->reg_id); - p.writeInt32((int)p_cur->rat); - writeStringToParcel(p,p_cur->ip_addr); - p.writeInt32((int)p_cur->fl_bw_est); - p.writeInt32((int)p_cur->rl_bw_est); - return 0; -} - -static int eventRatChange(Parcel &p, void *response, size_t responselen) -{ - if (response == NULL && responselen != 0) - { - CNE_LOGD("invalid response: NULL"); - return CND_E_INVALID_RESPONSE; - } - - CneRatInfoType *p_cur = ((CneRatInfoType *) response); - p.writeInt32((int)p_cur->rat); - - if (p_cur->rat == CNE_RAT_WLAN) - { - writeStringToParcel (p, p_cur->wlan.ssid); - } - return 0; -} - -static int -checkAndDequeueRequestInfo(struct RequestInfo *pRI) -{ - int ret = 0; - - if (pRI == NULL) { - return 0; - } - - pthread_mutex_lock(&s_pendingRequestsMutex); - - for(RequestInfo **ppCur = &s_pendingRequests - ; *ppCur != NULL - ; ppCur = &((*ppCur)->p_next) - ) { - if (pRI == *ppCur) { - ret = 1; - - *ppCur = (*ppCur)->p_next; - break; - } - } - - pthread_mutex_unlock(&s_pendingRequestsMutex); - - return ret; -} - -static void onCommandsSocketClosed() -{ - int ret; - RequestInfo *p_cur; - - /* mark pending requests as "cancelled" so we dont report responses */ - - ret = pthread_mutex_lock(&s_pendingRequestsMutex); - assert (ret == 0); - - p_cur = s_pendingRequests; - - for (p_cur = s_pendingRequests - ; p_cur != NULL - ; p_cur = p_cur->p_next - ) { - p_cur->cancelled = 1; - } - - ret = pthread_mutex_unlock(&s_pendingRequestsMutex); - assert (ret == 0); -} - -static void unsolicitedMessage(int unsolMessage, void *data, size_t datalen, int fd) -{ - int unsolMessageIndex; - int ret; - - if (s_registerCalled == 0) { - CNE_LOGD("unsolicitedMessage called before cnd_init ignored"); - return; - } - - Parcel p; - - p.writeInt32 (UNSOLICITED_MESSAGE); - p.writeInt32 (unsolMessage); - - ret = s_unsolMessages[unsolMessage] - .responseFunction(p, data, datalen); - - if (ret != 0) { - // Problem with the response. Don't continue; - CNE_LOGD("unsolicitedMessage: problem with response"); - return; - } - - ret = sendResponse(p, fd); - - return; - -} - -static int -processCommandBuffer(void *buffer, size_t buflen, int fd) -{ - Parcel p; - status_t status; - int32_t request; - int32_t token; - RequestInfo *pRI; - int ret; - - p.setData((uint8_t *) buffer, buflen); - - // status checked at end - status = p.readInt32(&request); - status = p.readInt32 (&token); - - CNE_LOGD("processCommandBuffer: fd=%d, requestcode=%d, token=%d", - fd, request, token); - - if (status != NO_ERROR) { - CNE_LOGD("processCommandBuffer: invalid request block"); - return -1; - } - - if (request < 1 || request >= (int32_t)NUM_ELEMS(s_commands)) { - CNE_LOGD("processCommandBuffer: unsupported request code %d token %d", - request, token); - return -1; - } - - pRI = (RequestInfo *)calloc(1, sizeof(RequestInfo)); - - if (pRI == NULL) { - CNE_LOGW("processCommandBuffer: calloc failed"); - return -1; - } - - pRI->token = token; - pRI->fd = fd; - pRI->pCI = &(s_commands[request]); - - ret = pthread_mutex_lock(&s_pendingRequestsMutex); - assert (ret == 0); - - pRI->p_next = s_pendingRequests; - s_pendingRequests = pRI; - - ret = pthread_mutex_unlock(&s_pendingRequestsMutex); - assert (ret == 0); - - pRI->pCI->dispatchFunction(p, pRI); - - return 0; -} - -static void processCommandsCallback(int fd, void *param) -{ - RecordStream *p_rs; - void *p_record; - size_t recordlen; - int ret; - - p_rs = (RecordStream *)param; - - for (;;) { - /* loop until EAGAIN/EINTR, end of stream, or other error */ - ret = record_stream_get_next(p_rs, &p_record, &recordlen); - CNE_LOGV ("processCommandsCallback: len=%d, ret=%d, fd=%d", recordlen, ret, fd); - if (ret == 0 && p_record == NULL) { - CNE_LOGV ("processCommandsCallback: end of stream"); - break; - } else if (ret < 0) { - break; - } else if (ret == 0) { /* && p_record != NULL */ - processCommandBuffer(p_record, recordlen, fd); - - } - } - CNE_LOGV ("processCommandsCallback: exit loop, ret=%d, errno=%d, fd=%d", - ret, errno, fd); - if (ret == 0 || !(errno == EAGAIN || errno == EINTR || errno == EBADF)) { - /* fatal error or end-of-stream */ - if (ret != 0) { - CNE_LOGD("error on reading command socket errno:%d\n", errno); - } else { - CNE_LOGD("EOS. Closing command socket."); - } - close(fd); - /* remove from watch list */ - for(int i=0; i<MAX_FD_EVENTS; i++) { - CNE_LOGD("processCommandsCallback: fd=%d, commandFd=%d", - fd, s_commands_event[i].fd); - if (s_commands_event[i].fd == fd) { - CNE_LOGD("processCommandsCallback: matched fd=%d for index=%d", - fd, i); - cnd_event_del(&s_commands_event[i]); - command_index--; - break; - } - } - record_stream_free(p_rs); - /* notify CNE of the socket closed */ - cne_processCommand(fd, CNE_NOTIFY_SOCKET_CLOSED_CMD, NULL, 0); - onCommandsSocketClosed(); - } - -} - -static void listenCallback (int fd, void *param) -{ - int ret; - int err; - RecordStream *p_rs; - struct sockaddr_un peeraddr; - socklen_t socklen = sizeof (peeraddr); - struct ucred creds; - socklen_t szCreds = sizeof(creds); - int s_fdCommand; - - CNE_LOGD("listenCallback: fd=%d, s_fdListen=%d", fd, s_fdListen); - assert (fd == s_fdListen); - s_fdCommand = accept(s_fdListen, (sockaddr *) &peeraddr, &socklen); - - if (s_fdCommand < 0 ) { - CNE_LOGD("Error on accept() errno:%d", errno); - /* start listening for new connections again */ - cnd_event_add(&s_listen_event); - return; - } - - errno = 0; - err = getsockopt(s_fdCommand, SOL_SOCKET, SO_PEERCRED, &creds, &szCreds); - ret = fcntl(s_fdCommand, F_SETFL, O_NONBLOCK); - - if (ret < 0) { - CNE_LOGD("Error setting O_NONBLOCK errno = %d", errno); - } - - CNE_LOGV("listenCallback: accept new connection, fd=%d", s_fdCommand); - - p_rs = record_stream_new(s_fdCommand, MAX_COMMAND_BYTES); - - // note: persistent = 1, not removed from table - if (command_index >= MAX_FD_EVENTS) - { - CNE_LOGD ("Error: exceeding number of supported connection"); - return; - } - - CNE_LOGV("listenCallback: command_index=%d, fd=%d", - command_index, s_fdCommand); - - cnd_event_set (&s_commands_event[command_index], s_fdCommand, 1, - processCommandsCallback, p_rs); - cnd_event_add (&s_commands_event[command_index]); - - command_index++; - - return; - -} - - -static void * -eventLoop(void *param) -{ - int ret; - int filedes[2]; - - CNE_LOGV ("eventLoop: s_started=%d", s_started); - - pthread_mutex_lock(&s_startupMutex); - - s_started = 1; - pthread_cond_broadcast(&s_startupCond); - - pthread_mutex_unlock(&s_startupMutex); - - cnd_event_loop(); - - - return NULL; -} - -extern "C" void -cnd_startEventLoop(void) -{ - int ret; - pthread_attr_t attr; - - /* spin up eventLoop thread and wait for it to get started */ - s_started = 0; - pthread_mutex_lock(&s_startupMutex); - - pthread_attr_init (&attr); - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - ret = pthread_create(&s_tid_dispatch, &attr, eventLoop, NULL); - - while (s_started == 0) { - pthread_cond_wait(&s_startupCond, &s_startupMutex); - } - - pthread_mutex_unlock(&s_startupMutex); - - if (ret < 0) { - CNE_LOGD("Failed to create dispatch thread errno:%d", errno); - return; - } -} - -extern "C" void -cnd_init (void) -{ - int ret; - - if (s_registerCalled > 0) { - CNE_LOGD("cnd_init has been called more than once. " - "Subsequent call ignored"); - return; - } - - s_registerCalled = 1; - cneServiceEnabled = cnd_event_init(); - if(cne_regMessageCb != NULL) - { - cne_regMessageCb(cnd_sendUnsolicitedMsg); - } - else - { - CNE_LOGD("cne_regMessageCb is NULL"); - } - - s_fdListen = android_get_control_socket(SOCKET_NAME_CND); - if (s_fdListen < 0) { - CNE_LOGD("Failed to get socket '" SOCKET_NAME_CND "'"); - exit(-1); - } - - ret = listen(s_fdListen, 4); - - if (ret < 0) { - CNE_LOGD("Failed to listen on control socket '%d': %s", - s_fdListen, strerror(errno)); - exit(-1); - } - - // persistent to accept multiple connections at same time - cnd_event_set (&s_listen_event, s_fdListen, 1, listenCallback, NULL); - cnd_event_add (&s_listen_event); - - -} - -extern "C" void -cnd_cap_init (void) -{ - __user_cap_header_struct hdr; - __user_cap_data_struct data; - struct passwd* usr_info; - - /* Gather Current Capabilities */ - hdr.version = _LINUX_CAPABILITY_VERSION; - hdr.pid = 0; - if (capget(&hdr, &data) < 0) - CNE_LOGE("cnd_cap_init could not gather current capabilities: %s\n",strerror(errno)); - - /* Tell kernel not clear capabilities when dropping root user id */ - if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0) - CNE_LOGE("cnd_cap_init could not inform kernel of current capabilities prior to dropping root uid.\n" ); - - /* Drop root uid and change to radio */ - usr_info = getpwnam(RUN_LEVEL_CND); - if (setuid(usr_info->pw_uid) < 0) - CNE_LOGE("cnd_cap_init could not drop root uid."); - - /* Set new process capabilities */ - data.effective = (1 << (CAP_NET_ADMIN))|(1 << (CAP_NET_RAW)); - data.permitted = data.effective; - data.inheritable = 0; - if (capset(&hdr, &data) < 0) - CNE_LOGE("cnd_cap_init could not set capabilities: %s\n",strerror(errno)); -} - -static void -cnd_commandComplete(CND_Token t, CND_Errno e, void *response, size_t responselen) -{ - RequestInfo *pRI; - int ret; - size_t errorOffset; - - pRI = (RequestInfo *)t; - - if (!checkAndDequeueRequestInfo(pRI)) { - CNE_LOGD ("cnd_commandComplete: invalid Token"); - return; - } - - if (pRI->cancelled == 0) { - Parcel p; - - p.writeInt32 (SOLICITED_RESPONSE); - p.writeInt32 (pRI->token); - errorOffset = p.dataPosition(); - p.writeInt32 (e); - - if (e == CND_E_SUCCESS) { - /* process response on success */ - ret = pRI->pCI->responseFunction(p, response, responselen); - /* if an error occurred, rewind and mark it */ - if (ret != 0) { - p.setDataPosition(errorOffset); - p.writeInt32 (ret); - } - } else { - CNE_LOGD ("cnd_commandComplete: Error"); - } - - if (pRI->fd < 0) { - CNE_LOGD ("cnd_commandComplete: Command channel closed"); - } - sendResponse(p, pRI->fd); - } -} - -} /* namespace android */ - - |