diff options
Diffstat (limited to 'hicn-light/src/hicn/config')
108 files changed, 3346 insertions, 10418 deletions
diff --git a/hicn-light/src/hicn/config/CMakeLists.txt b/hicn-light/src/hicn/config/CMakeLists.txt index 104026355..00ee24077 100644 --- a/hicn-light/src/hicn/config/CMakeLists.txt +++ b/hicn-light/src/hicn/config/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (c) 2017-2019 Cisco and/or its affiliates. +# Copyright (c) 2021-2022 Cisco and/or its affiliates. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: @@ -12,95 +12,28 @@ # limitations under the License. list(APPEND HEADER_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/commandOps.h - ${CMAKE_CURRENT_SOURCE_DIR}/commandParser.h - ${CMAKE_CURRENT_SOURCE_DIR}/configuration.h - ${CMAKE_CURRENT_SOURCE_DIR}/commandReturn.h - ${CMAKE_CURRENT_SOURCE_DIR}/symbolicNameTable.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlState.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlRoot.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlAddConnection.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlAdd.h - ${CMAKE_CURRENT_SOURCE_DIR}/configurationFile.h - ${CMAKE_CURRENT_SOURCE_DIR}/configurationListeners.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlAddRoute.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlAddPolicy.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlAddListener.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlListConnections.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlList.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlListListeners.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlListRoutes.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlListPolicies.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlQuit.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemove.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveListener.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveConnection.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveRoute.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemovePolicy.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlSet.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlUnset.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlSetDebug.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlUnsetDebug.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMe.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeEnable.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeDiscovery.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeTimescale.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheServe.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheStore.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheClear.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlCache.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlSetStrategy.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlSetWldr.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlAddPunting.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemovePunting.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlUpdate.h - ${CMAKE_CURRENT_SOURCE_DIR}/controlUpdateConnection.h + ${CMAKE_CURRENT_SOURCE_DIR}/configuration.h + ${CMAKE_CURRENT_SOURCE_DIR}/command.h + ${CMAKE_CURRENT_SOURCE_DIR}/commands.h + ${CMAKE_CURRENT_SOURCE_DIR}/parse.h ) list(APPEND SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/commandOps.c - ${CMAKE_CURRENT_SOURCE_DIR}/commandParser.c - ${CMAKE_CURRENT_SOURCE_DIR}/configuration.c - ${CMAKE_CURRENT_SOURCE_DIR}/configurationFile.c - ${CMAKE_CURRENT_SOURCE_DIR}/configurationListeners.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlState.c - ${CMAKE_CURRENT_SOURCE_DIR}/symbolicNameTable.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlAdd.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlAddConnection.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlAddRoute.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlAddPolicy.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlAddListener.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlList.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlListConnections.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlListListeners.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlListRoutes.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlListPolicies.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlQuit.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemove.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveListener.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveConnection.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemoveRoute.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemovePolicy.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlRoot.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlSet.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlSetDebug.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlUnset.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlUnsetDebug.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMe.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeEnable.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeDiscovery.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeTimescale.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlMapMeRetx.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheServe.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheStore.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlCacheClear.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlCache.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlSetStrategy.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlSetWldr.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlAddPunting.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlRemovePunting.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlUpdate.c - ${CMAKE_CURRENT_SOURCE_DIR}/controlUpdateConnection.c + ${CMAKE_CURRENT_SOURCE_DIR}/configuration.c + ${CMAKE_CURRENT_SOURCE_DIR}/configuration_file.c + ${CMAKE_CURRENT_SOURCE_DIR}/command_cache.c + ${CMAKE_CURRENT_SOURCE_DIR}/command_connection.c + ${CMAKE_CURRENT_SOURCE_DIR}/command_face.c + ${CMAKE_CURRENT_SOURCE_DIR}/command_listener.c + ${CMAKE_CURRENT_SOURCE_DIR}/command_mapme.c + ${CMAKE_CURRENT_SOURCE_DIR}/command_policy.c + ${CMAKE_CURRENT_SOURCE_DIR}/command_punting.c + ${CMAKE_CURRENT_SOURCE_DIR}/command_route.c + ${CMAKE_CURRENT_SOURCE_DIR}/command_strategy.c + ${CMAKE_CURRENT_SOURCE_DIR}/command_subscription.c + ${CMAKE_CURRENT_SOURCE_DIR}/command.c + ${CMAKE_CURRENT_SOURCE_DIR}/commands.c + ${CMAKE_CURRENT_SOURCE_DIR}/parse.c ) set(SOURCE_FILES ${SOURCE_FILES} PARENT_SCOPE) diff --git a/hicn-light/src/hicn/config/command.c b/hicn-light/src/hicn/config/command.c new file mode 100644 index 000000000..bee0d2663 --- /dev/null +++ b/hicn-light/src/hicn/config/command.c @@ -0,0 +1,119 @@ + +/** + * @file command.c + * @brief Implementation of commands. + */ + +#include <search.h> /* tfind, tdestroy, twalk */ +#include <stdio.h> +#include <ctype.h> +#include "command.h" +#include "parse.h" + +/* Commands are registered in the following tree. */ +static void *commands_root = NULL; /**< Tree ordered by name */ + +#ifdef __linux__ +static void nothing_to_free() {} + +__attribute__((destructor)) static void command_clear() { + tdestroy(commands_root, nothing_to_free); +} +#endif /* __linux__ */ + +static int _command_compare(const command_parser_t *c1, + const command_parser_t *c2) { + if (c1->object != c2->object) return c2->object - c1->object; + if (c1->action != c2->action) return c2->action - c1->action; + if (c1->nparams != c2->nparams) return c2->nparams - c1->nparams; + return 0; +} + +#define command_compare (int (*)(const void *, const void *))(_command_compare) + +void command_register(const command_parser_t *command) { + // Insert the command in the tree if the keys does not exist yet + tsearch(command, &commands_root, command_compare); +} + +const command_parser_t *command_search(const hc_action_t action, + hc_object_type_t object, + unsigned nparams) { + command_parser_t **command, search; + + search.action = action; + search.object = object; + search.nparams = nparams; + command = tfind(&search, &commands_root, command_compare); + + return command ? *command : NULL; +} + +static inline void to_lowercase(char *p) { + for (; *p; ++p) *p = tolower(*p); +} + +typedef struct { + hc_object_type_t object; + hc_action_t action; +} cmd_search_params_t; + +static hc_object_type_t prev_obj = OBJECT_UNDEFINED; +static hc_action_t prev_action = ACTION_UNDEFINED; +static void traversal_action(const void *nodep, VISIT which, + void *cmd_params0) { + cmd_search_params_t *cmd_params = cmd_params0; + + // Execute this function during inorder traversal + if (which != postorder && which != leaf) return; + + command_parser_t *datap; + datap = *(command_parser_t **)nodep; + char *obj_str = strdup(object_str(datap->object)); + to_lowercase(obj_str); + + // List all objects + if (cmd_params->object == OBJECT_UNDEFINED && + cmd_params->action == ACTION_UNDEFINED) { + if (datap->object == prev_obj) goto FREE_STR; + prev_obj = datap->object; + + printf("\thelp %s\n", obj_str); + goto FREE_STR; + } + + // List actions for specific object + if (datap->object != cmd_params->object) goto FREE_STR; + if (cmd_params->action == ACTION_UNDEFINED) { + if (datap->action == prev_action) goto FREE_STR; + prev_action = datap->action; + + printf("\thelp %s %s\n", obj_str, action_to_cmd_action(datap->action)); + goto FREE_STR; + } + + // List commands for specific object and action + if (datap->action != cmd_params->action) goto FREE_STR; + printf(" %s %s ", action_to_cmd_action(datap->action), obj_str); + for (int i = 0; i < datap->nparams; i++) + printf("<%s> ", datap->parameters[i].name); + printf("\n\n"); + // List options' details + if (datap->nparams == 0) goto FREE_STR; + for (int i = 0; i < datap->nparams; i++) + printf("%16s: %s\n", datap->parameters[i].name, datap->parameters[i].help); + printf("\n"); + +FREE_STR: + free(obj_str); +} + +void command_list(hc_object_type_t object, hc_action_t action) { +#if defined(__linux__) && !defined(__ANDROID__) + cmd_search_params_t cmd_params = {.object = object, .action = action}; + twalk_r(commands_root, traversal_action, &cmd_params); +#else + fprintf(stderr, "twalk_r() function only available on linux"); + (void)traversal_action; +#endif +} diff --git a/hicn-light/src/hicn/config/command.h b/hicn-light/src/hicn/config/command.h new file mode 100644 index 000000000..73d8edb1f --- /dev/null +++ b/hicn-light/src/hicn/config/command.h @@ -0,0 +1,179 @@ +#ifndef HICNLIGHT_CONFIG_COMMAND +#define HICNLIGHT_CONFIG_COMMAND + +/** + * @file command.h + * @brief Commands. + */ + +#include <stddef.h> // offsetof +#include <hicn/util/ip_address.h> + +#include <hicn/ctrl/api.h> + +/* Update sscanf accordingly in parse_cmd.c */ +#define MAX_PARAMETERS 10 +#define MAX_SCANF_PARAM_LEN 100 + +typedef int (*parser_hook_t)(void *arg); + +typedef enum { + TYPENAME_UNDEFINED, + TYPENAME_INT, + TYPENAME_UINT, + TYPENAME_STR, + TYPENAME_SYMBOLIC_OR_ID, + TYPENAME_INTERFACE_NAME, + TYPENAME_IP_ADDRESS, + TYPENAME_IP_PREFIX, + TYPENAME_ON_OFF, + TYPENAME_ENUM, + TYPENAME_POLICY_STATE, +} parser_typename_t; + +typedef struct { + parser_typename_t name; + union { + struct { + size_t max_size; + } str; + struct { + int min; + int max; + } sint; + struct { + int min; + int max; + } uint; + struct { + int (*from_str)(const char *str); + } enum_; + struct { + policy_tag_t tag; + } policy_state; + }; +} parser_type_t; + +typedef struct { + const char *name; + const char *help; + parser_type_t type; + size_t offset; + /* + * quick hack to let the functions update two or more parameters, like for + * IP_ADDRESS or IP_PREFIX types + */ + size_t offset2; + size_t offset3; +} command_parameter_t; + +typedef struct { + hc_action_t action; + hc_object_type_t object; + unsigned nparams; + command_parameter_t parameters[MAX_PARAMETERS]; + parser_hook_t post_hook; +} command_parser_t; + +#define TYPE_STRN(N) \ + (parser_type_t) { \ + .name = TYPENAME_STR, \ + .str = { \ + .max_size = N, \ + }, \ + } +#define TYPE_FMT_STRN(N) "%s" + +#define TYPE_INT(MIN, MAX) \ + (parser_type_t) { \ + .name = TYPENAME_INT, \ + .sint = { \ + .min = (MIN), \ + .max = (MAX), \ + }, \ + } +#define TYPE_FMT_INT "%d" + +#define TYPE_UINT(min, max) \ + (parser_type_t) { \ + .name = TYPENAME_UINT, \ + .uint = { \ + .min = min, \ + .max = max, \ + }, \ + } +#define TYPE_FMT_UINT "%u" + +#define TYPE_SYMBOLIC_OR_ID TYPE_STRN(SYMBOLIC_NAME_LEN) +#define TYPE_FMT_SYMBOLIC_OR_ID "%s" + +#define TYPE_INTERFACE_NAME TYPE_STRN(INTERFACE_LEN) +#define TYPE_FMT_INTERFACE_NAME "%s" + +#define TYPE_IP_ADDRESS \ + (parser_type_t) { .name = TYPENAME_IP_ADDRESS, } +#define TYPE_FMT_IP_ADDRESS "%s" + +#define TYPE_IP_PREFIX \ + (parser_type_t) { .name = TYPENAME_IP_PREFIX, } +#define TYPE_FMT_IP_PREFIX "%s" + +#define TYPE_ON_OFF \ + (parser_type_t) { .name = TYPENAME_ON_OFF, } +#define TYPE_FMT_ON_OFF "%s" + +#define TYPE_ENUM(x) \ + (parser_type_t) { \ + .name = TYPENAME_ENUM, \ + .enum_ = { \ + .from_str = (int (*)(const char *))x##_from_str, \ + }, \ + } +/* We need to allocate room for the intermediate string */ +#define TYPE_FMT_ENUM "%s" + +#define TYPE_POLICY_STATE(TAG) \ + (parser_type_t) { \ + .name = TYPENAME_POLICY_STATE, \ + .policy_state = { \ + .tag = TAG, \ + }, \ + } +/* We need to allocate room for the intermediate string */ +#define TYPE_FMT_POLICY_STATE "%s" + +/** + * \brief Register a protocol + * \param protocol Pointer to a protocol_t structure describing the protocol to + * register \return None + */ + +void command_register(const command_parser_t *command); + +/** + * \brief Search a registered protocol in the library according to its name + * \param[in] action The action of the command. + * \param[in] object The object of the command. + * \param[in] nparams The number of parameters expected in the command. + * \return A pointer to the corresponding command if any, NULL othewise + */ +const command_parser_t *command_search(hc_action_t action, + hc_object_type_t object, + unsigned nparams); + +/** + * @brief List the commands associated with the specified object and/or action. + * Use OBJECT_UNDEFINED and ACTION_UNDEFINED to list all the available objects. + * Use ACTION_UNDEFINED to list all the actions associated to the specified + * object. + * + * @param object The action of the command + * @param action The object of the command + */ +void command_list(hc_object_type_t object, hc_action_t action); + +#define COMMAND_REGISTER(MOD) \ + static void __init_##MOD(void) __attribute__((constructor)); \ + static void __init_##MOD(void) { command_register(&MOD); } + +#endif /* HICNLIGHT_CONFIG_COMMAND */ diff --git a/hicn-light/src/hicn/config/commandOps.c b/hicn-light/src/hicn/config/commandOps.c deleted file mode 100644 index dd8e148d0..000000000 --- a/hicn-light/src/hicn/config/commandOps.c +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#ifndef __ANDROID__ -#ifdef HAVE_ERRNO_H -#include <errno.h> -#else -#ifndef _WIN32 -extern int errno; -#endif -#endif -#endif - -#include <parc/algol/parc_Memory.h> -#include <parc/assert/parc_Assert.h> -#include <hicn/config/commandOps.h> -#include <hicn/config/commandParser.h> - -CommandOps *commandOps_Create(void *closure, const char *command, - void (*init)(CommandParser *parser, - CommandOps *ops), - CommandReturn (*execute)(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size), - void (*destroyer)(CommandOps **opsPtr)) { - parcAssertNotNull(command, "Parameter command must be non-null"); - parcAssertNotNull(execute, "Parameter execute must be non-null"); - CommandOps *ops = parcMemory_AllocateAndClear(sizeof(CommandOps)); - parcAssertNotNull(ops, "parcMemory_AllocateAndClear(%zu) returned NULL", - sizeof(CommandOps)); - - ops->closure = closure; - ops->command = parcMemory_StringDuplicate(command, strlen(command) + 1); - ops->init = init; - ops->execute = execute; - ops->destroyer = destroyer; - return ops; -} - -void commandOps_Destroy(CommandOps **opsPtr) { - parcAssertNotNull(opsPtr, "Parameter opsPtr must be non-null"); - parcAssertNotNull(*opsPtr, - "Parameter opsPtr must dereference to non-null pointer"); - - CommandOps *ops = *opsPtr; - parcMemory_Deallocate((void **)&(ops->command)); - // DO NOT call ops->destroyer, we are one! - parcMemory_Deallocate((void **)&ops); - - *opsPtr = NULL; -} diff --git a/hicn-light/src/hicn/config/commandOps.h b/hicn-light/src/hicn/config/commandOps.h deleted file mode 100644 index 784b91eb8..000000000 --- a/hicn-light/src/hicn/config/commandOps.h +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file command_Ops.h - * @brief The function structure defining a CLI command - * - * The function structure that defines a CLI command. Each command will return - * one of these which defines how to run the command. - * - */ - -#ifndef command_Ops_h -#define command_Ops_h - -#include <parc/algol/parc_List.h> - -#include <hicn/config/commandReturn.h> - -// forward reference -struct command_parser; - -struct command_ops; -typedef struct command_ops CommandOps; - -/** - * @typedef CommandOps - * @abstract Each command implements a CommandOps - * @constant closure is a user-specified pointer for any state the user needs - * @constant command The text string of the command, must be the spelled out - * string, e.g. "help list routes" - * @constant init A function to call to initialize the command at program - * startup - * @constant execute A function to call to execute the command - * @constant destroyer A function to call to release the command - * @discussion - * Typically, the root of the thee has an Init function that then initilizes - * the rest of the tree. For example: - * - * @code - * const CommandOps control_Root = { - * .closure = NULL, - * .command = "", // empty string for root - * .init = control_Root_Init, - * .execute = control_Root_Execute - * .destroyer = NULL - * }; - * @endcode - * - * The control_Root_Init function will then begin adding the subtree under root. - * For example: - * - * @code - * const CommandOps control_Add = { - * .closure = NULL, - * .command = "add", - * .init = control_Add_Init, - * .execute = control_Add_Execute, - * .destroyer = NULL - * }; - * - * static void - * control_Root_Init(ControlState *state, CommandOps *ops) - * { - * controlState_RegisterCommand(state, &control_Add); - * } - * @endcode - */ -struct command_ops { - void *closure; - char *command; - void (*init)(struct command_parser *parser, CommandOps *ops); - CommandReturn (*execute)(struct command_parser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - void (*destroyer)(CommandOps **opsPtr); -}; - -/** - * A helper function to create the pubically defined CommandOps. - * - * Retruns allocated memory of the command - * - * @param [in] command The string is copied - * - * @retval <#value#> <#explanation#> - * - * Example: - * @code - * <#example#> - * @endcode - */ -CommandOps *commandOps_Create( - void *closure, const char *command, - void (*init)(struct command_parser *parser, CommandOps *ops), - CommandReturn (*execute)(struct command_parser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size), - void (*destroyer)(CommandOps **opsPtr)); - -/** - * De-allocates the memory of the CommandOps and the copied command string - * - * <#Paragraphs Of Explanation#> - * - * @param [<#in out in,out#>] <#name#> <#description#> - * - * @retval <#value#> <#explanation#> - * - * Example: - * @code - * <#example#> - * @endcode - */ -void commandOps_Destroy(CommandOps **opsPtr); -#endif // command_Ops_h diff --git a/hicn-light/src/hicn/config/commandParser.c b/hicn-light/src/hicn/config/commandParser.c deleted file mode 100644 index f4652fe39..000000000 --- a/hicn-light/src/hicn/config/commandParser.c +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <parc/assert/parc_Assert.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include <parc/security/parc_Security.h> - -#include <parc/algol/parc_List.h> -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Time.h> -#include <parc/algol/parc_TreeRedBlack.h> - -#include <hicn/config/commandParser.h> - -#ifndef __ANDROID__ -#ifdef HAVE_ERRNO_H -#include <errno.h> -#else -#ifndef _WIN32 -extern int errno; -#endif -#endif -#endif - -struct command_parser { - // key = command, value = CommandOps - PARCTreeRedBlack *commandTree; - bool debugFlag; -}; - -static int _stringCompare(const void *key1, const void *key2) { - return strcasecmp((const char *)key1, (const char *)key2); -} - -CommandParser *commandParser_Create(void) { - CommandParser *state = parcMemory_AllocateAndClear(sizeof(CommandParser)); - parcAssertNotNull(state, "parcMemory_AllocateAndClear(%zu) returned NULL", - sizeof(CommandParser)); - - state->commandTree = parcTreeRedBlack_Create(_stringCompare, // key compare - NULL, // key free - NULL, // key copy - NULL, // value equals - NULL, // value free - NULL // value copy - ); - state->debugFlag = false; - return state; -} - -void commandParser_Destroy(CommandParser **parserPtr) { - CommandParser *parser = *parserPtr; - - // destroy every element if it has a destroyer - PARCArrayList *values = parcTreeRedBlack_Values(parser->commandTree); - if (values) { - for (int i = 0; i < parcArrayList_Size(values); i++) { - CommandOps *ops = parcArrayList_Get(values, i); - parcTreeRedBlack_Remove(parser->commandTree, ops->command); - if (ops->destroyer) { - ops->destroyer(&ops); - } - } - parcArrayList_Destroy(&values); - } - - parcTreeRedBlack_Destroy(&parser->commandTree); - - parcMemory_Deallocate((void **)&parser); - *parserPtr = NULL; -} - -void commandParser_SetDebug(CommandParser *state, bool debugFlag) { - state->debugFlag = debugFlag; -} - -bool commandParser_GetDebug(CommandParser *state) { return state->debugFlag; } - -void commandParser_RegisterCommand(CommandParser *state, CommandOps *ops) { - parcAssertNotNull(state, "Parameter state must be non-null"); - parcAssertNotNull(ops, "Parameter ops must be non-null"); - parcAssertNotNull(ops->command, "Operation command string must be non-null"); - - void *exists = parcTreeRedBlack_Get(state->commandTree, ops->command); - parcAssertNull(exists, "Command '%s' already exists in the tree %p\n", - ops->command, (void *)exists); - - parcTreeRedBlack_Insert(state->commandTree, (void *)ops->command, - (void *)ops); - - // if the command being registered asked for an init function to be called, - // call it - if (ops->init != NULL) { - ops->init(state, ops); - } -} - -static PARCList *parseStringIntoTokens(const char *originalString) { - PARCList *list = - parcList(parcArrayList_Create(parcArrayList_StdlibFreeFunction), - PARCArrayListAsPARCList); - - char *token; - - char *tofree = - parcMemory_StringDuplicate(originalString, strlen(originalString) + 1); - char *string = tofree; - - token = strtok(string, " \t\n"); - while (token != NULL) { - if (strlen(token) > 0) { - parcList_Add(list, strdup(token)); - } - token = strtok(NULL, " \t\n"); - } - - parcMemory_Deallocate((void **)&tofree); - - return list; -} - -/** - * Matches the user arguments to available commands, returning the command or - * NULL if not found - * - * <#Paragraphs Of Explanation#> - * - * @param [<#in out in,out#>] <#name#> <#description#> - * - * @return <#value#> <#explanation#> - * - * Example: - * @code - * <#example#> - * @endcode - */ -static CommandOps *commandParser_MatchCommand(CommandParser *state, - PARCList *args) { - // Find the longest matching prefix command. - // Pretty wildly inefficient - - size_t longest_token_count = 0; - char *longest_command = NULL; - - PARCArrayList *commands = parcTreeRedBlack_Keys(state->commandTree); - for (int i = 0; i < parcArrayList_Size(commands); i++) { - char *command = parcArrayList_Get(commands, i); - PARCList *command_tokens = parseStringIntoTokens(command); - - // is it a prefix match? - if (parcList_Size(args) >= parcList_Size(command_tokens)) { - bool possible_match = true; - for (int i = 0; i < parcList_Size(command_tokens) && possible_match; - i++) { - const char *a = parcList_GetAtIndex(command_tokens, i); - const char *b = parcList_GetAtIndex(args, i); - if (strncasecmp(a, b, strlen(a) + 1) != 0) { - possible_match = false; - } - } - - if (possible_match && - parcList_Size(command_tokens) > longest_token_count) { - longest_token_count = parcList_Size(command_tokens); - longest_command = command; - } - } - - parcList_Release(&command_tokens); - } - - parcArrayList_Destroy(&commands); - - if (longest_token_count == 0) { - return NULL; - } else { - CommandOps *ops = parcTreeRedBlack_Get(state->commandTree, longest_command); - parcAssertNotNull(ops, "Got null operations for command '%s'\n", - longest_command); - return ops; - } -} - -CommandReturn commandParser_DispatchCommand(CommandParser *state, - PARCList *args, - char *output, - size_t output_size) { - parcAssertNotNull(output, "output buffer is null\n"); - CommandOps *ops = commandParser_MatchCommand(state, args); - - if (ops == NULL) { - snprintf(output, output_size, "Command not found.\n"); - return CommandReturn_Failure; - } else { - return ops->execute(state, ops, args, output, output_size); - } -} - -bool commandParser_ContainsCommand(CommandParser *parser, const char *command) { - CommandOps *ops = parcTreeRedBlack_Get(parser->commandTree, command); - return (ops != NULL); -} diff --git a/hicn-light/src/hicn/config/commandParser.h b/hicn-light/src/hicn/config/commandParser.h deleted file mode 100644 index 882d55d26..000000000 --- a/hicn-light/src/hicn/config/commandParser.h +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file command_Parser.h - * @brief Creates a dictionary of commands and parses a command_line to match - * against them - * - * A user creates individual CommandParserEntry that map a command_line to a - * function to execute. The CommandParser then does a longest-matching prefix - * match of a command_line to the dictionary of commands and executes the - * appropriate command. - * - */ - -#ifndef command_parser_h -#define command_parser_h - -#include <hicn/config/commandOps.h> -#include <hicn/config/commandReturn.h> - -struct command_parser; -typedef struct command_parser CommandParser; - -/** - * controlState_Create - * - * Creates the global state for the Control program - * - * @return non-null A command parser - * - * Example: - * @code - * <#example#> - * @endcode - */ -CommandParser *commandParser_Create(void); - -/** - * Destroys the control state, closing all network connections - * - * <#Paragraphs Of Explanation#> - * - * @param [<#in out in,out#>] <#name#> <#description#> - * - * @return <#value#> <#explanation#> - * - * Example: - * @code - * <#example#> - * @endcode - */ -void commandParser_Destroy(CommandParser **statePtr); - -/** - * Registers a CommandOps with the system. - * - * Each command has its complete command prefix in the "command" field. - * RegisterCommand will put these command prefixes in to a tree and then match - * what a user types against the longest-matching prefix in the tree. If - * there's a match, it will call the "execute" function. - * - * When the parser is destroyed, each command's destroyer function will be - * called. - * - * @param [in] state An allocated ControlState - * @param [in] command The command to register with the system - * - * Example: - * @code - * static ControlReturn - * control_Root_Execute(CommandParser *parser, CommandOps *ops, PARCList - * *args) - * { - * printf("Root Command\n"); - * return CommandReturn_Success; - * } - * - * static ControlReturn - * control_FooBar_Execute(CommandParser *parser, CommandOps *ops, PARCList - * *args) - * { - * printf("Foo Bar Command\n"); - * return CommandReturn_Success; - * } - * - * const CommandOps control_Root = { - * .closure = NULL, - * .command = "", // empty string for root - * .init = NULL, - * .execute = control_Root_Execute - * }; - * - * const CommandOps control_FooBar = { - * .closure = NULL, - * .command = "foo bar", // empty string for root - * .init = NULL, - * .execute = control_FooBar_Execute - * }; - * - * void startup(void) - * { - * ControlState *state = controlState_Create("happy", "day"); - * controlState_RegisterCommand(state, control_FooBar); - * controlState_RegisterCommand(state, control_Root); - * - * // this executes "root" - * controlState_DispatchCommand(state, "foo"); - * controlState_Destroy(&state); - * } - * @endcode - */ -void commandParser_RegisterCommand(CommandParser *state, CommandOps *command); - -/** - * Performs a longest-matching prefix of the args to the command tree - * - * The command tree is created with controlState_RegisterCommand. - * - * @param [in] state The allocated ControlState - * @param [in] args Each command_line word parsed to the ordered list - * @param [in] output The allocated output string, if null, the normal printf is executed - * @param [in] output_size the size of output array string. It is ignored if the output string is null - * - * @return CommandReturn_Success the command was successful - * @return CommandReturn_Failure the command failed or was not found - * @return CommandReturn_Exit the command indicates that the interactive mode - * should exit - * - * Example: - * @code - * <#example#> - * @endcode - */ -CommandReturn commandParser_DispatchCommand(CommandParser *state, - PARCList *args, - char *output, - size_t output_size); - -/** - * Sets the Debug mode, which will print out much more information. - * - * Prints out much more diagnostic information about what hicn-light controller - * is doing. yes, you would make a CommandOps to set and unset this :) - * - * @param [in] debugFlag true means to print debug info, false means to turn it - * off - * - * Example: - * @code - * <#example#> - * @endcode - */ -void commandParser_SetDebug(CommandParser *state, bool debugFlag); - -/** - * Returns the debug state of ControlState - * - * <#Paragraphs Of Explanation#> - * - * @param [<#in out in,out#>] <#name#> <#description#> - * - * @return <#value#> <#explanation#> - * - * Example: - * @code - * <#example#> - * @endcode - */ -bool commandParser_GetDebug(CommandParser *state); - -/** - * Checks if the command is registered - * - * Checks if the exact command given is registered. This is not a prefix match. - * - * @param [<#in out in,out#>] <#name#> <#description#> - * - * @return true The command is registered - * @return false The command is not registered - * - * Example: - * @code - * <#example#> - * @endcode - */ -bool commandParser_ContainsCommand(CommandParser *parser, const char *command); -#endif // command_parser_h diff --git a/hicn-light/src/hicn/config/commandReturn.h b/hicn-light/src/hicn/config/commandReturn.h deleted file mode 100644 index 16ee93db1..000000000 --- a/hicn-light/src/hicn/config/commandReturn.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file command_Return.h - * @brief The return code used by CLI commands - * - * This return code is used throughout the command parser and command - * implementations to indicate success, failure, or if the program should exit. - * - */ - -#ifndef command_return_h -#define command_return_h - -/** - * @typedef ControlReturn - * @abstract A command returns one of (SUCCESS, FAILURE, EXIT) - * @constant SUCCESS means the command succeeded - * @constant FAILURE indicates failure - * @constant EXIT means the command indicated that hicn-light controller should - * exit. - * @discussion <#Discussion#> - */ -typedef enum command_return { - CommandReturn_Success, // command returned success - CommandReturn_Failure, // command failure - CommandReturn_Exit // command indicates program should exit -} CommandReturn; - -#endif // command_return_h diff --git a/hicn-light/src/hicn/config/command_cache.c b/hicn-light/src/hicn/config/command_cache.c new file mode 100644 index 000000000..073221cf0 --- /dev/null +++ b/hicn-light/src/hicn/config/command_cache.c @@ -0,0 +1,54 @@ +#include <math.h> +#include "command.h" + +/* Parameters */ + +#define serve \ + { \ + .name = "serve", \ + .help = \ + "Enables/disables replies from local content store. Either the " \ + "string 'on' or 'off'", \ + .type = TYPE_ON_OFF, .offset = offsetof(hc_cache_t, serve), \ + } + +#define store \ + { \ + .name = "store", \ + .help = \ + "enables/disables the storage of incoming data packets in the local " \ + "content store. Either the string 'on' or 'off'", \ + .type = TYPE_ON_OFF, .offset = offsetof(hc_cache_t, store), \ + } + +/* Commands */ + +static const command_parser_t command_cache_set_serve = { + .action = ACTION_SERVE, + .object = OBJECT_CACHE, + .nparams = 1, + .parameters = {serve}, +}; +COMMAND_REGISTER(command_cache_set_serve); + +static const command_parser_t command_cache_set_store = { + .action = ACTION_STORE, + .object = OBJECT_CACHE, + .nparams = 1, + .parameters = {store}, +}; +COMMAND_REGISTER(command_cache_set_store); + +static const command_parser_t command_cache_clear = { + .action = ACTION_CLEAR, + .object = OBJECT_CACHE, + .nparams = 0, +}; +COMMAND_REGISTER(command_cache_clear); + +static const command_parser_t command_cache_list = { + .action = ACTION_LIST, + .object = OBJECT_CACHE, + .nparams = 0, +}; +COMMAND_REGISTER(command_cache_list); diff --git a/hicn-light/src/hicn/config/command_connection.c b/hicn-light/src/hicn/config/command_connection.c new file mode 100644 index 000000000..069bf55a6 --- /dev/null +++ b/hicn-light/src/hicn/config/command_connection.c @@ -0,0 +1,128 @@ +#include <math.h> +#include "command.h" + +/* Parameters */ + +#define type_hicn \ + { \ + .name = "type", .help = "connection type (hICN)", \ + .type = TYPE_ENUM(face_type), .offset = offsetof(hc_connection_t, type), \ + } + +#define type_tcp_udp \ + { \ + .name = "type", .help = "connection type [tcp | udp]", \ + .type = TYPE_ENUM(face_type), .offset = offsetof(hc_connection_t, type), \ + } + +#define symbolic \ + { \ + .name = "symbolic", \ + .help = "symbolic name, e.g. 'conn1' (must be unique, start with alpha)", \ + .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_connection_t, name), \ + } + +#define local_address \ + { \ + .name = "local_addr", .help = "local IP address on which to bind.", \ + .type = TYPE_IP_ADDRESS, .offset = offsetof(hc_connection_t, local_addr), \ + .offset2 = offsetof(hc_connection_t, family), \ + } + +#define local_port \ + { \ + .name = "local_port", .help = "Local port.", \ + .type = TYPE_INT(1, UINT16_MAX), \ + .offset = offsetof(hc_connection_t, local_port), \ + } + +#define remote_address \ + { \ + .name = "remote_address", \ + .help = "The IPv4 or IPv6 or hostname of the remote system.", \ + .type = TYPE_IP_ADDRESS, .offset = offsetof(hc_connection_t, remote_addr), \ + .offset2 = offsetof(hc_connection_t, family), \ + } + +#define remote_port \ + { \ + .name = "remote_port", .help = "Remote port.", \ + .type = TYPE_INT(1, UINT16_MAX), \ + .offset = offsetof(hc_connection_t, remote_port), \ + } + +#define interface \ + { \ + .name = "interface", .help = "Interface on which to bind", \ + .type = TYPE_INTERFACE_NAME, \ + .offset = offsetof(hc_connection_t, interface_name), \ + } + +#define symbolic_or_id \ + { \ + .name = "symbolic", .help = "The connection symbolic name or id", \ + .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_connection_t, name), \ + } + +/* Commands */ + +int on_connection_create(hc_connection_t* connection) { + connection->admin_state = FACE_STATE_UP; + return 0; +} + +#if 0 +static command_parser_t command_connection_create4 = { + .action = ACTION_CREATE, + .object = OBJECT_CONNECTION, + .nparams = 4, + .parameters = {type_hicn, symbolic, local_address, remote_address}, + .post_hook = (parser_hook_t)on_connection_create, +}; +COMMAND_REGISTER(command_connection_create4); + +static const command_parser_t command_connection_create5 = { + .action = ACTION_CREATE, + .object = OBJECT_CONNECTION, + .nparams = 5, + .parameters = {type_hicn, symbolic, local_address, remote_address, + interface}, + .post_hook = (parser_hook_t)on_connection_create, +}; +COMMAND_REGISTER(command_connection_create5); +#endif + +static const command_parser_t command_connection_create6 = { + .action = ACTION_CREATE, + .object = OBJECT_CONNECTION, + .nparams = 6, + .parameters = {type_tcp_udp, symbolic, remote_address, remote_port, + local_address, local_port}, + .post_hook = (parser_hook_t)on_connection_create, +}; +COMMAND_REGISTER(command_connection_create6); + +static const command_parser_t command_connection_create7 = { + .action = ACTION_CREATE, + .object = OBJECT_CONNECTION, + .nparams = 7, + .parameters = {type_tcp_udp, symbolic, remote_address, remote_port, + local_address, local_port, interface}, + .post_hook = (parser_hook_t)on_connection_create, +}; +COMMAND_REGISTER(command_connection_create7); + +static const command_parser_t command_connection_list = { + .action = ACTION_LIST, + .object = OBJECT_CONNECTION, + .nparams = 0, +}; +COMMAND_REGISTER(command_connection_list); + +static const command_parser_t command_connection_remove = { + .action = ACTION_DELETE, + .object = OBJECT_CONNECTION, + .nparams = 1, + .parameters = {symbolic_or_id}, +}; +COMMAND_REGISTER(command_connection_remove); diff --git a/hicn-light/src/hicn/config/command_face.c b/hicn-light/src/hicn/config/command_face.c new file mode 100644 index 000000000..95ec404f0 --- /dev/null +++ b/hicn-light/src/hicn/config/command_face.c @@ -0,0 +1,16 @@ +#if 0 +#include "command.h" + +/* Parameters */ + +/* Commands */ + +// XXX missing add + +static const command_parser_t command_face_list = { + .action = ACTION_LIST, + .object = OBJECT_FACE, + .nparams = 0, +}; +COMMAND_REGISTER(command_face_list); +#endif
\ No newline at end of file diff --git a/hicn-light/src/hicn/config/command_listener.c b/hicn-light/src/hicn/config/command_listener.c new file mode 100644 index 000000000..8ad7c94be --- /dev/null +++ b/hicn-light/src/hicn/config/command_listener.c @@ -0,0 +1,111 @@ +#include <math.h> +#include "command.h" + +/* Parameters */ + +#define protocol_hicn \ + { \ + .name = "protocol", .help = "Protocol [hicn].", \ + .type = TYPE_ENUM(face_type), .offset = offsetof(hc_listener_t, type), \ + } + +#define protocol_tcp_udp \ + { \ + .name = "protocol", .help = "Protocol [tcp | udp]", \ + .type = TYPE_ENUM(face_type), .offset = offsetof(hc_listener_t, type), \ + } + +#define symbolic \ + { \ + .name = "symbolic", \ + .help = \ + "User defined name for listener, must start with alpha and be " \ + "alphanum", \ + .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_listener_t, name), \ + } + +#define local_address \ + { \ + .name = "local_addr", \ + .help = \ + "IPv4 or IPv6 address (or prefix protocol = hicn) assigend to the " \ + "local interface", \ + .type = TYPE_IP_ADDRESS, .offset = offsetof(hc_listener_t, local_addr), \ + .offset2 = offsetof(hc_listener_t, family), \ + } + +#define local_port \ + { \ + .name = "local_port", .help = "Local port.", \ + .type = TYPE_INT(1, UINT16_MAX), \ + .offset = offsetof(hc_listener_t, local_port), \ + } + +#define interface \ + { \ + .name = "interface", .help = "Interface on which to bind", \ + .type = TYPE_INTERFACE_NAME, \ + .offset = offsetof(hc_listener_t, interface_name), \ + } + +#define symbolic_or_id \ + { \ + .name = "symbolic", .help = "The listener symbolic name or id", \ + .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_listener_t, name), \ + } + +/* Commands */ + +/* The parse sets the wrong face_type_t for listener, we fix that here */ +int on_listener_create(hc_listener_t* listener) { + switch (listener->type) { + case FACE_TYPE_UDP: + listener->type = FACE_TYPE_UDP_LISTENER; + break; + case FACE_TYPE_TCP: + listener->type = FACE_TYPE_TCP_LISTENER; + break; + case FACE_TYPE_HICN: + listener->type = FACE_TYPE_HICN_LISTENER; + break; + default: + break; + } + return 0; +} + +#if 0 +static const command_parser_t command_listener_create4 = { + .action = ACTION_CREATE, + .object = OBJECT_LISTENER, + .nparams = 4, + .parameters = {protocol_hicn, symbolic, local_address, interface}, + .post_hook = (parser_hook_t)on_listener_create, +}; +COMMAND_REGISTER(command_listener_create4); +#endif + +static const command_parser_t command_listener_create6 = { + .action = ACTION_CREATE, + .object = OBJECT_LISTENER, + .nparams = 5, + .parameters = {protocol_tcp_udp, symbolic, local_address, local_port, + interface}, + .post_hook = (parser_hook_t)on_listener_create, +}; +COMMAND_REGISTER(command_listener_create6); + +static const command_parser_t command_listener_list = { + .action = ACTION_LIST, + .object = OBJECT_LISTENER, + .nparams = 0, +}; +COMMAND_REGISTER(command_listener_list); + +static const command_parser_t command_listener_remove = { + .action = ACTION_DELETE, + .object = OBJECT_LISTENER, + .nparams = 1, + .parameters = {symbolic_or_id}, +}; +COMMAND_REGISTER(command_listener_remove); diff --git a/hicn-light/src/hicn/config/command_mapme.c b/hicn-light/src/hicn/config/command_mapme.c new file mode 100644 index 000000000..a22e8b340 --- /dev/null +++ b/hicn-light/src/hicn/config/command_mapme.c @@ -0,0 +1,59 @@ +#include <math.h> +#include "command.h" + +/* Parameters */ + +#define target \ + { \ + .name = "target", \ + .help = \ + "Target for the set action, e.g. enable, discovery, timescale, retx", \ + .type = TYPE_ENUM(mapme_target), .offset = offsetof(hc_mapme_t, target), \ + } + +#define value \ + { \ + .name = "value", \ + .help = "Value to set for the target, e.g. 'on', 'off', milliseconds", \ + .type = TYPE_STRN(4), .offset = offsetof(hc_mapme_t, unparsed_arg), \ + } + +#define prefix \ + { \ + .name = "prefix", \ + .help = "The hicn name as IPv4 or IPv6 address (e.g 1234::0/64).", \ + .type = TYPE_IP_PREFIX, .offset = offsetof(hc_mapme_t, address), \ + .offset2 = offsetof(hc_mapme_t, len), \ + .offset3 = offsetof(hc_mapme_t, family), \ + } + +/* Commands */ + +// Parse the raw string argument into 'timescale' or 'enabled', +// necessary since the command dispatch is based on the number +// of arguments and not their type +int parse_args(hc_mapme_t* mapme) { + mapme->timescale = atoi(mapme->unparsed_arg); + + if (strcasecmp(mapme->unparsed_arg, "off") == 0) mapme->enabled = 0; + if (strcasecmp(mapme->unparsed_arg, "on") == 0) mapme->enabled = 1; + + return 0; +} + +static const command_parser_t command_mapme_set = { + .action = ACTION_SET, + .object = OBJECT_MAPME, + .nparams = 2, + .parameters = {target, value}, + .post_hook = (parser_hook_t)parse_args, +}; +COMMAND_REGISTER(command_mapme_set); + +static const command_parser_t command_mapme_update = { + .action = ACTION_UPDATE, + .object = OBJECT_MAPME, + .nparams = 1, + .parameters = {prefix}, +}; +COMMAND_REGISTER(command_mapme_update);
\ No newline at end of file diff --git a/hicn-light/src/hicn/config/command_policy.c b/hicn-light/src/hicn/config/command_policy.c new file mode 100644 index 000000000..1e802c3f5 --- /dev/null +++ b/hicn-light/src/hicn/config/command_policy.c @@ -0,0 +1,52 @@ +#if 0 +#include <hicn/policy.h> + +#include "command.h" + +/* Parameters */ + +#define prefix \ + { \ + .name = "prefix", \ + .help = "The hicn name as IPv4 or IPv6 address (e.g 1234::0/64).", \ + .type = TYPE_IP_PREFIX, .offset = offsetof(hc_policy_t, remote_addr), \ + .offset2 = offsetof(hc_policy_t, len), \ + .offset3 = offsetof(hc_policy_t, family), \ + } + +#define app_name \ + { \ + .name = "app_name", \ + .help = "The application name associated to this policy", \ + .type = TYPE_STR, .offset = offsetof(hc_policy_t, policy.app_name), \ + } + +/* Commands */ + +static const command_parser_t command_policy_create = { + .action = ACTION_CREATE, + .object = OBJECT_POLICY, + .nparams = 2 + POLICY_TAG_N, + .parameters = {prefix, app_name, +#define _(x, y) \ + { \ + .name = "flag:" #x, \ + .help = \ + "A value among [neutral|require|prefer|avoid|prohibit] with an " \ + "optional '!' character prefix for disabling changes", \ + .type = TYPE_POLICY_STATE(POLICY_TAG_##x), \ + .offset = offsetof(hc_policy_t, policy.tags), \ + }, + foreach_policy_tag +#undef _ + }, +}; +COMMAND_REGISTER(command_policy_create); + +static const command_parser_t command_policy_list = { + .action = ACTION_LIST, + .object = OBJECT_POLICY, + .nparams = 0, +}; +COMMAND_REGISTER(command_policy_list); +#endif
\ No newline at end of file diff --git a/hicn-light/src/hicn/config/command_punting.c b/hicn-light/src/hicn/config/command_punting.c new file mode 100644 index 000000000..8c7a6dec3 --- /dev/null +++ b/hicn-light/src/hicn/config/command_punting.c @@ -0,0 +1,40 @@ +#if 0 +#include "command.h" + +/* Parameters */ + +#define symbolic_or_id \ + { \ + .name = "symbolic_or_id", \ + .help = \ + "The symbolic name for an egress, or the egress punting id (see " \ + "'help list puntings')", \ + .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_punting_t, face_id), \ + } + +#define prefix \ + { \ + .name = "prefix", \ + .help = "Prefix to add as a punting rule. (example 1234::0/64)", \ + .type = TYPE_IP_PREFIX, .offset = offsetof(hc_punting_t, prefix), \ + .offset2 = offsetof(hc_punting_t, prefix_len), \ + .offset3 = offsetof(hc_punting_t, family), \ + } + +/* Commands */ + +static const command_parser_t command_punting_create = { + .action = ACTION_CREATE, + .object = OBJECT_PUNTING, + .nparams = 2, + .parameters = {symbolic_or_id, prefix}, +}; +COMMAND_REGISTER(command_punting_create); + +static const command_parser_t command_punting_list = { + .action = ACTION_LIST, + .object = OBJECT_PUNTING, + .nparams = 0, +}; +COMMAND_REGISTER(command_punting_list); +#endif
\ No newline at end of file diff --git a/hicn-light/src/hicn/config/command_route.c b/hicn-light/src/hicn/config/command_route.c new file mode 100644 index 000000000..dfbea101f --- /dev/null +++ b/hicn-light/src/hicn/config/command_route.c @@ -0,0 +1,53 @@ +#include <math.h> +#include "command.h" + +/* Parameters */ + +#define symbolic_or_id \ + { \ + .name = "symbolic_or_id", \ + .help = \ + "The symbolic name for an egress, or the egress route id (see 'help " \ + "list routes')", \ + .type = TYPE_SYMBOLIC_OR_ID, .offset = offsetof(hc_route_t, name), \ + } + +#define prefix \ + { \ + .name = "prefix", \ + .help = "The hicn name as IPv4 or IPv6 address (e.g 1234::0/64).", \ + .type = TYPE_IP_PREFIX, .offset = offsetof(hc_route_t, remote_addr), \ + .offset2 = offsetof(hc_route_t, len), \ + .offset3 = offsetof(hc_route_t, family), \ + } + +#define cost \ + { \ + .name = "cost", .help = "Positive integer representing cost.", \ + .type = TYPE_INT(1, 255), .offset = offsetof(hc_route_t, cost), \ + } + +/* Commands */ + +static const command_parser_t command_route_create = { + .action = ACTION_CREATE, + .object = OBJECT_ROUTE, + .nparams = 3, + .parameters = {symbolic_or_id, prefix, cost}, +}; +COMMAND_REGISTER(command_route_create); + +static const command_parser_t command_route_list = { + .action = ACTION_LIST, + .object = OBJECT_ROUTE, + .nparams = 0, +}; +COMMAND_REGISTER(command_route_list); + +static const command_parser_t command_route_remove = { + .action = ACTION_DELETE, + .object = OBJECT_ROUTE, + .nparams = 2, + .parameters = {symbolic_or_id, prefix}, +}; +COMMAND_REGISTER(command_route_remove); diff --git a/hicn-light/src/hicn/config/command_strategy.c b/hicn-light/src/hicn/config/command_strategy.c new file mode 100644 index 000000000..2341ac830 --- /dev/null +++ b/hicn-light/src/hicn/config/command_strategy.c @@ -0,0 +1,47 @@ +#include "command.h" + +/* Parameters */ +#define prefix \ + { \ + .name = "prefix", \ + .help = "The hicn name as IPv4 or IPv6 address (e.g 1234::0/64).", \ + .type = TYPE_IP_PREFIX, .offset = offsetof(hc_strategy_t, address), \ + .offset2 = offsetof(hc_strategy_t, len), \ + .offset3 = offsetof(hc_strategy_t, family), \ + } + +#define strategy \ + { \ + .name = "strategy", \ + .help = \ + "Strategy type (e.g. 'random', 'loadbalancer', 'low_latency', " \ + "'replication', 'bestpath').", \ + .type = TYPE_ENUM(strategy_type), .offset = offsetof(hc_strategy_t, type), \ + } + +#define local_prefix \ + { \ + .name = "local_prefix", \ + .help = "The hicn name as IPv4 or IPv6 address (e.g 1234::0/64).", \ + .type = TYPE_IP_PREFIX, .offset = offsetof(hc_strategy_t, local_address), \ + .offset2 = offsetof(hc_strategy_t, local_len), \ + .offset3 = offsetof(hc_strategy_t, local_family), \ + } + +/* Commands */ + +static const command_parser_t command_strategy_list = { + .action = ACTION_SET, + .object = OBJECT_STRATEGY, + .nparams = 2, + .parameters = {prefix, strategy}, +}; +COMMAND_REGISTER(command_strategy_list); + +static const command_parser_t local_prefix_add = { + .action = ACTION_CREATE, + .object = OBJECT_LOCAL_PREFIX, + .nparams = 3, + .parameters = {prefix, strategy, local_prefix}, +}; +COMMAND_REGISTER(local_prefix_add); diff --git a/hicn-light/src/hicn/config/command_subscription.c b/hicn-light/src/hicn/config/command_subscription.c new file mode 100644 index 000000000..89e3dcd98 --- /dev/null +++ b/hicn-light/src/hicn/config/command_subscription.c @@ -0,0 +1,23 @@ +#include "command.h" + +/* Parameters */ + +#define topics \ + { \ + .name = "topics", \ + .help = \ + "Topics to subscribe to, e.g. 6 (110 in binary) means topic 2 (10 in " \ + "binary, TOPIC_CONNECTION) and topic 4 (100 in binary, " \ + "TOPIC_LISTENER).", \ + .type = TYPE_INT(1, 255), .offset = offsetof(hc_subscription_t, topics), \ + } + +/* Commands */ + +static const command_parser_t command_subscription_create = { + .action = ACTION_CREATE, + .object = OBJECT_SUBSCRIPTION, + .nparams = 1, + .parameters = {topics}, +}; +COMMAND_REGISTER(command_subscription_create);
\ No newline at end of file diff --git a/hicn-light/src/hicn/config/commands.c b/hicn-light/src/hicn/config/commands.c new file mode 100644 index 000000000..e99e0b8f5 --- /dev/null +++ b/hicn-light/src/hicn/config/commands.c @@ -0,0 +1,1530 @@ +/* + * Copyright (c) 2021 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * + * Example: + * @code + * <#example#> + * @endcode + */ + +#ifndef _WIN32 +#include <arpa/inet.h> +#include <unistd.h> +#endif +#include <ctype.h> +#include <hicn/hicn-light/config.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include <hicn/core/connection.h> +#include <hicn/core/connection_table.h> +#include <hicn/core/forwarder.h> +//#include <hicn/core/system.h> +#ifdef WITH_MAPME +#include <hicn/core/mapme.h> +#endif /* WITH_MAPME */ + +#include <hicn/core/listener.h> //the listener list +#include <hicn/core/listener_table.h> +#include <hicn/core/subscription.h> +#include <hicn/ctrl/hicn-light-ng.h> +#include <hicn/utils/punting.h> +#include <hicn/util/log.h> +#include <hicn/validation.h> +#include <hicn/face.h> + +#include "commands.h" +#include "configuration.h" + +#define ETHERTYPE 0x0801 +#define DEFAULT_COST 1 +#define DEFAULT_PORT 1234 + +#define make_ack(msg) ((msg_header_t *)msg)->header.message_type = ACK_LIGHT +#define make_nack(msg) ((msg_header_t *)msg)->header.message_type = NACK_LIGHT + +#define msg_malloc_list(msg, COMMAND_ID, N, seq_number) \ + do { \ + msg = calloc(1, sizeof((msg)->header) + N * sizeof((msg)->payload)); \ + (msg)->header.message_type = RESPONSE_LIGHT; \ + (msg)->header.command_id = (COMMAND_ID); \ + (msg)->header.length = (uint16_t)(N); \ + (msg)->header.seq_num = (seq_number); \ + } while (0); + +// conn_id = UINT_MAX when symbolic_name is not found +static inline unsigned _symbolic_to_conn_id(forwarder_t *forwarder, + const char *symbolic_or_connid, + bool allow_self, + unsigned ingress_id) { + unsigned conn_id; + const connection_table_t *table = forwarder_get_connection_table(forwarder); + + if (allow_self && strcmp(symbolic_or_connid, "SELF") == 0) { + conn_id = ingress_id; + } else if (is_number(symbolic_or_connid, SYMBOLIC_NAME_LEN)) { + // case for conn_id as input + // XXX type issue ! XXX No check, see man + unsigned id = atoi(symbolic_or_connid); + if (id < 0) return CONNECTION_ID_UNDEFINED; + conn_id = id; + + if (!connection_table_validate_id(table, conn_id)) { + ERROR("ConnID not found, check list connections"); + conn_id = CONNECTION_ID_UNDEFINED; + } + } else { + // case for symbolic as input: check if symbolic name can be resolved + conn_id = connection_table_get_id_by_name(table, symbolic_or_connid); + if (connection_id_is_valid(conn_id)) { + DEBUG("Resolved symbolic name '%s' to conn_id %u", symbolic_or_connid, + conn_id); + } else { + WARN("Symbolic name '%s' could not be resolved", symbolic_or_connid); + } + } + + return conn_id; +} + +#define symbolic_to_conn_id(forwarder, symbolic) \ + _symbolic_to_conn_id(forwarder, symbolic, false, 0) + +#define symbolic_to_conn_id_self(forwarder, symbolic, ingress_id) \ + _symbolic_to_conn_id(forwarder, symbolic, true, ingress_id) + +connection_t *getConnectionBySymbolicOrId(forwarder_t *forwarder, + const char *symbolic_or_connid) { + connection_table_t *table = forwarder_get_connection_table(forwarder); + unsigned conn_id = symbolic_to_conn_id(forwarder, symbolic_or_connid); + if (!connection_id_is_valid(conn_id)) return NULL; + + /* conn_id is assumed validated here */ + return connection_table_at(table, conn_id); +} + +/* Listener */ + +uint8_t *configuration_on_listener_add(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: listener add (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_listener_add_t *msg = (msg_listener_add_t *)packet; + cmd_listener_add_t *control = &msg->payload; + + switch (control->type) { + case FACE_TYPE_UDP_LISTENER: + case FACE_TYPE_TCP_LISTENER: + case FACE_TYPE_HICN_LISTENER: + break; + default: + goto NACK; + } + + listener_table_t *table = forwarder_get_listener_table(forwarder); + assert(table); + + /* Verify that the listener DOES NOT exist */ + listener_t *listener = listener_table_get_by_name(table, control->symbolic); + if (listener) { + ERROR("Listener with name=%s already exists", control->symbolic); + goto NACK; + } + + address_t address; + if (address_from_ip_port(&address, control->family, &control->address, + control->port) < 0) { + WARN( + "Unsupported address type for HICN (ingress id %u): " + "must be either IPV4 or IPV6", + ingress_id); + goto NACK; + } + + if (!face_type_is_defined(control->type)) { + WARN("[configuration_on_listener_add] Invalid listener type"); + goto NACK; + } + + listener = listener_table_get_by_address(table, control->type, &address); + if (listener) { + char addr_str[NI_MAXHOST]; + int port; + address_to_string(&address, addr_str, &port); + ERROR("Listener for address=%s, type=%s already exists", addr_str, + face_type_str(control->type)); + goto NACK; + } + + // NOTE: interface_name is expected NULL for hICN listener + + listener = listener_create(control->type, &address, control->interface_name, + control->symbolic, forwarder); + if (!listener) goto NACK; + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +unsigned symbolic_to_listener_id(forwarder_t *forwarder, + const char *symbolic_or_listener_id) { + unsigned listener_id; + const listener_table_t *table = forwarder_get_listener_table(forwarder); + + if (is_number(symbolic_or_listener_id, SYMBOLIC_NAME_LEN)) { + // XXX type issue ! XXX No check, see man + unsigned id = atoi(symbolic_or_listener_id); + if (id < 0) return LISTENER_ID_UNDEFINED; + listener_id = id; + + if (!listener_table_validate_id(table, listener_id)) { + ERROR("Listener ID %d not found", id); + listener_id = LISTENER_ID_UNDEFINED; + } + } else { + // case for symbolic as input: check if symbolic name can be resolved + listener_id = listener_table_get_id_by_name(table, symbolic_or_listener_id); + if (listener_id_is_valid(listener_id)) { + DEBUG("Resolved symbolic name '%s' to conn_id %u", + symbolic_or_listener_id, listener_id); + } else { + WARN("Symbolic name '%s' could not be resolved", symbolic_or_listener_id); + } + } + + return listener_id; +} + +uint8_t *configuration_on_listener_remove(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: listener remove (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_listener_remove_t *msg = (msg_listener_remove_t *)packet; + cmd_listener_remove_t *control = &msg->payload; + + unsigned listener_id = + symbolic_to_listener_id(forwarder, control->symbolicOrListenerid); + if (!listener_id_is_valid(listener_id)) { + ERROR("Invalid listener id=%u", listener_id); + goto NACK; + } + + listener_table_t *listener_table = forwarder_get_listener_table(forwarder); + listener_t *listener = listener_table_get_by_id(listener_table, listener_id); + if (!listener) { + ERROR("Listener ID not found, check list listeners"); + goto NACK; + } + + // Do not remove listener if it is the one curretly used to send the command + connection_table_t *conn_table = forwarder_get_connection_table(forwarder); + connection_t *curr_connection = + connection_table_get_by_id(conn_table, ingress_id); + const address_pair_t *pair = connection_get_pair(curr_connection); + if (address_equals(listener_get_address(listener), + address_pair_get_local(pair))) { + ERROR("Cannot remove current listener"); + goto NACK; + } + + connection_table_t *table = forwarder_get_connection_table(forwarder); + connection_t *connection; + connection_table_foreach(table, connection, { + const address_pair_t *pair = connection_get_pair(connection); + if (!address_equals(listener_get_address(listener), + address_pair_get_local(pair))) + continue; + + unsigned conn_id = connection_table_get_connection_id(table, connection); + /* Remove connection from the FIB */ + forwarder_remove_connection_id_from_routes(forwarder, conn_id); + + /* Remove connection */ + connection_table_remove_by_id(table, conn_id); + }); + + /* Remove listener */ + listener_table_remove_by_id(listener_table, listener_id); + listener_finalize(listener); + WITH_DEBUG(listener_table_print_by_key(listener_table);) + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +// TODO(eloparco): Unused forwarder param +static inline void fill_listener_command(forwarder_t *forwarder, + listener_t *listener, + cmd_listener_list_item_t *cmd) { + assert(forwarder); + assert(listener); + assert(cmd); + + struct sockaddr_in *sin; + struct sockaddr_in6 *sin6; + + const address_t *addr = listener_get_address(listener); + + cmd->id = (uint32_t)listener_get_id(listener); + cmd->type = (uint8_t)listener_get_type(listener); + + switch (addr->as_ss.ss_family) { + case AF_INET: + sin = (struct sockaddr_in *)addr; + cmd->family = AF_INET; + cmd->address.v4.as_inaddr = sin->sin_addr; + cmd->port = sin->sin_port; + break; + case AF_INET6: + sin6 = (struct sockaddr_in6 *)addr; + cmd->family = AF_INET6; + cmd->address.v6.as_in6addr = sin6->sin6_addr; + cmd->port = sin6->sin6_port; + break; + default: + break; + } + + const char *name = listener_get_name(listener); + snprintf(cmd->name, SYMBOLIC_NAME_LEN, "%s", name); + const char *interface_name = listener_get_interface_name(listener); + snprintf(cmd->interface_name, SYMBOLIC_NAME_LEN, "%s", interface_name); +} + +uint8_t *configuration_on_listener_list(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: listener list (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + listener_table_t *table = forwarder_get_listener_table(forwarder); + size_t n = listener_table_len(table); + msg_listener_list_t *msg_received = (msg_listener_list_t *)packet; + uint8_t command_id = msg_received->header.command_id; + uint32_t seq_num = msg_received->header.seq_num; + + msg_listener_list_reply_t *msg; + msg_malloc_list(msg, command_id, n, seq_num) if (!msg) goto NACK; + + cmd_listener_list_item_t *payload = &msg->payload; + listener_t *listener; + listener_table_foreach(table, listener, { + fill_listener_command(forwarder, listener, payload); + payload++; + }); + + *reply_size = sizeof(msg->header) + n * sizeof(msg->payload); + return (uint8_t *)msg; + +NACK: + *reply_size = sizeof(msg_header_t); + make_nack(msg); + return (uint8_t *)msg; +} + +/* Connection */ + +uint8_t *configuration_on_connection_add(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: connection add (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_connection_add_t *msg = (msg_connection_add_t *)packet; + cmd_connection_add_t *control = &msg->payload; + + switch (control->type) { + case FACE_TYPE_UDP: + case FACE_TYPE_TCP: + case FACE_TYPE_HICN: + break; + default: + goto NACK; + } + + const char *symbolic_name = control->symbolic; + + if (!face_type_is_defined(control->type)) goto NACK; + + connection_table_t *table = forwarder_get_connection_table(forwarder); + if (connection_table_get_by_name(table, symbolic_name)) { + ERROR("Connection symbolic name already exists"); + goto NACK; + } + + address_pair_t pair; + if (address_pair_from_ip_port(&pair, control->family, &control->local_ip, + control->local_port, &control->remote_ip, + control->remote_port) < 0) + goto NACK; + + connection_t *connection = connection_table_get_by_pair(table, &pair); +#ifdef WITH_MAPME + connection_event_t event; +#endif /* WITH_MAPME */ + + if (!connection) { + connection = + connection_create(control->type, symbolic_name, &pair, forwarder); + if (!connection) { + ERROR("Failed to create %s connection", face_type_str(control->type)); + goto NACK; + } + +#ifdef WITH_MAPME + event = CONNECTION_EVENT_CREATE; +#endif /* WITH_MAPME */ + } else { + WARN("Connection already exists"); + +#ifdef WITH_MAPME + event = CONNECTION_EVENT_UPDATE; +#endif /* WITH_MAPME */ + } + +#ifdef WITH_POLICY + connection_set_tags(connection, control->tags); + connection_set_priority(connection, control->priority); +#endif /* WITH_POLICY */ + + connection_set_admin_state(connection, control->admin_state); + +#ifdef WITH_MAPME + /* Hook: new connection created through the control protocol */ + forwarder_on_connection_event(forwarder, connection, event); +#endif /* WITH_MAPME */ + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +/** + * Add an IP-based tunnel. + * + * The call can fail if the symbolic name is a duplicate. It could also fail if + * there's an problem creating the local side of the tunnel (i.e. the local + * socket address is not usable). + * + * @return true Tunnel added + * @return false Tunnel not added (an error) + */ + +uint8_t *configuration_on_connection_remove(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: connection remove (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_connection_remove_t *msg = (msg_connection_remove_t *)packet; + cmd_connection_remove_t *control = &msg->payload; + + unsigned conn_id = symbolic_to_conn_id_self( + forwarder, control->symbolic_or_connid, ingress_id); + if (!connection_id_is_valid(conn_id)) { + ERROR("Invalid connection id=%u", conn_id); + goto NACK; + } + + if (strcmp(control->symbolic_or_connid, "SELF") != 0 && + conn_id == ingress_id) { + ERROR("Cannot remove current connection"); + goto NACK; + } + + /* Remove connection from the FIB */ + forwarder_remove_connection_id_from_routes(forwarder, conn_id); + + /* Remove connection */ + connection_table_t *table = forwarder_get_connection_table(forwarder); + connection_t *connection = connection_table_get_by_id(table, conn_id); + connection_table_remove_by_id(table, conn_id); + + // Don't close the fd for SELF otherwise it won't be possible + // to send the reply back + if (strcmp(control->symbolic_or_connid, "SELF") != 0) + connection_finalize(connection); + WITH_DEBUG(connection_table_print_by_pair(table);) + +#ifdef WITH_MAPME + /* Hook: new connection created through the control protocol */ + forwarder_on_connection_event(forwarder, NULL, CONNECTION_EVENT_DELETE); +#endif /* WITH_MAPME */ + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +static inline void tolower_str(char *str) { + char *p = str; + for (; *p; p++) *p = tolower(*p); +} + +// TODO(eloparco): Forwarder param not used +static inline void fill_connections_command(forwarder_t *forwarder, + connection_t *connection, + cmd_connection_list_item_t *cmd) { + assert(forwarder); + assert(connection); + assert(cmd); + + struct sockaddr_in *sin; + struct sockaddr_in6 *sin6; + const address_pair_t *pair = connection_get_pair(connection); + + cmd->id = connection_get_id(connection), + cmd->state = connection_get_state(connection), + cmd->admin_state = connection_get_admin_state(connection), + cmd->type = connection_get_type(connection), +#ifdef WITH_POLICY + cmd->priority = connection_get_priority(connection), + cmd->tags = connection_get_tags(connection), +#endif /* WITH_POLICY */ + + snprintf(cmd->name, SYMBOLIC_NAME_LEN, "%s", connection_get_name(connection)); + tolower_str(cmd->name); + + snprintf(cmd->interface_name, SYMBOLIC_NAME_LEN, "%s", + connection_get_interface_name(connection)); + + switch (pair->local.as_ss.ss_family) { + case AF_INET: + cmd->family = AF_INET; + + sin = (struct sockaddr_in *)(&pair->local); + cmd->local_port = sin->sin_port; + cmd->local_addr.v4.as_inaddr = sin->sin_addr; + + sin = (struct sockaddr_in *)(&pair->remote); + cmd->remote_port = sin->sin_port; + cmd->remote_addr.v4.as_inaddr = sin->sin_addr; + break; + + case AF_INET6: + cmd->family = AF_INET6; + + sin6 = (struct sockaddr_in6 *)(&pair->local); + cmd->local_port = sin6->sin6_port; + cmd->local_addr.v6.as_in6addr = sin6->sin6_addr; + + sin6 = (struct sockaddr_in6 *)(&pair->remote); + cmd->remote_port = sin6->sin6_port; + cmd->remote_addr.v6.as_in6addr = sin6->sin6_addr; + break; + + default: + break; + } +} + +uint8_t *configuration_on_connection_list(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: connection list (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + connection_table_t *table = forwarder_get_connection_table(forwarder); + // -1 since current connection (i.e. the one used to send + // the command) is not considered + size_t n = connection_table_len(table) - 1; + msg_connection_list_t *msg_received = (msg_connection_list_t *)packet; + uint8_t command_id = msg_received->header.command_id; + uint32_t seq_num = msg_received->header.seq_num; + + msg_connection_list_reply_t *msg; + msg_malloc_list(msg, command_id, n, seq_num) if (!msg) goto NACK; + + cmd_connection_list_item_t *payload = &msg->payload; + connection_t *connection; + connection_table_foreach(table, connection, { + if (connection->id == ingress_id) continue; + fill_connections_command(forwarder, connection, payload); + payload++; + }); + + *reply_size = sizeof(msg->header) + n * sizeof(msg->payload); + return (uint8_t *)msg; + +NACK: + *reply_size = sizeof(msg_header_t); + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_connection_set_admin_state(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + assert(forwarder); + assert(packet); + + msg_connection_set_admin_state_t *msg = + (msg_connection_set_admin_state_t *)packet; + cmd_connection_set_admin_state_t *control = &msg->payload; + + if ((control->admin_state != FACE_STATE_UP) && + (control->admin_state != FACE_STATE_DOWN)) + goto NACK; + + connection_t *conn = + getConnectionBySymbolicOrId(forwarder, control->symbolic_or_connid); + if (!conn) goto NACK; + + connection_set_admin_state(conn, control->admin_state); + +#ifdef WITH_MAPME + /* Hook: connection event */ + forwarder_on_connection_event(forwarder, conn, + control->admin_state == FACE_STATE_UP + ? CONNECTION_EVENT_SET_UP + : CONNECTION_EVENT_SET_DOWN); +#endif /* WITH_MAPME */ + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_connection_update(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + assert(forwarder); + assert(packet); + +#ifdef WITH_POLICY + msg_connection_update_t *msg = (msg_connection_update_t *)packet; + cmd_connection_update_t *control = &msg->payload; + + connection_t *conn = + getConnectionBySymbolicOrId(forwarder, control->symbolic_or_connid); + if (!conn) goto NACK; + + connection_set_tags(conn, control->tags); + connection_set_admin_state(conn, control->admin_state); + if (control->priority > 0) connection_set_priority(conn, control->priority); + + make_ack(msg); + return (uint8_t *)msg; + +NACK: +#endif /* WITH_POLICY */ + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_connection_set_priority(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + assert(forwarder); + assert(packet); + +#ifdef WITH_POLICY + msg_connection_set_priority_t *msg = (msg_connection_set_priority_t *)packet; + cmd_connection_set_priority_t *control = &msg->payload; + + connection_t *conn = + getConnectionBySymbolicOrId(forwarder, control->symbolic_or_connid); + if (!conn) goto NACK; + + connection_set_priority(conn, control->priority); + +#ifdef WITH_MAPME + /* Hook: connection event */ + forwarder_on_connection_event(forwarder, conn, + CONNECTION_EVENT_PRIORITY_CHANGED); +#endif /* WITH_MAPME */ + + make_ack(msg); + return (uint8_t *)msg; + +NACK: +#endif /* WITH_POLICY */ + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_connection_set_tags(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + assert(forwarder); + assert(packet); + +#ifdef WITH_POLICY + msg_connection_set_tags_t *msg = (msg_connection_set_tags_t *)packet; + cmd_connection_set_tags_t *control = &msg->payload; + + connection_t *conn = + getConnectionBySymbolicOrId(forwarder, control->symbolic_or_connid); + if (!conn) goto NACK; + + connection_set_tags(conn, control->tags); + +#ifdef WITH_MAPME + /* Hook: connection event */ + forwarder_on_connection_event(forwarder, conn, CONNECTION_EVENT_TAGS_CHANGED); +#endif /* WITH_MAPME */ + + make_ack(msg); + return (uint8_t *)msg; + +NACK: +#endif /* WITH_POLICY */ + make_nack(msg); + return (uint8_t *)msg; +} + +/* Route */ + +uint8_t *configuration_on_route_add(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size) { + INFO("CMD: route add (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_route_add_t *msg = (msg_route_add_t *)packet; + cmd_route_add_t *control = &msg->payload; + + unsigned conn_id = symbolic_to_conn_id_self( + forwarder, control->symbolic_or_connid, ingress_id); + if (!connection_id_is_valid(conn_id)) goto NACK; + + ip_prefix_t prefix = {.family = control->family, + .address = control->address, + .len = control->len}; + + if (!forwarder_add_or_update_route(forwarder, &prefix, conn_id)) goto NACK; + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_route_remove(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: route remove (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_route_remove_t *msg = (msg_route_remove_t *)packet; + cmd_route_remove_t *control = &msg->payload; + + unsigned conn_id = + symbolic_to_conn_id(forwarder, control->symbolic_or_connid); + if (!connection_id_is_valid(conn_id)) goto NACK; + + ip_prefix_t prefix = {.family = control->family, + .address = control->address, + .len = control->len}; + + if (!forwarder_remove_route(forwarder, &prefix, conn_id)) goto NACK; + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_route_list(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size) { + INFO("CMD: route list (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + msg_route_list_t *msg_received = (msg_route_list_t *)packet; + uint8_t command_id = msg_received->header.command_id; + uint32_t seq_num = msg_received->header.seq_num; + const fib_t *fib = forwarder_get_fib(forwarder); + fib_entry_t *entry; + + /* + * Two step approach to precompute the number of entries to allocate + * + * NOTE: we might have routes with no or multiple next hops. + */ + size_t n = 0; + fib_foreach_entry(fib, entry, { + const nexthops_t *nexthops = fib_entry_get_nexthops(entry); + assert(nexthops_get_len(nexthops) == nexthops_get_curlen(nexthops)); + n += nexthops_get_len(nexthops); + }); + + msg_route_list_reply_t *msg; + msg_malloc_list(msg, command_id, n, seq_num); + if (!msg) goto NACK; + + cmd_route_list_item_t *payload = &msg->payload; + fib_foreach_entry(fib, entry, { + const nexthops_t *nexthops = fib_entry_get_nexthops(entry); + assert(nexthops_get_len(nexthops) == nexthops_get_curlen(nexthops)); + size_t num_nexthops = nexthops_get_len(nexthops); + + if (num_nexthops == 0) continue; + + NameBitvector *prefix = name_GetContentName(fib_entry_get_prefix(entry)); + + unsigned nexthop; + nexthops_foreach(nexthops, nexthop, { + address_t address; + nameBitvector_ToAddress(prefix, &address); + switch (address_family(&address)) { + case AF_INET: + payload->family = AF_INET; + payload->address.v4.as_inaddr = address4_ip(&address); + break; + case AF_INET6: + payload->family = AF_INET6; + payload->address.v6.as_in6addr = address6_ip(&address); + break; + default: + break; + } + payload->connection_id = nexthop; + payload->len = nameBitvector_GetLength(prefix); + payload->cost = DEFAULT_COST; + + payload++; + }); + }); + + *reply_size = sizeof(msg->header) + n * sizeof(msg->payload); + return (uint8_t *)msg; + +NACK: + *reply_size = sizeof(msg_header_t); + make_nack(msg); + return (uint8_t *)msg; +} + +/* Cache */ + +uint8_t *configuration_on_cache_set_store(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: cache set store (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_cache_set_store_t *msg = (msg_cache_set_store_t *)packet; + cmd_cache_set_store_t *control = &msg->payload; + + if ((control->activate != 0) && (control->activate != 1)) goto NACK; + bool value = (bool)control->activate; + + forwarder_cs_set_store(forwarder, value); + assert(forwarder_cs_get_store(forwarder) == value); + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_cache_set_serve(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: cache set serve (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_cache_set_serve_t *msg = (msg_cache_set_serve_t *)packet; + cmd_cache_set_serve_t *control = &msg->payload; + + if ((control->activate != 0) && (control->activate != 1)) goto NACK; + bool value = (bool)control->activate; + + forwarder_cs_set_serve(forwarder, value); + assert(forwarder_cs_get_serve(forwarder) == value); + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_cache_clear(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size) { + INFO("CMD: cache clear (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_cache_clear_t *msg = (msg_cache_clear_t *)packet; + + forwarder_cs_clear(forwarder); + + make_ack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_cache_list(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size) { + INFO("CMD: cache list (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + msg_cache_list_t *msg_received = (msg_cache_list_t *)packet; + uint32_t seq_num = msg_received->header.seq_num; + + msg_cache_list_reply_t *msg = malloc(sizeof(*msg)); + *msg = (msg_cache_list_reply_t){ + .header = {.message_type = RESPONSE_LIGHT, + .length = 1, + .seq_num = seq_num}, + .payload = { + .store_in_cs = forwarder_cs_get_store(forwarder), + .serve_from_cs = forwarder_cs_get_serve(forwarder), + .cs_size = forwarder_cs_get_size(forwarder), + .num_stale_entries = forwarder_cs_get_num_stale_entries(forwarder)}}; + + *reply_size = sizeof(*msg); + return (uint8_t *)msg; +} + +/* Strategy */ + +uint8_t *configuration_on_strategy_set(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: strategy set (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_strategy_set_t *msg = (msg_strategy_set_t *)packet; + cmd_strategy_set_t *control = &msg->payload; + + char prefix_s[MAXSZ_IP_PREFIX]; + ip_prefix_t prefix = { + .family = control->family, + .address = control->address, + .len = control->len, + }; + int rc = ip_prefix_snprintf(prefix_s, MAXSZ_IP_PREFIX, &prefix); + assert(rc < MAXSZ_IP_PREFIX); + if (rc < 0) goto NACK; + + strategy_type_t strategy = control->type; + configuration_t *config = forwarder_get_configuration(forwarder); + strategy_type_t existingFwdStrategy = + configuration_get_strategy(config, prefix_s); + strategy_options_t *options = NULL; + + Name name_prefix = EMPTY_NAME; + name_CreateFromAddress(&name_prefix, control->family, control->address, + control->len); + + // The strategy is not present in the hash table + // or has to be updated or to be restarted + if (existingFwdStrategy == STRATEGY_TYPE_UNDEFINED || + strategy != existingFwdStrategy || + (strategy == existingFwdStrategy && strategy == STRATEGY_TYPE_BESTPATH)) { + configuration_set_strategy(config, prefix_s, strategy); + + forwarder_set_strategy(forwarder, &name_prefix, strategy, options); + } else { + WITH_WARN({ + char *nameString = name_ToString(&name_prefix); + WARN("Strategy for prefix %s not updated", nameString); + free(nameString); + }) + } + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_strategy_add_local_prefix(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: strategy add local prefix (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_strategy_add_local_prefix_t *msg = + (msg_strategy_add_local_prefix_t *)packet; + cmd_strategy_add_local_prefix_t *control = &msg->payload; + + char prefix_s[MAXSZ_IP_PREFIX]; + ip_prefix_t prefix = { + .family = control->family, + .address = control->address, + .len = control->len, + }; + int rc = ip_prefix_snprintf(prefix_s, MAXSZ_IP_PREFIX, &prefix); + assert(rc < MAXSZ_IP_PREFIX); + if (rc < 0) goto NACK; + + strategy_type_t strategy = control->type; + configuration_t *config = forwarder_get_configuration(forwarder); + strategy_type_t existingFwdStrategy = + configuration_get_strategy(config, prefix_s); + + if (strategy != existingFwdStrategy) goto NACK; + + if (strategy != STRATEGY_TYPE_BESTPATH && + strategy != STRATEGY_TYPE_REPLICATION) + goto NACK; + + Name name_prefix = EMPTY_NAME; + name_CreateFromAddress(&name_prefix, control->family, control->address, + control->len); + + strategy_options_t options; + Name local_prefix = EMPTY_NAME; + name_CreateFromAddress(&local_prefix, control->local_family, + control->local_address, control->local_len); + + // for the moment bestpath and replication are the same but we distinguish the + // two in case they will diverge in the future + if (strategy == STRATEGY_TYPE_BESTPATH) { + options.bestpath.local_prefixes = create_local_prefixes(); + local_prefixes_add_prefix(options.bestpath.local_prefixes, &local_prefix); + } else { + options.replication.local_prefixes = create_local_prefixes(); + local_prefixes_add_prefix(options.replication.local_prefixes, + &local_prefix); + } + + forwarder_add_strategy_options(forwarder, &name_prefix, strategy, &options); + + free_local_prefixes(options.bestpath.local_prefixes); + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +/* WLDR */ + +uint8_t *configuration_on_wldr_set(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size) { + assert(forwarder); + assert(packet); + + msg_wldr_set_t *msg = (msg_wldr_set_t *)packet; + cmd_wldr_set_t *control = &msg->payload; + + if ((control->activate != 0) && (control->activate != 1)) goto NACK; + bool value = (bool)control->activate; + + unsigned conn_id = + symbolic_to_conn_id(forwarder, control->symbolic_or_connid); + if (!connection_id_is_valid(conn_id)) goto NACK; + + connection_table_t *table = forwarder_get_connection_table(forwarder); + connection_t *conn = connection_table_at(table, conn_id); + + if (value) connection_wldr_enable(conn, value); + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +/* Punting */ + +uint8_t *configuration_on_punting_add(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size) { + // #if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING) + msg_punting_add_t *msg = (msg_punting_add_t *)packet; + +#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING) + cmd_punting_add_t *control = &msg->payload; + if (ip_address_empty(&control->address)) goto NACK; + + /* This is for hICN listeners only */ + // XXX add check ! + // comments: + // EncapType: I use the Hicn encap since the punting is available only for + // Hicn listeners LocalAddress: The only listern for which we need punting + // rules is the main one, which has no address + // so I create a fake empty address. This need to be consistent + // with the address set at creation time + address_t fakeaddr; + memset(&fakeaddr, 0, sizeof(address_t)); + fakeaddr = ADDRESS_ANY(control->family, DEFAULT_PORT); + + listener_table_t *table = forwarder_get_listener_table(forwarder); + listener_t *listener = + listener_table_get_by_address(table, FACE_TYPE_HICN, &fakeaddr); + if (!listener) { + ERROR("the main listener does not exist"); + goto NACK; + } + + ip_prefix_t prefix = {.family = control->family, + .address = control->address, + .len = control->len}; + char prefix_s[MAXSZ_IP_PREFIX]; + int rc = ip_prefix_snprintf(prefix_s, MAXSZ_IP_PREFIX, &prefix); + assert(rc < MAXSZ_IP_PREFIX); + if (rc < 0) goto NACK; + + if (listener_punt(listener, prefix_s) < 0) { + ERROR("error while adding the punting rule"); + goto NACK; + } + + make_ack(msg); + return (uint8_t *)msg; + +NACK: +#endif + make_nack(msg); + return (uint8_t *)msg; +} + +/* MAP-Me */ + +#ifdef WITH_MAPME +uint8_t *configuration_on_mapme_enable(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: mapme enable (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_mapme_enable_t *msg = (msg_mapme_enable_t *)packet; + cmd_mapme_enable_t *control = &msg->payload; + + if ((control->activate != 0) && (control->activate != 1)) goto NACK; + bool value = (bool)control->activate; + + INFO("MAP-Me SET enable: %s", value ? "on" : "off"); + mapme_t *mapme = forwarder_get_mapme(forwarder); + if (!mapme) goto NACK; + mapme_set_enable(mapme, value); + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_mapme_set_discovery(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: mapme discovery (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_mapme_set_discovery_t *msg = (msg_mapme_set_discovery_t *)packet; + cmd_mapme_set_discovery_t *control = &msg->payload; + + if ((control->activate != 0) && (control->activate != 1)) goto NACK; + bool value = (bool)control->activate; + + INFO("MAP-Me SET discovery: %s", value ? "on" : "off"); + mapme_t *mapme = forwarder_get_mapme(forwarder); + if (!mapme) goto NACK; + mapme_set_discovery(mapme, value); + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_mapme_set_timescale(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: mapme timescale (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_mapme_set_timescale_t *msg = (msg_mapme_set_timescale_t *)packet; + cmd_mapme_set_timescale_t *control = &msg->payload; + + INFO("MAP-Me SET timescale: %u", control->timePeriod); + mapme_t *mapme = forwarder_get_mapme(forwarder); + if (!mapme) goto NACK; + mapme_set_timescale(mapme, control->timePeriod); + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_mapme_set_retx(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: mapme retransmission (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_mapme_set_retx_t *msg = (msg_mapme_set_retx_t *)packet; + cmd_mapme_set_retx_t *control = &msg->payload; + + INFO("MAP-Me SET retx: %u", control->timePeriod); + mapme_t *mapme = forwarder_get_mapme(forwarder); + if (!mapme) goto NACK; + mapme_set_retransmision(mapme, control->timePeriod); + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_mapme_send_update(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + assert(forwarder); + assert(packet); + + INFO("CMD: mapme send update (ingress=%d)", ingress_id); + msg_mapme_send_update_t *msg = (msg_mapme_send_update_t *)packet; + + *reply_size = sizeof(msg_header_t); + + fib_t *fib = forwarder_get_fib(forwarder); + if (!fib) goto NACK; + + mapme_t *mapme = forwarder_get_mapme(forwarder); + + /* + * The command triggers a mapme update for all prefixes produced on this face + * */ + fib_entry_t *entry; + fib_foreach_entry(fib, entry, { + const nexthops_t *nexthops = fib_entry_get_nexthops(entry); + unsigned nexthop; + nexthops_foreach(nexthops, nexthop, { + if (nexthop != ingress_id) continue; + /* This entry points to the producer face */ + mapme_set_all_adjacencies(mapme, entry); + break; + }); + }); + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} +#endif /* WITH_MAPME */ + +/* Policy */ + +uint8_t *configuration_on_policy_add(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size) { + assert(forwarder); + assert(packet); + +#ifdef WITH_POLICY + msg_policy_add_t *msg = (msg_policy_add_t *)packet; + cmd_policy_add_t *control = &msg->payload; + + ip_prefix_t prefix = {.family = control->family, + .address = control->address, + .len = control->len}; + + if (!forwarder_add_or_update_policy(forwarder, &prefix, &control->policy)) + goto NACK; + + make_ack(msg); + return (uint8_t *)msg; + +NACK: +#endif /* WITH_POLICY */ + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_policy_remove(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + assert(forwarder); + assert(packet); + +#ifdef WITH_POLICY + msg_policy_remove_t *msg = (msg_policy_remove_t *)packet; + cmd_policy_remove_t *control = &msg->payload; + + ip_prefix_t prefix = {.family = control->family, + .address = control->address, + .len = control->len}; + + if (!forwarder_remove_policy(forwarder, &prefix)) goto NACK; + + make_ack(msg); + return (uint8_t *)msg; + +NACK: +#endif /* WITH_POLICY */ + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_policy_list(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size) { + assert(forwarder); + assert(packet); + + const fib_t *fib = forwarder_get_fib(forwarder); + assert(fib); + size_t n = fib_get_size(fib); + +#ifdef WITH_POLICY + msg_policy_list_t *msg_received = (msg_policy_list_t *)packet; + uint8_t command_id = msg_received->header.command_id; + uint32_t seq_num = msg_received->header.seq_num; + + msg_policy_list_reply_t *msg; + msg_malloc_list(msg, command_id, n, seq_num); + if (!msg) goto NACK; + + cmd_policy_list_item_t *payload = &msg->payload; + + fib_entry_t *entry; + + fib_foreach_entry(fib, entry, { + NameBitvector *prefix = name_GetContentName(fib_entry_get_prefix(entry)); + address_t address; + nameBitvector_ToAddress(prefix, &address); + + switch (address_family(&address)) { + case AF_INET: + payload->family = AF_INET; + payload->address.v4.as_inaddr = address4_ip(&address); + break; + + case AF_INET6: + payload->family = AF_INET6; + payload->address.v6.as_in6addr = address6_ip(&address); + break; + + default: + break; + } + payload->len = nameBitvector_GetLength(prefix); + payload->policy = fib_entry_get_policy(entry); + + payload++; + }); + + return (uint8_t *)msg; +#endif /* WITH_POLICY */ + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +/* Subscription */ + +uint8_t *configuration_on_subscription_add(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: subscription add (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_subscription_add_t *msg = (msg_subscription_add_t *)packet; + cmd_subscription_add_t *control = &msg->payload; + hc_topics_t topics = control->topics; + + subscription_table_t *subscriptions = forwarder_get_subscriptions(forwarder); + assert(subscriptions); + + int ret = subscription_table_add_topics_for_connection(subscriptions, topics, + ingress_id); + if (ret < 0) goto NACK; + + WITH_DEBUG(subscription_table_print(subscriptions);) + + make_ack(msg); + return (uint8_t *)msg; + +NACK: + make_nack(msg); + return (uint8_t *)msg; +} + +uint8_t *configuration_on_subscription_remove(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size) { + INFO("CMD: subscription remove (ingress=%d)", ingress_id); + assert(forwarder); + assert(packet); + + *reply_size = sizeof(msg_header_t); + msg_subscription_add_t *msg = (msg_subscription_add_t *)packet; + cmd_subscription_add_t *control = &msg->payload; + hc_topics_t topics = control->topics; + + subscription_table_t *subscriptions = forwarder_get_subscriptions(forwarder); + assert(subscriptions); + + subscription_table_remove_topics_for_connection(subscriptions, topics, + ingress_id); + WITH_DEBUG(subscription_table_print(subscriptions);) + + make_ack(msg); + return (uint8_t *)msg; +} + +uint8_t *command_process(forwarder_t *forwarder, uint8_t *packet, + command_type_t command_type, unsigned ingress_id, + size_t *reply_size) { + uint8_t *reply = NULL; + + /* + * For most commands, the packet will simply be transformed into an ack. + * For list commands, a new message will be allocated, and the return value + * might eventually be NULL in case of an error. That is why the free the + * reply at the end in these circumstances. + * + * XXX rework this part. + */ + switch (command_type) { +#define _(l, u) \ + case COMMAND_TYPE_##u: \ + reply = configuration_on_##l(forwarder, packet, ingress_id, reply_size); \ + assert(reply); \ + break; + foreach_command_type +#undef _ + case COMMAND_TYPE_UNDEFINED : case COMMAND_TYPE_N + : ERROR("Unexpected command type"); + reply = packet; + make_nack(reply); + if (reply_size) *reply_size = sizeof(msg_header_t); + break; + } + + return reply; +} + +ssize_t command_process_msgbuf(forwarder_t *forwarder, msgbuf_t *msgbuf) { + assert(forwarder); + assert(msgbuf); + + uint8_t *packet = msgbuf_get_packet(msgbuf); + unsigned ingress_id = msgbuf_get_connection_id(msgbuf); + + uint8_t *reply = NULL; + size_t reply_size = 0; + + command_type_t command_type = msgbuf_get_command_type(msgbuf); + + reply = + command_process(forwarder, packet, command_type, ingress_id, &reply_size); + if (connection_id_is_valid(msgbuf->connection_id)) { + connection_table_t *table = forwarder_get_connection_table(forwarder); + const connection_t *connection = connection_table_at(table, ingress_id); + connection_send_packet(connection, reply, reply_size); + } + + switch (msgbuf->command.type) { + case COMMAND_TYPE_LISTENER_LIST: + case COMMAND_TYPE_CONNECTION_LIST: + case COMMAND_TYPE_ROUTE_LIST: + case COMMAND_TYPE_POLICY_LIST: + /* Free replies that have been allocated (not NACK's) */ + if (((msg_header_t *)reply)->header.message_type != NACK_LIGHT) + free(reply); + break; + default: + break; + } + + return msgbuf_get_len(msgbuf); +} diff --git a/hicn-light/src/hicn/config/commands.h b/hicn-light/src/hicn/config/commands.h new file mode 100644 index 000000000..cedf4de01 --- /dev/null +++ b/hicn-light/src/hicn/config/commands.h @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2021 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file commands.h + * @brief hicn-light configuration, such as in-band commands or CLI + * + * Manages all user configuration of the system, such as from the CLI or web + * interface It remembers the user commands and will be able to write out a + * config file. + * + */ + +#ifndef HICNLIGHT_COMMANDS_H +#define HICNLIGHT_COMMANDS_H + +#include "../core/msgbuf.h" +#include "../core/strategy.h" +#include <hicn/ctrl/api.h> +#include <hicn/ctrl/hicn-light-ng.h> + +uint8_t *command_process(forwarder_t *forwarder, uint8_t *packet, + command_type_t command_type, unsigned ingress_id, + size_t *reply_size); + +ssize_t command_process_msgbuf(forwarder_t *forwarder, msgbuf_t *msgbuf); + +uint8_t *configuration_on_listener_add(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size); + +uint8_t *configuration_on_listener_remove(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_listener_list(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_connection_add(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_connection_remove(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_connection_list(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_connection_set_admin_state(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_connection_update(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_connection_set_priority(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_connection_set_tags(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_route_add(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size); + +uint8_t *configuration_on_route_remove(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size); + +uint8_t *configuration_on_route_list(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size); + +uint8_t *configuration_on_cache_set_store(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_cache_set_serve(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_cache_clear(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size); + +uint8_t *configuration_on_strategy_set(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size); + +uint8_t *configuration_on_strategy_add_local_prefix(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_wldr_set(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size); + +uint8_t *configuration_on_punting_add(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size); + +#ifdef WITH_MAPME +uint8_t *configuration_on_mapme_enable(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size); + +uint8_t *configuration_on_mapme_set_discovery(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_mapme_set_timescale(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_mapme_set_retx(forwarder_t *forwarder, + uint8_t *packet, unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_mapme_send_update(forwarder_t *forwarder, + uint8_t *packet, + unsigned ingress_id, + size_t *reply_size); +#endif /* WITH_MAPME */ + +uint8_t *configuration_on_policy_add(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size); + +uint8_t *configuration_on_policy_remove(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, + size_t *reply_size); + +uint8_t *configuration_on_policy_list(forwarder_t *forwarder, uint8_t *packet, + unsigned ingress_id, size_t *reply_size); + +#endif // HICNLIGHT_COMMANDS_H diff --git a/hicn-light/src/hicn/config/configuration.c b/hicn-light/src/hicn/config/configuration.c index e414f05e3..9123ceebf 100644 --- a/hicn-light/src/hicn/config/configuration.c +++ b/hicn-light/src/hicn/config/configuration.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -26,1504 +26,169 @@ #include <unistd.h> #endif #include <ctype.h> -#include <parc/assert/parc_Assert.h> #include <hicn/hicn-light/config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <parc/algol/parc_HashMap.h> -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_String.h> - -#include <hicn/config/configurationListeners.h> -#include <hicn/config/symbolicNameTable.h> - #include <hicn/core/connection.h> -#include <hicn/core/connectionTable.h> +#include <hicn/core/connection_table.h> #include <hicn/core/forwarder.h> -#include <hicn/core/system.h> +//#include <hicn/core/system.h> #ifdef WITH_MAPME #include <hicn/core/mapme.h> #endif /* WITH_MAPME */ -#include <hicn/io/streamConnection.h> - -#include <hicn/io/hicnTunnel.h> -#include <hicn/io/tcpTunnel.h> -#include <hicn/io/udpTunnel.h> +#include <hicn/core/listener.h> //the listener list +#include <hicn/core/listener_table.h> +#include <hicn/ctrl/hicn-light-ng.h> +#include <hicn/utils/punting.h> +#include <hicn/util/log.h> +#include <hicn/face.h> -#include <parc/algol/parc_Unsigned.h> -#include <hicn/io/listener.h> //the listener list -#include <hicn/io/listenerSet.h> // needed to print -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -#include <hicn/utils/address.h> +#include "configuration.h" #define ETHERTYPE 0x0801 - -struct configuration { - Forwarder *forwarder; - Logger *logger; - - size_t maximumContentObjectStoreSize; - - // map from prefix (parcString) to strategy (parcString) - PARCHashMap *strategy_map; - - // translates between a symblic name and a connection id - SymbolicNameTable *symbolicNameTable; +#define DEFAULT_COST 1 +#define DEFAULT_PORT 1234 +#define DEFAULT_LOGLEVEL "info" +#define DEFAULT_CS_CAPACITY 100000 + +#define msg_malloc_list(msg, N, seq_number) \ + do { \ + msg = malloc(sizeof((msg)->header) + N * sizeof((msg)->payload)); \ + (msg)->header.message_type = RESPONSE_LIGHT; \ + (msg)->header.length = (uint16_t)(N); \ + (msg)->header.seq_num = (seq_number); \ + } while (0); + +struct configuration_s { + const char *fn_config; + uint16_t port; + uint16_t configuration_port; + size_t cs_capacity; + int loglevel; + const char *logfile; + int logfile_fd; + bool daemon; + kh_strategy_map_t *strategy_map; }; -// ======================================================================================== - -Connection * -getConnectionBySymbolicOrId(Configuration * config, const char * symbolicOrConnid) -{ - ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder); - unsigned connid; - Connection *conn = NULL; - - /* Try to resolve an eventual symbolic name as input */ - if (utils_IsNumber(symbolicOrConnid)) { - connid = (unsigned int)strtold(symbolicOrConnid, NULL); - - } else { - connid = symbolicNameTable_Get(config->symbolicNameTable, symbolicOrConnid); - if (connid == UINT32_MAX) { - if (logger_IsLoggable(config->logger, LoggerFacility_Config, - PARCLogLevel_Warning)) { - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error, - __func__, "Symbolic name '%s' could not be resolved", - symbolicOrConnid); - } - } - } - - /* Get connection by ID */ - conn = (Connection *)connectionTable_FindById( table, connid); - if (!conn) { - if (logger_IsLoggable(config->logger, LoggerFacility_Config, - PARCLogLevel_Warning)) { - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error, - __func__, "ConnID not found, check list connections"); - } - } - - return conn; -} - -// ======================================================================================== - -Configuration *configuration_Create(Forwarder *forwarder) { - parcAssertNotNull(forwarder, "Parameter hicn-fwd must be non-null"); - Configuration *config = parcMemory_AllocateAndClear(sizeof(Configuration)); - parcAssertNotNull(config, "parcMemory_AllocateAndClear(%zu) returned NULL", - sizeof(Configuration)); - config->forwarder = forwarder; - config->logger = logger_Acquire(forwarder_GetLogger(forwarder)); - config->maximumContentObjectStoreSize = 100000; - config->strategy_map = parcHashMap_Create(); - config->symbolicNameTable = symbolicNameTable_Create(); - - return config; -} - -void configuration_Destroy(Configuration **configPtr) { - parcAssertNotNull(configPtr, "Parameter must be non-null double poitner"); - parcAssertNotNull(*configPtr, - "Parameter must dereference to non-null pointer"); - - Configuration *config = *configPtr; - logger_Release(&config->logger); - parcHashMap_Release(&(config->strategy_map)); - symbolicNameTable_Destroy(&config->symbolicNameTable); - parcMemory_Deallocate((void **)&config); - *configPtr = NULL; -} - -struct iovec *configuration_ProcessRegisterHicnPrefix(Configuration *config, - struct iovec *request, - unsigned ingressId) { - header_control_message *header = request[0].iov_base; - add_route_command *control = request[1].iov_base; - - bool success = false; - - const char *symbolicOrConnid = control->symbolicOrConnid; - - if (strcmp(symbolicOrConnid, "SELF") == 0) { - success = forwarder_AddOrUpdateRoute(config->forwarder, control, ingressId); - } else if (utils_IsNumber(symbolicOrConnid)) { - // case for connid as input - unsigned connid = (unsigned)strtold(symbolicOrConnid, NULL); - ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder); - - // check if iconnID present in the fwd table - if (connectionTable_FindById(table, connid)) { - success = forwarder_AddOrUpdateRoute(config->forwarder, control, connid); - } else { - logger_Log(forwarder_GetLogger(config->forwarder), LoggerFacility_IO, - PARCLogLevel_Error, __func__, - "ConnID not found, check list connections"); - // failure - } - - } else { - // case for symbolic as input: check if symbolic name can be resolved - unsigned connid = - symbolicNameTable_Get(config->symbolicNameTable, symbolicOrConnid); - // connid = UINT_MAX when symbolicName is not found - if (connid != UINT32_MAX) { - if (logger_IsLoggable(config->logger, LoggerFacility_Config, - PARCLogLevel_Debug)) { - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Debug, - __func__, "Add route resolve name '%s' to connid %u", - symbolicOrConnid, connid); - } - - success = forwarder_AddOrUpdateRoute(config->forwarder, control, connid); - - } else { - if (logger_IsLoggable(config->logger, LoggerFacility_Config, - PARCLogLevel_Warning)) { - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Warning, - __func__, - "Add route symbolic name '%s' could not be resolved", - symbolicOrConnid); - } - // failure - } - } - - // generate ACK/NACK - struct iovec *response; - - if (success) { // ACK - response = utils_CreateAck(header, control, sizeof(add_route_command)); - } else { // NACK - response = utils_CreateNack(header, control, sizeof(add_route_command)); - } - - return response; -} - -struct iovec *configuration_ProcessUnregisterHicnPrefix(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - remove_route_command *control = request[1].iov_base; - - bool success = false; - - const char *symbolicOrConnid = control->symbolicOrConnid; - - if (utils_IsNumber(symbolicOrConnid)) { - // case for connid as input - unsigned connid = (unsigned)strtold(symbolicOrConnid, NULL); - ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder); - - // check if interface index present in the fwd table - if (connectionTable_FindById(table, connid)) { - success = forwarder_RemoveRoute(config->forwarder, control, connid); - } else { - logger_Log(forwarder_GetLogger(config->forwarder), LoggerFacility_IO, - PARCLogLevel_Error, __func__, - "ConnID not found, check list connections"); - // failure - } - - } else { - // case for symbolic as input: chech if symbolic name can be resolved - unsigned connid = - symbolicNameTable_Get(config->symbolicNameTable, symbolicOrConnid); - // connid = UINT_MAX when symbolicName is not found - if (connid != UINT32_MAX) { - if (logger_IsLoggable(config->logger, LoggerFacility_Config, - PARCLogLevel_Debug)) { - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Debug, - __func__, "Remove route resolve name '%s' to connid %u", - symbolicOrConnid, connid); - } - success = forwarder_RemoveRoute(config->forwarder, control, connid); - } else { - if (logger_IsLoggable(config->logger, LoggerFacility_Config, - PARCLogLevel_Warning)) { - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Warning, - __func__, - "Remove route symbolic name '%s' could not be resolved", - symbolicOrConnid); - } - // failure - } - } - - // generate ACK/NACK - struct iovec *response; - - if (success) { // ACK - response = utils_CreateAck(header, control, sizeof(remove_route_command)); - } else { // NACK - response = utils_CreateNack(header, control, sizeof(remove_route_command)); - } - - return response; -} - -struct iovec *configuration_ProcessRegistrationList(Configuration *config, - struct iovec *request) { - FibEntryList *fibList = forwarder_GetFibEntries(config->forwarder); - - size_t payloadSize = fibEntryList_Length(fibList); - size_t effective_payloadSize = 0; - size_t pointerLocation = 0; - struct sockaddr_in tmpAddr; - struct sockaddr_in6 tmpAddr6; - - // allocate payload, cast from void* to uint8_t* = bytes granularity - uint8_t *payloadResponse = - parcMemory_AllocateAndClear(sizeof(list_routes_command) * payloadSize); - - for (size_t i = 0; i < fibEntryList_Length(fibList); i++) { - FibEntry *entry = (FibEntry *)fibEntryList_Get(fibList, i); - NameBitvector *prefix = name_GetContentName(fibEntry_GetPrefix(entry)); - const NumberSet *nexthops = fibEntry_GetNexthops(entry); - - if (numberSet_Length(nexthops) == 0) - continue; - - if (numberSet_Length(nexthops) > 1) { - // payload extended, need reallocate, further entries via nexthops - payloadSize = payloadSize + numberSet_Length(nexthops) - 1; - payloadResponse = (uint8_t *) parcMemory_Reallocate( - payloadResponse, sizeof(list_routes_command) * payloadSize); - } - - for (size_t j = 0; j < numberSet_Length(nexthops); j++) { - list_routes_command *listRouteCommand = - (list_routes_command *)(payloadResponse + - (pointerLocation * - sizeof(list_routes_command))); - - Address *addressEntry = nameBitvector_ToAddress(prefix); - if (addressGetType(addressEntry) == ADDR_INET) { - addressGetInet(addressEntry, &tmpAddr); - listRouteCommand->addressType = ADDR_INET; - listRouteCommand->address.v4.as_inaddr = tmpAddr.sin_addr; - } else if (addressGetType(addressEntry) == ADDR_INET6) { - addressGetInet6(addressEntry, &tmpAddr6); - listRouteCommand->addressType = ADDR_INET6; - listRouteCommand->address.v6.as_in6addr = tmpAddr6.sin6_addr; - } - listRouteCommand->connid = numberSet_GetItem(nexthops, j); - listRouteCommand->len = nameBitvector_GetLength(prefix); - listRouteCommand->cost = 1; // cost - - pointerLocation++; - effective_payloadSize++; - addressDestroy(&addressEntry); - } - } - - // send response - header_control_message *header = request[0].iov_base; - header->messageType = RESPONSE_LIGHT; - header->length = (unsigned)effective_payloadSize; - - struct iovec *response = - parcMemory_AllocateAndClear(sizeof(struct iovec) * 2); - - response[0].iov_base = header; - response[0].iov_len = sizeof(header_control_message); - response[1].iov_base = payloadResponse; - response[1].iov_len = sizeof(list_routes_command) * effective_payloadSize; - - fibEntryList_Destroy(&fibList); - return response; -} - -static void configuration_SendResponse(Configuration *config, struct iovec *msg, - unsigned egressId) { - ConnectionTable *connectionTable = - forwarder_GetConnectionTable(config->forwarder); - const Connection *conn = connectionTable_FindById(connectionTable, egressId); - - if (conn == NULL) { - return; - } - connection_SendIOVBuffer(conn, msg, 2); -} - -struct iovec *configuration_ProcessCreateTunnel(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - add_connection_command *control = request[1].iov_base; - - bool success = false; - - Connection *conn; - const char *symbolicName = control->symbolic; - - Address *source = NULL; - Address *destination = NULL; - - if (symbolicNameTable_Exists(config->symbolicNameTable, symbolicName)) { - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error, - __func__, "Connection symbolic name already exists"); - goto ERR; - } - - if (control->ipType == ADDR_INET) { - source = - addressFromInaddr4Port(&control->localIp.v4.as_u32, &control->localPort); - destination = - addressFromInaddr4Port(&control->remoteIp.v4.as_u32, &control->remotePort); - } else if (control->ipType == ADDR_INET6) { - source = - addressFromInaddr6Port(&control->localIp.v6.as_in6addr, &control->localPort); - destination = - addressFromInaddr6Port(&control->remoteIp.v6.as_in6addr, &control->remotePort); - } else { - printf("Invalid IP type.\n"); // will generate a Nack - } - - AddressPair *pair = addressPair_Create(source, destination); - conn = (Connection *)connectionTable_FindByAddressPair( - forwarder_GetConnectionTable(config->forwarder), pair); - - addressPair_Release(&pair); - - if (!conn) { - IoOperations *ops = NULL; - switch (control->connectionType) { - case TCP_CONN: - // logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error, - // __func__, - // "Unsupported tunnel protocol: TCP"); - ops = tcpTunnel_Create(config->forwarder, source, destination); - break; - case UDP_CONN: - ops = udpTunnel_Create(config->forwarder, source, destination); - break; - case GRE_CONN: - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error, - __func__, "Unsupported tunnel protocol: GRE"); - break; -#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING) - case HICN_CONN: - ops = hicnTunnel_Create(config->forwarder, source, destination); - break; -#endif /* __APPLE__ _WIN32*/ - default: - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error, - __func__, "Unsupported tunnel protocol: %d", - control->connectionType); - break; - } - - if (ops != NULL) { - Connection *conn = connection_Create(ops); -#ifdef WITH_POLICY - connection_SetTags(conn, control->tags); - connection_SetPriority(conn, control->priority); -#endif /* WITH_POLICY */ +configuration_t *configuration_create() { + configuration_t *config = malloc(sizeof(configuration_t)); + if (!config) return NULL; - connection_SetAdminState(conn, control->admin_state); - - connectionTable_Add(forwarder_GetConnectionTable(config->forwarder), - conn); - symbolicNameTable_Add(config->symbolicNameTable, symbolicName, - connection_GetConnectionId(conn)); - -#ifdef WITH_MAPME - /* Hook: new connection created through the control protocol */ - forwarder_onConnectionEvent(config->forwarder, conn, CONNECTION_EVENT_CREATE); -#endif /* WITH_MAPME */ - - success = true; - - } else { - printf("failed, could not create IoOperations"); - } - - } else { -#ifdef WITH_POLICY - connection_SetTags(conn, control->tags); - connection_SetPriority(conn, control->priority); - connection_SetAdminState(conn, control->admin_state); - -#ifdef WITH_MAPME - /* Hook: new connection created through the control protocol */ - forwarder_onConnectionEvent(config->forwarder, conn, CONNECTION_EVENT_UPDATE); -#endif /* WITH_MAPME */ - if (source) - addressDestroy(&source); - if (destination) - addressDestroy(&destination); - - success = true; + config->fn_config = NULL; + config->port = PORT_NUMBER; + config->configuration_port = 2001; // TODO(eloparco): What is this? + config->cs_capacity = DEFAULT_CS_CAPACITY; + config->logfile = NULL; + config->logfile_fd = -1; +#ifndef _WIN32 + config->daemon = false; #else - printf("failed, symbolic name or connection already exist\n"); -#endif /* WITH_POLICY */ - } - - if (source) - addressDestroy(&source); - if (destination) - addressDestroy(&destination); - - if (!success) - goto ERR; - - // ACK - return utils_CreateAck(header, control, sizeof(add_connection_command)); - -ERR: - return utils_CreateNack(header, control, sizeof(add_connection_command)); -} - -struct iovec *configuration_ProcessRemoveListener(Configuration *config, - struct iovec *request, - unsigned ingressId) { - header_control_message *header = request[0].iov_base; - remove_listener_command *control = request[1].iov_base; - - bool success = false; - - const char *symbolicOrListenerid = control->symbolicOrListenerid; - int listenerId = -1; - ListenerSet *listenerSet = forwarder_GetListenerSet(config->forwarder); - if (utils_IsNumber(symbolicOrListenerid)) { - // case for connid as input - listenerId = (unsigned)strtold(symbolicOrListenerid, NULL); - } else { - listenerId = listenerSet_FindIdByListenerName(listenerSet, symbolicOrListenerid); - } - - if (listenerId >= 0) { - - ConnectionTable *connTable = forwarder_GetConnectionTable(config->forwarder); - ListenerOps *listenerOps = listenerSet_FindById(listenerSet, listenerId); - if (listenerOps) { - ConnectionList *connectionList = connectionTable_GetEntries(connTable); - for (size_t i = 0; i < connectionList_Length(connectionList); i++) { - Connection *connection = connectionList_Get(connectionList, i); - const AddressPair *addressPair = connection_GetAddressPair(connection); - const Address *address = addressPair_GetLocal(addressPair); - if (addressEquals(listenerOps->getListenAddress(listenerOps),address)) { - // case for connid as input - unsigned connid = connection_GetConnectionId(connection); - // remove connection from the FIB - forwarder_RemoveConnectionIdFromRoutes(config->forwarder, connid); - // remove connection - connectionTable_RemoveById(connTable, connid); - const char *symbolicConnection = symbolicNameTable_GetNameByIndex(config->symbolicNameTable,connid); - symbolicNameTable_Remove(config->symbolicNameTable, symbolicConnection); - } - } - connectionList_Destroy(&connectionList); - // remove listener - listenerSet_RemoveById(listenerSet, listenerId); - success = true; - } else { - logger_Log(forwarder_GetLogger(config->forwarder), LoggerFacility_IO, - PARCLogLevel_Error, __func__, - "Listener Id not found, check list listeners"); - } - } - - // generate ACK/NACK - struct iovec *response; - - if (success) { // ACK - response = - utils_CreateAck(header, control, sizeof(remove_listener_command)); - } else { // NACK - response = - utils_CreateNack(header, control, sizeof(remove_connection_command)); - } - - return response; -} - - -/** - * Add an IP-based tunnel. - * - * The call cal fail if the symbolic name is a duplicate. It could also fail if - * there's an problem creating the local side of the tunnel (i.e. the local - * socket address is not usable). - * - * @return true Tunnel added - * @return false Tunnel not added (an error) - */ - -struct iovec *configuration_ProcessRemoveTunnel(Configuration *config, - struct iovec *request, - unsigned ingressId) { - header_control_message *header = request[0].iov_base; - remove_connection_command *control = request[1].iov_base; - - bool success = false; - - const char *symbolicOrConnid = control->symbolicOrConnid; - ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder); - if (strcmp(symbolicOrConnid, "SELF") == 0) { - forwarder_RemoveConnectionIdFromRoutes(config->forwarder, ingressId); - connectionTable_RemoveById(table, ingressId); - -#ifdef WITH_MAPME - /* Hook: new connection created through the control protocol */ - forwarder_onConnectionEvent(config->forwarder, NULL, CONNECTION_EVENT_DELETE); -#endif /* WITH_MAPME */ - - success = true; - } else if (utils_IsNumber(symbolicOrConnid)) { - // case for connid as input - unsigned connid = (unsigned)strtold(symbolicOrConnid, NULL); - - // check if interface index present in the fwd table - //(it was missing and therefore caused a program crash) - if (connectionTable_FindById(table, connid)) { - // remove connection from the FIB - forwarder_RemoveConnectionIdFromRoutes(config->forwarder, connid); - // remove connection - connectionTable_RemoveById(table, connid); - // remove connection from symbolicNameTable - const char *symbolicConnection = symbolicNameTable_GetNameByIndex(config->symbolicNameTable,connid); - symbolicNameTable_Remove(config->symbolicNameTable, symbolicConnection); - -#ifdef WITH_MAPME - /* Hook: new connection created through the control protocol */ - forwarder_onConnectionEvent(config->forwarder, NULL, CONNECTION_EVENT_DELETE); -#endif /* WITH_MAPME */ - - success = true; - } else { - logger_Log(forwarder_GetLogger(config->forwarder), LoggerFacility_IO, - PARCLogLevel_Error, __func__, - "ConnID not found, check list connections"); - // failure - } - - } else { - // case for symbolic as input - // chech if symbolic name can be resolved - unsigned connid = - symbolicNameTable_Get(config->symbolicNameTable, symbolicOrConnid); - // connid = UINT_MAX when symbolicName is not found - if (connid != UINT32_MAX) { - if (logger_IsLoggable(config->logger, LoggerFacility_Config, - PARCLogLevel_Debug)) { - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Debug, - __func__, "Remove connection resolve name '%s' to connid %u", - symbolicOrConnid, connid); - } - - // remove connection from the FIB - forwarder_RemoveConnectionIdFromRoutes(config->forwarder, connid); - // remove connection - connectionTable_RemoveById(table, connid); - // remove connection from symbolicNameTable since we have symbolic input - symbolicNameTable_Remove(config->symbolicNameTable, symbolicOrConnid); - -#ifdef WITH_MAPME - /* Hook: new connection created through the control protocol */ - forwarder_onConnectionEvent(config->forwarder, NULL, CONNECTION_EVENT_DELETE); -#endif /* WITH_MAPME */ - - success = true; // to write - } else { - if (logger_IsLoggable(config->logger, LoggerFacility_Config, - PARCLogLevel_Warning)) { - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error, - __func__, - "Remove connection symbolic name '%s' could not be resolved", - symbolicOrConnid); - } - // failure - } - } - - - - // generate ACK/NACK - struct iovec *response; - - if (success) { // ACK - response = - utils_CreateAck(header, control, sizeof(remove_connection_command)); - } else { // NACK - response = - utils_CreateNack(header, control, sizeof(remove_connection_command)); - } - - return response; -} - -void _parc_strlwr(char *string) { - char *p = string; - while ((*p = tolower(*p))) { - p++; - } -} - -struct iovec *configuration_ProcessConnectionList(Configuration *config, - struct iovec *request) { - ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder); - ConnectionList *connList = connectionTable_GetEntries(table); - struct sockaddr_in tmpAddr; - struct sockaddr_in6 tmpAddr6; - - // allocate payload, cast from void* to uint8_t* fot bytes granularity - uint8_t *payloadResponse = parcMemory_AllocateAndClear( - sizeof(list_connections_command) * connectionList_Length(connList)); - - for (size_t i = 0; i < connectionList_Length(connList); i++) { - // Don't release original, it is not stored - Connection *original = connectionList_Get(connList, i); - - const AddressPair *addressPair = connection_GetAddressPair(original); - Address *localAddress = addressCopy(addressPair_GetLocal(addressPair)); - Address *remoteAddress = addressCopy(addressPair_GetRemote(addressPair)); - - // Fill payload by shifting and casting at each 'i' step. - list_connections_command *listConnectionsCommand = - (list_connections_command *)(payloadResponse + - (i * sizeof(list_connections_command))); - // set structure fields - - listConnectionsCommand->connid = connection_GetConnectionId(original); - - const char *connectionName = symbolicNameTable_GetNameByIndex(config->symbolicNameTable, connection_GetConnectionId(original)); - snprintf(listConnectionsCommand->connectionName, SYMBOLIC_NAME_LEN, "%s", connectionName); - _parc_strlwr(listConnectionsCommand->connectionName); - - snprintf(listConnectionsCommand->interfaceName, SYMBOLIC_NAME_LEN, "%s", ioOperations_GetInterfaceName(connection_GetIoOperations(original))); - - listConnectionsCommand->state = - connection_IsUp(original) ? IFACE_UP : IFACE_DOWN; - listConnectionsCommand->connectionData.admin_state = - (connection_GetAdminState(original) == CONNECTION_STATE_UP) ? IFACE_UP : IFACE_DOWN; - listConnectionsCommand->connectionData.connectionType = - ioOperations_GetConnectionType(connection_GetIoOperations(original)); - - listConnectionsCommand->connectionData.admin_state = connection_GetAdminState(original); - -#ifdef WITH_POLICY - listConnectionsCommand->connectionData.priority = connection_GetPriority(original); - listConnectionsCommand->connectionData.tags = connection_GetTags(original); -#endif /* WITH_POLICY */ - - if (addressGetType(localAddress) == ADDR_INET && - addressGetType(remoteAddress) == ADDR_INET) { - listConnectionsCommand->connectionData.ipType = ADDR_INET; - - // get local port/address - addressGetInet(localAddress, &tmpAddr); - listConnectionsCommand->connectionData.localPort = tmpAddr.sin_port; - listConnectionsCommand->connectionData.localIp.v4.as_inaddr = - tmpAddr.sin_addr; - memset(&tmpAddr, 0, sizeof(tmpAddr)); - // get remote port/address - addressGetInet(remoteAddress, &tmpAddr); - listConnectionsCommand->connectionData.remotePort = tmpAddr.sin_port; - listConnectionsCommand->connectionData.remoteIp.v4.as_inaddr = - tmpAddr.sin_addr; - - } else if (addressGetType(localAddress) == ADDR_INET6 && - addressGetType(remoteAddress) == ADDR_INET6) { - listConnectionsCommand->connectionData.ipType = ADDR_INET6; - - // get local port/address - addressGetInet6(localAddress, &tmpAddr6); - listConnectionsCommand->connectionData.localPort = tmpAddr6.sin6_port; - listConnectionsCommand->connectionData.localIp.v6.as_in6addr = tmpAddr6.sin6_addr; - memset(&tmpAddr6, 0, sizeof(tmpAddr6)); - // get remote port/address - addressGetInet6(remoteAddress, &tmpAddr6); - listConnectionsCommand->connectionData.remotePort = tmpAddr6.sin6_port; - listConnectionsCommand->connectionData.remoteIp.v6.as_in6addr = tmpAddr6.sin6_addr; - - } // no need further else, control on the addressed already done at the - // time of insertion in the connection table - addressDestroy(&localAddress); - addressDestroy(&remoteAddress); - } - - // send response - header_control_message *header = request[0].iov_base; - header->messageType = RESPONSE_LIGHT; - header->length = (uint16_t)connectionList_Length(connList); - - struct iovec *response = - parcMemory_AllocateAndClear(sizeof(struct iovec) * 2); - - response[0].iov_base = header; - response[0].iov_len = sizeof(header_control_message); - response[1].iov_base = payloadResponse; - response[1].iov_len = - sizeof(list_connections_command) * connectionList_Length(connList); - - connectionList_Destroy(&connList); - return response; -} - -struct iovec *configuration_ProcessListenersList(Configuration *config, - struct iovec *request) { - ListenerSet *listenerList = forwarder_GetListenerSet(config->forwarder); - struct sockaddr_in tmpAddr; - struct sockaddr_in6 tmpAddr6; - - // allocate payload, cast from void* to uint8_t* fot bytes granularity - uint8_t *payloadResponse = parcMemory_AllocateAndClear( - sizeof(list_listeners_command) * listenerSet_Length(listenerList)); - - for (size_t i = 0; i < listenerSet_Length(listenerList); i++) { - ListenerOps *listenerEntry = listenerSet_Get(listenerList, i); - - // Fill payload by shifting and casting at each 'i' step. - list_listeners_command *listListenersCommand = - (list_listeners_command *)(payloadResponse + - (i * sizeof(list_listeners_command))); - - listListenersCommand->connid = - (uint32_t)listenerEntry->getInterfaceIndex(listenerEntry); - listListenersCommand->encapType = - (uint8_t)listenerEntry->getEncapType(listenerEntry); - if (addressGetType((const Address *)listenerEntry->getListenAddress( - listenerEntry)) == ADDR_INET) { - addressGetInet( - (const Address *)listenerEntry->getListenAddress(listenerEntry), - &tmpAddr); - listListenersCommand->addressType = ADDR_INET; - listListenersCommand->address.v4.as_inaddr = tmpAddr.sin_addr; - listListenersCommand->port = tmpAddr.sin_port; - } else if (addressGetType((const Address *)listenerEntry->getListenAddress( - listenerEntry)) == ADDR_INET6) { - addressGetInet6( - (const Address *)listenerEntry->getListenAddress(listenerEntry), - &tmpAddr6); - listListenersCommand->addressType = ADDR_INET6; - listListenersCommand->address.v6.as_in6addr = tmpAddr6.sin6_addr; - listListenersCommand->port = tmpAddr6.sin6_port; - } - - const char * listenerName = listenerEntry->getListenerName(listenerEntry); - snprintf(listListenersCommand->listenerName, SYMBOLIC_NAME_LEN, "%s", listenerName); - if (listenerEntry->getEncapType(listenerEntry) == ENCAP_TCP || - listenerEntry->getEncapType(listenerEntry) == ENCAP_UDP) { - const char * interfaceName = listenerEntry->getInterfaceName(listenerEntry); - snprintf(listListenersCommand->interfaceName, SYMBOLIC_NAME_LEN, "%s", interfaceName); - } - } - - // send response - header_control_message *header = request[0].iov_base; - header->messageType = RESPONSE_LIGHT; - header->length = (uint16_t)listenerSet_Length(listenerList); - - struct iovec *response = - parcMemory_AllocateAndClear(sizeof(struct iovec) * 2); - - response[0].iov_base = header; - response[0].iov_len = sizeof(header_control_message); - response[1].iov_base = payloadResponse; - response[1].iov_len = - sizeof(list_listeners_command) * listenerSet_Length(listenerList); - - return response; -} - -struct iovec *configuration_ProcessCacheStore(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - ; - cache_store_command *control = request[1].iov_base; - ; - - bool success = false; - - switch (control->activate) { - case ACTIVATE_ON: - forwarder_SetChacheStoreFlag(config->forwarder, true); - if (forwarder_GetChacheStoreFlag(config->forwarder)) { - success = true; - } - break; - - case ACTIVATE_OFF: - forwarder_SetChacheStoreFlag(config->forwarder, false); - if (!forwarder_GetChacheStoreFlag(config->forwarder)) { - success = true; - } - break; - - default: - break; - } - - struct iovec *response; - if (success) { // ACK - response = utils_CreateAck(header, control, sizeof(cache_store_command)); - } else { // NACK - response = utils_CreateNack(header, control, sizeof(cache_store_command)); - } - - return response; -} - -struct iovec *configuration_ProcessCacheServe(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - cache_serve_command *control = request[1].iov_base; - - bool success = false; - - switch (control->activate) { - case ACTIVATE_ON: - forwarder_SetChacheServeFlag(config->forwarder, true); - if (forwarder_GetChacheServeFlag(config->forwarder)) { - success = true; - } - break; - - case ACTIVATE_OFF: - forwarder_SetChacheServeFlag(config->forwarder, false); - if (!forwarder_GetChacheServeFlag(config->forwarder)) { - success = true; - } - break; - - default: - break; - } - - struct iovec *response; - if (success) { // ACK - response = utils_CreateAck(header, control, sizeof(cache_store_command)); - } else { // NACK - response = utils_CreateNack(header, control, sizeof(cache_store_command)); - } - - return response; -} - -struct iovec *configuration_ProcessCacheClear(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - - forwarder_ClearCache(config->forwarder); - - struct iovec *response = utils_CreateAck(header, NULL, 0); - return response; -} - -size_t configuration_GetObjectStoreSize(Configuration *config) { - return config->maximumContentObjectStoreSize; -} + WSADATA wsaData = {0}; + WSAStartup(MAKEWORD(2, 2), &wsaData); +#endif + configuration_set_loglevel(config, loglevel_from_str(DEFAULT_LOGLEVEL)); + config->strategy_map = kh_init_strategy_map(); -void _configuration_StoreFwdStrategy(Configuration *config, const char *prefix, - strategy_type strategy) { - PARCString *prefixStr = parcString_Create(prefix); - PARCUnsigned *strategyValue = parcUnsigned_Create((unsigned)strategy); - parcHashMap_Put(config->strategy_map, prefixStr, strategyValue); - parcUnsigned_Release(&strategyValue); - parcString_Release(&prefixStr); + return config; } -struct iovec *configuration_SetWldr(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - set_wldr_command *control = request[1].iov_base; - ConnectionTable *table = forwarder_GetConnectionTable(config->forwarder); - Connection *conn = NULL; - bool success = false; +void configuration_free(configuration_t *config) { + assert(config); - const char *symbolicOrConnid = control->symbolicOrConnid; + const char *k_prefix; + unsigned _; + (void)_; - if (utils_IsNumber(symbolicOrConnid)) { - // case for connid as input: check if connID present in the fwd table - conn = (Connection *)connectionTable_FindById( - table, (unsigned)strtold(symbolicOrConnid, NULL)); - if (conn) { - success = true; - } else { - logger_Log(forwarder_GetLogger(config->forwarder), LoggerFacility_IO, - PARCLogLevel_Error, __func__, - "ConnID not found, check list connections"); // failure - } - } else { - // case for symbolic as input: check if symbolic name can be resolved - unsigned connid = - symbolicNameTable_Get(config->symbolicNameTable, symbolicOrConnid); - if (connid != UINT32_MAX) { - conn = (Connection *)connectionTable_FindById(table, connid); - if (conn) { - if (logger_IsLoggable(config->logger, LoggerFacility_Config, - PARCLogLevel_Debug)) { - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Debug, - __func__, "Set wldr resolve name '%s' to connid %u", - symbolicOrConnid, connid); - } - success = true; - } - } else { - if (logger_IsLoggable(config->logger, LoggerFacility_Config, - PARCLogLevel_Warning)) { - logger_Log(config->logger, LoggerFacility_Config, PARCLogLevel_Error, - __func__, "Symbolic name '%s' could not be resolved", - symbolicOrConnid); - } // failure - } - } + // Free the strategy hashmap + kh_foreach(config->strategy_map, k_prefix, _, { free((char *)k_prefix); }); + kh_destroy_strategy_map(config->strategy_map); - // generate ACK/NACK - struct iovec *response; - - if (success) { - switch (control->activate) { - case ACTIVATE_ON: - connection_EnableWldr(conn); - response = utils_CreateAck(header, control, sizeof(set_wldr_command)); - break; - - case ACTIVATE_OFF: - connection_DisableWldr(conn); - response = utils_CreateAck(header, control, sizeof(set_wldr_command)); - break; - - default: // received wrong value - response = utils_CreateNack(header, control, sizeof(set_wldr_command)); - break; - } - } else { - response = utils_CreateNack(header, control, sizeof(set_wldr_command)); - } - - return response; + free(config); } -strategy_type configuration_GetForwardingStrategy(Configuration *config, - const char *prefix) { - PARCString *prefixStr = parcString_Create(prefix); - const unsigned *val = parcHashMap_Get(config->strategy_map, prefixStr); - parcString_Release(&prefixStr); - - if (val == NULL) { - return LAST_STRATEGY_VALUE; - } else { - return (strategy_type)*val; - } +size_t configuration_get_cs_size(const configuration_t *config) { + return config->cs_capacity; } -struct iovec *configuration_SetForwardingStrategy(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - set_strategy_command *control = request[1].iov_base; - - const char *prefix = utils_PrefixLenToString( - control->addressType, &control->address, &control->len); - strategy_type strategy = control->strategyType; - strategy_type existingFwdStrategy = - configuration_GetForwardingStrategy(config, prefix); - - if (existingFwdStrategy == LAST_STRATEGY_VALUE || - strategy != existingFwdStrategy) { - // means such a new strategy is not present in the hash table or has to be - // updated - _configuration_StoreFwdStrategy(config, prefix, strategy); - Name *hicnPrefix = name_CreateFromAddress(control->addressType, - control->address, control->len); - Name *related_prefixes[MAX_FWD_STRATEGY_RELATED_PREFIXES]; - if(control->related_prefixes != 0){ - for(int i = 0; i < control->related_prefixes; i++){ - related_prefixes[i] = name_CreateFromAddress( - control->addresses_type[i], - control->addresses[i], control->lens[i]); - } - } - forwarder_SetStrategy(config->forwarder, hicnPrefix, strategy, - control->related_prefixes, related_prefixes); - name_Release(&hicnPrefix); - if(control->related_prefixes != 0){ - for(int i = 0; i < control->related_prefixes; i++){ - name_Release(&related_prefixes[i]); - } - } - } - - free((char *) prefix); - struct iovec *response = - utils_CreateAck(header, control, sizeof(set_strategy_command)); - - return response; +void configuration_set_cs_size(configuration_t *config, size_t size) { + config->cs_capacity = size; } -void configuration_SetObjectStoreSize(Configuration *config, - size_t maximumObjectCount) { - config->maximumContentObjectStoreSize = maximumObjectCount; - - forwarder_SetContentObjectStoreSize(config->forwarder, - config->maximumContentObjectStoreSize); +const char *configuration_get_fn_config(const configuration_t *config) { + return config->fn_config; } -Forwarder *configuration_GetForwarder(const Configuration *config) { - return config->forwarder; +void configuration_set_fn_config(configuration_t *config, + const char *fn_config) { + config->fn_config = fn_config; } -Logger *configuration_GetLogger(const Configuration *config) { - return config->logger; +void configuration_set_port(configuration_t *config, uint16_t port) { + config->port = port; } -struct iovec *configuration_MapMeEnable(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - mapme_activator_command *control = request[1].iov_base; - const char *stateString[2] = {"on", "off"}; - - PARCBufferComposer *composer = parcBufferComposer_Create(); - parcBufferComposer_Format(composer, - "The mapme enable setting received is: %s", - stateString[control->activate]); - - PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer); - char *result = parcBuffer_ToString(tempBuffer); - parcBuffer_Release(&tempBuffer); - puts(result); - parcMemory_Deallocate((void **)&result); - parcBufferComposer_Release(&composer); - - return utils_CreateAck(header, control, sizeof(mapme_timing_command)); +uint16_t configuration_get_port(const configuration_t *config) { + return config->port; } -struct iovec *configuration_MapMeDiscovery(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - mapme_activator_command *control = request[1].iov_base; - const char *stateString[2] = {"on", "off"}; - - PARCBufferComposer *composer = parcBufferComposer_Create(); - parcBufferComposer_Format(composer, - "The mapme discovery setting received is: %s", - stateString[control->activate]); - - PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer); - char *result = parcBuffer_ToString(tempBuffer); - parcBuffer_Release(&tempBuffer); - puts(result); - parcMemory_Deallocate((void **)&result); - parcBufferComposer_Release(&composer); - - return utils_CreateAck(header, control, sizeof(mapme_timing_command)); +void configuration_set_configuration_port(configuration_t *config, + uint16_t configuration_port) { + config->configuration_port = configuration_port; } -struct iovec *configuration_MapMeTimescale(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - mapme_timing_command *control = request[1].iov_base; - - PARCBufferComposer *composer = parcBufferComposer_Create(); - parcBufferComposer_Format(composer, - "The mapme timescale value received is: %u", - control->timePeriod); - - PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer); - char *result = parcBuffer_ToString(tempBuffer); - parcBuffer_Release(&tempBuffer); - puts(result); - parcMemory_Deallocate((void **)&result); - parcBufferComposer_Release(&composer); - - return utils_CreateAck(header, control, sizeof(mapme_timing_command)); -} - -struct iovec *configuration_MapMeRetx(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - mapme_timing_command *control = request[1].iov_base; - - PARCBufferComposer *composer = parcBufferComposer_Create(); - parcBufferComposer_Format( - composer, "The mapme retransmission time value received is: %u", - control->timePeriod); - - PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer); - char *result = parcBuffer_ToString(tempBuffer); - parcBuffer_Release(&tempBuffer); - puts(result); - parcMemory_Deallocate((void **)&result); - parcBufferComposer_Release(&composer); - - return utils_CreateAck(header, control, sizeof(mapme_timing_command)); +uint16_t configuration_get_configuration_port(const configuration_t *config) { + return config->configuration_port; } -struct iovec * configuration_MapMeSendUpdate(Configuration *config, - struct iovec *request, unsigned ingressId) { - header_control_message *header = request[0].iov_base; - mapme_send_update_command *control = request[1].iov_base; - - FIB * fib = forwarder_getFib(config->forwarder); - if (!fib) - goto ERR; - Name *prefix = name_CreateFromAddress(control->addressType, control->address, - control->len); - if (!prefix) - goto ERR; - FibEntry *entry = fib_Contains(fib, prefix); - name_Release(&prefix); - if (!entry) - goto ERR; - - const NumberSet * nexthops = fibEntry_GetNexthops(entry); - unsigned size = (unsigned) numberSet_Length(nexthops); - - /* The command is accepted iif triggered by (one of) the producer of this prefix */ - for (unsigned i = 0; i < size; i++) { - unsigned nhop = numberSet_GetItem(nexthops, i); - if (nhop == ingressId) { - MapMe * mapme = forwarder_getMapmeInstance(config->forwarder); - mapme_send_updates(mapme, entry, nexthops); - return utils_CreateAck(header, control, sizeof(mapme_timing_command)); - } - } - -ERR: - return utils_CreateNack(header, control, sizeof(connection_set_admin_state_command)); +void configuration_set_loglevel(configuration_t *config, int loglevel) { + config->loglevel = loglevel; + log_conf.log_level = loglevel; } - -struct iovec *configuration_ConnectionSetAdminState(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - connection_set_admin_state_command *control = request[1].iov_base; - - if ((control->admin_state != CONNECTION_STATE_UP) && (control->admin_state != CONNECTION_STATE_DOWN)) - return utils_CreateNack(header, control, sizeof(connection_set_admin_state_command)); - - Connection * conn = getConnectionBySymbolicOrId(config, control->symbolicOrConnid); - if (!conn) - return utils_CreateNack(header, control, sizeof(connection_set_admin_state_command)); - - connection_SetAdminState(conn, control->admin_state); - -#ifdef WITH_MAPME - /* Hook: connection event */ - forwarder_onConnectionEvent(config->forwarder, conn, - control->admin_state == CONNECTION_STATE_UP - ? CONNECTION_EVENT_SET_UP - : CONNECTION_EVENT_SET_DOWN); -#endif /* WITH_MAPME */ - - return utils_CreateAck(header, control, sizeof(connection_set_admin_state_command)); +int configuration_get_loglevel(const configuration_t *config) { + return config->loglevel; } -#ifdef WITH_POLICY - -struct iovec *configuration_ConnectionSetPriority(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - connection_set_priority_command *control = request[1].iov_base; - - Connection * conn = getConnectionBySymbolicOrId(config, control->symbolicOrConnid); - if (!conn) - return utils_CreateNack(header, control, sizeof(connection_set_priority_command)); - - connection_SetPriority(conn, control->priority); - -#ifdef WITH_MAPME - /* Hook: connection event */ - forwarder_onConnectionEvent(config->forwarder, conn, - CONNECTION_EVENT_PRIORITY_CHANGED); -#endif /* WITH_MAPME */ - - return utils_CreateAck(header, control, sizeof(connection_set_priority_command)); +void configuration_set_logfile(configuration_t *config, const char *logfile) { + config->logfile = logfile; + log_conf.log_file = fopen(logfile, "w"); + config->logfile_fd = fileno(log_conf.log_file); } -struct iovec *configuration_ConnectionSetTags(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - connection_set_tags_command *control = request[1].iov_base; - - Connection * conn = getConnectionBySymbolicOrId(config, control->symbolicOrConnid); - if (!conn) - return utils_CreateNack(header, control, sizeof(connection_set_tags_command)); - - connection_SetTags(conn, control->tags); - -#ifdef WITH_MAPME - /* Hook: connection event */ - forwarder_onConnectionEvent(config->forwarder, conn, - CONNECTION_EVENT_TAGS_CHANGED); -#endif /* WITH_MAPME */ - - return utils_CreateAck(header, control, sizeof(connection_set_tags_command)); +const char *configuration_get_logfile(const configuration_t *config) { + return config->logfile; } -struct iovec *configuration_ProcessPolicyAdd(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - add_policy_command *control = request[1].iov_base; - - if (forwarder_AddOrUpdatePolicy(config->forwarder, control)) { - return utils_CreateAck(header, control, sizeof(add_policy_command)); - } else { - return utils_CreateNack(header, control, sizeof(add_policy_command)); - } +int configuration_get_logfile_fd(const configuration_t *config) { + return config->logfile_fd; } -struct iovec *configuration_ProcessPolicyList(Configuration *config, - struct iovec *request) { - FibEntryList *fibList = forwarder_GetFibEntries(config->forwarder); - - size_t payloadSize = fibEntryList_Length(fibList); - struct sockaddr_in tmpAddr; - struct sockaddr_in6 tmpAddr6; - - // allocate payload, cast from void* to uint8_t* = bytes granularity - uint8_t *payloadResponse = - parcMemory_AllocateAndClear(sizeof(list_policies_command) * payloadSize); - - for (size_t i = 0; i < fibEntryList_Length(fibList); i++) { - FibEntry *entry = (FibEntry *)fibEntryList_Get(fibList, i); - NameBitvector *prefix = name_GetContentName(fibEntry_GetPrefix(entry)); - - list_policies_command *listPoliciesCommand = - (list_policies_command *)(payloadResponse + - (i * sizeof(list_policies_command))); - - Address *addressEntry = nameBitvector_ToAddress(prefix); - if (addressGetType(addressEntry) == ADDR_INET) { - addressGetInet(addressEntry, &tmpAddr); - listPoliciesCommand->addressType = ADDR_INET; - listPoliciesCommand->address.v4.as_inaddr = tmpAddr.sin_addr; - } else if (addressGetType(addressEntry) == ADDR_INET6) { - addressGetInet6(addressEntry, &tmpAddr6); - listPoliciesCommand->addressType = ADDR_INET6; - listPoliciesCommand->address.v6.as_in6addr = tmpAddr6.sin6_addr; - } - listPoliciesCommand->len = nameBitvector_GetLength(prefix); - listPoliciesCommand->policy = fibEntry_GetPolicy(entry); - - addressDestroy(&addressEntry); - } - - // send response - header_control_message *header = request[0].iov_base; - header->messageType = RESPONSE_LIGHT; - header->length = (unsigned)payloadSize; - - struct iovec *response = - parcMemory_AllocateAndClear(sizeof(struct iovec) * 2); - - response[0].iov_base = header; - response[0].iov_len = sizeof(header_control_message); - response[1].iov_base = payloadResponse; - response[1].iov_len = sizeof(list_policies_command) * payloadSize; - - fibEntryList_Destroy(&fibList); - return response; +void configuration_set_daemon(configuration_t *config, bool daemon) { + config->daemon = daemon; } -struct iovec *configuration_ProcessPolicyRemove(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - remove_policy_command *control = request[1].iov_base; - - if (forwarder_RemovePolicy(config->forwarder, control)) - return utils_CreateAck(header, control, sizeof(remove_policy_command)); - else - return utils_CreateNack(header, control, sizeof(remove_policy_command)); +bool configuration_get_daemon(const configuration_t *config) { + return config->daemon; } -struct iovec *configuration_UpdateConnection(Configuration *config, - struct iovec *request) { - header_control_message *header = request[0].iov_base; - update_connection_command *control = request[1].iov_base; - - Connection * conn = getConnectionBySymbolicOrId(config, control->symbolicOrConnid); - if (!conn) - return utils_CreateNack(header, control, sizeof(update_connection_command)); - - connection_SetTags(conn, control->tags); - connection_SetAdminState(conn, control->admin_state); - if (control->priority > 0) - connection_SetPriority(conn, control->priority); - - return utils_CreateAck(header, control, sizeof(update_connection_command)); +void configuration_set_strategy(configuration_t *config, const char *prefix, + strategy_type_t strategy_type) { + int res; + khiter_t k = kh_put_strategy_map(config->strategy_map, strdup(prefix), &res); + kh_value(config->strategy_map, k) = strategy_type; } -#endif /* WITH_POLICY */ - -// =========================== -// Main functions that deal with receiving commands, executing them, and sending -// ACK/NACK - -struct iovec *configuration_DispatchCommand(Configuration *config, - command_id command, - struct iovec *control, - unsigned ingressId) { - struct iovec *response = NULL; - switch (command) { - case ADD_LISTENER: - response = configurationListeners_Add(config, control, ingressId); - break; - - case ADD_CONNECTION: - response = configuration_ProcessCreateTunnel(config, control); - break; - - case LIST_CONNECTIONS: - response = configuration_ProcessConnectionList(config, control); - break; - - case ADD_ROUTE: - response = - configuration_ProcessRegisterHicnPrefix(config, control, ingressId); - break; - - case LIST_ROUTES: - response = configuration_ProcessRegistrationList(config, control); - break; - - case REMOVE_CONNECTION: - response = configuration_ProcessRemoveTunnel(config, control, ingressId); - break; - - case REMOVE_LISTENER: - response = configuration_ProcessRemoveListener(config, control, ingressId); - break; - - case REMOVE_ROUTE: - response = configuration_ProcessUnregisterHicnPrefix(config, control); - break; - - case CACHE_STORE: - response = configuration_ProcessCacheStore(config, control); - break; - - case CACHE_SERVE: - response = configuration_ProcessCacheServe(config, control); - break; - - case CACHE_CLEAR: - response = configuration_ProcessCacheClear(config, control); - break; - - case SET_STRATEGY: - response = configuration_SetForwardingStrategy(config, control); - break; - - case SET_WLDR: - response = configuration_SetWldr(config, control); - break; - - case ADD_PUNTING: - response = configurationListeners_AddPunting(config, control, ingressId); - break; - case LIST_LISTENERS: - response = configuration_ProcessListenersList(config, control); - break; - - case MAPME_ENABLE: - response = configuration_MapMeEnable(config, control); - break; - - case MAPME_DISCOVERY: - response = configuration_MapMeDiscovery(config, control); - break; - - case MAPME_TIMESCALE: - response = configuration_MapMeTimescale(config, control); - break; - - case MAPME_RETX: - response = configuration_MapMeRetx(config, control); - break; - - case MAPME_SEND_UPDATE: - response = configuration_MapMeSendUpdate(config, control, ingressId); - break; - - case CONNECTION_SET_ADMIN_STATE: - response = configuration_ConnectionSetAdminState(config, control); - break; - -#ifdef WITH_POLICY - case ADD_POLICY: - response = configuration_ProcessPolicyAdd(config, control); - break; - - case LIST_POLICIES: - response = configuration_ProcessPolicyList(config, control); - break; - - case REMOVE_POLICY: - response = configuration_ProcessPolicyRemove(config, control); - break; - - case UPDATE_CONNECTION: - response = configuration_UpdateConnection(config, control); - break; - - case CONNECTION_SET_PRIORITY: - response = configuration_ConnectionSetPriority(config, control); - break; - - case CONNECTION_SET_TAGS: - response = configuration_ConnectionSetTags(config, control); - break; -#endif /* WITH_POLICY */ - - default: - break; - } - - return response; +strategy_type_t configuration_get_strategy(const configuration_t *config, + const char *prefix) { + khiter_t k = kh_get_strategy_map(config->strategy_map, prefix); + if (k == kh_end(config->strategy_map)) return STRATEGY_TYPE_UNDEFINED; + return kh_val(config->strategy_map, k); } -void configuration_ReceiveCommand(Configuration *config, command_id command, - struct iovec *request, unsigned ingressId) { - parcAssertNotNull(config, "Parameter config must be non-null"); - parcAssertNotNull(request, "Parameter request must be non-null"); - struct iovec *response = - configuration_DispatchCommand(config, command, request, ingressId); - configuration_SendResponse(config, response, ingressId); - - /* - * The message is originally received by a listener, and will be freed in - * different parts of the code. - * - * For the special case of commands, a iovec is created, eg in - * udpListener::_readCommand, which has to be freed (it is commented in the - * listener). On the contrary, the original message is freed. - * - * From this function, commands are dispatched to different processing - * functions, which have two general behaviours: - * - * - LIST commands: - * . a payload for the response is allocated - * . a iovec for the response is allocated with header = request header, - * payload = newly allocated payload - * - * - Other commands: - * . a ack/nack packet is generated thanks to utils/utils.cc - * . this allocates a iovec which reuses the header of the request just - * updating the messageType field inside. - */ - parcMemory_Deallocate(&request); - - switch (command) { - case LIST_CONNECTIONS: - case LIST_ROUTES: // case LIST_INTERFACES: case ETC...: - case LIST_LISTENERS: - case LIST_POLICIES: - /* Deallocate payload */ - parcMemory_Deallocate(&response[1].iov_base); - break; - default: - break; - } - - parcMemory_Deallocate(&response); +void configuration_flush_log() { + if (log_conf.log_file) fclose(log_conf.log_file); } diff --git a/hicn-light/src/hicn/config/configuration.h b/hicn-light/src/hicn/config/configuration.h index 5090f1413..9861b6c9f 100644 --- a/hicn-light/src/hicn/config/configuration.h +++ b/hicn-light/src/hicn/config/configuration.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. + * Copyright (c) 2021 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: @@ -23,17 +23,18 @@ * */ -#ifndef configuration_h -#define configuration_h +#ifndef HICNLIGHT_CONFIGURATION_H +#define HICNLIGHT_CONFIGURATION_H -#include <hicn/core/logger.h> -#include <hicn/utils/commands.h> +#include "../base/khash.h" +#include "../core/msgbuf.h" +#include "../core/strategy.h" +#include <hicn/ctrl/api.h> +#include <hicn/ctrl/hicn-light-ng.h> -struct configuration; -typedef struct configuration Configuration; +KHASH_MAP_INIT_STR(strategy_map, unsigned); -struct forwarder; -typedef struct forwarder Forwarder; +typedef struct configuration_s configuration_t; /** * <#One Line Description#> @@ -49,7 +50,7 @@ typedef struct forwarder Forwarder; * <#example#> * @endcode */ -Configuration *configuration_Create(Forwarder *forwarder); +configuration_t *configuration_create(); /** * <#One Line Description#> @@ -65,13 +66,7 @@ Configuration *configuration_Create(Forwarder *forwarder); * <#example#> * @endcode */ -void configuration_Destroy(Configuration **configPtr); - -void configuration_SetupAllListeners(Configuration *config, uint16_t port, - const char *localPath); - -void configuration_ReceiveCommand(Configuration *config, command_id command, - struct iovec *request, unsigned ingressId); +void configuration_free(configuration_t *config); /** * Returns the configured size of the content store @@ -87,7 +82,7 @@ void configuration_ReceiveCommand(Configuration *config, command_id command, * <#example#> * @endcode */ -size_t configuration_GetObjectStoreSize(Configuration *config); +size_t configuration_get_cs_size(const configuration_t *config); /** * Sets the size of the content store (in objects, not bytes) @@ -101,52 +96,42 @@ size_t configuration_GetObjectStoreSize(Configuration *config); * <#example#> * @endcode */ -void configuration_SetObjectStoreSize(Configuration *config, - size_t maximumContentObjectCount); +void configuration_set_cs_size(configuration_t *config, size_t size); -strategy_type configuration_GetForwardingStrategy(Configuration *config, - const char *prefix); +const char *configuration_get_fn_config(const configuration_t *config); -/** - * Returns the Forwarder that owns the Configuration - * - * Returns the hicn-light Forwarder. Used primarily by associated classes in - * the configuration group. - * - * @param [in] config An allocated Configuration - * - * @return non-null The owning Forwarder - * @return null An error - * - * Example: - * @code - * { - * <#example#> - * } - * @endcode - */ -Forwarder *configuration_GetForwarder(const Configuration *config); +void configuration_set_fn_config(configuration_t *config, + const char *fn_config); -/** - * Returns the logger used by the Configuration subsystem - * - * Returns the logger specified when the Configuration was created. - * - * @param [in] config An allocated Configuration - * - * @retval non-null The logger - * @retval null An error - * - * Example: - * @code - * <#example#> - * @endcode - */ -Logger *configuration_GetLogger(const Configuration *config); +void configuration_set_port(configuration_t *config, uint16_t port); + +uint16_t configuration_get_port(const configuration_t *config); + +void configuration_set_configuration_port(configuration_t *config, + uint16_t configuration_port); + +uint16_t configuration_get_configuration_port(const configuration_t *config); + +void configuration_set_loglevel(configuration_t *config, int loglevel); + +int configuration_get_loglevel(const configuration_t *config); + +void configuration_set_logfile(configuration_t *config, const char *logfile); + +const char *configuration_get_logfile(const configuration_t *config); + +int configuration_get_logfile_fd(const configuration_t *config); + +void configuration_set_daemon(configuration_t *config, bool daemon); + +bool configuration_get_daemon(const configuration_t *config); + +void configuration_set_strategy(configuration_t *config, const char *prefix, + strategy_type_t strategy_type); + +strategy_type_t configuration_get_strategy(const configuration_t *config, + const char *prefix); -struct iovec *configuration_DispatchCommand(Configuration *config, - command_id command, - struct iovec *control, - unsigned ingressId); +void configuration_flush_log(); -#endif // configuration_h +#endif // HICNLIGHT_CONFIGURATION_H diff --git a/hicn-light/src/hicn/config/configurationFile.c b/hicn-light/src/hicn/config/configurationFile.c deleted file mode 100644 index ebf057fa6..000000000 --- a/hicn-light/src/hicn/config/configurationFile.c +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _WIN32 -#include <unistd.h> -#endif -#include <ctype.h> -#include <errno.h> -#include <hicn/hicn-light/config.h> -#include <stdio.h> -#include <string.h> - -#include <parc/algol/parc_ArrayList.h> -#include <parc/algol/parc_List.h> -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Object.h> -#include <parc/assert/parc_Assert.h> -#include <hicn/config/configuration.h> -#include <hicn/config/configurationFile.h> -#include <hicn/config/controlRoot.h> -#include <hicn/config/controlState.h> - -struct configuration_file { - Forwarder *forwarder; - const char *filename; - FILE *fh; - - size_t linesRead; - - // our custom state machine. - ControlState *controlState; -}; - -/* - * Called by a command to dispatch the correct command - */ -struct iovec *_writeRead(ControlState *state, struct iovec *msg) { - ConfigurationFile *configFile = - (ConfigurationFile *)controlState_GetUserdata(state); - - parcAssertNotNull(msg, "Parameter msg must be non-null"); - struct iovec *response = configuration_DispatchCommand( - forwarder_GetConfiguration(configFile->forwarder), - ((header_control_message *)msg[0].iov_base)->commandID, msg, 0); - - return response; -} - -/** - * Removes leading whitespace (space + tab). - * - * If the string is all whitespace, the return value will point to the - * terminating '\0'. - * - * @param [in] str A null-terminated c-string - * - * @retval non-null A pointer in to string of the first non-whitespace - * - * - * Example: - * @code - * <#example#> - * @endcode - */ -static char *_stripLeadingWhitespace(char *str) { - while (isspace(*str)) { - str++; - } - return str; -} - -/** - * Removes trailing whitespace - * - * Inserts a NULL after the last non-whitespace character, modiyfing the input - * string. - * - * @param [in] str A null-terminated c-string - * - * @return non-null A pointer to the input string - * - * Example: - * @code - * { - * <#example#> - * } - * @endcode - */ -static char *_stripTrailingWhitespace(char *str) { - char *p = str + strlen(str) - 1; - while (p > str && isspace(*p)) { - p--; - } - - // cap it. If no whitespace, p+1 == str + strlen(str), so will overwrite the - // current null. If all whitespace p+1 == str+1. For an empty string, p+1 = - // str. - *(p + 1) = 0; - - // this does not catch the case where the entire string is whitespace - if (p == str && isspace(*p)) { - *p = 0; - } - - return str; -} - -/** - * Removed leading and trailing whitespace - * - * Modifies the input string (may add a NULL at the end). Will return - * a pointer to the first non-whitespace character or the terminating NULL. - * - * @param [in] str A null-terminated c-string - * - * @return non-null A pointer in to the input string - * - * Example: - * @code - * { - * <#example#> - * } - * @endcode - */ -static char *_trim(char *str) { - return _stripTrailingWhitespace(_stripLeadingWhitespace(str)); -} - -/** - * Parse a string in to a PARCList with one word per element - * - * The string passed will be modified by inserting NULLs after each token. - * - * @param [in] str A c-string (will be modified) - * - * @retval non-null A PARCList where each item is a single word - * - * Example: - * @code - * <#example#> - * @endcode - */ -static PARCList *_parseArgs(char *str) { - PARCList *list = - parcList(parcArrayList_Create(NULL), PARCArrayListAsPARCList); - - const char delimiters[] = " \t"; - - char *token; - token = strtok(str, delimiters); - while (token != NULL) { - if (strlen(token) > 0) { - parcList_Add(list, strdup(token)); - } - token = strtok(NULL, delimiters); - } - // while ((token = strsep(&str, delimiters)) != NULL) { - // parcList_Add(list, token); - // } - - return list; -} - -// ============================================================= - -static void _destroy(ConfigurationFile **configFilePtr) { - ConfigurationFile *configFile = *configFilePtr; - parcMemory_Deallocate((void **)&configFile->filename); - - if (configFile->fh != NULL) { - fclose(configFile->fh); - } - - controlState_Destroy(&configFile->controlState); -} - -parcObject_ExtendPARCObject(ConfigurationFile, _destroy, NULL, NULL, NULL, NULL, - NULL, NULL); - -parcObject_ImplementRelease(configurationFile, ConfigurationFile); - -ConfigurationFile *configurationFile_Create(Forwarder *forwarder, - const char *filename) { - parcAssertNotNull(forwarder, "Parameter hicn-fwd must be non-null"); - parcAssertNotNull(filename, "Parameter filename must be non-null"); - - ConfigurationFile *configFile = parcObject_CreateInstance(ConfigurationFile); - - if (configFile) { - configFile->linesRead = 0; - configFile->forwarder = forwarder; - configFile->filename = - parcMemory_StringDuplicate(filename, strlen(filename)); - parcAssertNotNull(configFile->filename, "Could not copy string '%s'", - filename); - - // setup the control state for the command parser: last parameter NULL - // because - // writeRead still not implemented from configuration file. - configFile->controlState = - controlState_Create(configFile, _writeRead, false, - SRV_CTRL_IP, SRV_CTRL_PORT); - - // we do not register Help commands - controlState_RegisterCommand(configFile->controlState, - controlRoot_Create(configFile->controlState)); - - // open the file and make sure we can read it - configFile->fh = fopen(configFile->filename, "r"); - - if (configFile->fh) { - if (logger_IsLoggable(forwarder_GetLogger(forwarder), - LoggerFacility_Config, PARCLogLevel_Debug)) { - logger_Log(forwarder_GetLogger(forwarder), LoggerFacility_Config, - PARCLogLevel_Debug, __func__, "Open config file %s", - configFile->filename); - } - } else { - if (logger_IsLoggable(forwarder_GetLogger(forwarder), - LoggerFacility_Config, PARCLogLevel_Error)) { - logger_Log(forwarder_GetLogger(forwarder), LoggerFacility_Config, - PARCLogLevel_Error, __func__, - "Could not open config file %s: (%d) %s", - configFile->filename, errno, strerror(errno)); - } - - // failure cleanup the object -- this nulls it so final return null be - // NULL - configurationFile_Release(&configFile); - } - } - return configFile; -} - -bool configurationFile_Process(ConfigurationFile *configFile) { - parcAssertNotNull(configFile, "Parameter configFile must be non-null"); - - // default to a "true" return value and only set to false if we encounter an - // error. - bool success = true; - -#define BUFFERLEN 2048 - char buffer[BUFFERLEN]; - - configFile->linesRead = 0; - - // always clear errors and fseek to start of file in case we get called - // multiple times. - clearerr(configFile->fh); - rewind(configFile->fh); - - while (success && fgets(buffer, BUFFERLEN, configFile->fh) != NULL) { - configFile->linesRead++; - - char *stripedBuffer = _trim(buffer); - if (strlen(stripedBuffer) > 0) { - if (stripedBuffer[0] != '#') { - // not empty and not a comment - - // _parseArgs will modify the string - char *copy = - parcMemory_StringDuplicate(stripedBuffer, strlen(stripedBuffer)); - PARCList *args = _parseArgs(copy); - char output[8192]; - CommandReturn result = - controlState_DispatchCommand(configFile->controlState, args, output, sizeof(output)); - - // we ignore EXIT from the configuration file - if (result == CommandReturn_Failure) { - if (logger_IsLoggable(forwarder_GetLogger(configFile->forwarder), - LoggerFacility_Config, PARCLogLevel_Error)) { - logger_Log(forwarder_GetLogger(configFile->forwarder), - LoggerFacility_Config, PARCLogLevel_Error, __func__, - "Error on input file %s line %d: %s", - configFile->filename, configFile->linesRead, - stripedBuffer); - } - success = false; - } - for(int i = 0; i < parcList_Size(args); i++){ - free(parcList_GetAtIndex(args, i)); - } - parcList_Release(&args); - parcMemory_Deallocate((void **)©); - } - } - } - - if (ferror(configFile->fh)) { - if (logger_IsLoggable(forwarder_GetLogger(configFile->forwarder), - LoggerFacility_Config, PARCLogLevel_Error)) { - logger_Log(forwarder_GetLogger(configFile->forwarder), - LoggerFacility_Config, PARCLogLevel_Error, __func__, - "Error on input file %s line %d: (%d) %s", - configFile->filename, configFile->linesRead, errno, - strerror(errno)); - } - success = false; - } - - return success; -} diff --git a/hicn-light/src/hicn/config/configurationFile.h b/hicn-light/src/hicn/config/configurationFile.h deleted file mode 100644 index b748dfc15..000000000 --- a/hicn-light/src/hicn/config/configurationFile.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file configurationFile.h - * @brief Accepts a filename and provides a means to read it into Configuration - * - * Reads a configuration file and converts the lines in to configuration - * commands for use in Configuration. - * - * Accepts '#' lines as comments. Skips blank and whitespace-only lines. - * - */ - -#ifndef configurationFile_h -#define configurationFile_h - -#include <hicn/core/forwarder.h> - -struct configuration_file; -typedef struct configuration_file ConfigurationFile; - -/** - * Creates a ConfigurationFile to prepare to process the file - * - * Prepares the object and opens the file. Makes sure we can read the file. - * Does not read the file or process any commands from the file. - * - * @param [in] hicn-light An allocated Forwarder to configure with the file - * @param [in] filename The file to use - * - * @retval non-null An allocated ConfigurationFile that is readable - * @retval null An error - * - * Example: - * @code - * <#example#> - * @endcode - */ -ConfigurationFile *configurationFile_Create(Forwarder *forwarder, - const char *filename); - -/** - * Reads the configuration file line-by-line and issues commands to - * Configuration - * - * Reads the file line by line. Skips '#' and blank lines. - * - * Will stop on the first error. Lines already processed will not be un-done. - * - * @param [in] configFile An allocated ConfigurationFile - * - * @retval true The entire files was processed without error. - * @retval false There was an error in the file. - * - * Example: - * @code - * <#example#> - * @endcode - */ -bool configurationFile_Process(ConfigurationFile *configFile); - -// void configurationFile_ProcessForwardingStrategies(Configuration * config, -// ConfigurationFile * configFile); - -/** - * Closes the underlying file and releases memory - * - * <#Paragraphs Of Explanation#> - * - * @param [in,out] configFilePtr An allocated ConfigurationFile that will be - * NULL'd as output - * - * Example: - * @code - * <#example#> - * @endcode - */ -void configurationFile_Release(ConfigurationFile **configFilePtr); - -#endif /* defined(configurationFile_h) */ diff --git a/hicn-light/src/hicn/config/configurationListeners.c b/hicn-light/src/hicn/config/configurationListeners.c deleted file mode 100644 index 31a0c4776..000000000 --- a/hicn-light/src/hicn/config/configurationListeners.c +++ /dev/null @@ -1,629 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 _WIN32 -#include <arpa/inet.h> -#include <unistd.h> -#endif -#include <parc/assert/parc_Assert.h> -#include <hicn/hicn-light/config.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> - -#include <hicn/core/system.h> -#include <hicn/utils/interfaceSet.h> -#include <hicn/utils/punting.h> - -#include <hicn/config/configurationListeners.h> -#include <hicn/io/hicnListener.h> -#include <hicn/io/tcpListener.h> -#include <hicn/io/udpListener.h> - -#include <hicn/utils/address.h> -#include <hicn/utils/addressList.h> -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static bool _setupHicnListenerOnInet4(Forwarder *forwarder, - const char *symbolic, Address *address) { - bool success = false; -#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING) - ListenerOps *ops = - hicnListener_CreateInet(forwarder, (char *)symbolic, address); - if (ops != NULL) { - success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops); - parcAssertTrue(success, "Failed to add Hicn listener %s to ListenerSet", - symbolic); - } -#endif /* __APPLE__ _WIN32*/ - return success; -} - -static bool _setupHicnListenerOnInet6(Forwarder *forwarder, - const char *symbolic, Address *address) { - bool success = false; -#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING) - ListenerOps *ops = - hicnListener_CreateInet6(forwarder, (char *)symbolic, address); - if (ops != NULL) { - success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops); - parcAssertTrue(success, "Failed to add Hicn listener %s to ListenerSet", - symbolic); - } -#endif /* __APPLE__ _WIN32 */ - return success; -} - -bool configurationListeners_Remove(const Configuration *config) { - Logger *logger = configuration_GetLogger(config); - if (logger_IsLoggable(logger, LoggerFacility_Config, PARCLogLevel_Warning)) { - logger_Log(logger, LoggerFacility_Config, PARCLogLevel_Warning, __func__, - "Removing a listener not supported: ingress %u control %s"); - } - - return false; -} - -bool _AddPuntingInet(const Configuration *config, Punting *punting, - unsigned ingressId) { -#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING) - struct sockaddr *addr = parcNetwork_SockAddress("0.0.0.0", 1234); - if (addr == NULL) { - printf("Error creating address\n"); - return false; - } - - Address *fakeAddr = addressCreateFromInet((struct sockaddr_in *)addr); - - ListenerOps *listenerOps = listenerSet_Find( - forwarder_GetListenerSet(configuration_GetForwarder(config)), ENCAP_HICN, - fakeAddr); - addressDestroy(&fakeAddr); - - if (listenerOps == NULL) { - printf("the main listener (IPV4) does not exists\n"); - return false; - } - - struct sockaddr_in puntingAddr; - - Address *address = puntingGetAddress(punting); - if (address == NULL) return false; - - bool res = addressGetInet(address, &puntingAddr); - if (!res) { - printf("unable to read the punting address\n"); - return false; - } - - char prefix[INET_ADDRSTRLEN]; - inet_ntop(AF_INET, &(puntingAddr.sin_addr), prefix, INET_ADDRSTRLEN); - - char len[5]; - sprintf(len, "%d", puntingPrefixLen(punting)); - - char *prefixStr = - malloc(strlen(prefix) + strlen(len) + 2); //+1 for the zero-terminator - if (prefixStr == NULL) { - printf("error while create the prefix string\n"); - return false; - } - strcpy(prefixStr, prefix); - strcat(prefixStr, "/"); - strcat(prefixStr, len); - - res = hicnListener_Punting(listenerOps, prefixStr); - if (!res) { - printf("error while adding the punting rule\n"); - return false; - } - - return true; -#else - return false; -#endif -} - -bool _AddPuntingInet6(const Configuration *config, Punting *punting, - unsigned ingressId) { -#if !defined(__APPLE__) && !defined(_WIN32) && defined(PUNTING) - struct sockaddr *addr = parcNetwork_SockAddress("0::0", 1234); - if (addr == NULL) { - printf("Error creating address\n"); - return false; - } - - Address *fakeAddr = addressCreateFromInet6((struct sockaddr_in6 *)addr); - - // comments: - // EncapType: I use the Hicn encap since the punting is available only for - // Hicn listeners LocalAddress: The only listern for which we need punting - // rules is the main one, which has no address - // so I create a fake empty address. This need to be consistent - // with the address set at creation time - - ListenerOps *listenerOps = listenerSet_Find( - forwarder_GetListenerSet(configuration_GetForwarder(config)), ENCAP_HICN, - fakeAddr); - addressDestroy(&fakeAddr); - - if (listenerOps == NULL) { - printf("the main listener does not exists\n"); - return false; - } - - struct sockaddr_in6 puntingAddr; - bool res = addressGetInet6(puntingGetAddress(punting), &puntingAddr); - if (!res) { - printf("unable to read the punting address\n"); - return false; - } - - char prefix[INET6_ADDRSTRLEN]; - inet_ntop(AF_INET6, &(puntingAddr.sin6_addr), prefix, INET6_ADDRSTRLEN); - - char len[5]; - sprintf(len, "%d", puntingPrefixLen(punting)); - - char *prefixStr = - malloc(strlen(prefix) + strlen(len) + 2); //+1 for the zero-terminator - if (prefixStr == NULL) { - printf("error while create the prefix string\n"); - return false; - } - strcpy(prefixStr, prefix); - strcat(prefixStr, "/"); - strcat(prefixStr, len); - - res = hicnListener_Punting(listenerOps, prefixStr); - if (!res) { - printf("error while adding the punting rule\n"); - return false; - } - - return true; -#else - return false; -#endif -} - -//============= LIGHT COMMAN =============== - -static bool _addEther(Configuration *config, add_listener_command *control, - unsigned ingressId) { - // Not implemented - return false; -} - -/* - * Create a new IPV4/TCP listener. - * - * @param [in,out] forwarder The hicn-light forwarder instance - * @param [in] listenerName The name of the listener - * @param [in] addr4 The ipv4 address in network byte order - * @param [in] port The port number in network byte order - * @param [in] interfaceName The name of the interface to bind the socket - * - * return true if success, false otherwise - */ -static bool _setupTcpListenerOnInet(Forwarder *forwarder, char *listenerName, ipv4_addr_t *addr4, - uint16_t *port, char *interfaceName) { - parcAssertNotNull(listenerName, "Parameter listenerName must be non-null"); - - bool success = false; - - struct sockaddr_in addr; - memset(&addr, 0, sizeof(addr)); - addr.sin_family = AF_INET; - addr.sin_port = *port; - addr.sin_addr.s_addr = *addr4; - - ListenerOps *ops = tcpListener_CreateInet(forwarder, listenerName, addr, interfaceName); - if (ops) { - success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops); -#if 0 - parcAssertTrue(success, "Failed to add TCP listener on %s to ListenerSet", - addressToString(ops->getListenAddress(ops))); -#endif - } - return success; -} - - -/* - * Create a new IPV4/UDP listener. - * - * @param [in,out] forwarder The hicn-light forwarder instance - * @param [in] listenerName The name of the listener - * @param [in] addr4 The ipv4 address in network byte order - * @param [in] port The port number in network byte order - * @param [in] interfaceName The name of the interface to bind the socket - * - * return true if success, false otherwise - */ -static bool _setupUdpListenerOnInet(Forwarder *forwarder, char *listenerName, ipv4_addr_t *addr4, - uint16_t *port, char *interfaceName) { - bool success = false; - - struct sockaddr_in addr; - memset(&addr, 0, sizeof(addr)); - addr.sin_family = AF_INET; - addr.sin_port = *port; - addr.sin_addr.s_addr = *addr4; - - ListenerOps *ops = udpListener_CreateInet(forwarder, listenerName, addr, interfaceName); - if (ops) { - success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops); -#if 0 - parcAssertTrue(success, "Failed to add UDP listener on %s to ListenerSet", - addressToString(ops->getListenAddress(ops))); -#endif - } - return success; -} - - -/* - * Create a new IPV6/TCP listener. - * - * @param [in,out] forwarder The hicn-light forwarder instance - * @param [in] addr6 The ipv6 address in network byte order - * @param [in] port The port number in network byte order - * @param [in] interfaceName The name of the interface to bind the socket - * - * return true if success, false otherwise - */ -static bool _setupTcpListenerOnInet6Light(Forwarder *forwarder, char *listenerName, - ipv6_addr_t *addr6, uint16_t *port, char *interfaceName, - uint32_t scopeId) { - bool success = false; - - struct sockaddr_in6 addr; - memset(&addr, 0, sizeof(addr)); - addr.sin6_family = AF_INET6; - addr.sin6_port = *port; - addr.sin6_addr = *addr6; - addr.sin6_scope_id = scopeId; - - ListenerOps *ops = tcpListener_CreateInet6(forwarder, listenerName, addr, interfaceName); - if (ops) { - success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops); -#if 0 - parcAssertTrue(success, "Failed to add TCP6 listener on %s to ListenerSet", - addressToString(ops->getListenAddress(ops))); -#endif - } - return success; -} - - -/* - * Create a new IPV6/UDP listener. - * - * @param [in,out] forwarder The hicn-light forwarder instance - * @param [in] listenerName The name of the listener - * @param [in] addr6 The ipv6 address in network byte order - * @param [in] port The port number in network byte order - * @param [in] interfaceName The name of the interface to bind the socket - * - * return true if success, false otherwise - */ -static bool _setupUdpListenerOnInet6Light(Forwarder *forwarder, char *listenerName, - ipv6_addr_t *addr6, uint16_t *port, char *interfaceName) { - bool success = false; - - struct sockaddr_in6 addr; - memset(&addr, 0, sizeof(addr)); - addr.sin6_family = AF_INET6; - addr.sin6_port = *port; - addr.sin6_addr = *addr6; - addr.sin6_scope_id = 0; - - ListenerOps *ops = udpListener_CreateInet6(forwarder, listenerName, addr, interfaceName); - if (ops) { - success = listenerSet_Add(forwarder_GetListenerSet(forwarder), ops); -#if 0 - parcAssertTrue(success, "Failed to add UDP6 listener on %s to ListenerSet", - addressToString(ops->getListenAddress(ops))); -#endif - } - return success; -} - -/* - * Create a new HICN listener. - * - * @param [in] config The configuration - * @param [in] control The control command - * @param [in] port The connection id of the command - * - * return true if success, false otherwise - */ -bool _addHicn(Configuration *config, add_listener_command *control, - unsigned ingressId) { - bool success = false; - const char *symbolic = control->symbolic; - Address *localAddress = NULL; - - switch (control->addressType) { - case ADDR_INET: { - localAddress = - addressFromInaddr4Port(&control->address.v4.as_u32, &control->port); - success = _setupHicnListenerOnInet4(configuration_GetForwarder(config), - symbolic, localAddress); - break; - } - - case ADDR_INET6: { - localAddress = - addressFromInaddr6Port(&control->address.v6.as_in6addr, &control->port); - success = _setupHicnListenerOnInet6(configuration_GetForwarder(config), - symbolic, localAddress); - break; - } - - default: - if (logger_IsLoggable(configuration_GetLogger(config), - LoggerFacility_Config, PARCLogLevel_Warning)) { - logger_Log(configuration_GetLogger(config), LoggerFacility_Config, - PARCLogLevel_Warning, __func__, - "Unsupported address type for HICN (ingress id %u): " - "must be either IPV4 or IPV6", - ingressId); - } - break; - } - - if (success == true && localAddress != NULL) { - if (logger_IsLoggable(configuration_GetLogger(config), - LoggerFacility_Config, PARCLogLevel_Info)) { - char * str = addressToString(localAddress); - logger_Log(configuration_GetLogger(config), LoggerFacility_Config, - PARCLogLevel_Info, __func__, - "Setup hicn listener on address %s", - str); - parcMemory_Deallocate((void **)&str); - } - } - - addressDestroy(&localAddress); - - return success; -} - -bool _addIP(Configuration *config, add_listener_command *control, - unsigned ingressId) { - bool success = false; - char *symbolic = control->symbolic; - - switch (control->addressType) { - case ADDR_INET: { - - if (control->connectionType == UDP_CONN) { - success = - _setupUdpListenerOnInet(configuration_GetForwarder(config), symbolic, - &control->address.v4.as_u32, &control->port, control->interfaceName); - } else if (control->connectionType == TCP_CONN) { - success = - _setupTcpListenerOnInet(configuration_GetForwarder(config), symbolic, - &control->address.v4.as_u32, &control->port, control->interfaceName); - } - break; - } - - case ADDR_INET6: { - if (control->connectionType == UDP_CONN) { - success = _setupUdpListenerOnInet6Light( - configuration_GetForwarder(config), symbolic, &control->address.v6.as_in6addr, - &control->port, control->interfaceName); - } else if (control->connectionType == TCP_CONN) { - success = _setupTcpListenerOnInet6Light( - configuration_GetForwarder(config), symbolic, &control->address.v6.as_in6addr, - &control->port, control->interfaceName, 0); - } - break; - } - - default: - if (logger_IsLoggable(configuration_GetLogger(config), - LoggerFacility_Config, PARCLogLevel_Warning)) { - char *addrStr = utils_CommandAddressToString( - control->addressType, &control->address, &control->port); - logger_Log( - configuration_GetLogger(config), LoggerFacility_Config, - PARCLogLevel_Warning, __func__, - "Unsupported address type for IP encapsulation ingress id %u: %s", - ingressId, addrStr); - parcMemory_Deallocate((void **)&addrStr); - } - break; - } - - if (success) { - if (logger_IsLoggable(configuration_GetLogger(config), - LoggerFacility_Config, PARCLogLevel_Info)) { - char *addrStr = utils_CommandAddressToString( - control->addressType, &control->address, &control->port); - logger_Log(configuration_GetLogger(config), LoggerFacility_Config, - PARCLogLevel_Info, __func__, "Setup listener on address %s", - addrStr); - parcMemory_Deallocate((void **)&addrStr); - } - } - - return success; -} - -struct iovec *configurationListeners_Add(Configuration *config, - struct iovec *request, - unsigned ingressId) { - header_control_message *header = request[0].iov_base; - add_listener_command *control = request[1].iov_base; - - bool success = false; - - ListenerSet *listenerSet = forwarder_GetListenerSet(configuration_GetForwarder(config)); - int listenerId = listenerSet_FindIdByListenerName(listenerSet, control->symbolic); - - if (listenerId < 0) { - if (control->listenerMode == ETHER_MODE) { - parcTrapNotImplemented("Add Ethernet Listener is not supported"); - success = _addEther(config, control, ingressId); - // it is a failure - } else if (control->listenerMode == IP_MODE) { - success = _addIP(config, control, ingressId); - } else if (control->listenerMode == HICN_MODE) { - success = _addHicn(config, control, ingressId); - } else { - Logger *logger = configuration_GetLogger(config); - if (logger_IsLoggable(logger, LoggerFacility_Config, - PARCLogLevel_Warning)) { - logger_Log(logger, LoggerFacility_Config, PARCLogLevel_Warning, __func__, - "Unsupported encapsulation mode (ingress id %u)", ingressId); - } - } - } - - // generate ACK/NACK - struct iovec *response; - - if (success) { // ACK - response = utils_CreateAck(header, control, sizeof(add_listener_command)); - } else { // NACK - response = utils_CreateNack(header, control, sizeof(add_listener_command)); - } - - return response; -} - -struct iovec *configurationListeners_AddPunting(Configuration *config, - struct iovec *request, - unsigned ingressId) { - header_control_message *header = request[0].iov_base; - add_punting_command *control = request[1].iov_base; - - const char *symbolicOrConnid = control->symbolicOrConnid; - uint32_t len = control->len; - in_port_t port = htons(1234); - bool success = false; - - if (control->addressType == ADDR_INET) { - Address *address = addressFromInaddr4Port(&control->address.v4.as_u32, &port); - Punting *punting = puntingCreate(symbolicOrConnid, address, len); - success = _AddPuntingInet(config, punting, ingressId); - addressDestroy(&address); - } else if (control->addressType == ADDR_INET6) { - Address *address = addressFromInaddr6Port(&control->address.v6.as_in6addr, &port); - Punting *punting = puntingCreate(symbolicOrConnid, address, len); - success = _AddPuntingInet6(config, punting, ingressId); - addressDestroy(&address); - } else { - printf("Invalid IP type.\n"); // will generate a Nack - return utils_CreateNack(header, control, sizeof(add_punting_command)); - } - - // generate ACK/NACK - struct iovec *response; - if (success) { // ACK - response = utils_CreateAck(header, control, sizeof(add_punting_command)); - } else { // NACK - response = utils_CreateNack(header, control, sizeof(add_punting_command)); - } - - return response; -} - -//=========================== INITIAL LISTENERS ==================== - -static void _setupListenersOnAddress(Forwarder *forwarder, char *listenerName, - const Address *address, uint16_t port, - char *interfaceName) { - address_type type = addressGetType(address); - switch (type) { - case ADDR_INET: { - struct sockaddr_in tmp; - addressGetInet(address, &tmp); - _setupTcpListenerOnInet(forwarder, listenerName, &tmp.sin_addr.s_addr, &port, interfaceName); - break; - } - - case ADDR_INET6: { - struct sockaddr_in6 tmp; - addressGetInet6(address, &tmp); - _setupTcpListenerOnInet6Light(forwarder, listenerName, &tmp.sin6_addr, &port, interfaceName, - tmp.sin6_scope_id); - break; - } - - case ADDR_LINK: - // not used - break; - - default: - // dont' know how to handle this, so no listeners - break; - } -} - -void configurationListeners_SetupAll(const Configuration *config, uint16_t port, - const char *localPath) { - Forwarder *forwarder = configuration_GetForwarder(config); - InterfaceSet *set = system_Interfaces(forwarder); - - size_t interfaceSetLen = interfaceSetLength(set); - for (size_t i = 0; i < interfaceSetLen; i++) { - Interface *iface = interfaceSetGetByOrdinalIndex(set, i); - - const AddressList *addresses = interfaceGetAddresses(iface); - size_t addressListLen = addressListLength(addresses); - - for (size_t j = 0; j < addressListLen; j++) { - const Address *address = addressListGetItem(addresses, j); - - // Do not start on link address - char listenerName[SYMBOLIC_NAME_LEN]; -#if defined(__ANDROID__) || defined(_WIN32) - snprintf(listenerName, SYMBOLIC_NAME_LEN, "local_%zu", i); -#else - snprintf(listenerName, SYMBOLIC_NAME_LEN, "local_%ld", i); -#endif - if (addressGetType(address) != ADDR_LINK) { - _setupListenersOnAddress(forwarder, listenerName, address, port, - (char *)interfaceGetName(iface)); - } - } - } - - interfaceSetDestroy(&set); -} - -void configurationListeners_SetutpLocalIPv4(const Configuration *config, - uint16_t port) { - Forwarder *forwarder = configuration_GetForwarder(config); - in_addr_t addr = inet_addr("127.0.0.1"); - uint16_t network_byte_order_port = htons(port); - - char listenerNameUdp[SYMBOLIC_NAME_LEN] = "lo_udp"; - char listenerNameTcp[SYMBOLIC_NAME_LEN] = "lo_tcp"; - char *loopback_interface = "lo"; - _setupUdpListenerOnInet(forwarder, listenerNameUdp,(ipv4_addr_t *)&(addr), - &network_byte_order_port, loopback_interface); - _setupTcpListenerOnInet(forwarder, listenerNameTcp, (ipv4_addr_t *)&(addr), - &network_byte_order_port, loopback_interface); -} diff --git a/hicn-light/src/hicn/config/configurationListeners.h b/hicn-light/src/hicn/config/configurationListeners.h deleted file mode 100644 index b09ad5167..000000000 --- a/hicn-light/src/hicn/config/configurationListeners.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file configurationListeners.h - * @brief Configuration routines related to Listeners - * - * Adding and removing listeners. - * - */ - -#ifndef configurationListeners_h -#define configurationListeners_h - -#include <hicn/config/configuration.h> -#include <hicn/core/forwarder.h> - -#include <hicn/utils/address.h> - -/** - * Setup udp, tcp, and local listeners - * - * Will bind to all available IP protocols on the given port. - * Does not add Ethernet listeners. - * - * @param port is the UPD and TCP port to use - * @param localPath is the AF_UNIX path to use, if NULL no AF_UNIX listener is - * setup - * - * Example: - * @code - * <#example#> - * @endcode - */ -void configurationListeners_SetupAll(const Configuration *config, uint16_t port, - const char *localPath); - -void configurationListeners_SetutpLocalIPv4(const Configuration *config, - uint16_t port); - -bool configurationListeners_Remove(const Configuration *config); - -// light functions - -/** - * Add new listener. - * - * @param request The request coming from hicnLightControl or the - * configuration file. The bytes in the request are - * ordered following the network byte order convention. - * - * @param ingressId The connection id of the incoming request. - */ -struct iovec *configurationListeners_Add(Configuration *config, - struct iovec *request, - unsigned ingressId); - -struct iovec *configurationListeners_AddPunting(Configuration *config, - struct iovec *request, - unsigned ingressId); - -#endif /* defined(configurationListeners_h) */ diff --git a/hicn-light/src/hicn/config/configuration_file.c b/hicn-light/src/hicn/config/configuration_file.c new file mode 100644 index 000000000..2e8e7a6ac --- /dev/null +++ b/hicn-light/src/hicn/config/configuration_file.c @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2021 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 _WIN32 +#include <unistd.h> +#endif +#include <ctype.h> +#include <errno.h> +#include <stdio.h> +#include <string.h> +#include <hicn/config/configuration_file.h> +#include <hicn/util/sstrncpy.h> + +#include "commands.h" +#include "parse.h" + +#define BUFFERLEN 2048 + +static char *_trim(char *str) { + char *end; + + // Trim leading space + while (isspace((unsigned char)*str)) str++; + + if (*str == 0) // All spaces? + return str; + + // Trim trailing space + end = str + strnlen_s(str, BUFFERLEN) - 1; + while (end > str && isspace((unsigned char)*end)) end--; + + // Write new null terminator character + end[1] = '\0'; + + return str; +} + +bool configuration_file_process(forwarder_t *forwarder, const char *filename) { + assert(forwarder); + assert(filename); + + int linesRead = 0; + FILE *f = fopen(filename, "r"); + if (!f) { + ERROR("Could not open configuration file %s: (%d) %s", filename, errno, + strerror(errno)); + goto ERR_OPEN; + } + DEBUG("Opening configuration file %s", filename); + + char buffer[BUFFERLEN]; + bool success = true; + // TODO(eloparco): We could use a fake socket since we only need the vft + hc_sock_t *s = hc_sock_create_forwarder(HICNLIGHT_NG); + if (!s) { + ERROR("Could not create socket"); + goto ERR_SOCK; + } + + while (success && fgets(buffer, BUFFERLEN, f) != NULL) { + linesRead++; + + char *cmd = _trim(buffer); + if (strnlen_s(cmd, BUFFERLEN) <= 0) continue; + if (cmd[0] == '#') continue; + + INFO("Processing command: %s", cmd); + hc_command_t command = {}; + if (parse(cmd, &command) < 0) { + ERROR("Error parsing command : '%s'", cmd); + continue; + } + + // TODO(eloparco): Handle all commands + hc_result_t *result = NULL; + if (command.action == ACTION_CREATE) { + if (command.object.type == OBJECT_LISTENER) { + result = hc_listener_create_conf(s, &command.object.listener); + } else if (command.object.type == OBJECT_CONNECTION) { + result = hc_connection_create_conf(s, &command.object.connection); + } else if (command.object.type == OBJECT_ROUTE) { + result = hc_route_create_conf(s, &command.object.route); + } else if (command.object.type == OBJECT_LOCAL_PREFIX) { + result = hc_strategy_add_local_prefix_conf(s, &command.object.strategy); + } + } else if (command.action == ACTION_SET) { + if (command.object.type == OBJECT_STRATEGY) { + result = hc_strategy_set_conf(s, &command.object.strategy); + } + } + if (result == NULL) { + ERROR("Command '%s' not supported", cmd); + continue; + } + + size_t _unused; + hc_msg_t *msg = hc_result_get_msg(s, result); + command_type_t cmd_id = hc_result_get_cmd_id(s, result); + bool success = hc_result_get_success(s, result); + if (success == false) { + ERROR("Error serializing command : '%s'", cmd); + continue; + } + + command_process(forwarder, (uint8_t *)msg, cmd_id, CONNECTION_ID_UNDEFINED, + &_unused); + hc_result_free(result); + } + hc_sock_free(s); + + if (ferror(f)) { + ERROR("Error on input file %s line %d: (%d) %s", filename, linesRead, errno, + strerror(errno)); + goto ERR_READ; + } + fclose(f); + return true; + +ERR_SOCK: + hc_sock_free(s); +ERR_READ: + fclose(f); +ERR_OPEN: + return false; +} diff --git a/hicn-light/src/hicn/config/configuration_file.h b/hicn-light/src/hicn/config/configuration_file.h new file mode 100644 index 000000000..4d9535ab7 --- /dev/null +++ b/hicn-light/src/hicn/config/configuration_file.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file configuration_file.h + * @brief Accepts a filename and provides a means to read it into Configuration + * + * Reads a configuration file and converts the lines in to configuration + * commands for use in Configuration. + * + * Accepts '#' lines as comments. Skips blank and whitespace-only lines. + * + */ + +#ifndef configuration_file_h +#define configuration_file_h + +#include <hicn/core/forwarder.h> + +/** + * Configure hicn-light by reading a configuration file line-by-line and + * issueing commands to the forwarder. + * + * The configuration file is a set of lines, just like used in hicnLightControl. + * You need to have "add listener" lines in the file to receive connections. No + * default listeners are configured. + * + * This function reads the file line by line, skipping '#' and blank lines, and + * will stop on the first error. Lines already processed will not be un-done. + * + * @param[in] forwarder An allocated forwarder_t + * @param[in] filename The path to the configuration file + * + * @retval true The entire files was processed without error. + * @retval false There was an error in the file. + * + * Example: + * @code + * <#example#> + * @endcode + */ +bool configuration_file_process(forwarder_t* forwarder, const char* filename); + +#endif /* defined(configuration_file_h) */ diff --git a/hicn-light/src/hicn/config/controlAdd.c b/hicn-light/src/hicn/config/controlAdd.c deleted file mode 100644 index cac8e7913..000000000 --- a/hicn-light/src/hicn/config/controlAdd.c +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <parc/assert/parc_Assert.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlAdd.h> -#include <hicn/config/controlAddConnection.h> -#include <hicn/config/controlAddListener.h> -#include <hicn/config/controlAddPunting.h> -#include <hicn/config/controlAddRoute.h> -#ifdef WITH_POLICY -#include <hicn/config/controlAddPolicy.h> -#endif /* WITH_POLICY */ - -// =================================================== - -static void _controlAdd_Init(CommandParser *parser, CommandOps *ops); - -static CommandReturn _controlAdd_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static CommandReturn _controlAdd_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -// =================================================== - -static const char *command_add = "add"; -static const char *help_command_add = "help add"; - -CommandOps *webControlAdd_Create(ControlState *state) { - return commandOps_Create(state, command_add, _controlAdd_Init, - _controlAdd_Execute, commandOps_Destroy); -} - -CommandOps *controlAdd_CreateHelp(ControlState *state) { - return commandOps_Create(state, help_command_add, NULL, - _controlAdd_HelpExecute, commandOps_Destroy); -} - -// =================================================== - -static CommandReturn _controlAdd_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - CommandOps *ops_add_connection = controlAddConnection_Create(NULL); - CommandOps *ops_add_route = controlAddRoute_Create(NULL); - CommandOps *ops_add_punting = controlAddPunting_Create(NULL); - CommandOps *ops_add_listener = controlAddListener_Create(NULL); -#ifdef WITH_POLICY - CommandOps *ops_add_policy = controlAddPolicy_Create(NULL); -#endif /* WITH_POLICY */ -#ifdef WITH_POLICY - snprintf(output, output_size, "Available commands:\n %s\n %s\n %s\n %s\n %s\n\n", - ops_add_connection->command, - ops_add_route->command, - ops_add_punting->command, - ops_add_listener->command, - ops_add_policy->command); -#else - snprintf(output, output_size, "Available commands:\n %s\n %s\n %s\n %s\n\n", - ops_add_connection->command, - ops_add_route->command, - ops_add_punting->command, - ops_add_listener->command); - -#endif /* WITH_POLICY */ - - commandOps_Destroy(&ops_add_connection); - commandOps_Destroy(&ops_add_route); - commandOps_Destroy(&ops_add_punting); - commandOps_Destroy(&ops_add_listener); -#ifdef WITH_POLICY - commandOps_Destroy(&ops_add_policy); -#endif /* WITH_POLICY */ - return CommandReturn_Success; -} - -static void _controlAdd_Init(CommandParser *parser, CommandOps *ops) { - ControlState *state = ops->closure; - controlState_RegisterCommand(state, controlAddListener_HelpCreate(state)); - controlState_RegisterCommand(state, controlAddListener_Create(state)); - controlState_RegisterCommand(state, controlAddConnection_HelpCreate(state)); - controlState_RegisterCommand(state, controlAddRoute_HelpCreate(state)); - controlState_RegisterCommand(state, controlAddConnection_Create(state)); - controlState_RegisterCommand(state, controlAddRoute_Create(state)); - controlState_RegisterCommand(state, controlAddPunting_Create(state)); - controlState_RegisterCommand(state, controlAddPunting_HelpCreate(state)); -#ifdef WITH_POLICY - controlState_RegisterCommand(state, controlAddPolicy_HelpCreate(state)); - controlState_RegisterCommand(state, controlAddPolicy_Create(state)); -#endif /* WITH_POLICY */ -} - -static CommandReturn _controlAdd_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - return _controlAdd_HelpExecute(parser, ops, args, output, output_size); -} diff --git a/hicn-light/src/hicn/config/controlAdd.h b/hicn-light/src/hicn/config/controlAdd.h deleted file mode 100644 index 7c160b5f7..000000000 --- a/hicn-light/src/hicn/config/controlAdd.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_Add.h - * @brief Command-line "add" node - * - * Implements the "add" node of the CLI tree - * - * - */ - -#ifndef control_Add_h -#define control_Add_h - -#include <hicn/config/controlState.h> - -CommandOps *webControlAdd_Create(ControlState *state); -CommandOps *controlAdd_CreateHelp(ControlState *state); -#endif // control_Add_h diff --git a/hicn-light/src/hicn/config/controlAddConnection.c b/hicn-light/src/hicn/config/controlAddConnection.c deleted file mode 100644 index eed37f3ad..000000000 --- a/hicn-light/src/hicn/config/controlAddConnection.c +++ /dev/null @@ -1,450 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <ctype.h> -#include <parc/assert/parc_Assert.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> - -#include <hicn/config/controlAddConnection.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -// =================================================== - -static void _controlAddConnection_Init(CommandParser *parser, CommandOps *ops); -static CommandReturn _controlAddConnection_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlAddConnection_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -// =================================================== - -#ifdef __linux__ -static CommandReturn _controlAddConnection_HicnHelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlAddConnection_HicnExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -#endif - -static CommandReturn _controlAddConnection_UdpHelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlAddConnection_UdpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static CommandReturn _controlAddConnection_TcpHelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlAddConnection_TcpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -// =================================================== - -static const char *_commandAddConnection = "add connection"; -#ifdef __linux__ -static const char *_commandAddConnectionHicn = "add connection hicn"; -#endif -static const char *_commandAddConnectionUdp = "add connection udp"; -static const char *_commandAddConnectionTcp = "add connection tcp"; -static const char *_commandAddConnectionHelp = "help add connection"; -#ifdef __linux__ -static const char *_commandAddConnectionHicnHelp = "help add connection hicn"; -#endif -static const char *_commandAddConnectionUdpHelp = "help add connection udp"; -static const char *_commandAddConnectionTcpHelp = "help add connection tcp"; - -// =================================================== - -CommandOps *controlAddConnection_Create(ControlState *state) { - return commandOps_Create(state, _commandAddConnection, - _controlAddConnection_Init, - _controlAddConnection_Execute, commandOps_Destroy); -} - -CommandOps *controlAddConnection_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandAddConnectionHelp, NULL, - _controlAddConnection_HelpExecute, - commandOps_Destroy); -} - -// =================================================== - -#ifdef __linux__ -static CommandOps *_controlAddConnection_HicnCreate(ControlState *state) { - return commandOps_Create(state, _commandAddConnectionHicn, NULL, - _controlAddConnection_HicnExecute, - commandOps_Destroy); -} -#endif - -static CommandOps *_controlAddConnection_UdpCreate(ControlState *state) { - return commandOps_Create(state, _commandAddConnectionUdp, NULL, - _controlAddConnection_UdpExecute, - commandOps_Destroy); -} - -static CommandOps *_controlAddConnection_TcpCreate(ControlState *state) { - return commandOps_Create(state, _commandAddConnectionTcp, NULL, - _controlAddConnection_TcpExecute, - commandOps_Destroy); -} - -// =================================================== -#ifdef __linux__ -static CommandOps *_controlAddConnection_HicnHelpCreate(ControlState *state) { - return commandOps_Create(state, _commandAddConnectionHicnHelp, NULL, - _controlAddConnection_HicnHelpExecute, - commandOps_Destroy); -} -#endif - -static CommandOps *_controlAddConnection_UdpHelpCreate(ControlState *state) { - return commandOps_Create(state, _commandAddConnectionUdpHelp, NULL, - _controlAddConnection_UdpHelpExecute, - commandOps_Destroy); -} - -static CommandOps *_controlAddConnection_TcpHelpCreate(ControlState *state) { - return commandOps_Create(state, _commandAddConnectionTcpHelp, NULL, - _controlAddConnection_TcpHelpExecute, - commandOps_Destroy); -} - -// =================================================== - -static CommandReturn _controlAddConnection_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { -#ifdef __linux__ - snprintf(output, output_size, "Available commands:\n %s\n %s\n %s\n\n", - _commandAddConnectionHicn, - _commandAddConnectionUdp, - _commandAddConnectionTcp); -#else - snprintf(output, output_size, "Available commands:\n %s\n %s\n\n", - _commandAddConnectionUdp, - _commandAddConnectionTcp); -#endif - return CommandReturn_Success; -} - -static void _controlAddConnection_Init(CommandParser *parser, CommandOps *ops) { - ControlState *state = ops->closure; -#ifdef __linux__ - controlState_RegisterCommand(state, - _controlAddConnection_HicnHelpCreate(state)); -#endif - controlState_RegisterCommand(state, - _controlAddConnection_UdpHelpCreate(state)); - controlState_RegisterCommand(state, - _controlAddConnection_TcpHelpCreate(state)); -#ifdef __linux__ - controlState_RegisterCommand(state, _controlAddConnection_HicnCreate(state)); -#endif - controlState_RegisterCommand(state, _controlAddConnection_UdpCreate(state)); - controlState_RegisterCommand(state, _controlAddConnection_TcpCreate(state)); -} - -static CommandReturn _controlAddConnection_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - return _controlAddConnection_HelpExecute(parser, ops, args, output, output_size); -} - -// =================================================== -// functions general to all connection types - -/** - * Create a tunnel in the forwarder based on the addresses - * - * Caller retains ownership of memory. - * The symbolic name will be used to refer to this connection. It must be unqiue - * otherwise the forwarder will reject this commend. - * - * @param [in] parser An allocated CommandParser - * @param [in] ops Allocated CommandOps (needed to extract ControlState) - * @param [in] localAddress the local IP and port. The port may be the wildcard - * value. - * @param [in] remoteAddress The remote IP and port (both must be specified) - * @param [in] tunnelType The tunneling protocol - * @param [in] symbolic The symbolic name for the connection (must be unique) - * @param [in] output Output buffer - * @param [in] output_size Output buffer size - * - * @return <#value#> <#explanation#> - * - * Example: - * @code - * { - * struct sockaddr_in *anyAddress = parcNetwork_SockInet4AddressAny(); - * struct sockaddr_in *remote = - * parcNetwork_SockInet4Address("192.168.1.2", 9695); - * - * Address *localAddress = addressCreateFromInet(anyAddress); - * Address *remoteAddress = addressCreateFromInet(remote); - * - * control_CreateTunnel(state, localAddress, remoteAddress, IPTUN_TCP, - * "conn7"); - * - * addressDestroy(&localAddress); - * addressDestroy(&remoteAddress); - * parcMemory_Deallocate((void **)&remote); - * parcMemory_Deallocate((void **)&anyAddress); - * } - * @endcode - */ - -static CommandReturn _controlAddConnection_CreateTunnel(CommandParser *parser, - CommandOps *ops, const char *local_ip, - const char *local_port, - const char *remote_ip, - const char *remote_port, - connection_type tunnelType, - const char *symbolic, - char *output, - size_t output_size) { - ControlState *state = ops->closure; - // a request like this always has an interface index of 0 [FIELD REMOVED] - // unsigned int interfaceIndex = 0; - - // allocate command payload - add_connection_command *addConnectionCommand = - parcMemory_AllocateAndClear(sizeof(add_connection_command)); - - // check and set IP addresses - if (inet_pton(AF_INET, remote_ip, &addConnectionCommand->remoteIp.v4.as_u32) == - 1 && - inet_pton(AF_INET, local_ip, &addConnectionCommand->localIp.v4.as_u32) == 1) { - addConnectionCommand->ipType = ADDR_INET; - - } else if (inet_pton(AF_INET6, remote_ip, - &addConnectionCommand->remoteIp.v6.as_in6addr) == 1 && - inet_pton(AF_INET6, local_ip, - &addConnectionCommand->localIp.v6.as_in6addr) == 1) { - addConnectionCommand->ipType = ADDR_INET6; - - } else { - snprintf(output, output_size, "Error: local address %s not same type as remote address %s\n", - local_ip, remote_ip); - parcMemory_Deallocate(&addConnectionCommand); - return CommandReturn_Failure; - } - - // Fill remaining payload fields - addConnectionCommand->connectionType = tunnelType; - strcpy(addConnectionCommand->symbolic, symbolic); - addConnectionCommand->remotePort = htons((uint16_t)atoi(remote_port)); - addConnectionCommand->localPort = htons((uint16_t)atoi(local_port)); - - // send message and receive response - struct iovec *response = - utils_SendRequest(state, ADD_CONNECTION, addConnectionCommand, - sizeof(add_connection_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} - -static CommandReturn _controlAddConnection_IpHelp(CommandParser *parser, - CommandOps *ops, - PARCList *args, - const char *protocol, - char *output, - size_t output_size) { - snprintf(output, output_size, - #ifdef __linux__ - "add connection hicn <symbolic> <remote_ip> <local_ip>\n" - #endif - "add connection udp <symbolic> <remote_ip> <port> <local_ip> <port>\n" - " <symbolic> : symbolic name, e.g. 'conn1' (must be " - "unique, start with alpha)\n" - " <remote_ip> : the IPv4 or IPv6 or hostname of the remote system\n" - " <local_ip> : optional local IP address to bind to\n" - "\n"); - return CommandReturn_Success; -} - -#ifdef __linux__ -static CommandReturn _controlAddConnection_HicnHelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - _controlAddConnection_IpHelp(parser, ops, args, "hicn", output, output_size); - - return CommandReturn_Success; -} - -static CommandReturn _controlAddConnection_HicnExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - static const int _indexSymbolic = 3; - static const int _indexRemAddr = 4; - static const int _indexLocAddr = 5; - - if (parcList_Size(args) != 6) { - _controlAddConnection_HicnHelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - char *symbolic = parcList_GetAtIndex(args, _indexSymbolic); - - if (!utils_ValidateSymbolicName(symbolic)) { - snprintf(output, output_size, "Invalid symbolic name. Must begin with alpha and contain only " - "alphanum.\n"); - return CommandReturn_Failure; - } - - char *remote_ip = parcList_GetAtIndex(args, _indexRemAddr); - char *local_ip = parcList_GetAtIndex(args, _indexLocAddr); - char *port = "1234"; // this is a random port number that will be ignored - - return _controlAddConnection_CreateTunnel( - parser, ops, local_ip, port, remote_ip, port, HICN_CONN, symbolic, output, output_size); -} -#endif - -static CommandReturn _controlAddConnection_UdpHelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - _controlAddConnection_IpHelp(parser, ops, args, "udp", output, output_size); - - return CommandReturn_Success; -} - -static CommandReturn _controlAddConnection_UdpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - static const int _indexSymbolic = 3; - static const int _indexRemAddr = 4; - static const int _indexRemPort = 5; - static const int _indexLocAddr = 6; - static const int _indexLocPort = 7; - - if (parcList_Size(args) != 8) { - _controlAddConnection_UdpHelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - char *symbolic = parcList_GetAtIndex(args, _indexSymbolic); - size_t offset = 0; - if (!utils_ValidateSymbolicName(symbolic)) { - snprintf(output, output_size, - "Invalid symbolic name. Must begin with alpha and contain only " - "alphanum.\n"); - return CommandReturn_Failure; - } - - char *remote_ip = parcList_GetAtIndex(args, _indexRemAddr); - char *local_ip = parcList_GetAtIndex(args, _indexLocAddr); - - char *remote_port = parcList_GetAtIndex(args, _indexRemPort); - char *local_port = parcList_GetAtIndex(args, _indexLocPort); - - return _controlAddConnection_CreateTunnel(parser, ops, local_ip, local_port, - remote_ip, remote_port, UDP_CONN, - symbolic, - output + offset, output_size - offset); -} - -static CommandReturn _controlAddConnection_TcpHelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - _controlAddConnection_IpHelp(parser, ops, args, "tcp", output, output_size); - - return CommandReturn_Success; -} - -static CommandReturn _controlAddConnection_TcpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - static const int _indexSymbolic = 3; - static const int _indexRemAddr = 4; - static const int _indexRemPort = 5; - static const int _indexLocAddr = 6; - static const int _indexLocPort = 7; - - if (parcList_Size(args) != 8) { - _controlAddConnection_UdpHelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - char *symbolic = parcList_GetAtIndex(args, _indexSymbolic); - if (!utils_ValidateSymbolicName(symbolic)) { - snprintf(output, output_size, "Invalid symbolic name. Must begin with alpha and contain only " - "alphanum.\n"); - return CommandReturn_Failure; - } - - char *remote_ip = parcList_GetAtIndex(args, _indexRemAddr); - char *local_ip = parcList_GetAtIndex(args, _indexLocAddr); - - char *remote_port = parcList_GetAtIndex(args, _indexRemPort); - char *local_port = parcList_GetAtIndex(args, _indexLocPort); - - return _controlAddConnection_CreateTunnel(parser, ops, local_ip, local_port, - remote_ip, remote_port, TCP_CONN, - symbolic, - output, output_size); -} diff --git a/hicn-light/src/hicn/config/controlAddConnection.h b/hicn-light/src/hicn/config/controlAddConnection.h deleted file mode 100644 index 546388efc..000000000 --- a/hicn-light/src/hicn/config/controlAddConnection.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_AddConnection.h - * @brief Command-line "add connection" node - * - * Implements the "add connection" node of the CLI tree - * - * - */ - -#ifndef controlAddConnection_h -#define controlAddConnection_h - -#include <hicn/config/controlState.h> -CommandOps *controlAddConnection_Create(ControlState *state); -CommandOps *controlAddConnection_HelpCreate(ControlState *state); -#endif // controlAddConnection_h diff --git a/hicn-light/src/hicn/config/controlAddListener.c b/hicn-light/src/hicn/config/controlAddListener.c deleted file mode 100644 index df84c4691..000000000 --- a/hicn-light/src/hicn/config/controlAddListener.c +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <ctype.h> -#include <inttypes.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> - -#include <hicn/config/controlAddListener.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlAddListener_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlAddListener_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *command_add_listener = "add listener"; -static const char *command_help_add_listener = "help add listener"; - -CommandOps *controlAddListener_Create(ControlState *state) { - return commandOps_Create(state, command_add_listener, NULL, - _controlAddListener_Execute, commandOps_Destroy); -} - -CommandOps *controlAddListener_HelpCreate(ControlState *state) { - return commandOps_Create(state, command_help_add_listener, NULL, - _controlAddListener_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static const int _indexProtocol = 2; -static const int _indexSymbolic = 3; -static const int _indexAddress = 4; -static const int _indexPort = 5; -static const int _indexInterfaceName = 6; - -static CommandReturn _controlAddListener_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, - "commands:\n" -#ifdef __linux__ - " add listener hicn <symbolic> <localAddress> \n" -#endif - " add listener udp <symbolic> <localAddress> <port> <interface>\n" - " add listener tcp <symbolic> <localAddress> <port> <interface>\n" - "\n" - " symbolic: User defined name for listener, must start with " - "alpha and be alphanum\n" -#ifdef __linux__ - " protocol: hicn | udp\n" -#else - " protocol: udp\n" -#endif - " localAddress: IPv4 or IPv6 address (or prefix protocol = hicn) " - "assigend to the local interface\n" - " port: Udp port\n" - " interface: interface\n" - "\n" - "Notes:\n" - " The symblic name must be unique or the source will reject it.\n" -#ifdef __linux__ - " If protocol = hicn: the address 0::0 indicates the main listern, " - "for which we can set punting rules.\n" -#endif - ); - return CommandReturn_Success; -} - -static CommandReturn _CreateListener(CommandParser *parser, CommandOps *ops, - const char *symbolic, const char *addr, - const char *port, char *interfaceName, listener_mode mode, - connection_type type, - char *output, - size_t output_size) { - ControlState *state = ops->closure; - - // allocate command payload - add_listener_command *addListenerCommand = - parcMemory_AllocateAndClear(sizeof(add_listener_command)); - - // check and set IP address - if (inet_pton(AF_INET, addr, &addListenerCommand->address.v4.as_u32) == 1) { - addListenerCommand->addressType = ADDR_INET; - - } else if (inet_pton(AF_INET6, addr, &addListenerCommand->address.v6.as_in6addr) == 1) { - addListenerCommand->addressType = ADDR_INET6; - - } else { - snprintf(output, output_size, "Error: %s is not a valid network address \n", addr); - parcMemory_Deallocate(&addListenerCommand); - return CommandReturn_Failure; - } - - // Fill remaining payload fields - size_t name_size = strlen((const char *)interfaceName); - if(name_size > SYMBOLIC_NAME_LEN){ - //cut the string - name_size = SYMBOLIC_NAME_LEN; - } - - memcpy(addListenerCommand->interfaceName, interfaceName, name_size); - addListenerCommand->listenerMode = mode; - addListenerCommand->connectionType = type; - addListenerCommand->port = htons((uint16_t)atoi(port)); - strcpy(addListenerCommand->symbolic, symbolic); - - // send message and receive response - struct iovec *response = utils_SendRequest( - state, ADD_LISTENER, addListenerCommand, sizeof(add_listener_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} - -static CommandReturn _controlAddListener_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 5 && parcList_Size(args) != 7) { - _controlAddListener_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - CommandReturn result = CommandReturn_Failure; - - const char *symbolic = parcList_GetAtIndex(args, _indexSymbolic); - - if (!utils_ValidateSymbolicName(symbolic)) { - snprintf(output, output_size, - "Error: symbolic name must begin with an alpha and be alphanum " - "after\n"); - return result; - } - - const char *protocol = parcList_GetAtIndex(args, _indexProtocol); - const char *host = parcList_GetAtIndex(args, _indexAddress); - char *interfaceName = parcList_GetAtIndex(args, _indexInterfaceName); - if ((strcasecmp("hicn", protocol) == 0)) { - const char *port = - "1234"; // this is a random port number that will be ignored - - // here we discard the prefix len if it exists, since we don't use it in - // code but we let libhicn to find the right ip address. - return _CreateListener(parser, ops, symbolic, host, port, "hicn", HICN_MODE, - HICN_CONN, output, output_size); - } - const char *port = parcList_GetAtIndex(args, _indexPort); - - if ((strcasecmp("udp", protocol) == 0)) { - return _CreateListener(parser, ops, symbolic, host, port, interfaceName, IP_MODE, - UDP_CONN, output, output_size); - } else if ((strcasecmp("tcp", protocol) == 0)) { - return _CreateListener(parser, ops, symbolic, host, port, interfaceName, IP_MODE, - TCP_CONN, output, output_size); - } else { - _controlAddListener_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - if (result == CommandReturn_Failure) snprintf(output, output_size, "creation failed\n"); - - return result; -} diff --git a/hicn-light/src/hicn/config/controlAddListener.h b/hicn-light/src/hicn/config/controlAddListener.h deleted file mode 100644 index 6516d1779..000000000 --- a/hicn-light/src/hicn/config/controlAddListener.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_AddListener.h - * @brief Add a listener to an interface - * - * <#Detailed Description#> - * - */ - -#ifndef Control_AddListener_h -#define Control_AddListener_h - -#include <hicn/config/controlState.h> -CommandOps *controlAddListener_Create(ControlState *state); -CommandOps *controlAddListener_HelpCreate(ControlState *state); -#endif // Control_AddListener_h diff --git a/hicn-light/src/hicn/config/controlAddPolicy.c b/hicn-light/src/hicn/config/controlAddPolicy.c deleted file mode 100644 index 66439d29c..000000000 --- a/hicn-light/src/hicn/config/controlAddPolicy.c +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifdef WITH_POLICY - -#include <hicn/hicn-light/config.h> - -#include <ctype.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> - -#include <hicn/config/controlAddPolicy.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> -#include <hicn/utils/token.h> - -static CommandReturn _controlAddPolicy_Execute(CommandParser *parser, - CommandOps *ops, PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlAddPolicy_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandAddPolicy = "add policy"; -static const char *_commandAddPolicyHelp = "help add policy"; - -CommandOps *controlAddPolicy_Create(ControlState *state) { - return commandOps_Create(state, _commandAddPolicy, NULL, - _controlAddPolicy_Execute, commandOps_Destroy); -} - -CommandOps *controlAddPolicy_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandAddPolicyHelp, NULL, - _controlAddPolicy_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlAddPolicy_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - size_t output_offset = snprintf(output, output_size, "commands:\n" - " add policy <prefix> <app_name>"); - - #define _(x, y) output_offset += snprintf(output + output_offset, output_size - output_offset, " FLAG:%s", policy_tag_str[POLICY_TAG_ ## x]); - foreach_policy_tag - #undef _ - - output_offset += snprintf(output + output_offset, output_size - output_offset,"\n"); - printf("\n"); - output_offset += snprintf(output + output_offset, output_size - output_offset, - " prefix: The hicn name as IPv4 or IPv6 address (e.g 1234::0/64)\n" - " app_name: The application name associated to this policy\n" - " FLAG:*: A value among [neutral|require|prefer|avoid|prohibit] with an optional '!' character prefix for disabling changes\n" - "\n"); - - return CommandReturn_Success; -} - -static CommandReturn _controlAddPolicy_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - ControlState *state = ops->closure; - - if (parcList_Size(args) != 11) { - _controlAddPolicy_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - const char *prefixStr = parcList_GetAtIndex(args, 2); - char *addr = (char *)malloc((strlen(prefixStr) + 1) * sizeof(char)); - - // separate address and len - char *slash; - uint32_t len = 0; - strcpy(addr, prefixStr); - slash = strrchr(addr, '/'); - if (slash != NULL) { - len = atoi(slash + 1); - *slash = '\0'; - } - - // allocate command payload - add_policy_command *addPolicyCommand = - parcMemory_AllocateAndClear(sizeof(add_policy_command)); - - // check and set IP address - if (inet_pton(AF_INET, addr, &addPolicyCommand->address.v4.as_u32) == 1) { - if (len > 32) { - snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n"); - parcMemory_Deallocate(&addPolicyCommand); - free(addr); - return CommandReturn_Failure; - } - addPolicyCommand->addressType = ADDR_INET; - } else if (inet_pton(AF_INET6, addr, &addPolicyCommand->address.v6.as_in6addr) == 1) { - if (len > 128) { - snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n"); - parcMemory_Deallocate(&addPolicyCommand); - free(addr); - return CommandReturn_Failure; - } - addPolicyCommand->addressType = ADDR_INET6; - } else { - snprintf(output, output_size, "Error: %s is not a valid network address \n", addr); - parcMemory_Deallocate(&addPolicyCommand); - free(addr); - return CommandReturn_Failure; - } - - free(addr); - - addPolicyCommand->len = len; - - hicn_policy_t policy; - snprintf((char*)policy.app_name, APP_NAME_LEN, "%s", (char*)parcList_GetAtIndex(args, 3)); - for (int i=4; i < 11; i++) { - const char *tag = parcList_GetAtIndex(args, i); - policy_tag_state_t tag_state; - tag_state.disabled = (tag[0] == '!') ? 1 : 0; - if (strcmp(&tag[tag_state.disabled], "neutral") == 0) { - tag_state.state = POLICY_STATE_NEUTRAL; - } else if (strcmp(&tag[tag_state.disabled], "require") == 0) { - tag_state.state = POLICY_STATE_REQUIRE; - } else if (strcmp(&tag[tag_state.disabled], "prefer") == 0) { - tag_state.state = POLICY_STATE_PREFER; - } else if (strcmp(&tag[tag_state.disabled], "avoid") == 0) { - tag_state.state = POLICY_STATE_AVOID; - } else if (strcmp(&tag[tag_state.disabled], "prohibit") == 0) { - tag_state.state = POLICY_STATE_PROHIBIT; - } else { - snprintf(output, output_size, "ERROR: invalid tag value '%s'\n", tag); - parcMemory_Deallocate(&addPolicyCommand); - free(addr); - return CommandReturn_Failure; - } - - policy.tags[i-4] = tag_state; - - } - - addPolicyCommand->policy = policy; - - // send message and receive response - struct iovec *response = utils_SendRequest(state, ADD_POLICY, addPolicyCommand, - sizeof(add_policy_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} - -#endif /* WITH_POLICY */ diff --git a/hicn-light/src/hicn/config/controlAddPolicy.h b/hicn-light/src/hicn/config/controlAddPolicy.h deleted file mode 100644 index 273e3a476..000000000 --- a/hicn-light/src/hicn/config/controlAddPolicy.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_AddPolicy.h - * @brief Add a static policy - * - * Implements the "add policy" node of the CLI tree - * - */ - -#ifndef Control_AddPolicy_h -#define Control_AddPolicy_h - -#ifdef WITH_POLICY - -#include <hicn/config/controlState.h> -CommandOps *controlAddPolicy_Create(ControlState *state); -CommandOps *controlAddPolicy_HelpCreate(ControlState *state); - -#endif /* WITH_POLICY */ - -#endif // Control_AddPolicy_h diff --git a/hicn-light/src/hicn/config/controlAddPunting.c b/hicn-light/src/hicn/config/controlAddPunting.c deleted file mode 100644 index 41d846d55..000000000 --- a/hicn-light/src/hicn/config/controlAddPunting.c +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <ctype.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> -#include <hicn/utils/punting.h> - -#include <hicn/config/controlAddPunting.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlAddPunting_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlAddPunting_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandAddPunting = "add punting"; -static const char *_commandAddPuntingHelp = "help add punting"; - -static const int _indexSymbolic = 2; -static const int _indexPrefix = 3; - -CommandOps *controlAddPunting_Create(ControlState *state) { - return commandOps_Create(state, _commandAddPunting, NULL, - _controlAddPunting_Execute, commandOps_Destroy); -} - -CommandOps *controlAddPunting_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandAddPuntingHelp, NULL, - _controlAddPunting_HelpExecute, commandOps_Destroy); -} - -// ===================================================== - -static CommandReturn _controlAddPunting_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "add punting <symbolic> <prefix>\n" - " <symbolic> : listener symbolic name\n" - " <address> : prefix to add as a punting rule. (example " - "1234::0/64)\n" - "\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlAddPunting_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - ControlState *state = ops->closure; - - if (parcList_Size(args) != 4) { - _controlAddPunting_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - const char *symbolicOrConnid = parcList_GetAtIndex(args, _indexSymbolic); - - if (!utils_ValidateSymbolicName(symbolicOrConnid) && - !utils_IsNumber(symbolicOrConnid)) { - snprintf(output, output_size, - "ERROR: Invalid symbolic or connid:\n" - "symbolic name must begin with an alpha followed by alphanum;\nconnid " - "must be an integer\n"); - return CommandReturn_Failure; - } - - const char *prefixStr = parcList_GetAtIndex(args, _indexPrefix); - char *addr = (char *)malloc((strlen(prefixStr) + 1) * sizeof(char)); - - // separate address and len - char *slash; - uint32_t len = 0; - strcpy(addr, prefixStr); - slash = strrchr(addr, '/'); - if (slash != NULL) { - len = atoi(slash + 1); - *slash = '\0'; - } - - // allocate command payload - add_punting_command *addPuntingCommand = - parcMemory_AllocateAndClear(sizeof(add_punting_command)); - - // check and set IP address - if (inet_pton(AF_INET, addr, &addPuntingCommand->address.v4.as_u32) == 1) { - if (len > 32) { - snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n"); - parcMemory_Deallocate(&addPuntingCommand); - free(addr); - return CommandReturn_Failure; - } - addPuntingCommand->addressType = ADDR_INET; - } else if (inet_pton(AF_INET6, addr, &addPuntingCommand->address.v6.as_in6addr) == 1) { - if (len > 128) { - snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n"); - parcMemory_Deallocate(&addPuntingCommand); - free(addr); - return CommandReturn_Failure; - } - addPuntingCommand->addressType = ADDR_INET6; - } else { - snprintf(output, output_size, "Error: %s is not a valid network address \n", addr); - parcMemory_Deallocate(&addPuntingCommand); - free(addr); - return CommandReturn_Failure; - } - - free(addr); - - // Fill remaining payload fields - addPuntingCommand->len = len; - strcpy(addPuntingCommand->symbolicOrConnid, symbolicOrConnid); - - // send message and receive response - struct iovec *response = utils_SendRequest( - state, ADD_PUNTING, addPuntingCommand, sizeof(add_punting_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} - -// ====================================================================== diff --git a/hicn-light/src/hicn/config/controlAddPunting.h b/hicn-light/src/hicn/config/controlAddPunting.h deleted file mode 100644 index 9cab76359..000000000 --- a/hicn-light/src/hicn/config/controlAddPunting.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 controlAddPunting_h -#define controlAddPunting_h - -#include <hicn/config/controlState.h> -CommandOps *controlAddPunting_Create(ControlState *state); -CommandOps *controlAddPunting_HelpCreate(ControlState *state); -#endif diff --git a/hicn-light/src/hicn/config/controlAddRoute.c b/hicn-light/src/hicn/config/controlAddRoute.c deleted file mode 100644 index 78c0173ea..000000000 --- a/hicn-light/src/hicn/config/controlAddRoute.c +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <ctype.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> - -#include <hicn/config/controlAddRoute.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlAddRoute_Execute(CommandParser *parser, - CommandOps *ops, PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlAddRoute_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandAddRoute = "add route"; -static const char *_commandAddRouteHelp = "help add route"; - -CommandOps *controlAddRoute_Create(ControlState *state) { - return commandOps_Create(state, _commandAddRoute, NULL, - _controlAddRoute_Execute, commandOps_Destroy); -} - -CommandOps *controlAddRoute_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandAddRouteHelp, NULL, - _controlAddRoute_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlAddRoute_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "commands:\n" - " add route <symbolic | connid> <prefix> <cost>\n" - "\n" - " symbolic: The symbolic name for an exgress\n" - " connid: The egress connection id (see 'help list connections')\n" - " prefix: The hicn name as IPv4 or IPv6 address (e.g 1234::0/64)\n" - " cost: positive integer representing cost\n" - "\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlAddRoute_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - ControlState *state = ops->closure; - - if (parcList_Size(args) != 5) { - _controlAddRoute_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - const char *symbolicOrConnid = parcList_GetAtIndex(args, 2); - - if (!utils_ValidateSymbolicName(symbolicOrConnid) && - !utils_IsNumber(symbolicOrConnid)) { - snprintf(output, output_size, "ERROR: Invalid symbolic or connid:\nsymbolic name must begin with an " - "alpha followed by alphanum;\nconnid must be an integer\n"); - return CommandReturn_Failure; - } - - unsigned cost = atoi(parcList_GetAtIndex(args, 4)); - - if (cost == 0) { - snprintf(output, output_size, "ERROR: cost must be positive integer, got %u from '%s'\n", cost, - (char *)parcList_GetAtIndex(args, 4)); - return CommandReturn_Failure; - } - - const char *prefixStr = parcList_GetAtIndex(args, 3); - char *addr = (char *)malloc((strlen(prefixStr) + 1) * sizeof(char)); - - // separate address and len - char *slash; - uint32_t len = 0; - strcpy(addr, prefixStr); - slash = strrchr(addr, '/'); - if (slash != NULL) { - len = atoi(slash + 1); - *slash = '\0'; - } - - // allocate command payload - add_route_command *addRouteCommand = - parcMemory_AllocateAndClear(sizeof(add_route_command)); - - // check and set IP address - if (inet_pton(AF_INET, addr, &addRouteCommand->address.v4.as_u32) == 1) { - if (len > 32) { - snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n"); - parcMemory_Deallocate(&addRouteCommand); - free(addr); - return CommandReturn_Failure; - } - addRouteCommand->addressType = ADDR_INET; - } else if (inet_pton(AF_INET6, addr, &addRouteCommand->address.v6.as_in6addr) == 1) { - if (len > 128) { - snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n"); - parcMemory_Deallocate(&addRouteCommand); - free(addr); - return CommandReturn_Failure; - } - addRouteCommand->addressType = ADDR_INET6; - } else { - snprintf(output, output_size, "Error: %s is not a valid network address \n", addr); - parcMemory_Deallocate(&addRouteCommand); - free(addr); - return CommandReturn_Failure; - } - - free(addr); - - // Fill remaining payload fields - addRouteCommand->len = len; - addRouteCommand->cost = (uint16_t)cost; - strcpy(addRouteCommand->symbolicOrConnid, symbolicOrConnid); - - // send message and receive response - struct iovec *response = utils_SendRequest(state, ADD_ROUTE, addRouteCommand, - sizeof(add_route_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlAddRoute.h b/hicn-light/src/hicn/config/controlAddRoute.h deleted file mode 100644 index 9588c0f42..000000000 --- a/hicn-light/src/hicn/config/controlAddRoute.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_AddRoute.h - * @brief Add a static route - * - * Implements the "add route" node of the CLI tree - * - */ - -#ifndef Control_AddRoute_h -#define Control_AddRoute_h - -#include <hicn/config/controlState.h> -CommandOps *controlAddRoute_Create(ControlState *state); -CommandOps *controlAddRoute_HelpCreate(ControlState *state); -#endif // Control_AddRoute_h diff --git a/hicn-light/src/hicn/config/controlCache.c b/hicn-light/src/hicn/config/controlCache.c deleted file mode 100644 index b6010fcfd..000000000 --- a/hicn-light/src/hicn/config/controlCache.c +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/security/parc_Security.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlCache.h> -#include <hicn/config/controlCacheClear.h> -#include <hicn/config/controlCacheServe.h> -#include <hicn/config/controlCacheStore.h> - -static void _controlCache_Init(CommandParser *parser, CommandOps *ops); -static CommandReturn _controlCache_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlCache_HelpExecute(CommandParser *parser, - CommandOps *ops, PARCList *args, - char *output, - size_t output_size); - -static const char *_commandCache = "cache"; -static const char *_commandCacheHelp = "help cache"; - -CommandOps *controlCache_Create(ControlState *state) { - return commandOps_Create(state, _commandCache, _controlCache_Init, - _controlCache_Execute, commandOps_Destroy); -} - -CommandOps *controlCache_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandCacheHelp, NULL, - _controlCache_HelpExecute, commandOps_Destroy); -} - -// ===================================================== - -static CommandReturn _controlCache_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - CommandOps *ops_cache_serve = controlCacheServe_HelpCreate(NULL); - CommandOps *ops_cache_store = controlCacheStore_HelpCreate(NULL); - CommandOps *ops_cache_clear = controlCacheClear_HelpCreate(NULL); - - snprintf(output, output_size, "Available commands:\n" - " %s\n %s\n %s\n\n", - ops_cache_serve->command, - ops_cache_store->command, - ops_cache_clear->command); - commandOps_Destroy(&ops_cache_serve); - commandOps_Destroy(&ops_cache_store); - commandOps_Destroy(&ops_cache_clear); - - return CommandReturn_Success; -} - -static void _controlCache_Init(CommandParser *parser, CommandOps *ops) { - ControlState *state = ops->closure; - controlState_RegisterCommand(state, controlCacheServe_HelpCreate(state)); - controlState_RegisterCommand(state, controlCacheStore_HelpCreate(state)); - controlState_RegisterCommand(state, controlCacheClear_HelpCreate(state)); - controlState_RegisterCommand(state, controlCacheServe_Create(state)); - controlState_RegisterCommand(state, controlCacheStore_Create(state)); - controlState_RegisterCommand(state, controlCacheClear_Create(state)); -} - -static CommandReturn _controlCache_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - return _controlCache_HelpExecute(parser, ops, args, output, output_size); -} - -// ====================================================================== diff --git a/hicn-light/src/hicn/config/controlCache.h b/hicn-light/src/hicn/config/controlCache.h deleted file mode 100644 index c2f2402f1..000000000 --- a/hicn-light/src/hicn/config/controlCache.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 controlCache_h -#define controlCache_h - -#include <hicn/config/controlState.h> -CommandOps *controlCache_Create(ControlState *state); -CommandOps *controlCache_HelpCreate(ControlState *state); -#endif // controlCache_h diff --git a/hicn-light/src/hicn/config/controlCacheClear.c b/hicn-light/src/hicn/config/controlCacheClear.c deleted file mode 100644 index afd8f6fc1..000000000 --- a/hicn-light/src/hicn/config/controlCacheClear.c +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlCacheClear.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlCacheClear_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlCacheClear_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandCacheClear = "cache clear"; -static const char *_commandCacheClearHelp = "help cache clear"; - -// ==================================================== - -CommandOps *controlCacheClear_Create(ControlState *state) { - return commandOps_Create(state, _commandCacheClear, NULL, - _controlCacheClear_Execute, commandOps_Destroy); -} - -CommandOps *controlCacheClear_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandCacheClearHelp, NULL, - _controlCacheClear_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlCacheClear_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "cache clear\n\n"); - - return CommandReturn_Success; -} - -static CommandReturn _controlCacheClear_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 2) { - _controlCacheClear_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - ControlState *state = ops->closure; - // send message and receive response - struct iovec *response = utils_SendRequest(state, CACHE_CLEAR, NULL, 0); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlCacheClear.h b/hicn-light/src/hicn/config/controlCacheClear.h deleted file mode 100644 index 025758c34..000000000 --- a/hicn-light/src/hicn/config/controlCacheClear.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file controlCacheClear.h - * @brief Clear the cache - * - * Removes all the cached data form the local content store (if available) - * - */ - -#ifndef Control_CacheClear_h -#define Control_CacheClear_h - -#include <hicn/config/controlState.h> -CommandOps *controlCacheClear_Create(ControlState *state); -CommandOps *controlCacheClear_HelpCreate(ControlState *state); -#endif // Control_CacheClear_h diff --git a/hicn-light/src/hicn/config/controlCacheServe.c b/hicn-light/src/hicn/config/controlCacheServe.c deleted file mode 100644 index a4454037d..000000000 --- a/hicn-light/src/hicn/config/controlCacheServe.c +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlCacheServe.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlCacheServe_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlCacheServe_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandCacheServe = "cache serve"; -static const char *_commandCacheServeHelp = "help cache serve"; - -// ==================================================== - -CommandOps *controlCacheServe_Create(ControlState *state) { - return commandOps_Create(state, _commandCacheServe, NULL, - _controlCacheServe_Execute, commandOps_Destroy); -} - -CommandOps *controlCacheServe_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandCacheServeHelp, NULL, - _controlCacheServe_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlCacheServe_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "cache serve [on|off]\n\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlCacheServe_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 3) { - _controlCacheServe_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - bool active; - if (strcmp(parcList_GetAtIndex(args, 2), "on") == 0) { - active = true; - } else if (strcmp(parcList_GetAtIndex(args, 2), "off") == 0) { - active = false; - } else { - _controlCacheServe_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - cache_serve_command *cacheServeCommand = - parcMemory_AllocateAndClear(sizeof(cache_serve_command)); - if (active) { - cacheServeCommand->activate = ACTIVATE_ON; - } else { - cacheServeCommand->activate = ACTIVATE_OFF; - } - - ControlState *state = ops->closure; - // send message and receive response - struct iovec *response = utils_SendRequest( - state, CACHE_SERVE, cacheServeCommand, sizeof(cache_serve_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlCacheServe.h b/hicn-light/src/hicn/config/controlCacheServe.h deleted file mode 100644 index afebc0601..000000000 --- a/hicn-light/src/hicn/config/controlCacheServe.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 Control_CacheServe_h -#define Control_CacheServe_h - -#include <hicn/config/controlState.h> -CommandOps *controlCacheServe_Create(ControlState *state); -CommandOps *controlCacheServe_HelpCreate(ControlState *state); -#endif // Control_CacheServe_h diff --git a/hicn-light/src/hicn/config/controlCacheStore.c b/hicn-light/src/hicn/config/controlCacheStore.c deleted file mode 100644 index 9f2a18146..000000000 --- a/hicn-light/src/hicn/config/controlCacheStore.c +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlCacheStore.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlCacheStore_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlCacheStore_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandCacheStore = "cache store"; -static const char *_commandCacheStoreHelp = "help cache store"; - -// ==================================================== - -CommandOps *controlCacheStore_Create(ControlState *state) { - return commandOps_Create(state, _commandCacheStore, NULL, - _controlCacheStore_Execute, commandOps_Destroy); -} - -CommandOps *controlCacheStore_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandCacheStoreHelp, NULL, - _controlCacheStore_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlCacheStore_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "cache store [on|off]\n\n"); - - return CommandReturn_Success; -} - -static CommandReturn _controlCacheStore_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 3) { - _controlCacheStore_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - bool active; - if (strcmp(parcList_GetAtIndex(args, 2), "on") == 0) { - active = true; - } else if (strcmp(parcList_GetAtIndex(args, 2), "off") == 0) { - active = false; - } else { - _controlCacheStore_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - cache_store_command *cacheStoreCommand = - parcMemory_AllocateAndClear(sizeof(cache_store_command)); - if (active) { - cacheStoreCommand->activate = ACTIVATE_ON; - } else { - cacheStoreCommand->activate = ACTIVATE_OFF; - } - - ControlState *state = ops->closure; - // send message and receive response - struct iovec *response = utils_SendRequest( - state, CACHE_STORE, cacheStoreCommand, sizeof(cache_store_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlCacheStore.h b/hicn-light/src/hicn/config/controlCacheStore.h deleted file mode 100644 index e32bf5663..000000000 --- a/hicn-light/src/hicn/config/controlCacheStore.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 Control_CacheStore_h -#define Control_CacheStore_h - -#include <hicn/config/controlState.h> -CommandOps *controlCacheStore_Create(ControlState *state); -CommandOps *controlCacheStore_HelpCreate(ControlState *state); -#endif // Control_CacheStore_h diff --git a/hicn-light/src/hicn/config/controlList.c b/hicn-light/src/hicn/config/controlList.c deleted file mode 100644 index 353856c43..000000000 --- a/hicn-light/src/hicn/config/controlList.c +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/security/parc_Security.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlList.h> -#include <hicn/config/controlListConnections.h> -//#include <hicn/config/controlListInterfaces.h> -#include <hicn/config/controlListListeners.h> -#include <hicn/config/controlListRoutes.h> -#ifdef WITH_POLICY -#include <hicn/config/controlListPolicies.h> -#endif /* WITH_POLICY */ - -static void _controlList_Init(CommandParser *parser, CommandOps *ops); -static CommandReturn _controlList_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlList_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandList = "list"; -static const char *_commandListHelp = "help list"; - -CommandOps *controlList_Create(ControlState *state) { - return commandOps_Create(state, _commandList, _controlList_Init, - _controlList_Execute, commandOps_Destroy); -} - -CommandOps *controlList_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandListHelp, NULL, - _controlList_HelpExecute, commandOps_Destroy); -} - -// ===================================================== - -static CommandReturn _controlList_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - CommandOps *ops_list_connections = controlListConnections_HelpCreate(NULL); - // CommandOps *ops_list_interfaces = controlListInterfaces_HelpCreate(NULL); - CommandOps *ops_list_routes = controlListRoutes_HelpCreate(NULL); - CommandOps *ops_list_listeners = controlListListeners_HelpCreate(NULL); -#ifdef WITH_POLICY - CommandOps *ops_list_policies = controlListPolicies_HelpCreate(NULL); -#endif /* WITH_POLICY */ - - snprintf(output, output_size, "Available commands:\n" - " %s\n" - " %s\n" - " %s\n" -#ifdef WITH_POLICY - " %s\n" -#endif /* WITH_POLICY */ - "\n", - ops_list_connections->command, - ops_list_routes->command, - ops_list_listeners->command -#ifdef WITH_POLICY - , ops_list_policies->command -#endif /* WITH_POLICY */ - ); - - commandOps_Destroy(&ops_list_connections); - // commandOps_Destroy(&ops_list_interfaces); - commandOps_Destroy(&ops_list_routes); - commandOps_Destroy(&ops_list_listeners); -#ifdef WITH_POLICY - commandOps_Destroy(&ops_list_policies); -#endif /* WITH_POLICY */ - - return CommandReturn_Success; -} - -static void _controlList_Init(CommandParser *parser, CommandOps *ops) { - ControlState *state = ops->closure; - controlState_RegisterCommand(state, controlListConnections_HelpCreate(state)); - // controlState_RegisterCommand(state, - // controlListInterfaces_HelpCreate(state)); - controlState_RegisterCommand(state, controlListListeners_HelpCreate(state)); - controlState_RegisterCommand(state, controlListRoutes_HelpCreate(state)); - controlState_RegisterCommand(state, controlListConnections_Create(state)); - // controlState_RegisterCommand(state, controlListInterfaces_Create(state)); - controlState_RegisterCommand(state, controlListRoutes_Create(state)); - controlState_RegisterCommand(state, controlListListeners_Create(state)); -#ifdef WITH_POLICY - controlState_RegisterCommand(state, controlListPolicies_HelpCreate(state)); - controlState_RegisterCommand(state, controlListPolicies_Create(state)); -#endif /* WITH_POLICY */ -} - -static CommandReturn _controlList_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - return _controlList_HelpExecute(parser, ops, args, output, output_size); -} - -// ====================================================================== diff --git a/hicn-light/src/hicn/config/controlList.h b/hicn-light/src/hicn/config/controlList.h deleted file mode 100644 index d497e5179..000000000 --- a/hicn-light/src/hicn/config/controlList.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_List.h - * @brief Root node for the "list" commands - * - * Implements the "list" node of the CLI tree. - * - */ - -#ifndef controlList_h -#define controlList_h - -#include <hicn/config/controlState.h> -CommandOps *controlList_Create(ControlState *state); -CommandOps *controlList_HelpCreate(ControlState *state); -#endif // controlList_h diff --git a/hicn-light/src/hicn/config/controlListConnections.c b/hicn-light/src/hicn/config/controlListConnections.c deleted file mode 100644 index 6406ba8c3..000000000 --- a/hicn-light/src/hicn/config/controlListConnections.c +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlListConnections.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlListConnections_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlListConnections_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandListConnections = "list connections"; -static const char *_commandListConnectionsHelp = "help list connections"; -const char *connTypeString[6] = {"GRE", "TCP", "UDP", "MCAST", "L2", "HICN"}; -const char *stateString[3] = {"UP", "DOWN", "UNKNOWN"}; - -CommandOps *controlListConnections_Create(ControlState *state) { - return commandOps_Create(state, _commandListConnections, NULL, - _controlListConnections_Execute, commandOps_Destroy); -} - -CommandOps *controlListConnections_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandListConnectionsHelp, NULL, - _controlListConnections_HelpExecute, - commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlListConnections_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { -snprintf(output, output_size, "%s", "list connections: displays a 1-line summary of each connection\n" - "\n" - "The columns are:\n" - " connection id : an integer index for the connection\n" - " state : UP or DOWN\n" - " local address : the local network address associated with the " - "connection\n" - " remote address: the remote network address associated with the " - "connection\n" - " protocol : the network protocol (tcp, udp, gre, mcast, " - "ether)\n" - "\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlListConnections_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 2) { - _controlListConnections_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } -#ifdef WITH_POLICY - char flags_str[POLICY_TAG_N+1]; - char *s; -#endif /* WITH_POLICY */ - - ControlState *state = ops->closure; - - // send message and receive response - struct iovec *response = utils_SendRequest(state, LIST_CONNECTIONS, NULL, 0); - if (!response) { // get NULL pointer = FAILURE - return CommandReturn_Failure; - } - - // Process/Print message - header_control_message *receivedHeader = - (header_control_message *)response[0].iov_base; - uint8_t *receivedPayload = (uint8_t *)response[1].iov_base; - - char *sourceString = NULL; - char *destinationString = NULL; - - // Allocate output to pass to the main function if the call is not interactive - char **commandOutputMain = NULL; - if (!controlState_IsInteractive(state) && receivedHeader->length > 0) { - commandOutputMain = - parcMemory_Allocate(sizeof(char *) * receivedHeader->length); - for (size_t j = 0; j < receivedHeader->length; j++) { - commandOutputMain[j] = parcMemory_Allocate(sizeof(char) * 256); - } - } -size_t output_offset = 0; - -#ifdef WITH_POLICY - output_offset = snprintf(output, output_size, "%5s %10s %12s %6s %40s %40s %5s %s %s\n", "id", "name", "admin_state", "state", "source", "destination", "type", "priority", "flags"); -#else - output_offset = snprintf(output, output_size, "%5s %10s %12s %6s %40s %40s %5s\n", "id", "name", "admin_state", "state", "source", "destination", "type"); -#endif /* WITH_POLICY */ - - // Process/Print payload - - for (int i = 0; i < receivedHeader->length; i++) { - list_connections_command *listConnectionsCommand = - (list_connections_command *)(receivedPayload + - (i * sizeof(list_connections_command))); - - sourceString = utils_CommandAddressToString( - listConnectionsCommand->connectionData.ipType, - &listConnectionsCommand->connectionData.localIp, - &listConnectionsCommand->connectionData.localPort); - - destinationString = utils_CommandAddressToString( - listConnectionsCommand->connectionData.ipType, - &listConnectionsCommand->connectionData.remoteIp, - &listConnectionsCommand->connectionData.remotePort); - - PARCBufferComposer *composer = parcBufferComposer_Create(); - -#ifdef WITH_POLICY - - s = flags_str; -#define _(x, y) *s++ = policy_tags_has(listConnectionsCommand->connectionData.tags, POLICY_TAG_ ## x) ? y : '.'; -foreach_policy_tag -#undef _ - *s = '\0'; - - parcBufferComposer_Format( - composer, "%5d %10s %12s %6s %40s %40s %5s [%6d] [%s]", listConnectionsCommand->connid, listConnectionsCommand->connectionName, - stateString[listConnectionsCommand->connectionData.admin_state], - stateString[listConnectionsCommand->state], sourceString, - destinationString, - connTypeString[listConnectionsCommand->connectionData.connectionType], - listConnectionsCommand->connectionData.priority, - flags_str); - -#else - parcBufferComposer_Format( - composer, "%5d %10s %12s %6s %40s %40s %5s", listConnectionsCommand->connid, listConnectionsCommand->connectionName, - stateString[listConnectionsCommand->admin_state], - stateString[listConnectionsCommand->state], sourceString, - destinationString, - connTypeString[listConnectionsCommand->connectionData.connectionType]); -#endif /* WITH_POLICY */ - - PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer); - char *result = parcBuffer_ToString(tempBuffer); - parcBuffer_Release(&tempBuffer); - - if (!controlState_IsInteractive(state)) { - strcpy(commandOutputMain[i], result); - } - output_offset += snprintf(output + output_offset, output_size - output_offset, "%s\n", result); - parcMemory_Deallocate((void **)&result); - parcBufferComposer_Release(&composer); - } - - controlState_SetCommandOutput(state, commandOutputMain); - - // DEALLOCATE - parcMemory_Deallocate((void **)&sourceString); - parcMemory_Deallocate((void **)&destinationString); - parcMemory_Deallocate(&receivedHeader); // free response[0].iov_base - parcMemory_Deallocate(&receivedPayload); // free response[1].iov_base - parcMemory_Deallocate(&response); // free iovec pointer - - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlListConnections.h b/hicn-light/src/hicn/config/controlListConnections.h deleted file mode 100644 index cd5c21cec..000000000 --- a/hicn-light/src/hicn/config/controlListConnections.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_ListConnections.h - * @brief List the current connections of hicn-light - * - * Implements the "list connections" node of the CLI tree - * - */ - -#ifndef Control_ListConnections_h -#define Control_ListConnections_h - -#include <hicn/config/controlState.h> -CommandOps *controlListConnections_Create(ControlState *state); -CommandOps *controlListConnections_HelpCreate(ControlState *state); -#endif // Control_ListConnections_h diff --git a/hicn-light/src/hicn/config/controlListInterfaces.c b/hicn-light/src/hicn/config/controlListInterfaces.c deleted file mode 100644 index c632a1d21..000000000 --- a/hicn-light/src/hicn/config/controlListInterfaces.c +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlListInterfaces.h> - -static CommandReturn _controlListInterfaces_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlListInterfaces_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandListInterfaces = "list interfaces"; -static const char *_commandListInterfacesHelp = "help list interfaces"; - -// ==================================================== - -CommandOps *controlListInterfaces_Create(ControlState *state) { - return commandOps_Create(state, _commandListInterfaces, NULL, - _controlListInterfaces_Execute, commandOps_Destroy); -} - -CommandOps *controlListInterfaces_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandListInterfacesHelp, NULL, - _controlListInterfaces_HelpExecute, - commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlListInterfaces_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "list interfaces\n\n") - return CommandReturn_Success; -} - -static CommandReturn _controlListInterfaces_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 2) { - _controlListInterfaces_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - //========================== NOT IMPLEMENTED - //=========================== - - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlListInterfaces.h b/hicn-light/src/hicn/config/controlListInterfaces.h deleted file mode 100644 index f885835ed..000000000 --- a/hicn-light/src/hicn/config/controlListInterfaces.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_ListInterfaces.h - * @brief List the icn-light interfaces - * - * Implements the "list interfaces" and "help list interfaces" nodes of the - * command tree - * - */ - -#ifndef Control_ListInterfaces_h -#define Control_ListInterfaces_h - -#include <hicn/config/controlState.h> -CommandOps *controlListInterfaces_Create(ControlState *state); -CommandOps *controlListInterfaces_HelpCreate(ControlState *state); -#endif // Control_ListInterfaces_h diff --git a/hicn-light/src/hicn/config/controlListListeners.c b/hicn-light/src/hicn/config/controlListListeners.c deleted file mode 100644 index c189dfc36..000000000 --- a/hicn-light/src/hicn/config/controlListListeners.c +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/assert/parc_Assert.h> - -#include <hicn/config/controlListListeners.h> -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlListListeners_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlListListeners_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandListListeners = "list listeners"; -static const char *_commandListListenersHelp = "help list listeners"; -static const char *listenerType[5] = {"TCP", "UDP", "ETHER", "LOCAL", "HICN"}; - -// ==================================================== - -CommandOps *controlListListeners_Create(ControlState *state) { - return commandOps_Create(state, _commandListListeners, NULL, - _controlListListeners_Execute, commandOps_Destroy); -} - -CommandOps *controlListListeners_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandListListenersHelp, NULL, - _controlListListeners_HelpExecute, - commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlListListeners_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "list listeners\n\n"); - - return CommandReturn_Success; -} - -static CommandReturn _controlListListeners_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 2) { - _controlListListeners_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - ControlState *state = ops->closure; - - // send message and receive response - struct iovec *response = utils_SendRequest(state, LIST_LISTENERS, NULL, 0); - if (!response) { // get NULL pointer = FAILURE - return CommandReturn_Failure; - } - - // Process/Print message - header_control_message *receivedHeader = - (header_control_message *)response[0].iov_base; - uint8_t *receivedPayload = (uint8_t *)response[1].iov_base; - - // Allocate output to pass to the main function if the call is not interactive - char **commandOutputMain = NULL; - if (!controlState_IsInteractive(state) && receivedHeader->length > 0) { - commandOutputMain = - parcMemory_Allocate(sizeof(char *) * receivedHeader->length); - for (size_t j = 0; j < receivedHeader->length; j++) { - commandOutputMain[j] = parcMemory_Allocate(sizeof(char) * 128); - } - } - - char *addrString = NULL; - size_t output_offset = 0; - if (receivedHeader->length > 0) { - output_offset = snprintf(output, output_size, "%6.6s %.*s %50.70s %6s %10s\n", "iface", SYMBOLIC_NAME_LEN, "name", "address", "type", "interface"); - - } else { - output_offset = snprintf(output, output_size, " --- No entry in the list \n"); - } - - for (int i = 0; i < receivedHeader->length; i++) { - list_listeners_command *listListenersCommand = - (list_listeners_command *)(receivedPayload + - (i * sizeof(list_listeners_command))); - - addrString = utils_CommandAddressToString(listListenersCommand->addressType, - &listListenersCommand->address, - &listListenersCommand->port); - - PARCBufferComposer *composer = parcBufferComposer_Create(); - - if (strcmp(listenerType[listListenersCommand->encapType], "UDP") == 0 || - strcmp(listenerType[listListenersCommand->encapType], "TCP") == 0) { - parcBufferComposer_Format(composer, "%6u %.*s %50.70s %6s %10s", - listListenersCommand->connid, - SYMBOLIC_NAME_LEN, listListenersCommand->listenerName, - addrString, - listenerType[listListenersCommand->encapType], - listListenersCommand->interfaceName); - } else { - parcBufferComposer_Format(composer, "%6u %.*s %50.70s %6s", - listListenersCommand->connid, - SYMBOLIC_NAME_LEN, listListenersCommand->listenerName, - addrString, - listenerType[listListenersCommand->encapType]); - } - - PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer); - char *result = parcBuffer_ToString(tempBuffer); - parcBuffer_Release(&tempBuffer); - - if (!controlState_IsInteractive(state)) { - strncpy(commandOutputMain[i], result, 128); - } - output_offset += snprintf(output + output_offset, output_size - output_offset, "%s\n", result); - parcMemory_Deallocate((void **)&result); - parcBufferComposer_Release(&composer); - } - - controlState_SetCommandOutput(state, commandOutputMain); - - // DEALLOCATE - parcMemory_Deallocate((void **)&addrString); - parcMemory_Deallocate(&receivedHeader); // free response[0].iov_base - parcMemory_Deallocate(&receivedPayload); // free response[1].iov_base - parcMemory_Deallocate(&response); // free iovec pointer - - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlListListeners.h b/hicn-light/src/hicn/config/controlListListeners.h deleted file mode 100644 index 11ec07579..000000000 --- a/hicn-light/src/hicn/config/controlListListeners.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_ListListeners.h - * @brief List the icn-light listeners - * - * Implements the "list listeners" and "help list listeners" nodes of the - * command tree - * - */ - -#ifndef Control_ListListeners_h -#define Control_ListListeners_h - -#include <hicn/config/controlState.h> -CommandOps *controlListListeners_Create(ControlState *state); -CommandOps *controlListListeners_HelpCreate(ControlState *state); -#endif // Control_ListListeners_h diff --git a/hicn-light/src/hicn/config/controlListPolicies.c b/hicn-light/src/hicn/config/controlListPolicies.c deleted file mode 100644 index 8eae6453b..000000000 --- a/hicn-light/src/hicn/config/controlListPolicies.c +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifdef WITH_POLICY -#include <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Time.h> - -#include <hicn/config/controlListPolicies.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlListPolicies_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlListPolicies_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandListPolicies = "list policies"; -static const char *_commandListPoliciesHelp = "help list policies"; - -// ==================================================== - -CommandOps *controlListPolicies_Create(ControlState *state) { - return commandOps_Create(state, _commandListPolicies, NULL, - _controlListPolicies_Execute, commandOps_Destroy); -} - -CommandOps *controlListPolicies_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandListPoliciesHelp, NULL, - _controlListPolicies_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlListPolicies_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "command: list policies\n\n"); - return CommandReturn_Success; -} - -#define MAX(x,y) (x > y ? x : y) -#define MAXSZ_COLUMN MAX(MAXSZ_POLICY_TAG, MAXSZ_POLICY_TAG_STATE) - -#define MAXSZ_STR_STAT 10 -#define MAXSZ_APP_NAME 25 - -typedef struct { - #define _(x, y) char x[MAXSZ_POLICY_TAG_STATE]; - foreach_policy_tag - #undef _ -} tag_state_str_t; - -static CommandReturn _controlListPolicies_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 2) { - _controlListPolicies_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - ControlState *state = ops->closure; - - // send message and receive response - struct iovec *response = utils_SendRequest(state, LIST_POLICIES, NULL, 0); - if (!response) { // get NULL pointer = FAILURE - return CommandReturn_Failure; - } - - // Process/Print message - header_control_message *receivedHeader = - (header_control_message *)response[0].iov_base; - uint8_t *receivedPayload = (uint8_t *)response[1].iov_base; - if (!receivedPayload) { - snprintf(output, output_size, "No payload!\n"); - return CommandReturn_Failure; - } - - // Allocate output to pass to the main function if the call is not interactive - char **commandOutputMain = NULL; - if (!controlState_IsInteractive(state) && receivedHeader->length > 0) { - commandOutputMain = - parcMemory_Allocate(sizeof(char *) * receivedHeader->length); - for (size_t j = 0; j < receivedHeader->length; j++) { - commandOutputMain[j] = parcMemory_Allocate(sizeof(char) * 128); - } - } - - char *addrString = NULL; - in_port_t port = htons(1234); // this is a random port number that is ignored - size_t output_offset = 0; - if (receivedHeader->length > 0) { - output_offset += snprintf(output, output_size, "%*s %*s", MAXSZ_PREFIX, "prefix", MAXSZ_APP_NAME /*APP_NAME_LEN*/, "app_name"); - #define _(x, y) output_offset += snprintf(output + output_offset, output_size - output_offset, " %*s",MAXSZ_COLUMN, policy_tag_str[POLICY_TAG_ ## x]); - foreach_policy_tag - #undef _ - output_offset += snprintf(output + output_offset, output_size - output_offset, "\n"); - } else { - output_offset += snprintf(output, output_size, " --- No entry in the list \n"); - } - - tag_state_str_t str; - - for (int i = 0; i < receivedHeader->length; i++) { - list_policies_command *listPoliciesCommand = - (list_policies_command *)(receivedPayload + - (i * sizeof(list_policies_command))); - -#if 0 - char tag_s[MAXSZ_POLICY_TAG_STATE * POLICY_TAG_N]; - - policy_tag_state_snprintf((char*)&tag_s[MAXSZ_POLICY_TAG_STATE * POLICY_TAG_ ## x], \ - MAXSZ_POLICY_TAG_STATE, \ - &listPoliciesCommand->policy.tags[POLICY_TAG_ ## x]); -#endif - - #define _(x, y) policy_tag_state_snprintf(str.x, MAXSZ_POLICY_TAG_STATE, &listPoliciesCommand->policy.tags[POLICY_TAG_ ## x]); - foreach_policy_tag - #undef _ - - addrString = utils_CommandAddressToString( - listPoliciesCommand->addressType, &listPoliciesCommand->address, &port); - -#if 0 - PARCBufferComposer *composer = parcBufferComposer_Create(); - - parcBufferComposer_Format( - composer, "%*s %*s" - #define _(x, y) " %*s" - foreach_policy_tag - #undef _ - "%s", - MAXSZ_PREFIX, addrString, APP_NAME_LEN, listPoliciesCommand->policy.app_name, - #define _(x, y) MAXSZ_COLUMN, str.x, - foreach_policy_tag - #undef _ - ""); - - PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer); - char *result = parcBuffer_ToString(tempBuffer); - parcBuffer_Release(&tempBuffer); - - if (!controlState_IsInteractive(state)) { - strcpy(commandOutputMain[i], result); - } - - puts(result); - parcMemory_Deallocate((void **)&result); - parcBufferComposer_Release(&composer); -#else - - output_offset = snprintf(output + output_offset, output_size - output_offset, "%*s %*s", - MAXSZ_PREFIX, addrString, MAXSZ_APP_NAME /*APP_NAME_LEN*/, listPoliciesCommand->policy.app_name); - #define _(x, y) output_offset += snprintf(output + output_offset, output_size - output_offset, " %*s", MAXSZ_COLUMN, str.x); - foreach_policy_tag - #undef _ - - output_offset = snprintf(output + output_offset, output_size - output_offset, "\n"); - - - /*printf("%*s %*s" - #define _(x, y) " %*s" - foreach_policy_tag - #undef _ - "%s\n", - MAXSZ_PREFIX, addrString, MAXSZ_APP_NAME *//*APP_NAME_LEN*//*, listPoliciesCommand->policy.app_name, - #define _(x, y) MAXSZ_COLUMN, str.x, - foreach_policy_tag - #undef _ - "");*/ - -#endif - } - - output_offset += snprintf(output + output_offset, output_size - output_offset, "\nSTATISTICS\n\n"); - // STATISTICS - output_offset += snprintf(output + output_offset, output_size - output_offset, "%*s %*s %*s | %*s | %*s | %*s\n", - MAXSZ_PREFIX, "", MAXSZ_APP_NAME /*APP_NAME_LEN*/, "", - 3*MAXSZ_STR_STAT+2, "WIRED", 3*MAXSZ_STR_STAT+2, "WIFI", 3*MAXSZ_STR_STAT+2, "CELLULAR", 3*MAXSZ_STR_STAT+2, "ALL"); - output_offset += snprintf(output + output_offset, output_size - output_offset, "%*s %*s %*s %*s %*s | %*s %*s %*s | %*s %*s %*s | %*s %*s %*s\n", - MAXSZ_PREFIX, "prefix", MAXSZ_APP_NAME /*APP_NAME_LEN*/, "app_name", - MAXSZ_STR_STAT, "throughput", MAXSZ_STR_STAT, "latency", MAXSZ_STR_STAT, "loss_rate", - MAXSZ_STR_STAT, "throughput", MAXSZ_STR_STAT, "latency", MAXSZ_STR_STAT, "loss_rate", - MAXSZ_STR_STAT, "throughput", MAXSZ_STR_STAT, "latency", MAXSZ_STR_STAT, "loss_rate", - MAXSZ_STR_STAT, "throughput", MAXSZ_STR_STAT, "latency", MAXSZ_STR_STAT, "loss_rate"); - for (int i = 0; i < receivedHeader->length; i++) { - list_policies_command *listPoliciesCommand = - (list_policies_command *)(receivedPayload + - (i * sizeof(list_policies_command))); - addrString = utils_CommandAddressToString( - listPoliciesCommand->addressType, &listPoliciesCommand->address, &port); - output_offset += snprintf(output + output_offset, output_size - output_offset, "%*s %*s %*.2f %*.2f %*.2f | %*.2f %*.2f %*.2f | %*.2f %*.2f %*.2f | %*.2f %*.2f %*.2f\n", - MAXSZ_PREFIX, addrString, MAXSZ_APP_NAME, listPoliciesCommand->policy.app_name, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wired.throughput, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wired.latency, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wired.loss_rate, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wifi.throughput, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wifi.latency, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.wifi.loss_rate, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.cellular.throughput, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.cellular.latency, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.cellular.loss_rate, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.all.throughput, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.all.latency, - MAXSZ_STR_STAT, listPoliciesCommand->policy.stats.all.loss_rate); - } - - controlState_SetCommandOutput(state, commandOutputMain); - - // DEALLOCATE - parcMemory_Deallocate((void **)&addrString); - parcMemory_Deallocate(&receivedHeader); // free response[0].iov_base - parcMemory_Deallocate(&receivedPayload); // free response[1].iov_base - parcMemory_Deallocate(&response); // free iovec pointer - - return CommandReturn_Success; -} - -#endif /* WITH_POLICY */ diff --git a/hicn-light/src/hicn/config/controlListPolicies.h b/hicn-light/src/hicn/config/controlListPolicies.h deleted file mode 100644 index 7aa0bdd26..000000000 --- a/hicn-light/src/hicn/config/controlListPolicies.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_ListPolicies.h - * @brief List the icn-light policies - * - * Implements the "list policies" and "help list policies" nodes of the command tree - * - */ -#ifndef Control_ListPolicies_h -#define Control_ListPolicies_h - -#ifdef WITH_POLICY - -#include <hicn/config/controlState.h> -CommandOps *controlListPolicies_Create(ControlState *state); -CommandOps *controlListPolicies_HelpCreate(ControlState *state); - -#endif /* WITH_POLICY */ - -#endif // Control_ListPolicies_h diff --git a/hicn-light/src/hicn/config/controlListRoutes.c b/hicn-light/src/hicn/config/controlListRoutes.c deleted file mode 100644 index 395251b94..000000000 --- a/hicn-light/src/hicn/config/controlListRoutes.c +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Time.h> - -#include <hicn/config/controlListRoutes.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlListRoutes_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlListRoutes_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandListRoutes = "list routes"; -static const char *_commandListRoutesHelp = "help list routes"; - -// ==================================================== - -CommandOps *controlListRoutes_Create(ControlState *state) { - return commandOps_Create(state, _commandListRoutes, NULL, - _controlListRoutes_Execute, commandOps_Destroy); -} - -CommandOps *controlListRoutes_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandListRoutesHelp, NULL, - _controlListRoutes_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlListRoutes_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "command: list routes\n" - "\n" - "This command will fetch the prefix routing table. For each route, it " - "will list:\n" - " iface: interface\n" - " protocol: the routing protocol, such as STATIC, CONNECTED, etc.\n" - " type: LMP or EXACT (longest matching prefix or exact match)\n" - " cost: The route cost, lower being preferred\n" - " next: List of next hops by interface id\n" - " prefix: name prefix\n" - "\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlListRoutes_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 2) { - _controlListRoutes_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - ControlState *state = ops->closure; - - // send message and receive response - struct iovec *response = utils_SendRequest(state, LIST_ROUTES, NULL, 0); - if (!response) { // get NULL pointer = FAILURE - return CommandReturn_Failure; - } - - // Process/Print message - header_control_message *receivedHeader = - (header_control_message *)response[0].iov_base; - uint8_t *receivedPayload = (uint8_t *)response[1].iov_base; - - // Allocate output to pass to the main function if the call is not interactive - char **commandOutputMain = NULL; - if (!controlState_IsInteractive(state) && receivedHeader->length > 0) { - commandOutputMain = - parcMemory_Allocate(sizeof(char *) * receivedHeader->length); - for (size_t j = 0; j < receivedHeader->length; j++) { - commandOutputMain[j] = parcMemory_Allocate(sizeof(char) * 128); - } - } - - char *addrString = NULL; - in_port_t port = htons(1234); // this is a random port number that is ignored - size_t output_offset = 0; - if (receivedHeader->length > 0) { - output_offset = snprintf(output, output_size, "%6.6s %8.8s %70.70s %s\n", "iface", "cost", "prefix", "len"); - } else { - output_offset = snprintf(output, output_size, " --- No entry in the list \n"); - } - - for (int i = 0; i < receivedHeader->length; i++) { - list_routes_command *listRoutesCommand = - (list_routes_command *)(receivedPayload + - (i * sizeof(list_routes_command))); - - addrString = utils_CommandAddressToString( - listRoutesCommand->addressType, &listRoutesCommand->address, &port); - - PARCBufferComposer *composer = parcBufferComposer_Create(); - - parcBufferComposer_Format( - composer, "%6u %8u %70.70s %3d", listRoutesCommand->connid, - listRoutesCommand->cost, addrString, listRoutesCommand->len); - - PARCBuffer *tempBuffer = parcBufferComposer_ProduceBuffer(composer); - char *result = parcBuffer_ToString(tempBuffer); - parcBuffer_Release(&tempBuffer); - - if (!controlState_IsInteractive(state)) { - strcpy(commandOutputMain[i], result); - } - - output_offset += snprintf(output + output_offset, output_size - output_offset, "%s\n", result); - parcMemory_Deallocate((void **)&result); - parcBufferComposer_Release(&composer); - } - - controlState_SetCommandOutput(state, commandOutputMain); - - // DEALLOCATE - parcMemory_Deallocate((void **)&addrString); - parcMemory_Deallocate(&receivedHeader); // free response[0].iov_base - parcMemory_Deallocate(&receivedPayload); // free response[1].iov_base - parcMemory_Deallocate(&response); // free iovec pointer - - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlListRoutes.h b/hicn-light/src/hicn/config/controlListRoutes.h deleted file mode 100644 index 341552add..000000000 --- a/hicn-light/src/hicn/config/controlListRoutes.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_ListRoutes.h - * @brief List the icn-light routes - * - * Implements the "list routes" and "help list routes" nodes of the command tree - * - */ -#ifndef Control_ListRoutes_h -#define Control_ListRoutes_h - -#include <hicn/config/controlState.h> -CommandOps *controlListRoutes_Create(ControlState *state); -CommandOps *controlListRoutes_HelpCreate(ControlState *state); -#endif // Control_ListRoutes_h diff --git a/hicn-light/src/hicn/config/controlMapMe.c b/hicn-light/src/hicn/config/controlMapMe.c deleted file mode 100644 index b292ee0f0..000000000 --- a/hicn-light/src/hicn/config/controlMapMe.c +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/assert/parc_Assert.h> - -#include <hicn/config/controlMapMe.h> -#include <hicn/config/controlMapMeDiscovery.h> -#include <hicn/config/controlMapMeEnable.h> -#include <hicn/config/controlMapMeRetx.h> -#include <hicn/config/controlMapMeTimescale.h> - -static void _controlMapMe_Init(CommandParser *parser, CommandOps *ops); -static CommandReturn _controlMapMe_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlMapMe_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandMapMe = "mapme"; -static const char *_commandMapMeHelp = "help mapme"; - -CommandOps *controlMapMe_Create(ControlState *state) { - return commandOps_Create(state, _commandMapMe, _controlMapMe_Init, - _controlMapMe_Execute, commandOps_Destroy); -} - -CommandOps *controlMapMe_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandMapMeHelp, NULL, - _controlMapMe_HelpExecute, commandOps_Destroy); -} - -// ===================================================== - -static CommandReturn _controlMapMe_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - CommandOps *ops_mapme_enable = controlMapMeEnable_HelpCreate(NULL); - CommandOps *ops_mapme_discovery = controlMapMeDiscovery_HelpCreate(NULL); - CommandOps *ops_mapme_timescale = controlMapMeTimescale_HelpCreate(NULL); - CommandOps *ops_mapme_retx = controlMapMeRetx_HelpCreate(NULL); - - snprintf(output, output_size, "Available commands:\n" - " %s\n %s\n %s\n %s\n\n", - ops_mapme_enable->command, - ops_mapme_discovery->command, - ops_mapme_timescale->command, - ops_mapme_retx->command); - - commandOps_Destroy(&ops_mapme_enable); - commandOps_Destroy(&ops_mapme_discovery); - commandOps_Destroy(&ops_mapme_timescale); - commandOps_Destroy(&ops_mapme_retx); - - return CommandReturn_Success; -} - -static void _controlMapMe_Init(CommandParser *parser, CommandOps *ops) { - ControlState *state = ops->closure; - controlState_RegisterCommand(state, controlMapMeEnable_HelpCreate(state)); - controlState_RegisterCommand(state, controlMapMeDiscovery_HelpCreate(state)); - controlState_RegisterCommand(state, controlMapMeTimescale_HelpCreate(state)); - controlState_RegisterCommand(state, controlMapMeRetx_HelpCreate(state)); - controlState_RegisterCommand(state, controlMapMeEnable_Create(state)); - controlState_RegisterCommand(state, controlMapMeDiscovery_Create(state)); - controlState_RegisterCommand(state, controlMapMeTimescale_Create(state)); - controlState_RegisterCommand(state, controlMapMeRetx_Create(state)); -} - -static CommandReturn _controlMapMe_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - return _controlMapMe_HelpExecute(parser, ops, args, output, output_size); -} - -// ====================================================================== diff --git a/hicn-light/src/hicn/config/controlMapMe.h b/hicn-light/src/hicn/config/controlMapMe.h deleted file mode 100644 index 3edd78989..000000000 --- a/hicn-light/src/hicn/config/controlMapMe.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 controlMapMe_h -#define controlMapMe_h - -#include <hicn/config/controlState.h> -CommandOps *controlMapMe_Create(ControlState *state); -CommandOps *controlMapMe_HelpCreate(ControlState *state); -#endif // controlMapMe_h diff --git a/hicn-light/src/hicn/config/controlMapMeDiscovery.c b/hicn-light/src/hicn/config/controlMapMeDiscovery.c deleted file mode 100644 index 6ec941141..000000000 --- a/hicn-light/src/hicn/config/controlMapMeDiscovery.c +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/assert/parc_Assert.h> -#include <hicn/config/controlMapMeDiscovery.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlMapMeDiscovery_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlMapMeDiscovery_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandMapMeDiscovery = "mapme discovery"; -static const char *_commandMapMeDiscoveryHelp = "help mapme discovery"; - -// ==================================================== - -CommandOps *controlMapMeDiscovery_Create(ControlState *state) { - return commandOps_Create(state, _commandMapMeDiscovery, NULL, - _controlMapMeDiscovery_Execute, commandOps_Destroy); -} - -CommandOps *controlMapMeDiscovery_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandMapMeDiscoveryHelp, NULL, - _controlMapMeDiscovery_HelpExecute, - commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlMapMeDiscovery_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "mapme discovery [on|off]\n\n"); - - return CommandReturn_Success; -} - -static CommandReturn _controlMapMeDiscovery_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 3) { - _controlMapMeDiscovery_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - bool active; - if (strcmp(parcList_GetAtIndex(args, 2), "on") == 0) { - active = true; - } else if (strcmp(parcList_GetAtIndex(args, 2), "off") == 0) { - active = false; - } else { - _controlMapMeDiscovery_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - mapme_activator_command *mapmeDiscoveryCommand = - parcMemory_AllocateAndClear(sizeof(mapme_activator_command)); - if (active) { - mapmeDiscoveryCommand->activate = ACTIVATE_ON; - } else { - mapmeDiscoveryCommand->activate = ACTIVATE_OFF; - } - - ControlState *state = ops->closure; - // send message and receive response - struct iovec *response = - utils_SendRequest(state, MAPME_DISCOVERY, mapmeDiscoveryCommand, - sizeof(mapme_activator_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlMapMeDiscovery.h b/hicn-light/src/hicn/config/controlMapMeDiscovery.h deleted file mode 100644 index c2832632a..000000000 --- a/hicn-light/src/hicn/config/controlMapMeDiscovery.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 Control_MapMeDiscovery_h -#define Control_MapMeDiscovery_h - -#include <hicn/config/controlState.h> -CommandOps *controlMapMeDiscovery_Create(ControlState *state); -CommandOps *controlMapMeDiscovery_HelpCreate(ControlState *state); -#endif // Control_MapMeDiscovery_h diff --git a/hicn-light/src/hicn/config/controlMapMeEnable.c b/hicn-light/src/hicn/config/controlMapMeEnable.c deleted file mode 100644 index 0595cc346..000000000 --- a/hicn-light/src/hicn/config/controlMapMeEnable.c +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/assert/parc_Assert.h> -#include <hicn/config/controlMapMeEnable.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlMapMeEnable_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlMapMeEnable_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandMapMeEnable = "mapme enable"; -static const char *_commandMapMeEnableHelp = "help mapme enable"; - -// ==================================================== - -CommandOps *controlMapMeEnable_Create(ControlState *state) { - return commandOps_Create(state, _commandMapMeEnable, NULL, - _controlMapMeEnable_Execute, commandOps_Destroy); -} - -CommandOps *controlMapMeEnable_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandMapMeEnableHelp, NULL, - _controlMapMeEnable_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlMapMeEnable_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "mapme enable [on|off]\n\n"); - - return CommandReturn_Success; -} - -static CommandReturn _controlMapMeEnable_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 3) { - _controlMapMeEnable_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - bool active; - if (strcmp(parcList_GetAtIndex(args, 2), "on") == 0) { - active = true; - } else if (strcmp(parcList_GetAtIndex(args, 2), "off") == 0) { - active = false; - } else { - _controlMapMeEnable_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - mapme_activator_command *mapmeEnableCommand = - parcMemory_AllocateAndClear(sizeof(mapme_activator_command)); - if (active) { - mapmeEnableCommand->activate = ACTIVATE_ON; - } else { - mapmeEnableCommand->activate = ACTIVATE_OFF; - } - - ControlState *state = ops->closure; - // send message and receive response - struct iovec *response = utils_SendRequest( - state, MAPME_ENABLE, mapmeEnableCommand, sizeof(mapme_activator_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlMapMeEnable.h b/hicn-light/src/hicn/config/controlMapMeEnable.h deleted file mode 100644 index 0ce4970f3..000000000 --- a/hicn-light/src/hicn/config/controlMapMeEnable.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 Control_MapMeEnable_h -#define Control_MapMeEnable_h - -#include <hicn/config/controlState.h> -CommandOps *controlMapMeEnable_Create(ControlState *state); -CommandOps *controlMapMeEnable_HelpCreate(ControlState *state); -#endif // Control_MapMeEnable_h diff --git a/hicn-light/src/hicn/config/controlMapMeRetx.c b/hicn-light/src/hicn/config/controlMapMeRetx.c deleted file mode 100644 index 9f37ca6f5..000000000 --- a/hicn-light/src/hicn/config/controlMapMeRetx.c +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/assert/parc_Assert.h> -#include <hicn/config/controlMapMeRetx.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlMapMeRetx_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlMapMeRetx_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandMapMeRetx = "mapme retx"; -static const char *_commandMapMeRetxHelp = "help mapme retx"; - -// ==================================================== - -CommandOps *controlMapMeRetx_Create(ControlState *state) { - return commandOps_Create(state, _commandMapMeRetx, NULL, - _controlMapMeRetx_Execute, commandOps_Destroy); -} - -CommandOps *controlMapMeRetx_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandMapMeRetxHelp, NULL, - _controlMapMeRetx_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlMapMeRetx_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "mapme retx <milliseconds>\n\n"); - - return CommandReturn_Success; -} - -static CommandReturn _controlMapMeRetx_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 3) { - _controlMapMeRetx_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - const char *rtx = parcList_GetAtIndex(args, 2); - if (!utils_IsNumber(rtx)) { - snprintf(output, output_size, - "ERROR: retransmission value (expressed in ms) must be a positive " - "integer \n"); - return CommandReturn_Failure; - } - - mapme_timing_command *mapmeRetxCommand = - parcMemory_AllocateAndClear(sizeof(mapme_timing_command)); - mapmeRetxCommand->timePeriod = (unsigned)strtold(rtx, NULL); - - ControlState *state = ops->closure; - // send message and receive response - struct iovec *response = utils_SendRequest( - state, MAPME_RETX, mapmeRetxCommand, sizeof(mapme_timing_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlMapMeRetx.h b/hicn-light/src/hicn/config/controlMapMeRetx.h deleted file mode 100644 index 3e3b2de15..000000000 --- a/hicn-light/src/hicn/config/controlMapMeRetx.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 Control_MapMeRetx_h -#define Control_MapMeRetx_h - -#include <hicn/config/controlState.h> -CommandOps *controlMapMeRetx_Create(ControlState *state); -CommandOps *controlMapMeRetx_HelpCreate(ControlState *state); -#endif // Control_MapMeRetx_h diff --git a/hicn-light/src/hicn/config/controlMapMeTimescale.c b/hicn-light/src/hicn/config/controlMapMeTimescale.c deleted file mode 100644 index 51701aa2f..000000000 --- a/hicn-light/src/hicn/config/controlMapMeTimescale.c +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/assert/parc_Assert.h> -#include <hicn/config/controlMapMeTimescale.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlMapMeTimescale_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlMapMeTimescale_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandMapMeTimescale = "mapme timescale"; -static const char *_commandMapMeTimescaleHelp = "help mapme timescale"; - -// ==================================================== - -CommandOps *controlMapMeTimescale_Create(ControlState *state) { - return commandOps_Create(state, _commandMapMeTimescale, NULL, - _controlMapMeTimescale_Execute, commandOps_Destroy); -} - -CommandOps *controlMapMeTimescale_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandMapMeTimescaleHelp, NULL, - _controlMapMeTimescale_HelpExecute, - commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlMapMeTimescale_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "mapme timescale <milliseconds>\n\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlMapMeTimescale_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 3) { - _controlMapMeTimescale_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - const char *ts = parcList_GetAtIndex(args, 2); - if (!utils_IsNumber(ts)) { - snprintf(output, output_size, - "ERROR: timescale value (expressed in ms) must be a positive integer " - "\n"); - return CommandReturn_Failure; - } - - mapme_timing_command *mapmeTimescaleCommand = - parcMemory_AllocateAndClear(sizeof(mapme_timing_command)); - mapmeTimescaleCommand->timePeriod = (unsigned)strtold(ts, NULL); - - ControlState *state = ops->closure; - // send message and receive response - struct iovec *response = - utils_SendRequest(state, MAPME_TIMESCALE, mapmeTimescaleCommand, - sizeof(mapme_timing_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlMapMeTimescale.h b/hicn-light/src/hicn/config/controlMapMeTimescale.h deleted file mode 100644 index 947d00a5d..000000000 --- a/hicn-light/src/hicn/config/controlMapMeTimescale.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 Control_MapMeTimescale_h -#define Control_MapMeTimescale_h - -#include <hicn/config/controlState.h> -CommandOps *controlMapMeTimescale_Create(ControlState *state); -CommandOps *controlMapMeTimescale_HelpCreate(ControlState *state); -#endif // Control_MapMeTimescale_h diff --git a/hicn-light/src/hicn/config/controlQuit.c b/hicn-light/src/hicn/config/controlQuit.c deleted file mode 100644 index 621880d13..000000000 --- a/hicn-light/src/hicn/config/controlQuit.c +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/security/parc_Security.h> - -#include <hicn/config/controlQuit.h> - -static CommandReturn _controlQuit_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlQuit_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandQuit = "quit"; -static const char *_commandQuitHelp = "help quit"; - -// ==================================================== - -CommandOps *controlQuit_Create(ControlState *state) { - return commandOps_Create(state, _commandQuit, NULL, _controlQuit_Execute, - commandOps_Destroy); -} - -CommandOps *controlQuit_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandQuitHelp, NULL, - _controlQuit_HelpExecute, commandOps_Destroy); -} - -// ============================================== - -static CommandReturn _controlQuit_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "Exits the interactive control program\n\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlQuit_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "exiting interactive shell\n"); - return CommandReturn_Exit; -} diff --git a/hicn-light/src/hicn/config/controlQuit.h b/hicn-light/src/hicn/config/controlQuit.h deleted file mode 100644 index b45d5e215..000000000 --- a/hicn-light/src/hicn/config/controlQuit.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_Quit.h - * @brief The quit command - * - * Implements the "quit" and "help quit" nodes of the command tree - * - */ -#ifndef Control_Quit_h -#define Control_Quit_h - -#include <hicn/config/controlState.h> -CommandOps *controlQuit_Create(ControlState *state); -CommandOps *controlQuit_HelpCreate(ControlState *state); -#endif // Control_Quit_h diff --git a/hicn-light/src/hicn/config/controlRemove.c b/hicn-light/src/hicn/config/controlRemove.c deleted file mode 100644 index b1a88b5c1..000000000 --- a/hicn-light/src/hicn/config/controlRemove.c +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/security/parc_Security.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlRemove.h> -#include <hicn/config/controlRemoveListener.h> -#include <hicn/config/controlRemoveConnection.h> -#include <hicn/config/controlRemovePunting.h> -#include <hicn/config/controlRemoveRoute.h> -#ifdef WITH_POLICY -#include <hicn/config/controlRemovePolicy.h> -#endif /* WITH_POLICY */ - -static void _controlRemove_Init(CommandParser *parser, CommandOps *ops); -static CommandReturn _controlRemove_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlRemove_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandRemove = "remove"; -static const char *_commandRemoveHelp = "help remove"; - -// ==================================================== - -CommandOps *controlRemove_Create(ControlState *state) { - return commandOps_Create(state, _commandRemove, _controlRemove_Init, - _controlRemove_Execute, commandOps_Destroy); -} - -CommandOps *controlRemove_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandRemoveHelp, NULL, - _controlRemove_HelpExecute, commandOps_Destroy); -} - -// ============================================== - -static CommandReturn _controlRemove_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - CommandOps *ops_remove_connection = controlRemoveConnection_Create(NULL); - CommandOps *ops_remove_listener = controlRemoveListener_Create(NULL); - CommandOps *ops_remove_route = controlRemoveRoute_Create(NULL); - CommandOps *ops_remove_punting = controlRemovePunting_Create(NULL); -#ifdef WITH_POLICY - CommandOps *ops_remove_policy = controlRemovePolicy_Create(NULL); -#endif /* WITH_POLICY */ - - snprintf(output, output_size, "Available commands:\n" - " %s\n" - " %s\n" - " %s\n" - " %s\n" -#ifdef WITH_POLICY - " %s\n" -#endif /* WITH_POLICY */ - "\n", - ops_remove_connection->command, - ops_remove_listener->command, - ops_remove_route->command, - ops_remove_punting->command -#ifdef WITH_POLICY - , ops_remove_policy->command -#endif /* WITH_POLICY */ - ); - - commandOps_Destroy(&ops_remove_connection); - commandOps_Destroy(&ops_remove_listener); - commandOps_Destroy(&ops_remove_route); - commandOps_Destroy(&ops_remove_punting); -#ifdef WITH_POLICY - commandOps_Destroy(&ops_remove_policy); -#endif /* WITH_POLICY */ - return CommandReturn_Success; -} - -static void _controlRemove_Init(CommandParser *parser, CommandOps *ops) { - ControlState *state = ops->closure; - controlState_RegisterCommand(state, - controlRemoveConnection_HelpCreate(state)); - controlState_RegisterCommand(state, - controlRemoveListener_HelpCreate(state)); - controlState_RegisterCommand(state, controlRemoveRoute_HelpCreate(state)); - controlState_RegisterCommand(state, controlRemoveConnection_Create(state)); - controlState_RegisterCommand(state, controlRemoveListener_Create(state)); - controlState_RegisterCommand(state, controlRemoveRoute_Create(state)); - controlState_RegisterCommand(state, controlRemovePunting_Create(state)); - controlState_RegisterCommand(state, controlRemovePunting_HelpCreate(state)); -#ifdef WITH_POLICY - controlState_RegisterCommand(state, controlRemovePolicy_HelpCreate(state)); - controlState_RegisterCommand(state, controlRemovePolicy_Create(state)); -#endif /* WITH_POLICY */ -} - -static CommandReturn _controlRemove_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - return _controlRemove_HelpExecute(parser, ops, args, output, output_size); -} diff --git a/hicn-light/src/hicn/config/controlRemove.h b/hicn-light/src/hicn/config/controlRemove.h deleted file mode 100644 index 863555728..000000000 --- a/hicn-light/src/hicn/config/controlRemove.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_Remove.h - * @brief Implements the remove node of the CLI tree - * - * Implements the "remove" and "help remove" nodes of the command tree - * - */ -#ifndef controlRemove_h -#define controlRemove_h - -#include <hicn/config/controlState.h> -CommandOps *controlRemove_Create(ControlState *state); -CommandOps *controlRemove_HelpCreate(ControlState *state); -#endif // controlRemove_h diff --git a/hicn-light/src/hicn/config/controlRemoveConnection.c b/hicn-light/src/hicn/config/controlRemoveConnection.c deleted file mode 100644 index a6cfae1e5..000000000 --- a/hicn-light/src/hicn/config/controlRemoveConnection.c +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <ctype.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> -#include <hicn/utils/address.h> - -#include <hicn/config/controlRemoveConnection.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlRemoveConnection_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlRemoveConnection_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -// =================================================== - -static const char *_commandRemoveConnection = "remove connection"; -static const char *_commandRemoveConnectionHelp = "help remove connection"; - -// ==================================================== - -CommandOps *controlRemoveConnection_Create(ControlState *state) { - return commandOps_Create(state, _commandRemoveConnection, NULL, - _controlRemoveConnection_Execute, - commandOps_Destroy); -} - -CommandOps *controlRemoveConnection_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandRemoveConnectionHelp, NULL, - _controlRemoveConnection_HelpExecute, - commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlRemoveConnection_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "command:\n" - " remove connection <symbolic|id>\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlRemoveConnection_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - ControlState *state = ops->closure; - - if (parcList_Size(args) != 3) { - _controlRemoveConnection_HelpExecute(parser, ops, args, output, output_size); - return false; - } - - if ((strcmp(parcList_GetAtIndex(args, 0), "remove") != 0) || - (strcmp(parcList_GetAtIndex(args, 1), "connection") != 0)) { - _controlRemoveConnection_HelpExecute(parser, ops, args, output, output_size); - return false; - } - - const char *symbolicOrConnid = parcList_GetAtIndex(args, 2); - - if (!utils_ValidateSymbolicName(symbolicOrConnid) && - !utils_IsNumber(symbolicOrConnid)) { - snprintf(output, output_size, - "ERROR: Invalid symbolic or connid:\nsymbolic name must begin with an " - "alpha followed by alphanum;\nconnid must be an integer\n"); - return CommandReturn_Failure; - } - - // allocate command payload - remove_connection_command *removeConnectionCommand = - parcMemory_AllocateAndClear(sizeof(remove_connection_command)); - // fill payload - strcpy(removeConnectionCommand->symbolicOrConnid, symbolicOrConnid); - - // send message and receive response - struct iovec *response = - utils_SendRequest(state, REMOVE_CONNECTION, removeConnectionCommand, - sizeof(remove_connection_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlRemoveConnection.h b/hicn-light/src/hicn/config/controlRemoveConnection.h deleted file mode 100644 index 51d3a52a8..000000000 --- a/hicn-light/src/hicn/config/controlRemoveConnection.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_RemoveConnection.h - * @brief Remove a connection from the connection table - * - * Implements the "remove connection" and "help remove connection" nodes of the - * CLI tree - * - */ - -#ifndef Control_RemoveConnection_h -#define Control_RemoveConnection_h - -#include <hicn/config/controlState.h> -CommandOps *controlRemoveConnection_Create(ControlState *state); -CommandOps *controlRemoveConnection_HelpCreate(ControlState *state); -#endif // Control_RemoveConnection_h diff --git a/hicn-light/src/hicn/config/controlRemoveListener.c b/hicn-light/src/hicn/config/controlRemoveListener.c deleted file mode 100644 index 7525316f1..000000000 --- a/hicn-light/src/hicn/config/controlRemoveListener.c +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <ctype.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> -#include <hicn/utils/address.h> - -#include <hicn/config/controlRemoveListener.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlRemoveListener_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlRemoveListener_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -// =================================================== - -static const char *_commandRemoveListener = "remove listener"; -static const char *_commandRemoveListenerHelp = "help remove listener"; - -// ==================================================== - -CommandOps *controlRemoveListener_Create(ControlState *state) { - return commandOps_Create(state, _commandRemoveListener, NULL, - _controlRemoveListener_Execute, - commandOps_Destroy); -} - -CommandOps *controlRemoveListener_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandRemoveListenerHelp, NULL, - _controlRemoveListener_HelpExecute, - commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlRemoveListener_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "command:\n" - " remove listener <symbolic|id>\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlRemoveListener_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - ControlState *state = ops->closure; - - if (parcList_Size(args) != 3) { - _controlRemoveListener_HelpExecute(parser, ops, args, output, output_size); - return false; - } - - if ((strcmp(parcList_GetAtIndex(args, 0), "remove") != 0) || - (strcmp(parcList_GetAtIndex(args, 1), "listener") != 0)) { - _controlRemoveListener_HelpExecute(parser, ops, args, output, output_size); - return false; - } - - const char *listenerId = parcList_GetAtIndex(args, 2); - -if (!utils_ValidateSymbolicName(listenerId) && - !utils_IsNumber(listenerId)) { - snprintf(output, output_size, - "ERROR: Invalid symbolic or listenerId:\nsymbolic name must begin with an " - "alpha followed by alphanum;\nlistenerId must be an integer\n"); - return CommandReturn_Failure; - } - - // allocate command payload - remove_listener_command *removeListenerCommand = - parcMemory_AllocateAndClear(sizeof(remove_listener_command)); - // fill payload - //removeListenerCommand->listenerId = atoi(listenerId); - snprintf(removeListenerCommand->symbolicOrListenerid, SYMBOLIC_NAME_LEN, "%s", listenerId); - - // send message and receive response - struct iovec *response = - utils_SendRequest(state, REMOVE_LISTENER, removeListenerCommand, - sizeof(remove_listener_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlRemoveListener.h b/hicn-light/src/hicn/config/controlRemoveListener.h deleted file mode 100644 index 794d1e1a9..000000000 --- a/hicn-light/src/hicn/config/controlRemoveListener.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_RemoveConnection.h - * @brief Remove a connection from the connection table - * - * Implements the "remove connection" and "help remove connection" nodes of the - * CLI tree - * - */ - -#ifndef Control_RemoveListener_h -#define Control_RemoveListener_h - -#include <hicn/config/controlState.h> -CommandOps *controlRemoveListener_Create(ControlState *state); -CommandOps *controlRemoveListener_HelpCreate(ControlState *state); -#endif // Control_RemoveListener_h diff --git a/hicn-light/src/hicn/config/controlRemovePolicy.c b/hicn-light/src/hicn/config/controlRemovePolicy.c deleted file mode 100644 index 35741396e..000000000 --- a/hicn-light/src/hicn/config/controlRemovePolicy.c +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifdef WITH_POLICY - -#include <hicn/hicn-light/config.h> - -#include <ctype.h> -#include <parc/algol/parc_List.h> -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> -#include <parc/assert/parc_Assert.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <hicn/utils/address.h> - -#include <hicn/config/controlRemovePolicy.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlRemovePolicy_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlRemovePolicy_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -// =================================================== - -static const char *_commandRemovePolicy = "remove policy"; -static const char *_commandRemovePolicyHelp = "help remove policy"; - -// ==================================================== - -CommandOps *controlRemovePolicy_Create(ControlState *state) { - return commandOps_Create(state, _commandRemovePolicy, NULL, - _controlRemovePolicy_Execute, commandOps_Destroy); -} - -CommandOps *controlRemovePolicy_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandRemovePolicyHelp, NULL, - _controlRemovePolicy_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlRemovePolicy_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "commands:\n" - " remove policy <prefix>\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlRemovePolicy_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - ControlState *state = ops->closure; - - if (parcList_Size(args) != 3) { - _controlRemovePolicy_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - const char *prefixStr = parcList_GetAtIndex(args, 2); - char *addr = (char *)malloc(sizeof(char) * (strlen(prefixStr) + 1)); - - // separate address and len - char *slash; - uint32_t len = 0; - strcpy(addr, prefixStr); - slash = strrchr(addr, '/'); - if (slash != NULL) { - len = atoi(slash + 1); - *slash = '\0'; - } - - // allocate command payload - remove_policy_command *removePolicyCommand = - parcMemory_AllocateAndClear(sizeof(remove_policy_command)); - - // check and set IP address - if (inet_pton(AF_INET, addr, &removePolicyCommand->address.v4.as_u32) == 1) { - if (len > 32) { - snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n"); - parcMemory_Deallocate(&removePolicyCommand); - free(addr); - return CommandReturn_Failure; - } - removePolicyCommand->addressType = ADDR_INET; - } else if (inet_pton(AF_INET6, addr, &removePolicyCommand->address.v6.as_in6addr) == - 1) { - if (len > 128) { - snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n"); - parcMemory_Deallocate(&removePolicyCommand); - free(addr); - return CommandReturn_Failure; - } - removePolicyCommand->addressType = ADDR_INET6; - } else { - snprintf(output, output_size, "Error: %s is not a valid network address \n", addr); - parcMemory_Deallocate(&removePolicyCommand); - free(addr); - return CommandReturn_Failure; - } - - free(addr); - // Fill remaining payload fields - removePolicyCommand->len = len; - - // send message and receive response - struct iovec *response = utils_SendRequest( - state, REMOVE_POLICY, removePolicyCommand, sizeof(remove_policy_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} - -#endif /* WITH_POLICY */ diff --git a/hicn-light/src/hicn/config/controlRemovePolicy.h b/hicn-light/src/hicn/config/controlRemovePolicy.h deleted file mode 100644 index ebe098985..000000000 --- a/hicn-light/src/hicn/config/controlRemovePolicy.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_RemovePolicy.h - * @brief Remove a policy from the FIB - * - * Implements the "remove policy" and "help remove policy" nodes of the command - * tree - * - */ - -#ifndef Control_RemovePolicy_h -#define Control_RemovePolicy_h - -#ifdef WITH_POLICY - -#include <hicn/config/controlState.h> -CommandOps *controlRemovePolicy_Create(ControlState *state); -CommandOps *controlRemovePolicy_HelpCreate(ControlState *state); - -#endif /* WITH_POLICY */ - -#endif // Control_RemovePolicy_h diff --git a/hicn-light/src/hicn/config/controlRemovePunting.c b/hicn-light/src/hicn/config/controlRemovePunting.c deleted file mode 100644 index 84d096b81..000000000 --- a/hicn-light/src/hicn/config/controlRemovePunting.c +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <ctype.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> -#include <hicn/utils/address.h> - -#include <hicn/config/controlRemovePunting.h> - -static CommandReturn _controlRemovePunting_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlRemovePunting_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -// =================================================== - -static const char *_commandRemovePunting = "remove punting"; -static const char *_commandRemovePuntingHelp = "help punting connection"; - -// ==================================================== - -CommandOps *controlRemovePunting_Create(ControlState *state) { - return commandOps_Create(state, _commandRemovePunting, NULL, - _controlRemovePunting_Execute, commandOps_Destroy); -} - -CommandOps *controlRemovePunting_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandRemovePuntingHelp, NULL, - _controlRemovePunting_HelpExecute, - commandOps_Destroy); -} - -// ==================================================== - -// ==================================================== - -static CommandReturn _controlRemovePunting_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "remove punting <symbolic> <prefix>\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlRemovePunting_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "command not implemented\n"); - return _controlRemovePunting_HelpExecute(parser, ops, args, output, output_size); -} - -// ================================================== diff --git a/hicn-light/src/hicn/config/controlRemovePunting.h b/hicn-light/src/hicn/config/controlRemovePunting.h deleted file mode 100644 index 858d6f969..000000000 --- a/hicn-light/src/hicn/config/controlRemovePunting.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_RemovePunting.h - * - */ - -#ifndef Control_RemovePunting_h -#define Control_RemovePunting_h - -#include <hicn/config/controlState.h> -CommandOps *controlRemovePunting_Create(ControlState *state); -CommandOps *controlRemovePunting_HelpCreate(ControlState *state); -#endif // Control_RemovePunting_h diff --git a/hicn-light/src/hicn/config/controlRemoveRoute.c b/hicn-light/src/hicn/config/controlRemoveRoute.c deleted file mode 100644 index eb5642d98..000000000 --- a/hicn-light/src/hicn/config/controlRemoveRoute.c +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <ctype.h> -#include <parc/algol/parc_List.h> -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> -#include <parc/assert/parc_Assert.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <hicn/utils/address.h> - -#include <hicn/config/controlRemoveRoute.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlRemoveRoute_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlRemoveRoute_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -// =================================================== - -static const char *_commandRemoveRoute = "remove route"; -static const char *_commandRemoveRouteHelp = "help remove route"; - -// ==================================================== - -CommandOps *controlRemoveRoute_Create(ControlState *state) { - return commandOps_Create(state, _commandRemoveRoute, NULL, - _controlRemoveRoute_Execute, commandOps_Destroy); -} - -CommandOps *controlRemoveRoute_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandRemoveRouteHelp, NULL, - _controlRemoveRoute_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlRemoveRoute_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "commands:\n" - " remove route <symbolic | connid> <prefix>\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlRemoveRoute_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - ControlState *state = ops->closure; - - if (parcList_Size(args) != 4) { - _controlRemoveRoute_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - const char *symbolicOrConnid = parcList_GetAtIndex(args, 2); - - if (!utils_ValidateSymbolicName(symbolicOrConnid) && - !utils_IsNumber(symbolicOrConnid)) { - snprintf(output, output_size, - "ERROR: Invalid symbolic or connid:\nsymbolic name must begin with an " - "alpha followed by alphanum;\nconnid must be an integer\n"); - return CommandReturn_Failure; - } - - const char *prefixStr = parcList_GetAtIndex(args, 3); - char *addr = (char *)malloc(sizeof(char) * (strlen(prefixStr) + 1)); - - // separate address and len - char *slash; - uint32_t len = 0; - strcpy(addr, prefixStr); - slash = strrchr(addr, '/'); - if (slash != NULL) { - len = atoi(slash + 1); - *slash = '\0'; - } - - // allocate command payload - remove_route_command *removeRouteCommand = - parcMemory_AllocateAndClear(sizeof(remove_route_command)); - - // check and set IP address - if (inet_pton(AF_INET, addr, &removeRouteCommand->address.v4.as_u32) == 1) { - if (len > 32) { - snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n"); - parcMemory_Deallocate(&removeRouteCommand); - free(addr); - return CommandReturn_Failure; - } - removeRouteCommand->addressType = ADDR_INET; - } else if (inet_pton(AF_INET6, addr, &removeRouteCommand->address.v6.as_in6addr) == - 1) { - if (len > 128) { - snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n"); - parcMemory_Deallocate(&removeRouteCommand); - free(addr); - return CommandReturn_Failure; - } - removeRouteCommand->addressType = ADDR_INET6; - } else { - snprintf(output, output_size, "Error: %s is not a valid network address \n", addr); - parcMemory_Deallocate(&removeRouteCommand); - free(addr); - return CommandReturn_Failure; - } - - free(addr); - // Fill remaining payload fields - removeRouteCommand->len = len; - strcpy(removeRouteCommand->symbolicOrConnid, symbolicOrConnid); - - // send message and receive response - struct iovec *response = utils_SendRequest( - state, REMOVE_ROUTE, removeRouteCommand, sizeof(remove_route_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlRemoveRoute.h b/hicn-light/src/hicn/config/controlRemoveRoute.h deleted file mode 100644 index 5e152b2fd..000000000 --- a/hicn-light/src/hicn/config/controlRemoveRoute.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_RemoveRoute.h - * @brief Remove a route from the FIB - * - * Implements the "remove route" and "help remove route" nodes of the command - * tree - * - */ - -#ifndef Control_RemoveRoute_h -#define Control_RemoveRoute_h - -#include <hicn/config/controlState.h> -CommandOps *controlRemoveRoute_Create(ControlState *state); -CommandOps *controlRemoveRoute_HelpCreate(ControlState *state); -#endif // Control_RemoveRoute_h diff --git a/hicn-light/src/hicn/config/controlRoot.c b/hicn-light/src/hicn/config/controlRoot.c deleted file mode 100644 index 39a1fa6b5..000000000 --- a/hicn-light/src/hicn/config/controlRoot.c +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <hicn/config/controlAdd.h> -#include <hicn/config/controlCache.h> -#include <hicn/config/controlList.h> -#include <hicn/config/controlMapMe.h> -#include <hicn/config/controlQuit.h> -#include <hicn/config/controlRemove.h> -#include <hicn/config/controlRoot.h> -#include <hicn/config/controlSet.h> -#include <hicn/config/controlUnset.h> -#ifdef WITH_POLICY -#include <hicn/config/controlUpdate.h> -#endif /* WITH_POLICY */ - -static void _controlRoot_Init(CommandParser *parser, CommandOps *ops); -static CommandReturn _controlRoot_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlRoot_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandRoot = ""; -static const char *_commandRootHelp = "help"; - -// ==================================================== - -CommandOps *controlRoot_Create(ControlState *state) { - return commandOps_Create(state, _commandRoot, _controlRoot_Init, - _controlRoot_Execute, commandOps_Destroy); -} - -CommandOps *controlRoot_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandRootHelp, NULL, - _controlRoot_HelpExecute, commandOps_Destroy); -} - -// =================================================== - -static CommandReturn _controlRoot_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - size_t output_offset = snprintf(output, output_size, "Command-line execution:\n" - " controller [--server <server-ip>] [--port <server-port>] " - "command\n" - "\n" - "Interactive execution:\n" - " controller [--server <server-ip>] [--port <server-port>]\n" - "\n" - "If the keystore is not specified, the default path is used. Keystore " - "must exist prior to running program.\n" - "If the password is not specified, the user will be prompted.\n" - "\n"); - - CommandOps *ops_help_add = controlAdd_CreateHelp(NULL); - CommandOps *ops_help_list = controlList_HelpCreate(NULL); - CommandOps *ops_help_quit = controlQuit_HelpCreate(NULL); - CommandOps *ops_help_remove = controlRemove_HelpCreate(NULL); - CommandOps *ops_help_set = controlSet_HelpCreate(NULL); - CommandOps *ops_help_unset = controlUnset_HelpCreate(NULL); - CommandOps *ops_help_cache = controlCache_HelpCreate(NULL); - CommandOps *ops_help_mapme = controlMapMe_HelpCreate(NULL); -#ifdef WITH_POLICY - CommandOps *ops_help_update = controlUpdate_HelpCreate(NULL); -#endif /* WITH_POLICY */ - - snprintf(output + output_offset, output_size - output_offset,"Available commands:\n" - " %s\n" - " %s\n" - " %s\n" - " %s\n" - " %s\n" - " %s\n" - " %s\n" - " %s\n" -#ifdef WITH_POLICY - " %s\n" -#endif /* WITH_POLICY */ - "\n", - ops_help_add->command, - ops_help_list->command, - ops_help_quit->command, - ops_help_remove->command, - ops_help_set->command, - ops_help_unset->command, - ops_help_cache->command, - ops_help_mapme->command -#ifdef WITH_POLICY - , ops_help_update->command -#endif /* WITH_POLICY */ - ); - - commandOps_Destroy(&ops_help_add); - commandOps_Destroy(&ops_help_list); - commandOps_Destroy(&ops_help_quit); - commandOps_Destroy(&ops_help_remove); - commandOps_Destroy(&ops_help_set); - commandOps_Destroy(&ops_help_unset); - commandOps_Destroy(&ops_help_cache); - commandOps_Destroy(&ops_help_mapme); -#ifdef WITH_POLICY - commandOps_Destroy(&ops_help_update); -#endif /* WITH_POLICY */ - - return CommandReturn_Success; -} - -static void _controlRoot_Init(CommandParser *parser, CommandOps *ops) { - ControlState *state = ops->closure; - - controlState_RegisterCommand(state, controlAdd_CreateHelp(state)); - controlState_RegisterCommand(state, controlList_HelpCreate(state)); - controlState_RegisterCommand(state, controlQuit_HelpCreate(state)); - controlState_RegisterCommand(state, controlRemove_HelpCreate(state)); - controlState_RegisterCommand(state, controlSet_HelpCreate(state)); - controlState_RegisterCommand(state, controlUnset_HelpCreate(state)); - controlState_RegisterCommand(state, controlCache_HelpCreate(state)); - controlState_RegisterCommand(state, controlMapMe_HelpCreate(state)); -#ifdef WITH_POLICY - controlState_RegisterCommand(state, controlUpdate_HelpCreate(state)); -#endif /* WITH_POLICY */ - - controlState_RegisterCommand(state, webControlAdd_Create(state)); - controlState_RegisterCommand(state, controlList_Create(state)); - controlState_RegisterCommand(state, controlQuit_Create(state)); - controlState_RegisterCommand(state, controlRemove_Create(state)); - controlState_RegisterCommand(state, controlSet_Create(state)); - controlState_RegisterCommand(state, controlUnset_Create(state)); - controlState_RegisterCommand(state, controlCache_Create(state)); - controlState_RegisterCommand(state, controlMapMe_Create(state)); -#ifdef WITH_POLICY - controlState_RegisterCommand(state, controlUpdate_Create(state)); -#endif /* WITH_POLICY */ -} - -static CommandReturn _controlRoot_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - return CommandReturn_Success; -} - -// ====================================================================== diff --git a/hicn-light/src/hicn/config/controlRoot.h b/hicn-light/src/hicn/config/controlRoot.h deleted file mode 100644 index 154b81a80..000000000 --- a/hicn-light/src/hicn/config/controlRoot.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_Root.h - * @brief Root of the command tree - * - * Implements the root of the command tree. This is the one module that - * needs to be seeded to the control state to build the whole tree. - * - */ - -#ifndef Control_Root_h -#define Control_Root_h - -#include <hicn/config/controlState.h> -CommandOps *controlRoot_Create(ControlState *state); -CommandOps *controlRoot_HelpCreate(ControlState *state); -#endif // Control_Root_h diff --git a/hicn-light/src/hicn/config/controlSet.c b/hicn-light/src/hicn/config/controlSet.c deleted file mode 100644 index 37d56e593..000000000 --- a/hicn-light/src/hicn/config/controlSet.c +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/security/parc_Security.h> - -#include <hicn/config/controlSet.h> -#include <hicn/config/controlSetDebug.h> -#include <hicn/config/controlSetStrategy.h> -#include <hicn/config/controlSetWldr.h> - -static void _controlSet_Init(CommandParser *parser, CommandOps *ops); -static CommandReturn _controlSet_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlSet_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandSet = "set"; -static const char *_commandSetHelp = "help set"; - -// =========================================================== - -CommandOps *controlSet_Create(ControlState *state) { - return commandOps_Create(state, _commandSet, _controlSet_Init, - _controlSet_Execute, commandOps_Destroy); -} - -CommandOps *controlSet_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandSetHelp, NULL, - _controlSet_HelpExecute, commandOps_Destroy); -} - -// =========================================================== - -static void _controlSet_Init(CommandParser *parser, CommandOps *ops) { - ControlState *state = ops->closure; - controlState_RegisterCommand(state, controlSetDebug_Create(state)); - controlState_RegisterCommand(state, controlSetDebug_HelpCreate(state)); - controlState_RegisterCommand(state, controlSetStrategy_Create(state)); - controlState_RegisterCommand(state, controlSetStrategy_HelpCreate(state)); - controlState_RegisterCommand(state, controlSetWldr_Create(state)); - controlState_RegisterCommand(state, controlSetWldr_HelpCreate(state)); -} - -static CommandReturn _controlSet_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - CommandOps *ops_help_set_debug = controlSetDebug_HelpCreate(NULL); - CommandOps *ops_help_set_strategy = controlSetStrategy_HelpCreate(NULL); - CommandOps *ops_help_set_wldr = controlSetWldr_HelpCreate(NULL); - - snprintf(output, output_size, "Available commands:\n %s\n %s\n %s\n\n", - ops_help_set_debug->command, - ops_help_set_strategy->command, - ops_help_set_wldr->command); - - commandOps_Destroy(&ops_help_set_debug); - commandOps_Destroy(&ops_help_set_strategy); - commandOps_Destroy(&ops_help_set_wldr); - return CommandReturn_Success; -} - -static CommandReturn _controlSet_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - return _controlSet_HelpExecute(parser, ops, args, output, output_size); -} diff --git a/hicn-light/src/hicn/config/controlSet.h b/hicn-light/src/hicn/config/controlSet.h deleted file mode 100644 index abe2a611d..000000000 --- a/hicn-light/src/hicn/config/controlSet.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_Set.h - * @brief Implements the set node of the CLI tree - * - * Implements the "set" and "help set" nodes of the command tree - * - */ -#ifndef Control_Set_h -#define Control_Set_h - -#include <hicn/config/controlState.h> -CommandOps *controlSet_Create(ControlState *state); -CommandOps *controlSet_HelpCreate(ControlState *state); -#endif // Control_Set_h diff --git a/hicn-light/src/hicn/config/controlSetDebug.c b/hicn-light/src/hicn/config/controlSetDebug.c deleted file mode 100644 index a5dcc89c1..000000000 --- a/hicn-light/src/hicn/config/controlSetDebug.c +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlSetDebug.h> -#include <hicn/core/dispatcher.h> -#include <hicn/core/forwarder.h> - -static CommandReturn _controlSetDebug_Execute(CommandParser *parser, - CommandOps *ops, PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlSetDebug_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandSetDebug = "set debug"; -static const char *_commandSetDebugHelp = "help set debug"; - -// ==================================================== - -CommandOps *controlSetDebug_Create(ControlState *state) { - return commandOps_Create(state, _commandSetDebug, NULL, - _controlSetDebug_Execute, commandOps_Destroy); -} - -CommandOps *controlSetDebug_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandSetDebugHelp, NULL, - _controlSetDebug_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlSetDebug_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "set debug: will enable the debug flag for more verbose output\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlSetDebug_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 2) { - _controlSetDebug_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - ControlState *state = ops->closure; - controlState_SetDebug(state, true); - snprintf(output, output_size, "Debug flag set\n\n"); - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlSetDebug.h b/hicn-light/src/hicn/config/controlSetDebug.h deleted file mode 100644 index fabeb6952..000000000 --- a/hicn-light/src/hicn/config/controlSetDebug.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_SetDebug.h - * @brief Sets the debug flag for more verbose output - * - * Implements the "set debug" and "help set debug" nodes of the command tree - * - */ - -#ifndef Control_SetDebug_h -#define Control_SetDebug_h - -#include <hicn/config/controlState.h> -CommandOps *controlSetDebug_Create(ControlState *state); -CommandOps *controlSetDebug_HelpCreate(ControlState *state); -#endif // Control_SetDebug_h diff --git a/hicn-light/src/hicn/config/controlSetStrategy.c b/hicn-light/src/hicn/config/controlSetStrategy.c deleted file mode 100644 index fe0ba84a0..000000000 --- a/hicn-light/src/hicn/config/controlSetStrategy.c +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> - -#include <hicn/config/controlSetDebug.h> -#include <hicn/core/dispatcher.h> -#include <hicn/core/forwarder.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlSetStrategy_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlSetStrategy_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandSetStrategy = "set strategy"; -static const char *_commandSetStrategyHelp = "help set strategy"; - -static const char *_commandSetStrategyOptions[LAST_STRATEGY_VALUE] = { - "loadbalancer", - "random", - "low_latency", -}; - -// ==================================================== - -CommandOps *controlSetStrategy_Create(ControlState *state) { - return commandOps_Create(state, _commandSetStrategy, NULL, - _controlSetStrategy_Execute, commandOps_Destroy); -} - -CommandOps *controlSetStrategy_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandSetStrategyHelp, NULL, - _controlSetStrategy_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -strategy_type _validStrategy(const char *strategy) { - strategy_type validStrategy = LAST_STRATEGY_VALUE; - - for (int i = 0; i < LAST_STRATEGY_VALUE; i++) { - if (strcmp(_commandSetStrategyOptions[i], strategy) == 0) { - validStrategy = i; - break; - } - } - return validStrategy; -} - -static void _getAddressAndLen(const char * prefixStr, char *addr, uint32_t *len){ - char *slash; - strcpy(addr, prefixStr); - slash = strrchr(addr, '/'); - if (slash != NULL) { - *len = atoi(slash + 1); - *slash = '\0'; - } -} - -static bool _checkAndSetIp(set_strategy_command * setStrategyCommand, - int index, - char * addr, - uint32_t len, - char *output, - size_t output_size){ - // check and set IP address - int res; - if(index == -1) - res = inet_pton(AF_INET, addr, &setStrategyCommand->address.v4.as_u32); - else - res = inet_pton(AF_INET, addr, - &setStrategyCommand->addresses[index].v4.as_u32); - - if(res == 1) { - if (len == UINT32_MAX) { - snprintf(output, output_size, "Netmask not specified: set to 32 by default\n"); - len = 32; - } else if (len > 32) { - snprintf(output, output_size, "ERROR: exceeded INET mask length, max=32\n"); - return false; - } - if(index == -1) - setStrategyCommand->addressType = ADDR_INET; - else - setStrategyCommand->addresses_type[index] = ADDR_INET; - - } else { - - if(index == -1) - res = inet_pton(AF_INET6, addr, - &setStrategyCommand->address.v6.as_in6addr); - else - res = inet_pton(AF_INET6, addr, - &setStrategyCommand->addresses[index].v6.as_in6addr); - - if(res == 1) { - if (len == UINT32_MAX) { - snprintf(output, output_size, "Netmask not specified: set to 128 by default\n"); - len = 128; - } else if (len > 128) { - snprintf(output, output_size, "ERROR: exceeded INET6 mask length, max=128\n"); - return false; - } - - if(index == -1) - setStrategyCommand->addressType = ADDR_INET6; - else - setStrategyCommand->addresses_type[index] = ADDR_INET6; - - } else { - snprintf(output, output_size, "Error: %s is not a valid network address \n", addr); - - return false; - } - } - return true; -} - -static CommandReturn _controlSetStrategy_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, - "set strategy <prefix> <strategy> " - "[related_prefix1 related_preifx2 ...]\n" - "prefix: ipv4/ipv6 address (ex: 1234::/64)\n" - "strategy: strategy identifier\n" - "optinal: list of related prefixes (max %u)\n" - "available strategies:\n" - " random\n" - " loadbalancer\n" - " low_latency\n\n", - MAX_FWD_STRATEGY_RELATED_PREFIXES); - return CommandReturn_Success; -} - - -static CommandReturn _controlSetStrategy_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (output) { - output[0] = '\0'; - } - ControlState *state = ops->closure; - - if (parcList_Size(args) < 4 || - parcList_Size(args) > (4 + MAX_FWD_STRATEGY_RELATED_PREFIXES)) { - _controlSetStrategy_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - if (((strcmp(parcList_GetAtIndex(args, 0), "set") != 0) || - (strcmp(parcList_GetAtIndex(args, 1), "strategy") != 0))) { - _controlSetStrategy_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - const char *prefixStr = parcList_GetAtIndex(args, 2); - char *addr = (char *)malloc(sizeof(char) * (strlen(prefixStr) + 1)); - uint32_t len = UINT32_MAX; - _getAddressAndLen(prefixStr, addr, &len); - - // allocate command payload - set_strategy_command *setStrategyCommand = - parcMemory_AllocateAndClear(sizeof(set_strategy_command)); - - bool success = _checkAndSetIp(setStrategyCommand, -1, addr, len, output, output_size); - if(!success){ - parcMemory_Deallocate(&setStrategyCommand); - free(addr); - return CommandReturn_Failure; - } - - const char *strategyStr = parcList_GetAtIndex(args, 3); - // check valid strategy - strategy_type strategy; - if ((strategy = _validStrategy(strategyStr)) == LAST_STRATEGY_VALUE) { - size_t output_offset = strlen(output); - output_offset += snprintf(output + output_offset, output_size - output_offset, "Error: invalid strategy \n"); - - parcMemory_Deallocate(&setStrategyCommand); - _controlSetStrategy_HelpExecute(parser, ops, args, output + output_offset, output_size - output_offset); - free(addr); - return CommandReturn_Failure; - } - - free(addr); - - // Fill remaining payload fields - setStrategyCommand->len = len; - setStrategyCommand->strategyType = strategy; - size_t output_offset = strlen(output); - //check additional prefixes - if(parcList_Size(args) > 4){ - uint32_t index = 4; //first realted prefix - uint32_t addr_index = 0; - setStrategyCommand->related_prefixes = (uint8_t)parcList_Size(args) - 4; - while(index < parcList_Size(args)){ - const char *str = parcList_GetAtIndex(args, index); - char *rel_addr = (char *)malloc(sizeof(char) * (strlen(str) + 1)); - uint32_t rel_len = UINT32_MAX; - _getAddressAndLen(str, rel_addr, &rel_len); - bool success = _checkAndSetIp(setStrategyCommand, addr_index, - rel_addr, rel_len, output + output_offset, output_size - output_offset); - if(!success){ - parcMemory_Deallocate(&setStrategyCommand); - free(rel_addr); - return CommandReturn_Failure; - } - output_offset = strlen(output); - setStrategyCommand->lens[addr_index] = rel_len; - free(rel_addr); - index++; - addr_index++; - } - }else{ - setStrategyCommand->related_prefixes = 0; - } - - // send message and receive response - struct iovec *response = utils_SendRequest( - state, SET_STRATEGY, setStrategyCommand, sizeof(set_strategy_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlSetStrategy.h b/hicn-light/src/hicn/config/controlSetStrategy.h deleted file mode 100644 index 7ad56ccba..000000000 --- a/hicn-light/src/hicn/config/controlSetStrategy.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 Control_SetStrategy_h -#define Control_SetStrategy_h - -#include <hicn/config/controlState.h> -CommandOps *controlSetStrategy_Create(ControlState *state); -CommandOps *controlSetStrategy_HelpCreate(ControlState *state); -#endif // Control_SetStrategy_h diff --git a/hicn-light/src/hicn/config/controlSetWldr.c b/hicn-light/src/hicn/config/controlSetWldr.c deleted file mode 100644 index 0d4a7eca2..000000000 --- a/hicn-light/src/hicn/config/controlSetWldr.c +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlSetDebug.h> -#include <hicn/core/dispatcher.h> -#include <hicn/core/forwarder.h> - -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlSetWldr_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlSetWldr_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandSetWldr = "set wldr"; -static const char *_commandSetWldrHelp = "help set wldr"; - -// ==================================================== - -CommandOps *controlSetWldr_Create(ControlState *state) { - return commandOps_Create(state, _commandSetWldr, NULL, - _controlSetWldr_Execute, commandOps_Destroy); -} - -CommandOps *controlSetWldr_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandSetWldrHelp, NULL, - _controlSetWldr_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlSetWldr_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "set wldr <on|off> <connection_id>\n\n"); - - return CommandReturn_Success; -} - -static CommandReturn _controlSetWldr_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - ControlState *state = ops->closure; - - if (parcList_Size(args) != 4) { - _controlSetWldr_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - if (((strcmp(parcList_GetAtIndex(args, 0), "set") != 0) || - (strcmp(parcList_GetAtIndex(args, 1), "wldr") != 0))) { - _controlSetWldr_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - bool active; - if (strcmp(parcList_GetAtIndex(args, 2), "on") == 0) { - active = true; - } else if (strcmp(parcList_GetAtIndex(args, 2), "off") == 0) { - active = false; - } else { - _controlSetWldr_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - // check if valid connid - const char *symbolicOrConnid = parcList_GetAtIndex(args, 3); - - if (!utils_ValidateSymbolicName(symbolicOrConnid) && - !utils_IsNumber(symbolicOrConnid)) { - snprintf(output, output_size, - "ERROR: Invalid symbolic or connid:\nsymbolic name must begin with an " - "alpha followed by alphanum;\nconnid must be an integer\n"); - return CommandReturn_Failure; - } - - // allocate command payload - set_wldr_command *setWldrCommand = - parcMemory_AllocateAndClear(sizeof(set_wldr_command)); - strcpy(setWldrCommand->symbolicOrConnid, symbolicOrConnid); - if (active) { - setWldrCommand->activate = ACTIVATE_ON; - } else { - setWldrCommand->activate = ACTIVATE_OFF; - } - - // send message and receive response - struct iovec *response = utils_SendRequest(state, SET_WLDR, setWldrCommand, - sizeof(set_wldr_command)); - - if (!response) { // get NULL pointer - return CommandReturn_Failure; - } - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlSetWldr.h b/hicn-light/src/hicn/config/controlSetWldr.h deleted file mode 100644 index 3c01110e4..000000000 --- a/hicn-light/src/hicn/config/controlSetWldr.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 Control_SetWldr_h -#define Control_SetWldr_h - -#include <hicn/config/controlState.h> -CommandOps *controlSetWldr_Create(ControlState *state); -CommandOps *controlSetWldr_HelpCreate(ControlState *state); -#endif // Control_SetWldr_h diff --git a/hicn-light/src/hicn/config/controlState.c b/hicn-light/src/hicn/config/controlState.c deleted file mode 100644 index acdae9e52..000000000 --- a/hicn-light/src/hicn/config/controlState.c +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> -#include <string.h> - -#include <parc/security/parc_Security.h> - -#include <parc/algol/parc_List.h> -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> -#include <parc/algol/parc_Time.h> -#include <parc/algol/parc_TreeRedBlack.h> - -#include <hicn/config/commandParser.h> -#include <hicn/config/controlRoot.h> -#include <hicn/config/controlState.h> - -#include <hicn/utils/commands.h> - -struct controller_state { - CommandParser *parser; - bool debugFlag; - - void *userdata; - struct iovec *(*writeRead)(ControlState *state, struct iovec *msg); - int sockfd; - char **commandOutput; - bool isInteractive; -}; - -int controlState_connectToFwdDeamon(char *server_ip, uint16_t port) { - int sockfd; - struct sockaddr_in servaddr; - - if ((sockfd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) { - printf("\nSocket Creation Failed \n"); - return EXIT_FAILURE; - } - - memset(&servaddr, 0, sizeof(servaddr)); - - // Filling server information - servaddr.sin_family = AF_INET; - servaddr.sin_port = htons(port); - inet_pton(AF_INET, server_ip, &(servaddr.sin_addr.s_addr)); - - // Establish connection - if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { - printf("\nConnection Failed: hicn-light Daemon is not running \n"); - return -1; - } - - return sockfd; -} - -ControlState *controlState_Create( - void *userdata, - struct iovec *(*writeRead)(ControlState *state, struct iovec *msg), - bool openControllerConnetion, - char *server_ip, uint16_t port) { - ControlState *state = parcMemory_AllocateAndClear(sizeof(ControlState)); - parcAssertNotNull(state, "parcMemory_AllocateAndClear(%zu) returned NULL", - sizeof(ControlState)); - state->parser = commandParser_Create(); - - state->userdata = userdata; - state->writeRead = writeRead; - state->debugFlag = false; - state->commandOutput = NULL; - state->isInteractive = true; - - if (openControllerConnetion) { - state->sockfd = controlState_connectToFwdDeamon(server_ip, port); - if (state->sockfd == -1) { - return NULL; - } - } else { - state->sockfd = 2; // stderr - } - - return state; -} - -void controlState_Destroy(ControlState **statePtr) { - parcAssertNotNull(statePtr, "Parameter statePtr must be non-null"); - parcAssertNotNull(*statePtr, - "Parameter statePtr must dereference t non-null"); - ControlState *state = *statePtr; - // printf("sockid destroyed: %d\n", state->sockfd); - // close the connection with the fwd deamon - shutdown(state->sockfd, 2); - - commandParser_Destroy(&state->parser); - parcMemory_Deallocate((void **)&state); - *statePtr = NULL; -} - -void controlState_SetDebug(ControlState *state, bool debugFlag) { - parcAssertNotNull(state, "Parameter state must be non-null"); - state->debugFlag = debugFlag; - commandParser_SetDebug(state->parser, debugFlag); -} - -bool controlState_GetDebug(ControlState *state) { - parcAssertNotNull(state, "Parameter state must be non-null"); - return state->debugFlag; -} - -void controlState_RegisterCommand(ControlState *state, CommandOps *ops) { - parcAssertNotNull(state, "Parameter state must be non-null"); - commandParser_RegisterCommand(state->parser, ops); -} - -struct iovec *controlState_WriteRead(ControlState *state, struct iovec *msg) { - parcAssertNotNull(state, "Parameter state must be non-null"); - parcAssertNotNull(msg, "Parameter msg must be non-null"); - - return state->writeRead(state, msg); -} - -static PARCList *_controlState_ParseStringIntoTokens( - const char *originalString) { - PARCList *list = - parcList(parcArrayList_Create(parcArrayList_StdlibFreeFunction), - PARCArrayListAsPARCList); - - char *token; - - char *tofree = - parcMemory_StringDuplicate(originalString, strlen(originalString) + 1); - char *string = tofree; - - token = strtok(string, " \t\n"); - while (token != NULL) { - if (strlen(token) > 0) { - parcList_Add(list, strdup(token)); - } - token = strtok(NULL, " \t\n"); - } - - parcMemory_Deallocate((void **)&tofree); - - return list; -} - -CommandReturn controlState_DispatchCommand(ControlState *state, - PARCList *args, - char *output, - size_t output_size) { - parcAssertNotNull(state, "Parameter state must be non-null"); - return commandParser_DispatchCommand(state->parser, args, output, output_size); -} - -int controlState_Interactive(ControlState *state) { - parcAssertNotNull(state, "Parameter state must be non-null"); - char *line = NULL; - size_t linecap = 0; - CommandReturn controlReturn = CommandReturn_Success; - char output[8192]; - while (controlReturn != CommandReturn_Exit && !feof(stdin)) { - fputs("> ", stdout); - fflush(stdout); - ssize_t failure = getline(&line, &linecap, stdin); - parcAssertTrue(failure > -1, "Error getline"); - - PARCList *args = _controlState_ParseStringIntoTokens(line); - - controlReturn = controlState_DispatchCommand(state, args, output, sizeof(output)); - printf("%s", output); - // release and get command - parcList_Release(&args); - } - return 0; -} - -void controlState_SetCommandOutput(ControlState *state, char **commandData) { - state->commandOutput = commandData; -} - -void controlState_ReleaseCommandOutput(ControlState *state, char **commandData, - size_t commandLenght) { - for (size_t i = 0; i < commandLenght; i++) { - parcMemory_Deallocate(&commandData[i]); - } - parcMemory_Deallocate(&commandData); - state->commandOutput = NULL; -} - -char **controlState_GetCommandOutput(ControlState *state) { - return state->commandOutput; -} - -// size_t -// controlState_GetCommandLen(ControlState *state){ - -// } - -void controlState_SetInteractiveFlag(ControlState *state, bool interactive) { - state->isInteractive = interactive; -} - -bool controlState_IsInteractive(ControlState *state) { - return state->isInteractive; -} - -int controlState_GetSockfd(ControlState *state) { - parcAssertNotNull(state, "Parameter state must be non-null"); - return state->sockfd; -} - -void *controlState_GetUserdata(ControlState *state) { - parcAssertNotNull(state, "Parameter state must be non-null"); - return state->userdata; -} - -bool controlState_isConfigFile(ControlState *state) { - parcAssertNotNull(state, "Parameter state must be non-null"); - if (state->sockfd != 2) { - return false; - } else { - return true; - } -} diff --git a/hicn-light/src/hicn/config/controlState.h b/hicn-light/src/hicn/config/controlState.h deleted file mode 100644 index 52b1f6655..000000000 --- a/hicn-light/src/hicn/config/controlState.h +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file controlState.h - * @brief A control program for hicn-light using CLI commands - * - * Implements the state machine for the control program. It takes a "writeRead" - * function as part of the constructor. This abstracts out the backend. It - * could be a Portal from hicnLightControl program down to the forwarder or it - * could be an internal function within hicn-light. - * - */ - -#ifndef control_h -#define control_h - -#include <parc/algol/parc_List.h> -#include <hicn/config/commandParser.h> - -#include <hicn/utils/commands.h> - -#define SRV_CTRL_IP "127.0.0.1" -#define SRV_CTRL_PORT 9695 - -struct controller_state; -typedef struct controller_state ControlState; - -/** - * controlState_Create - * - * Creates the global state for the Control program. The user provides the - * writeRead function for sending and receiving the message wrapping command - * arguments. For configuration file inside hicn-light, it would make direct - * calls to Configuration -> Dispatcher. - * - * @param [in] userdata A closure passed back to the user when calling - * writeRead. - * @param [in] writeRead The function to write then read configuration messages - * to hicn-light - * - * @return non-null The control state - * - * Example: - * @code - * <#example#> - * @endcode - */ - -ControlState *controlState_Create( - void *userdata, - struct iovec *(*writeRead)(ControlState *state, struct iovec *msg), - bool openControllerConnetion, - char * server_ip, uint16_t port); - -/** - * Destroys the control state, closing all network connections - * - * <#Paragraphs Of Explanation#> - * - * @param [<#in out in,out#>] <#name#> <#description#> - * - * @return <#value#> <#explanation#> - * - * Example: - * @code - * <#example#> - * @endcode - */ -void controlState_Destroy(ControlState **statePtr); - -/** - * Registers a CommandOps with the system. - * - * Each command has its complete command prefix in the "command" field. - * RegisterCommand will put these command prefixes in to a tree and then match - * what a user types against the longest-matching prefix in the tree. If - * there's a match, it will call the "execute" function. - * - * @param [in] state An allocated ControlState - * @param [in] command The command to register with the system - * - * Example: - * @code - * static CommandReturn - * control_Root_Execute(CommandParser *parser, CommandOps *ops, PARCList - * *args) - * { - * printf("Root Command\n"); - * return CommandReturn_Success; - * } - * - * static CommandReturn - * control_FooBar_Execute(CommandParser *parser, CommandOps *ops, PARCList - * *args) - * { - * printf("Foo Bar Command\n"); - * return CommandReturn_Success; - * } - * - * const CommandOps control_Root = { - * .command = "", // empty string for root - * .init = NULL, - * .execute = control_Root_Execute - * }; - * - * const CommandOps control_FooBar = { - * .command = "foo bar", // empty string for root - * .init = NULL, - * .execute = control_FooBar_Execute - * }; - * - * void startup(void) - * { - * ControlState *state = controlState_Create("happy", "day"); - * controlState_RegisterCommand(state, control_FooBar); - * controlState_RegisterCommand(state, control_Root); - * - * // this executes "root" - * controlState_DispatchCommand(state, "foo"); - * controlState_Destroy(&state); - * } - * @endcode - */ -void controlState_RegisterCommand(ControlState *state, CommandOps *command); - -/** - * Performs a longest-matching prefix of the args to the command tree - * - * The command tree is created with controlState_RegisterCommand. - * - * @param [in] state The allocated ControlState - * @param [in] args Each command_line word parsed to the ordered list - * @param [in] output Output string - * @param [in] output_length output string max length - * - * @return CommandReturn_Success the command was successful - * @return CommandReturn_Failure the command failed or was not found - * @return CommandReturn_Exit the command indicates that the interactive mode - * should exit - * - * Example: - * @code - * <#example#> - * @endcode - */ -CommandReturn controlState_DispatchCommand(ControlState *state, - PARCList *args, - char *output, - size_t output_length); - -/** - * Begin an interactive shell - * - * <#Paragraphs Of Explanation#> - * - * @param [<#in out in,out#>] <#name#> <#description#> - * - * @return <#value#> <#explanation#> - * - * Example: - * @code - * <#example#> - * @endcode - */ -int controlState_Interactive(ControlState *state); - -/** - * Write then Read a command - * - * @param [<#in out in,out#>] <#name#> <#description#> - * - * @return <#value#> <#explanation#> - * - * Example: - * @code - * <#example#> - * @endcode - */ -struct iovec *controlState_WriteRead(ControlState *state, struct iovec *msg); - -/** - * Sets the Debug mode, which will print out much more information. - * - * Prints out much more diagnostic information about what hicn-light controller - * is doing. yes, you would make a CommandOps to set and unset this :) - * - * @param [in] debugFlag true means to print debug info, false means to turn it - * off - * - * Example: - * @code - * <#example#> - * @endcode - */ -void controlState_SetDebug(ControlState *state, bool debugFlag); - -/** - * Returns the debug state of ControlState - * - * <#Paragraphs Of Explanation#> - * - * @param [<#in out in,out#>] <#name#> <#description#> - * - * @return <#value#> <#explanation#> - * - * Example: - * @code - * <#example#> - * @endcode - */ -bool controlState_GetDebug(ControlState *state); -#endif // control_h - -void controlState_SetCommandOutput(ControlState *state, char **commandData); - -void controlState_ReleaseCommandOutput(ControlState *state, char **commandData, - size_t commandLenght); - -char **controlState_GetCommandOutput(ControlState *state); - -void controlState_SetInteractiveFlag(ControlState *state, bool interactive); - -bool controlState_IsInteractive(ControlState *state); - -void *controlState_GetUserdata(ControlState *state); - -bool controlState_isConfigFile(ControlState *state); - -int controlState_GetSockfd(ControlState *state); diff --git a/hicn-light/src/hicn/config/controlUnset.c b/hicn-light/src/hicn/config/controlUnset.c deleted file mode 100644 index e05ba2286..000000000 --- a/hicn-light/src/hicn/config/controlUnset.c +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/security/parc_Security.h> - -#include <hicn/config/controlUnset.h> -#include <hicn/config/controlUnsetDebug.h> - -static void _controlUnset_Init(CommandParser *parser, CommandOps *ops); - -static CommandReturn _controlUnset_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlUnset_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandUnset = "unset"; -static const char *_commandUnsetHelp = "help unset"; - -// =========================================================== - -CommandOps *controlUnset_Create(ControlState *state) { - return commandOps_Create(state, _commandUnset, _controlUnset_Init, - _controlUnset_Execute, commandOps_Destroy); -} - -CommandOps *controlUnset_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandUnsetHelp, NULL, - _controlUnset_HelpExecute, commandOps_Destroy); -} - -// =========================================================== - -static void _controlUnset_Init(CommandParser *parser, CommandOps *ops) { - ControlState *state = ops->closure; - controlState_RegisterCommand(state, controlUnsetDebug_Create(state)); - controlState_RegisterCommand(state, controlUnsetDebug_HelpCreate(state)); -} - -static CommandReturn _controlUnset_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - CommandOps *ops_help_unset_debug = controlUnsetDebug_HelpCreate(NULL); - snprintf(output, output_size, "Available commands:\n %s\n\n", ops_help_unset_debug->command); - - commandOps_Destroy(&ops_help_unset_debug); - return CommandReturn_Success; -} - -static CommandReturn _controlUnset_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - return _controlUnset_HelpExecute(parser, ops, args, output, output_size); -} diff --git a/hicn-light/src/hicn/config/controlUnset.h b/hicn-light/src/hicn/config/controlUnset.h deleted file mode 100644 index 9d9cb5c44..000000000 --- a/hicn-light/src/hicn/config/controlUnset.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_Unset.h - * @brief Implements the unset node of the CLI tree - * - * Implements the "unset" and "help unset" nodes of the command tree - * - */ -#ifndef Control_Unset_h -#define Control_Unset_h - -#include <hicn/config/controlState.h> -CommandOps *controlUnset_Create(ControlState *state); -CommandOps *controlUnset_HelpCreate(ControlState *state); -#endif // Control_Unset_h diff --git a/hicn-light/src/hicn/config/controlUnsetDebug.c b/hicn-light/src/hicn/config/controlUnsetDebug.c deleted file mode 100644 index ac2a4e028..000000000 --- a/hicn-light/src/hicn/config/controlUnsetDebug.c +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlUnsetDebug.h> -#include <hicn/core/dispatcher.h> -#include <hicn/core/forwarder.h> - -static CommandReturn _controlUnsetDebug_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlUnsetDebug_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandUnsetDebug = "unset debug"; -static const char *_commandUnsetDebugHelp = "help unset debug"; - -// ==================================================== - -CommandOps *controlUnsetDebug_Create(ControlState *state) { - return commandOps_Create(state, _commandUnsetDebug, NULL, - _controlUnsetDebug_Execute, commandOps_Destroy); -} - -CommandOps *controlUnsetDebug_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandUnsetDebugHelp, NULL, - _controlUnsetDebug_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static CommandReturn _controlUnsetDebug_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - snprintf(output, output_size, "unset debug: will disable the debug flag\n\n"); - return CommandReturn_Success; -} - -static CommandReturn _controlUnsetDebug_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if (parcList_Size(args) != 2) { - _controlUnsetDebug_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - ControlState *state = ops->closure; - controlState_SetDebug(state, false); - snprintf(output, output_size, "Debug flag cleared\n\n"); - - return CommandReturn_Success; -} diff --git a/hicn-light/src/hicn/config/controlUnsetDebug.h b/hicn-light/src/hicn/config/controlUnsetDebug.h deleted file mode 100644 index c76ba8c98..000000000 --- a/hicn-light/src/hicn/config/controlUnsetDebug.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_UnsetDebug.h - * @brief Unsets the debug flag for more verbose output - * - * Implements the "unset debug" and "help unset debug" nodes of the CLI tree - * - */ - -#ifndef Control_UnsetDebug_h -#define Control_UnsetDebug_h - -#include <hicn/config/controlState.h> -CommandOps *controlUnsetDebug_Create(ControlState *state); -CommandOps *controlUnsetDebug_HelpCreate(ControlState *state); -#endif // Control_UnsetDebug_h diff --git a/hicn-light/src/hicn/config/controlUpdate.c b/hicn-light/src/hicn/config/controlUpdate.c deleted file mode 100644 index 095bbf01e..000000000 --- a/hicn-light/src/hicn/config/controlUpdate.c +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifdef WITH_POLICY - -#include <hicn/hicn-light/config.h> - -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/security/parc_Security.h> - -#include <parc/algol/parc_Memory.h> - -#include <hicn/config/controlUpdate.h> -#include <hicn/config/controlUpdateConnection.h> - -static void _controlUpdate_Init(CommandParser *parser, CommandOps *ops); -static CommandReturn _controlUpdate_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlUpdate_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *_commandUpdate = "update"; -static const char *_commandUpdateHelp = "help update"; - -CommandOps *controlUpdate_Create(ControlState *state) { - return commandOps_Create(state, _commandUpdate, _controlUpdate_Init, - _controlUpdate_Execute, commandOps_Destroy); -} - -CommandOps *controlUpdate_HelpCreate(ControlState *state) { - return commandOps_Create(state, _commandUpdateHelp, NULL, - _controlUpdate_HelpExecute, commandOps_Destroy); -} - -// ===================================================== - -static CommandReturn _controlUpdate_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - //CommandOps *ops_update_connections = controlUpdateConnections_HelpCreate(NULL); - // CommandOps *ops_update_interfaces = controlUpdateInterfaces_HelpCreate(NULL); - //CommandOps *ops_update_routes = controlUpdateRoutes_HelpCreate(NULL); - CommandOps *ops_update_listeners = controlUpdateConnection_HelpCreate(NULL); - snprintf(output, output_size, - "Available commands:\n %s\n\n", - ops_update_listeners->command); - - - - // commandOps_Destroy(&ops_update_connections); - // commandOps_Destroy(&ops_update_interfaces); - //commandOps_Destroy(&ops_update_routes); - commandOps_Destroy(&ops_update_listeners); - - return CommandReturn_Success; -} - -static void _controlUpdate_Init(CommandParser *parser, CommandOps *ops) { - ControlState *state = ops->closure; - //controlState_RegisterCommand(state, controlUpdateConnections_HelpCreate(state)); - // controlState_RegisterCommand(state, - // controlUpdateInterfaces_HelpCreate(state)); - controlState_RegisterCommand(state, controlUpdateConnection_HelpCreate(state)); - //controlState_RegisterCommand(state, controlUpdateRoutes_HelpCreate(state)); - //controlState_RegisterCommand(state, controlUpdateConnections_Create(state)); - // controlState_RegisterCommand(state, controlUpdateInterfaces_Create(state)); - //controlState_RegisterCommand(state, controlUpdateRoutes_Create(state)); - controlState_RegisterCommand(state, controlUpdateConnection_Create(state)); -} - -static CommandReturn _controlUpdate_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - return _controlUpdate_HelpExecute(parser, ops, args, output, output_size); -} - -#endif /* WITH_POLICY */ diff --git a/hicn-light/src/hicn/config/controlUpdate.h b/hicn-light/src/hicn/config/controlUpdate.h deleted file mode 100644 index 0007ab653..000000000 --- a/hicn-light/src/hicn/config/controlUpdate.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_Update.h - * @brief Root node for the "update" commands - * - * Implements the "update" node of the CLI tree. - * - */ - -#ifndef controlUpdate_h -#define controlUpdate_h - -#ifdef WITH_POLICY - -#include <hicn/config/controlState.h> -CommandOps *controlUpdate_Create(ControlState *state); -CommandOps *controlUpdate_HelpCreate(ControlState *state); - -#endif /* WITH_POLICY */ - -#endif // controlUpdate_h diff --git a/hicn-light/src/hicn/config/controlUpdateConnection.c b/hicn-light/src/hicn/config/controlUpdateConnection.c deleted file mode 100644 index 70a017d4f..000000000 --- a/hicn-light/src/hicn/config/controlUpdateConnection.c +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifdef WITH_POLICY - -#include <hicn/hicn-light/config.h> - -#include <ctype.h> -#include <inttypes.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> - -#include <parc/assert/parc_Assert.h> - -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_Network.h> - -#include <hicn/config/controlUpdateConnection.h> - -#include <hicn/policy.h> -#include <hicn/utils/commands.h> -#include <hicn/utils/utils.h> - -static CommandReturn _controlUpdateConnection_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); -static CommandReturn _controlUpdateConnection_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size); - -static const char *command_update_connection = "update connection"; -static const char *command_help_update_connection = "help update connection"; - -CommandOps *controlUpdateConnection_Create(ControlState *state) { - return commandOps_Create(state, command_update_connection, NULL, - _controlUpdateConnection_Execute, commandOps_Destroy); -} - -CommandOps *controlUpdateConnection_HelpCreate(ControlState *state) { - return commandOps_Create(state, command_help_update_connection, NULL, - _controlUpdateConnection_HelpExecute, commandOps_Destroy); -} - -// ==================================================== - -static const int _indexSymbolic = 2; -static const int _indexTags = 3; - -static CommandReturn _controlUpdateConnection_HelpExecute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - - snprintf(output, output_size, - "commands:\n" - " update connection <symbolic | id> <tags> \n" - "\n" - " symbolic: User defined name for connection, must start with " - "alpha and be alphanum\n" - " id: Identifier for the connection\n" - " tags: A string representing tags\n"); - return CommandReturn_Success; -} - - -static CommandReturn _controlUpdateConnection_Execute(CommandParser *parser, - CommandOps *ops, - PARCList *args, - char *output, - size_t output_size) { - if ((parcList_Size(args) != 3) && (parcList_Size(args) != 4)) { - _controlUpdateConnection_HelpExecute(parser, ops, args, output, output_size); - return CommandReturn_Failure; - } - - const char *symbolicOrConnid = parcList_GetAtIndex(args, _indexSymbolic); - - if (!utils_ValidateSymbolicName(symbolicOrConnid) && - !utils_IsNumber(symbolicOrConnid)) { - snprintf(output, output_size, - "ERROR: Invalid symbolic or connid:\nsymbolic name must begin with an " - "alpha followed by alphanum;\nconnid must be an integer\n"); - return CommandReturn_Failure; - } - - policy_tags_t tags = POLICY_TAGS_EMPTY; - if (parcList_Size(args) == 4) { - const char *str_tags = parcList_GetAtIndex(args, _indexTags); - - for (unsigned i = 0; str_tags[i] != 0; i++) { - switch(tolower(str_tags[i])) { - case 'e': - policy_tags_add(&tags, POLICY_TAG_WIRED); - break; - case 'w': - policy_tags_add(&tags, POLICY_TAG_WIFI); - break; - case 'c': - policy_tags_add(&tags, POLICY_TAG_CELLULAR); - break; - case 'b': - policy_tags_add(&tags, POLICY_TAG_BEST_EFFORT); - break; - case 'r': - policy_tags_add(&tags, POLICY_TAG_REALTIME); - break; - case 'm': - policy_tags_add(&tags, POLICY_TAG_MULTIPATH); - break; - case 't': - policy_tags_add(&tags, POLICY_TAG_TRUSTED); - break; - } - } - } - ControlState *state = ops->closure; - - // allocate command payload - update_connection_command *updateConnectionCommand = - parcMemory_AllocateAndClear(sizeof(update_connection_command)); - updateConnectionCommand->tags = tags; - strcpy(updateConnectionCommand->symbolicOrConnid, symbolicOrConnid); - - // send message and receive response - struct iovec *response = utils_SendRequest( - state, UPDATE_CONNECTION, updateConnectionCommand, sizeof(update_connection_command)); - - if (!response) // get NULL pointer - return CommandReturn_Failure; - - parcMemory_Deallocate(&response); // free iovec pointer - return CommandReturn_Success; -} - -#endif /* WITH_POLICY */ diff --git a/hicn-light/src/hicn/config/controlUpdateConnection.h b/hicn-light/src/hicn/config/controlUpdateConnection.h deleted file mode 100644 index eea303202..000000000 --- a/hicn-light/src/hicn/config/controlUpdateConnection.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file control_UpdateConnection.h - * @brief Update a connection to an interface - * - * <#Detailed Description#> - * - */ - -#ifndef Control_UpdateConnection_h -#define Control_UpdateConnection_h - -#ifdef WITH_POLICY - -#include <hicn/config/controlState.h> -CommandOps *controlUpdateConnection_Create(ControlState *state); -CommandOps *controlUpdateConnection_HelpCreate(ControlState *state); - -#endif /* WITH_POLICY */ - -#endif // Control_UpdateConnection_h diff --git a/hicn-light/src/hicn/config/parse.c b/hicn-light/src/hicn/config/parse.c new file mode 100644 index 000000000..ba9c0b348 --- /dev/null +++ b/hicn-light/src/hicn/config/parse.c @@ -0,0 +1,402 @@ +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include <errno.h> + +//#include <hicn/ctrl/cli.h> +#include <hicn/util/log.h> +#include <hicn/util/sstrncpy.h> +#include "parse.h" + +/* + * As there is no portable way to generate a va_list to use with sscanf to + * support a variable number of arguments, and no way to use a variable array + * initialize in a nested struct, we use a fixed maximum number of parameters + * + * NOTE: update sscanf accordingly + */ + +#include "command.h" + +const char *action_str[] = { +#define _(x) [ACTION_##x] = #x, + foreach_action +#undef _ +}; + +#define action_str(x) action_str[x] + +hc_action_t action_from_str(const char *action_str) { +#define _(x) \ + if (strcasecmp(action_str, #x) == 0) \ + return ACTION_##x; \ + else + foreach_action +#undef _ + if (strcasecmp(action_str, "add") == 0) return ACTION_CREATE; + else if (strcasecmp(action_str, "remove") == 0) return ACTION_DELETE; + else return ACTION_UNDEFINED; +} + +const char *object_str[] = { +#define _(x) [OBJECT_##x] = #x, + foreach_object +#undef _ +}; + +#define object_str(x) object_str[x] + +hc_object_type_t object_from_str(const char *object_str) { +#define _(x) \ + if (strcasecmp(object_str, #x) == 0) \ + return OBJECT_##x; \ + else + foreach_object +#undef _ + return OBJECT_UNDEFINED; +} + +const char *action_to_cmd_action(hc_action_t action) { + switch (action) { + case ACTION_CREATE: + return "add"; + case ACTION_UPDATE: + return "update"; + case ACTION_DELETE: + return "remove"; + case ACTION_LIST: + return "list"; + case ACTION_SET: + return "set"; + case ACTION_SERVE: + return "serve"; + case ACTION_STORE: + return "store"; + case ACTION_CLEAR: + return "clear"; + default: + return "UNDEFINED"; + } +} + +const char *parser_type_fmt(const parser_type_t *type) { + switch (type->name) { + case TYPENAME_INT: + return TYPE_FMT_INT; + case TYPENAME_UINT: + return TYPE_FMT_UINT; + case TYPENAME_STR: + return TYPE_FMT_STRN(type->str.max_size); + case TYPENAME_SYMBOLIC_OR_ID: + return TYPE_FMT_SYMBOLIC_OR_ID; + case TYPENAME_INTERFACE_NAME: + return TYPE_FMT_INTERFACE_NAME; + case TYPENAME_IP_ADDRESS: + return TYPE_FMT_IP_ADDRESS; + case TYPENAME_IP_PREFIX: + return TYPE_FMT_IP_PREFIX; + case TYPENAME_ON_OFF: + return TYPE_FMT_ON_OFF; + case TYPENAME_ENUM: + return TYPE_FMT_ENUM; + case TYPENAME_POLICY_STATE: + return TYPE_FMT_POLICY_STATE; + case TYPENAME_UNDEFINED: + default: + return NULL; + } +} + +int parser_type_func(const parser_type_t *type, void *src, void *dst, + void *dst2, void *dst3) { + ip_address_t addr; + char *addr_str; + char *len_str; + int len, tmp, rc; + + switch (type->name) { + case TYPENAME_INT: + tmp = *(int *)src; + if (tmp < type->sint.min || tmp > type->sint.max) { + ERROR("Input number (%d) not inside range [%d, %d]", tmp, + type->sint.min, type->sint.max); + return -1; + } + *(int *)dst = *(int *)src; + break; + case TYPENAME_UINT: + tmp = *(int *)src; + if (tmp < type->uint.min || tmp > type->uint.max) { + ERROR("Input number (%d) not inside range [%d, %d]", tmp, + type->uint.min, type->uint.max); + return -1; + } + *(unsigned *)dst = *(unsigned *)src; + break; + case TYPENAME_STR: + rc = strcpy_s(dst, type->str.max_size, src); + if (rc != EOK) { + ERROR("Input string is too long"); + return -1; + } + break; + case TYPENAME_IP_ADDRESS: + rc = ip_address_pton((char *)src, &addr); + if (rc < 0) { + ERROR("Wrong IP address format"); + return -1; + } + + *(ip_address_t *)dst = addr; + *(int *)dst2 = ip_address_get_family((char *)src); + break; + case TYPENAME_ON_OFF: + if (strcmp((char *)src, "off") == 0) { + *(unsigned *)dst = 0; + } else if (strcmp((char *)src, "on") == 0) { + *(unsigned *)dst = 1; + } else { + ERROR("on/off are the only possible values"); + return -1; + } + break; + case TYPENAME_IP_PREFIX: + addr_str = strtok((char *)src, "/"); + len_str = strtok(NULL, " "); + rc = ip_address_pton((char *)src, &addr); + if (rc < 0) { + ERROR("Wrong IP address format"); + return -1; + } + len = atoi(len_str); + + *(ip_address_t *)dst = addr; + *(int *)dst2 = len; + *(int *)dst3 = ip_address_get_family(addr_str); + break; + case TYPENAME_ENUM: + /* Enum index from string */ + assert(type->enum_.from_str); + *(int *)dst = type->enum_.from_str((char *)src); + break; + case TYPENAME_POLICY_STATE: { + assert(IS_VALID_POLICY_TAG(type->policy_state.tag)); + policy_tag_t tag = type->policy_state.tag; + /* Format string is "%ms" */ + const char *str = *(const char **)src; + policy_tag_state_t *pts = ((policy_tag_state_t *)dst); + pts[tag].disabled = (str[0] == '!') ? 1 : 0; + pts[tag].state = policy_state_from_str(str + pts[tag].disabled); + break; + } + case TYPENAME_UNDEFINED: + default: + ERROR("Unknown format"); + return -1; + } + return 0; +} + +int parse_params(const command_parser_t *parser, const char *params_s, + hc_command_t *command) { + char fmt[1024]; + int n; + size_t size = 0; + char *pos = fmt; + /* Update MAX_PARAMETERS accordingly in command.h */ + char sscanf_params[MAX_PARAMETERS][MAX_SCANF_PARAM_LEN]; + + unsigned count = 0; + for (unsigned i = 0; i < parser->nparams; i++) { + const command_parameter_t *p = &parser->parameters[i]; + const char *_fmt = parser_type_fmt(&p->type); + // printf(" _fmt=%s\n", _fmt); + if (!_fmt) { + WARN("Ignored parameter %s with unknown type formatter", p->name); + continue; + } + n = snprintf(pos, 1024 - size, "%s", _fmt); + pos += n; + + *pos = ' '; + pos++; + + size += n + 1; + count++; + } + *pos = '\0'; + DEBUG("parser format: %s", fmt); + + int ret = sscanf(params_s, fmt, sscanf_params[0], sscanf_params[1], + sscanf_params[2], sscanf_params[3], sscanf_params[4], + sscanf_params[5], sscanf_params[6], sscanf_params[7], + sscanf_params[8], sscanf_params[9]); + if (ret != parser->nparams) { + ERROR("Parsing failed: check for string used where integer was expected"); + goto ERR; + } + + for (unsigned i = 0; i < count; i++) { + const command_parameter_t *p = &parser->parameters[i]; + if (parser_type_func(&p->type, sscanf_params[i], + &command->object.as_uint8 + p->offset, + &command->object.as_uint8 + p->offset2, + &command->object.as_uint8 + p->offset3) < 0) { + ERROR("Error during parsing of parameter '%s' value", p->name); + goto ERR; + } + } + return 0; + +ERR: + return -1; +} + +int parse(const char *cmd, hc_command_t *command) { + int nparams = 0; + char action_s[MAX_SCANF_PARAM_LEN]; + char object_s[MAX_SCANF_PARAM_LEN]; + char params_s[MAX_SCANF_PARAM_LEN]; + + // if n = 2 later, params_s is uninitialized + memset(params_s, 0, MAX_SCANF_PARAM_LEN * sizeof(char)); + + errno = 0; + int n = sscanf(cmd, "%s %s%[^\n]s", action_s, object_s, params_s); + if ((n < 2) || (n > 3)) { + if (errno != 0) perror("scanf"); + return -1; + } + + command->action = action_from_str(action_s); + command->object.type = object_from_str(object_s); + + if (strnlen_s(params_s, MAX_SCANF_PARAM_LEN) > 0) { + for (char *ptr = params_s; (ptr = strchr(ptr, ' ')) != NULL; ptr++) + nparams++; + } + + /* + * This checks is important even with 0 parameters as it checks whether the + * command exists. + */ + const command_parser_t *parser = + command_search(command->action, command->object.type, nparams); + if (!parser) { + ERROR("Could not find parser for command '%s %s'", action_s, object_s); + return -1; + } + + if (strnlen_s(params_s, MAX_SCANF_PARAM_LEN) > 0) { + if (parse_params(parser, params_s, command) < 0) return -1; + } + + if (parser->post_hook) parser->post_hook(&command->object.as_uint8); + return 0; +} + +int help(const char *cmd) { + int nparams = 1; + char action_s[MAX_SCANF_PARAM_LEN]; + char object_s[MAX_SCANF_PARAM_LEN]; + char params_s[MAX_SCANF_PARAM_LEN]; + hc_object_type_t object = OBJECT_UNDEFINED; + hc_action_t action = ACTION_UNDEFINED; + + int n = sscanf(cmd, "help %[^\n]s", params_s); + + // No arguments provided to the help command: just list available objects + if (n != 1) goto CMD_LIST; + + // Count number of provided parameters + for (char *ptr = params_s; (ptr = strchr(ptr, ' ')) != NULL; ptr++) nparams++; + if (nparams > 2) { + fprintf(stderr, "Error: too many arguments.\n"); + return -1; + } + + // Object specified: list actions available for that object + if (nparams == 1) { + object = object_from_str(params_s); + if (object == OBJECT_UNDEFINED) { + fprintf(stderr, "Error: undefined object.\n"); + return -1; + } + + goto CMD_LIST; + } + + // Object and action specified: list detailed commands + n = sscanf(params_s, "%s %[^\n]s", object_s, action_s); + assert(n == 2); + object = object_from_str(object_s); + action = action_from_str(action_s); + if (object == OBJECT_UNDEFINED || action == ACTION_UNDEFINED) { + fprintf(stderr, "Error: undefined object and/or action.\n"); + return -1; + } + +CMD_LIST: + printf("Available commands:\n"); + command_list(object, action); + return 0; +} + +#if 0 // tests +/* For the tests, we will need to test all non-compliant inputs */ +const char * cmds[] = { + "add connection hicn conn1 8.8.8.8 127.0.0.1 eth0", + "add connection udp <symbolic> <remote_ip> <port> <local_ip> <port> eth0", + "add listener udp lst1 127.0.0.1 9695 eth0", + //"add face", + "add route 3 b001::/16 1", + //"add punting", + //"add strategy", + "add policy b001::/16 webex require avoid prohibit !prohibit neutral !require prefer", + "list connection", // need pluralize + "list listener", + "list face", + "list route", + "list punting", + "list strategy", + "list policy", + "remove connection 1", + "remove listener 1", + //"remove face", + "remove route 1 b001::/16", + //"remove punting", + //"remove policy", + "set debug", + "unset debug", + "set strategy b001::/16 random", // related prefixes (10 max) ? + "set strategy b001::/16 load_balancer", + "set strategy b001::/16 low_latency", + "set strategy b001::/16 replication", + "set strategy b001::/16 bestpath", + "set wldr <on|off> <connection_id>", // on-off vs unset + "cache clear", + "cache store on/off", // set/unset + "cache serve on/off", + "mapme enable on/off", + "mapme discovery on/off", + "mapme timescale 500ms", + "mapme retx 500ms", + "update connection conn1 WT", +}; + +#define array_size(x) sizeof(x) / sizeof(typeof(x[0])) +int main() +{ + for (unsigned i = 0; i < array_size(cmds); i++) { + printf("PARSING [%d] %s\n", i, cmds[i]); + if (parse(cmds[i]) < 0) { + ERROR("Could not parse command: %s\n", cmds[i]); + continue; + } + } + exit(EXIT_SUCCESS); + +ERR: + exit(EXIT_FAILURE); +} +#endif diff --git a/hicn-light/src/hicn/config/parse.h b/hicn-light/src/hicn/config/parse.h new file mode 100644 index 000000000..06269208a --- /dev/null +++ b/hicn-light/src/hicn/config/parse.h @@ -0,0 +1,15 @@ +#ifndef HICNLIGHT_PARSE_CMD +#define HICNLIGHT_PARSE_CMD + +#include <hicn/ctrl/api.h> + +int parse(const char* cmd, hc_command_t* command); +int help(const char* cmd); + +/** + * @brief Convert the action enum to the action name used in the commands (e.g. + * from ACTION_CREATE to "add"). + */ +const char* action_to_cmd_action(hc_action_t action); + +#endif /* HICNLIGHT_PARSE_CMD */ diff --git a/hicn-light/src/hicn/config/symbolicNameTable.c b/hicn-light/src/hicn/config/symbolicNameTable.c deleted file mode 100644 index e5ae81d3e..000000000 --- a/hicn-light/src/hicn/config/symbolicNameTable.c +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 <ctype.h> -#include <parc/algol/parc_Hash.h> -#include <parc/algol/parc_HashCodeTable.h> -#include <parc/algol/parc_Memory.h> -#include <parc/assert/parc_Assert.h> -#include <hicn/hicn-light/config.h> -#include <stdio.h> - -#include <hicn/config/symbolicNameTable.h> - -struct symblic_name_table { - PARCHashCodeTable *symbolicNameTable; - PARCHashCodeTable *indexToNameTable; -}; - -// ======================================================================================== -// symbolic name table functions - -static bool _symbolicNameEquals(const void *keyA, const void *keyB) { - return (strcasecmp((const char *)keyA, (const char *)keyB) == 0); -} - -static HashCodeType _symbolicNameHash(const void *keyA) { - const char *str = (const char *)keyA; - size_t length = strlen(str); - return parcHash32_Data(str, length); -} - -static bool _connectionIdEquals(const void *keyA, const void *keyB) { - unsigned idA = *((unsigned *)keyA); - unsigned idB = *((unsigned *)keyB); - return (idA == idB); -} - -static HashCodeType _connectionIdHash(const void *keyA) { - unsigned idA = *((unsigned *)keyA); - return parcHash32_Int32(idA); -} - -// ======================================================================================== - -SymbolicNameTable *symbolicNameTable_Create(void) { - SymbolicNameTable *table = parcMemory_Allocate(sizeof(SymbolicNameTable)); - - if (table) { - // key = char * - // value = uint32_t * - table->symbolicNameTable = parcHashCodeTable_Create( - _symbolicNameEquals, _symbolicNameHash, parcMemory_DeallocateImpl, - parcMemory_DeallocateImpl); - table->indexToNameTable = parcHashCodeTable_Create( - _connectionIdEquals, _connectionIdHash, parcMemory_DeallocateImpl, - parcMemory_DeallocateImpl); - } - - return table; -} - -void symbolicNameTable_Destroy(SymbolicNameTable **tablePtr) { - SymbolicNameTable *table = *tablePtr; - parcHashCodeTable_Destroy(&table->symbolicNameTable); - parcHashCodeTable_Destroy(&table->indexToNameTable); - parcMemory_Deallocate((void **)&table); - *tablePtr = NULL; -} - -static char *_createKey(const char *symbolicName) { - char *key = parcMemory_StringDuplicate(symbolicName, strlen(symbolicName)); - - // convert key to upper case - char *p = key; - - // keeps looping until the first null - while ((*p = toupper(*p))) { - p++; - } - return key; -} - -bool symbolicNameTable_Exists(SymbolicNameTable *table, - const char *symbolicName) { - parcAssertNotNull(table, "Parameter table must be non-null"); - parcAssertNotNull(symbolicName, "Parameter symbolicName must be non-null"); - - char *key = _createKey(symbolicName); - bool found = (parcHashCodeTable_Get(table->symbolicNameTable, key) != NULL); - parcMemory_Deallocate((void **)&key); - return found; -} - -void symbolicNameTable_Remove(SymbolicNameTable *table, - const char *symbolicName) { - parcAssertNotNull(table, "Parameter table must be non-null"); - parcAssertNotNull(symbolicName, "Parameter symbolicName must be non-null"); - - char *key = _createKey(symbolicName); - - unsigned id = symbolicNameTable_Get(table, symbolicName); - uint32_t *value = parcMemory_Allocate(sizeof(uint32_t)); - *value = id; - - parcHashCodeTable_Del(table->symbolicNameTable, key); - parcHashCodeTable_Del(table->indexToNameTable, value); - parcMemory_Deallocate((void **)&key); - parcMemory_Deallocate((void **)&value); -} - -bool symbolicNameTable_Add(SymbolicNameTable *table, const char *symbolicName, - unsigned connid) { - parcAssertNotNull(table, "Parameter table must be non-null"); - parcAssertNotNull(symbolicName, "Parameter symbolicName must be non-null"); - parcAssertTrue(connid < UINT32_MAX, "Parameter connid must be less than %u", - UINT32_MAX); - - char *key1 = _createKey(symbolicName); - - uint32_t *value1 = parcMemory_Allocate(sizeof(uint32_t)); - *value1 = connid; - - bool success = parcHashCodeTable_Add(table->symbolicNameTable, key1, value1); - if (!success) - goto ERR_NAME; - - char *key2 = _createKey(symbolicName); - - uint32_t *value2 = parcMemory_Allocate(sizeof(uint32_t)); - *value2 = connid; - - success = parcHashCodeTable_Add(table->indexToNameTable, value2, key2); - if (!success) - goto ERR_INDEX; - - goto END; - -ERR_INDEX: - parcMemory_Deallocate((void **)&key2); - parcMemory_Deallocate((void **)&value2); - parcHashCodeTable_Del(table->symbolicNameTable, key1); -ERR_NAME: - parcMemory_Deallocate((void **)&key1); - parcMemory_Deallocate((void **)&value1); -END: - return success; - -} - -unsigned symbolicNameTable_Get(SymbolicNameTable *table, - const char *symbolicName) { - parcAssertNotNull(table, "Parameter table must be non-null"); - parcAssertNotNull(symbolicName, "Parameter symbolicName must be non-null"); - - unsigned connid = UINT32_MAX; - - char *key = _createKey(symbolicName); - - uint32_t *value = parcHashCodeTable_Get(table->symbolicNameTable, key); - if (value) - connid = *value; - - parcMemory_Deallocate((void **)&key); - return connid; -} - -const char *symbolicNameTable_GetNameByIndex(SymbolicNameTable *table, - unsigned id) { - parcAssertNotNull(table, "Parameter table must be non-null"); - - uint32_t *value = parcMemory_Allocate(sizeof(uint32_t)); - *value = id; - - const char *name = parcHashCodeTable_Get(table->indexToNameTable, value); - if (name == NULL) name = ""; - - parcMemory_Deallocate((void **)&value); - return name; -} diff --git a/hicn-light/src/hicn/config/symbolicNameTable.h b/hicn-light/src/hicn/config/symbolicNameTable.h deleted file mode 100644 index 69919cf00..000000000 --- a/hicn-light/src/hicn/config/symbolicNameTable.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2017-2019 Cisco and/or its affiliates. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file symbolicNameTable.h - * @brief The symbolic name table maps a string name to a connection id - * - * When configuring tunnels/connections, the user provides a string name - * (symbolic name) that they will use to refer to that connection. The symblic - * name table translates that symbolic name to a connection id. - * - */ - -#ifndef symbolicNameTable_h -#define symbolicNameTable_h - -struct symblic_name_table; -typedef struct symblic_name_table SymbolicNameTable; - -#include <stdbool.h> - -/** - * Creates a symbolic name table - * - * Allocates a SymbolicNameTable, which will store the symbolic names - * in a hash table. - * - * @retval non-null An allocated SymbolicNameTable - * @retval null An error - * - * Example: - * @code - * <#example#> - * @endcode - */ -SymbolicNameTable *symbolicNameTable_Create(void); - -/** - * Destroys a name table - * - * All keys and data are released. - * - * @param [in,out] tablePtr A pointer to a SymbolicNameTable, which will be - * NULL'd - * - * Example: - * @code - * <#example#> - * @endcode - */ -void symbolicNameTable_Destroy(SymbolicNameTable **tablePtr); - -/** - * Checks if the name (case insensitive) is in the table - * - * Does a case-insensitive match to see if the name is in the table - * - * @param [in] table An allocated SymbolicNameTable - * @param [in] symbolicName The name to check for - * - * @retval true The name is in the table - * @retval false The name is not in the talbe - * - * Example: - * @code - * <#example#> - * @endcode - */ -bool symbolicNameTable_Exists(SymbolicNameTable *table, - const char *symbolicName); - -/** - * Adds a (name, connid) pair to the table. - * - * The name is stored case insensitive. The value UINT_MAX is used to indicate - * a non-existent key, so it should not be stored as a value in the table. - * - * @param [in] table An allocated SymbolicNameTable - * @param [in] symbolicName The name to save (will make a copy) - * @param [in] connid The connection id to associate with the name - * - * @retval true The pair was added - * @retval false The pair was not added (likely duplicate key) - * - * Example: - * @code - * <#example#> - * @endcode - */ -bool symbolicNameTable_Add(SymbolicNameTable *table, const char *symbolicName, - unsigned connid); - -/** - * Returns the connection id associated with the symbolic name - * - * This function will look for the given name (case insensitive) and return the - * corresponding connid. If the name is not in the table, the function will - * return UINT_MAX. - * - * @param [in] table An allocated SymbolicNameTable - * @param [in] symbolicName The name to retrieve - * - * @retval UINT_MAX symbolicName not found - * @retval number the corresponding connid. - * - * Example: - * @code - * <#example#> - * @endcode - */ -unsigned symbolicNameTable_Get(SymbolicNameTable *table, - const char *symbolicName); - -void symbolicNameTable_Remove(SymbolicNameTable *table, - const char *symbolicName); -const char *symbolicNameTable_GetNameByIndex(SymbolicNameTable *table, - unsigned id); - -#endif /* defined(symbolicNameTable_h) */ |