diff options
author | Luca Muscariello <lumuscar@cisco.com> | 2022-03-30 22:29:28 +0200 |
---|---|---|
committer | Mauro Sardara <msardara@cisco.com> | 2022-03-31 19:51:47 +0200 |
commit | c46e5df56b67bb8ea7a068d39324c640084ead2b (patch) | |
tree | eddeb17785938e09bc42eec98ee09b8a28846de6 /hicn-light/src/hicn/command_line | |
parent | 18fa668f25d3cc5463417ce7df6637e31578e898 (diff) |
feat: boostrap hicn 22.02
The current patch provides several new features, improvements,
bug fixes and also complete rewrite of entire components.
- lib
The hicn packet parser has been improved with a new packet
format fully based on UDP. The TCP header is still temporarily
supported but the UDP header will replace completely the new hicn
packet format. Improvements have been made to make sure every
packet parsing operation is made via this library. The current
new header can be used as header between the payload and the
UDP header or as trailer in the UDP surplus area to be tested
when UDP options will start to be used.
- hicn-light
The portable packet forwarder has been completely rewritten from
scratch with the twofold objective to improve performance and
code size but also to drop dependencies such as libparc which is
now removed by the current implementation.
- hicn control
the control library is the agent that is used to program the
packet forwarders via their binary API. This component has
benefited from significant improvements in terms of interaction
model which is now event driven and more robust to failures.
- VPP plugin has been updated to support VPP 22.02
- transport
Major improvement have been made to the RTC protocol, to the
support of IO modules and to the security sub system. Signed
manifests are the default data authenticity and integrity framework.
Confidentiality can be enabled by sharing the encryption key to the
prod/cons layer. The library has been tested with group key based
applications such as broadcast/multicast and real-time on-line
meetings with trusted server keys or MLS.
- testing
Unit testing has been introduced using GoogleTest. One third of
the code base is covered by unit testing with priority on
critical features. Functional testing has also been introduce
using Docker, linux bridging and Robot Framework to define
test with Less Code techniques to facilitate the extension
of the coverage.
Co-authored-by: Mauro Sardara <msardara@cisco.com>
Co-authored-by: Jordan Augé <jordan.auge+fdio@cisco.com>
Co-authored-by: Michele Papalini <micpapal@cisco.com>
Co-authored-by: Angelo Mantellini <manangel@cisco.com>
Co-authored-by: Jacques Samain <jsamain@cisco.com>
Co-authored-by: Olivier Roques <oroques+fdio@cisco.com>
Co-authored-by: Enrico Loparco <eloparco@cisco.com>
Co-authored-by: Giulio Grassi <gigrassi@cisco.com>
Change-Id: I75d0ef70f86d921e3ef503c99271216ff583c215
Signed-off-by: Luca Muscariello <muscariello@ieee.org>
Signed-off-by: Mauro Sardara <msardara@cisco.com>
Diffstat (limited to 'hicn-light/src/hicn/command_line')
5 files changed, 0 insertions, 863 deletions
diff --git a/hicn-light/src/hicn/command_line/CMakeLists.txt b/hicn-light/src/hicn/command_line/CMakeLists.txt deleted file mode 100644 index 16c23dc5c..000000000 --- a/hicn-light/src/hicn/command_line/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -add_subdirectory(controller) -add_subdirectory(daemon) diff --git a/hicn-light/src/hicn/command_line/controller/CMakeLists.txt b/hicn-light/src/hicn/command_line/controller/CMakeLists.txt deleted file mode 100644 index 4cbd49220..000000000 --- a/hicn-light/src/hicn/command_line/controller/CMakeLists.txt +++ /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. - -list(APPEND CONTROLLER_SRC - hicnLightControl_main.c -) - -if (WIN32) - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /NODEFAULTLIB:\"LIBCMT\"" ) -endif() - -if (NOT DISABLE_EXECUTABLES) - if (${CMAKE_SYSTEM_NAME} MATCHES Android) - set(LINK_FLAGS "-Wl,--unresolved-symbols=ignore-in-object-files") - endif() - - build_executable(${HICN_LIGHT_CONTROL} - SOURCES ${CONTROLLER_SRC} - LINK_LIBRARIES ${LIBHICN_LIGHT_STATIC} - DEPENDS ${LIBHICN_LIGHT_STATIC} - COMPONENT ${HICN_LIGHT} - DEFINITIONS ${COMPILER_DEFINITIONS} - LINK_FLAGS ${LINK_FLAGS} - ) -endif () diff --git a/hicn-light/src/hicn/command_line/controller/hicnLightControl_main.c b/hicn-light/src/hicn/command_line/controller/hicnLightControl_main.c deleted file mode 100644 index e6a97c4e2..000000000 --- a/hicn-light/src/hicn/command_line/controller/hicnLightControl_main.c +++ /dev/null @@ -1,382 +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 <hicn/utils/utils.h> - - -#ifndef _WIN32 -#include <arpa/inet.h> -#include <getopt.h> -#include <netinet/in.h> -#include <sys/socket.h> -#include <sys/uio.h> -#include <unistd.h> -#include <arpa/inet.h> -#endif -#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_IdentityFile.h> -#include <parc/security/parc_Security.h> - -#include <parc/algol/parc_ArrayList.h> -#include <parc/algol/parc_List.h> -#include <parc/algol/parc_Memory.h> -#include <parc/algol/parc_SafeMemory.h> - -#include <hicn/core/dispatcher.h> -#include <hicn/core/forwarder.h> - -#include <errno.h> -#include <hicn/config/controlRoot.h> -#include <hicn/config/controlState.h> - -#include <hicn/utils/commands.h> - - - -size_t commandOutputLen = 0; // preserve the number of structs composing - // payload in case on not interactive call. - -// REMINDER: when a new_command is added, the following array has to be updated -// with the sizeof(new_command). It allows to allocate the buffer for receiving -// the payload of the DAEMON RESPONSE after the header has beed read. Each -// command identifier (typedef enum command_id) corresponds to a position in the -// following array. -static int payloadLengthController[LAST_COMMAND_VALUE] = { - sizeof(add_listener_command), - sizeof(add_connection_command), - sizeof(list_connections_command), // needed when get response from FWD - sizeof(add_route_command), - sizeof(list_routes_command), // needed when get response from FWD - sizeof(remove_connection_command), - sizeof(remove_listener_command), - sizeof(remove_route_command), - sizeof(cache_store_command), - sizeof(cache_serve_command), - 0, // cache clear - sizeof(set_strategy_command), - sizeof(set_wldr_command), - sizeof(add_punting_command), - sizeof(list_listeners_command), // needed when get response from FWD - sizeof(mapme_activator_command), - sizeof(mapme_activator_command), - sizeof(mapme_timing_command), - sizeof(mapme_timing_command), - sizeof(mapme_send_update_command), - sizeof(connection_set_admin_state_command), -#ifdef WITH_POLICY - sizeof(add_policy_command), - sizeof(list_policies_command), - sizeof(remove_policy_command), - sizeof(update_connection_command), - sizeof(connection_set_priority_command), - sizeof(connection_set_tags_command), -#endif -}; - -typedef struct controller_main_state { - ControlState *controlState; -} ControlMainState; - -static void _printRed(const char *output) { -#ifndef _WIN32 - printf("\033[0;31m%s", output); -#else - HANDLE hConsole = NULL; - WORD currentConsoleAttr; - CONSOLE_SCREEN_BUFFER_INFO csbi; - hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - if (GetConsoleScreenBufferInfo(hConsole, &csbi)) - currentConsoleAttr = csbi.wAttributes; - SetConsoleTextAttribute(hConsole, 4); - printf("%s", output); - SetConsoleTextAttribute(hConsole, currentConsoleAttr); -#endif -} - -static void _printWhite(const char *output) { -#ifndef _WIN32 - printf("\033[0m%s", output); -#else - HANDLE hConsole = NULL; - WORD currentConsoleAttr; - CONSOLE_SCREEN_BUFFER_INFO csbi; - hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - if (GetConsoleScreenBufferInfo(hConsole, &csbi)) - currentConsoleAttr = csbi.wAttributes; - SetConsoleTextAttribute(hConsole, 7); - printf("%s", output); - SetConsoleTextAttribute(hConsole, currentConsoleAttr); -#endif -} - -static void _displayForwarderLogo(void) { - _printRed(" ____ ___ _ "); - _printWhite(" __ _ __ _ __ __\n"); - _printRed(" / __// _ \\ (_)___ "); - _printWhite(" / / (_)____ ___ ____/ /(_)___ _ / / / /_\n"); - _printRed(" / _/ / // /_ / // _ \\ "); - _printWhite(" / _ \\ / // __// _ \\___/ // // _ `// _ \\/ __/\n"); - _printRed("/_/ /____/(_)/_/ \\___/ "); - _printWhite("/_//_//_/ \\__//_//_/ /_//_/ \\_, //_//_/\\__/\n"); - _printWhite( - " /___/ " - "\n"); - printf("\n"); -} - -static void _displayUsage(char *programName) { - printf("Usage: %s -h\n", programName); - printf( - "hicn-light is the 1.0 source, which runs on each end system and as a " - "software source\n"); - printf( - "on intermediate systems. controller is the program to configure the " - "source, daemon.\n"); - printf("\n"); - printf("Options:\n"); - printf("-h = This help screen\n"); - printf( - "commands = configuration line to send to hicn-light (use 'help' " - "for list)\n"); - printf("\n"); -} - -static int _parseArgs(int argc, char *argv[], char **server_ip, - uint16_t *server_port, PARCList *commandList){ - static struct option longFormOptions[] = { - {"help", no_argument, 0, 'h'}, - {"server", required_argument, 0, 'S'}, - {"port", required_argument, 0, 'P'}, - {0, 0, 0, 0}}; - - int c; - - while (1) { - // getopt_long stores the option index here. - int optionIndex = 0; - - c = getopt_long(argc, argv, "hS:P:", longFormOptions, &optionIndex); - - // Detect the end of the options. - if (c == -1) { - break; - } - - switch (c) { - case 'S': - { - *server_ip = optarg; - struct sockaddr_in sa; - int result = inet_pton(AF_INET, *server_ip, &(sa.sin_addr)); - //inet_pton() returns 1 on success - if(result != 1){ - return 0; - } - break; - } - case 'P': - { - char * port_str = optarg; - if(utils_IsNumber(port_str)){ - *server_port = (uint16_t) strtol(port_str, NULL, 10); - } else { - return 0; - } - break; - } - case 'h': - default: - return 0; - } - } - - if (optind < argc) { - while (optind < argc) { - parcList_Add(commandList, argv[optind]); - optind++; - } - } - - return 1; -} - -struct iovec *_writeAndReadMessage(ControlState *state, struct iovec *msg) { - parcAssertNotNull(msg, "Parameter msg must be non-null"); - int sockfd = controlState_GetSockfd(state); - - // check if request has a payload - if (((header_control_message *)msg[0].iov_base)->length > - 0) { // command with payload - // write header + payload (compatibility issue: two write needed instead of - // the writev) -#ifndef _WIN32 - if (write(sockfd, msg[0].iov_base, (unsigned int)msg[0].iov_len) < 0 || - write(sockfd, msg[1].iov_base, (unsigned int)msg[1].iov_len) < 0) { -#else - if (send(sockfd, msg[0].iov_base, (int)msg[0].iov_len, 0) == SOCKET_ERROR || - send(sockfd, msg[1].iov_base, (int)msg[1].iov_len, 0) == SOCKET_ERROR) { -#endif - printf("\nError while sending the Message: cannot write on socket \n"); - exit(EXIT_FAILURE); - } - parcMemory_Deallocate(&msg[1].iov_base); - } else { // command without payload, e.g. 'list' - // write header only -#ifndef _WIN32 - if (write(sockfd, msg[0].iov_base, msg[0].iov_len) < 0) { -#else - int result = send(sockfd, msg[0].iov_base, (int)msg[0].iov_len, 0); - if (result == SOCKET_ERROR) { -#endif - printf("\nError while sending the Message: cannot write on socket \n"); - exit(EXIT_FAILURE); - } - } - parcMemory_Deallocate(&msg[0].iov_base); - - // ======= RECEIVE ======= - - header_control_message *headerResponse = - (header_control_message *)parcMemory_AllocateAndClear( - sizeof(header_control_message)); - if (recv(sockfd, (char *)headerResponse, sizeof(header_control_message), 0) < - 0) { - printf("\nError in Receiving the Message \n"); - exit(EXIT_FAILURE); - } - - if (headerResponse->messageType < RESPONSE_LIGHT || - headerResponse->messageType >= LAST_MSG_TYPE_VALUE) { - char *checkFinMsg = parcMemory_Reallocate(headerResponse, 32); -#ifndef _WIN32 - if (recv(sockfd, checkFinMsg, sizeof(checkFinMsg), - MSG_PEEK | MSG_DONTWAIT) == 0) { -#else - if (recv(sockfd, checkFinMsg, sizeof(checkFinMsg), MSG_PEEK) == 0) { -#endif - // if recv returns zero, that means the connection has been closed: - close(sockfd); - printf("\nConnection terminated by the Daemon. Exiting... \n"); - exit(EXIT_SUCCESS); - } else { - printf("\nError: Unrecognized message type received \n"); - exit(EXIT_FAILURE); - } - } - - void *payloadResponse = NULL; - - if ((commandOutputLen = headerResponse->length) > 0) { - payloadResponse = parcMemory_AllocateAndClear( - payloadLengthController[headerResponse->commandID] * - headerResponse->length); - - if (recv(sockfd, payloadResponse, - payloadLengthController[headerResponse->commandID] * - headerResponse->length, - 0) < 0) { - printf("\nError in Receiving the Message \n"); - exit(EXIT_FAILURE); - } - } - - struct iovec *response = - parcMemory_AllocateAndClear(sizeof(struct iovec) * 2); - - response[0].iov_base = headerResponse; - response[0].iov_len = sizeof(header_control_message); - response[1].iov_base = payloadResponse; - response[1].iov_len = payloadLengthController[headerResponse->commandID] * - headerResponse->length; - - return response; -} - -int main(int argc, char *argv[]) { - _displayForwarderLogo(); - -#ifdef _WIN32 - WSADATA wsaData; - WSAStartup(MAKEWORD(2, 2), &wsaData); -#endif - - if (argc == 2 && strcmp("-h", argv[1]) == 0) { - _displayUsage(argv[0]); - exit(EXIT_SUCCESS); - } - - PARCList *commands = - parcList(parcArrayList_Create(NULL), PARCArrayListAsPARCList); - - char *server_ip = SRV_CTRL_IP; - uint16_t server_port = SRV_CTRL_PORT; - if (!_parseArgs(argc, argv, &server_ip, - &server_port, commands)) { - _displayUsage(argv[0]); - parcList_Release(&commands); - exit(EXIT_FAILURE); - } - - ControlMainState mainState; - mainState.controlState = - controlState_Create(&mainState, _writeAndReadMessage, true, - server_ip, server_port); - if (mainState.controlState == NULL) { - exit(EXIT_FAILURE); - } - - controlState_RegisterCommand(mainState.controlState, - controlRoot_HelpCreate(mainState.controlState)); - controlState_RegisterCommand(mainState.controlState, - controlRoot_Create(mainState.controlState)); - - if (parcList_Size(commands) > 0) { - controlState_SetInteractiveFlag(mainState.controlState, false); - char output[8192]; - controlState_DispatchCommand(mainState.controlState, commands, output, sizeof(output)); - printf("%s", output); - char **commandOutputMain = - controlState_GetCommandOutput(mainState.controlState); - if (commandOutputMain != NULL && commandOutputLen > 0) { -#if 0 - for (size_t j = 0; j < commandOutputLen; j++) { - printf("Output %zu: %s \n", j, commandOutputMain[j]); - } -#endif - controlState_ReleaseCommandOutput(mainState.controlState, - commandOutputMain, commandOutputLen); - } - // release - - } else { - controlState_Interactive(mainState.controlState); - } - - parcList_Release(&commands); - - controlState_Destroy(&mainState.controlState); -#ifdef _WIN32 - WSACleanup(); -#endif - return EXIT_SUCCESS; -} diff --git a/hicn-light/src/hicn/command_line/daemon/CMakeLists.txt b/hicn-light/src/hicn/command_line/daemon/CMakeLists.txt deleted file mode 100644 index a86826f09..000000000 --- a/hicn-light/src/hicn/command_line/daemon/CMakeLists.txt +++ /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. - -list(APPEND DAEMON_SRC - hicnLightDaemon_main.c -) - -if (WIN32) - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /NODEFAULTLIB:\"LIBCMT\"") -endif() - -if(NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Android") - build_executable(${HICN_LIGHT_DAEMON} - SOURCES ${DAEMON_SRC} - LINK_LIBRARIES ${LIBHICN_LIGHT_STATIC} - DEPENDS ${LIBHICN_LIGHT_STATIC} - COMPONENT ${HICN_LIGHT} - DEFINITIONS ${COMPILER_DEFINITIONS} - ) -endif () diff --git a/hicn-light/src/hicn/command_line/daemon/hicnLightDaemon_main.c b/hicn-light/src/hicn/command_line/daemon/hicnLightDaemon_main.c deleted file mode 100644 index ab7039f5e..000000000 --- a/hicn-light/src/hicn/command_line/daemon/hicnLightDaemon_main.c +++ /dev/null @@ -1,414 +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 <errno.h> -#include <fcntl.h> -#include <stdbool.h> -#include <stdint.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/stat.h> - -#include <hicn/hicn-light/config.h> -#include <parc/algol/parc_FileOutputStream.h> -#include <parc/logging/parc_LogLevel.h> -#include <parc/logging/parc_LogReporterFile.h> -#include <parc/logging/parc_LogReporterTextStdout.h> - -#include <parc/assert/parc_Assert.h> - -#include <hicn/core/dispatcher.h> -#include <hicn/core/forwarder.h> - -static void _printRed(const char *output) { -#ifndef _WIN32 - printf("\033[0;31m%s", output); -#else - HANDLE hConsole = NULL; - WORD currentConsoleAttr; - CONSOLE_SCREEN_BUFFER_INFO csbi; - hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - if (GetConsoleScreenBufferInfo(hConsole, &csbi)) - currentConsoleAttr = csbi.wAttributes; - SetConsoleTextAttribute(hConsole, 4); - printf("%s", output); - SetConsoleTextAttribute(hConsole, currentConsoleAttr); -#endif -} - -static void _printWhite(const char *output) { -#ifndef _WIN32 - printf("\033[0m%s", output); -#else - HANDLE hConsole = NULL; - WORD currentConsoleAttr; - CONSOLE_SCREEN_BUFFER_INFO csbi; - hConsole = GetStdHandle(STD_OUTPUT_HANDLE); - if (GetConsoleScreenBufferInfo(hConsole, &csbi)) - currentConsoleAttr = csbi.wAttributes; - SetConsoleTextAttribute(hConsole, 7); - printf("%s", output); - SetConsoleTextAttribute(hConsole, currentConsoleAttr); -#endif -} - -static void _displayForwarderLogo(void) { - _printRed(" ____ ___ _ "); - _printWhite(" __ _ __ _ __ __\n"); - _printRed(" / __// _ \\ (_)___ "); - _printWhite(" / / (_)____ ___ ____/ /(_)___ _ / / / /_\n"); - _printRed(" / _/ / // /_ / // _ \\ "); - _printWhite(" / _ \\ / // __// _ \\___/ // // _ `// _ \\/ __/\n"); - _printRed("/_/ /____/(_)/_/ \\___/ "); - _printWhite("/_//_//_/ \\__//_//_/ /_//_/ \\_, //_//_/\\__/\n"); - _printWhite( - " /___/ " - "\n"); - printf("\n"); -} - -static void _usage(int exitCode) { -#ifndef _WIN32 - printf( - "Usage: hicn-light-daemon [--port port] [--capacity objectStoreSize] " - "[--log facility=level] [--log-file filename] [--config file]\n"); -#else - printf( - "Usage: hicn-light-daemon.exe [--port port] [--daemon] [--capacity objectStoreSize] " - "[--log facility=level] [--log-file filename] [--config file]\n"); -#endif - printf("\n"); - printf( - "hicn-light run as a daemon is the program to launch the forwarder, " - "either as a console program\n"); - printf( - "or a background daemon (detatched from console). Once running, use the " - "program controller to\n"); - printf("configure hicn-light.\n"); - printf("\n"); - printf( - "The configuration file contains configuration lines as per " - "controller\n"); - printf( - "If logging level or content store capacity is set in the configuraiton " - "file, it overrides the command_line\n"); - printf( - "When a configuration file is specified, no default listeners on 'port' " - "are setup. Only 'add listener' lines\n"); - printf("in the configuration file matter.\n"); - printf("\n"); - printf( - "If no configuration file is specified, daemon will listen on TCP and " - "UDP ports specified by\n"); - printf( - "the --port flag (or default port). It will listen on both IPv4 and " - "IPv6 if available.\n"); - printf("\n"); - printf("Options:\n"); - printf("--port = tcp port for in-bound connections\n"); -#ifndef _WIN32 - printf("--daemon = start as daemon process\n"); -#endif - printf("--objectStoreSize = maximum number of content objects to cache\n"); - printf( - "--log = sets a facility to a given log level. You can have " - "multiple of these.\n"); - printf( - " facilities: all, config, core, io, message, " - "processor\n"); - printf( - " levels: debug, info, notice, warning, error, " - "critical, alert, off\n"); - printf(" example: daemon --log io=debug --log core=off\n"); - printf( - "--log-file = file to write log messages to (required in daemon " - "mode)\n"); - printf("--config = configuration filename\n"); - printf("\n"); - exit(exitCode); -} - -static void _setLogLevelToLevel(int logLevelArray[LoggerFacility_END], - LoggerFacility facility, - const char *levelString) { - PARCLogLevel level = parcLogLevel_FromString(levelString); - - if (level < PARCLogLevel_All) { - // we have a good facility and level - logLevelArray[facility] = level; - } else { - printf("Invalid log level string %s\n", levelString); - _usage(EXIT_FAILURE); - } -} - -/** - * string: "facility=level" - * Set the right thing in the logger - */ -static void _setLogLevel(int logLevelArray[LoggerFacility_END], - const char *string) { - char *tofree = parcMemory_StringDuplicate(string, strlen(string)); - char *p = tofree; - - char *facilityString = strtok(p, "="); - if (facilityString) { - char *levelString = strtok(NULL, "="); - - if (strcasecmp(facilityString, "all") == 0) { - for (LoggerFacility facility = 0; facility < LoggerFacility_END; - facility++) { - _setLogLevelToLevel(logLevelArray, facility, levelString); - } - } else { - LoggerFacility facility; - for (facility = 0; facility < LoggerFacility_END; facility++) { - if (strcasecmp(facilityString, logger_FacilityString(facility)) == 0) { - break; - } - } - - if (facility < LoggerFacility_END) { - _setLogLevelToLevel(logLevelArray, facility, levelString); - } else { - printf("Invalid facility string %s\n", facilityString); - _usage(EXIT_FAILURE); - } - } - } - - parcMemory_Deallocate((void **)&tofree); -} - -#ifndef _WIN32 -static void _daemonize(void) { - if (getppid() == 1) { - // already a daemon - return; - } - - int forkReturn = fork(); - parcTrapUnexpectedStateIf(forkReturn < 0, "Fork error") - - if (forkReturn > 0) { - // parent exits - exit(EXIT_SUCCESS); - } - - // Child daemon detaches - printf("child continuing, pid = %u\n", getpid()); - - // get a new process group independent from old parent - setsid(); - - /* close all descriptors */ -#ifdef __ANDROID__ - for (int i = sysconf(_SC_OPEN_MAX); i >= 0; --i) { - close(i); - } -#else - for (int i = getdtablesize(); i >= 0; --i) { - close(i); - } -#endif - // reset errno because it might be seg to EBADF from the close calls above - errno = 0; - - // Redirect stdin and stdout and stderr to /dev/null - const char *devnull = "/dev/null"; - int nullfile = open(devnull, O_RDWR); - parcAssertTrue(nullfile >= 0, "Error opening file '%s': (%d) %s", devnull, - errno, strerror(errno)); - - int ret; - ret = dup(nullfile); - parcAssertTrue(ret == 1, "Error duping fd 1 got %d file: (%d) %s", ret, errno, - strerror(errno)); - ret = dup(nullfile); - parcAssertTrue(ret == 2, "Error duping fd 2, got %d file: (%d) %s", ret, - errno, strerror(errno)); - - // forwarder will capture signals -} -#endif - -static Logger *_createLogfile(const char *logfile) { -#ifndef _WIN32 - int logfd = open(logfile, O_WRONLY | O_APPEND | O_CREAT, S_IWUSR | S_IRUSR); -#else - int logfd = - _open(logfile, _O_WRONLY | _O_APPEND | _O_CREAT, _S_IWRITE | _S_IREAD); -#endif - if (logfd < 0) { - fprintf(stderr, "Error opening %s for writing: (%d) %s\n", logfile, errno, - strerror(errno)); - exit(EXIT_FAILURE); - } - -#ifndef _WIN32 - chmod(logfile, S_IRWXU); -#endif - - PARCFileOutputStream *fos = parcFileOutputStream_Create(logfd); - PARCOutputStream *pos = parcFileOutputStream_AsOutputStream(fos); - PARCLogReporter *reporter = parcLogReporterFile_Create(pos); - - Logger *logger = logger_Create(reporter, parcClock_Wallclock()); - - parcOutputStream_Release(&pos); - parcLogReporter_Release(&reporter); - - return logger; -} - -int main(int argc, const char *argv[]) { - _displayForwarderLogo(); -#ifndef _WIN32 - bool daemon = false; -#else - WSADATA wsaData = {0}; - WSAStartup(MAKEWORD(2, 2), &wsaData); -#endif - - uint16_t port = PORT_NUMBER; - uint16_t configurationPort = 2001; - int capacity = -1; - const char *configFileName = NULL; - - char *logfile = NULL; - - if (argc == 2 && strcasecmp(argv[1], "-h") == 0) { - _usage(EXIT_SUCCESS); - } - - int logLevelArray[LoggerFacility_END]; - for (int i = 0; i < LoggerFacility_END; i++) { - logLevelArray[i] = -1; - } - - for (int i = 0; i < argc; i++) { - if (argv[i][0] == '-') { - if (strcmp(argv[i], "--config") == 0) { - configFileName = argv[i + 1]; - i++; - } else if (strcmp(argv[i], "--port") == 0) { - port = atoi(argv[i + 1]); - i++; -#ifndef _WIN32 - } else if (strcmp(argv[i], "--daemon") == 0) { - daemon = true; -#endif - } else if (strcmp(argv[i], "--capacity") == 0 || - strcmp(argv[i], "-c") == 0) { - capacity = atoi(argv[i + 1]); - i++; - } else if (strcmp(argv[i], "--log") == 0) { - _setLogLevel(logLevelArray, argv[i + 1]); - i++; - } else if (strcmp(argv[i], "--log-file") == 0) { - if (logfile) { - // error cannot repeat - fprintf(stderr, "Cannot specify --log-file more than once\n"); - _usage(EXIT_FAILURE); - } - - logfile = parcMemory_StringDuplicate(argv[i + 1], strlen(argv[i + 1])); - i++; - } else { - _usage(EXIT_FAILURE); - } - } - } - - // set restrictive umask, in case we create any files - umask(027); - -#ifndef _WIN32 - if (daemon && (logfile == NULL)) { - fprintf(stderr, "Must specify a logfile when running in daemon mode\n"); - _usage(EXIT_FAILURE); - } - - if (daemon) { - // inside this call, parent will EXIT_SUCCESS and child will continue - _daemonize(); - } -#endif - - Logger *logger = NULL; - if (logfile) { - logger = _createLogfile(logfile); - parcMemory_Deallocate((void **)&logfile); - } else { - PARCLogReporter *stdoutReporter = parcLogReporterTextStdout_Create(); - logger = logger_Create(stdoutReporter, parcClock_Wallclock()); - parcLogReporter_Release(&stdoutReporter); - } - - for (int i = 0; i < LoggerFacility_END; i++) { - if (logLevelArray[i] > -1) { - logger_SetLogLevel(logger, i, logLevelArray[i]); - } - } - - // this will update the clock to the tick clock - Forwarder *forwarder = forwarder_Create(logger); - - if (forwarder == NULL) { - logger_Log(logger, LoggerFacility_Core, PARCLogLevel_Error, "daemon", - "Forwarder initialization failed. Are you running it with sudo " - "privileges?"); - logger_Release(&logger); - return -1; - } - - Configuration *configuration = forwarder_GetConfiguration(forwarder); - - if (capacity > -1) { - configuration_SetObjectStoreSize(configuration, capacity); - } - - forwarder_SetupLocalListeners(forwarder, port); - if (configFileName) { - forwarder_SetupFromConfigFile(forwarder, configFileName); - } - - Dispatcher *dispatcher = forwarder_GetDispatcher(forwarder); - - logger_Log(logger, LoggerFacility_Core, PARCLogLevel_Alert, "daemon", - "hicn-light running port %d configuration-port %d", port, - configurationPort); - - dispatcher_Run(dispatcher); - - logger_Log(logger, LoggerFacility_Core, PARCLogLevel_Alert, "daemon", - "hicn-light exiting port %d", port); - - forwarder_Destroy(&forwarder); - -#ifndef _WIN32 - //sleep(2); -#else - //Sleep(2000); - WSACleanup(); -#endif - - logger_Release(&logger); - return 0; -} |