├── dist └── .gitkeep ├── dozord ├── NEWS ├── ChangeLog ├── AUTHORS ├── README ├── Makefile.am ├── app-config.h ├── logger.h ├── dozord.8 ├── socket-server.h ├── command.h ├── command.c ├── nightshift-mqtt.h ├── logger.c ├── app-config.c ├── nightshift-mqtt.c ├── socket-server.c ├── main.c └── INSTALL ├── libdozor ├── NEWS ├── ChangeLog ├── AUTHORS ├── README ├── Makefile.am ├── session.h ├── utils.h ├── rc4.h ├── device-event.h ├── utils.c ├── dozor.h ├── rc4.c ├── dozor-crypto.h ├── event.h ├── device-event.c ├── dozor-crypto.c ├── libdozor.c ├── event.c └── INSTALL ├── tools ├── NEWS ├── ChangeLog ├── AUTHORS ├── Makefile.am ├── README ├── parser.c └── INSTALL ├── version.m4 ├── Makefile.am ├── liblogger ├── Makefile.am ├── liblogger.h └── liblogger.c ├── .gitignore ├── contrib └── systemd │ └── nightshift.service ├── .vscode └── settings.json ├── .github └── workflows │ └── c-cpp.yml ├── configure.ac ├── test └── tcp_client.c ├── Roadmap.md ├── README.md └── LICENSE /dist/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /dozord/NEWS: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /libdozor/NEWS: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tools/NEWS: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /dozord/ChangeLog: -------------------------------------------------------------------------------- 1 | Initial release -------------------------------------------------------------------------------- /libdozor/ChangeLog: -------------------------------------------------------------------------------- 1 | Initial release -------------------------------------------------------------------------------- /tools/ChangeLog: -------------------------------------------------------------------------------- 1 | Initial release -------------------------------------------------------------------------------- /version.m4: -------------------------------------------------------------------------------- 1 | m4_define([VERSION_NUMBER], [0.9.6]) -------------------------------------------------------------------------------- /dozord/AUTHORS: -------------------------------------------------------------------------------- 1 | AUTHORS 2 | ------- 3 | 4 | 5 | Denis Morozov 6 | 7 | -------------------------------------------------------------------------------- /tools/AUTHORS: -------------------------------------------------------------------------------- 1 | AUTHORS 2 | ------- 3 | 4 | 5 | Denis Morozov 6 | 7 | -------------------------------------------------------------------------------- /libdozor/AUTHORS: -------------------------------------------------------------------------------- 1 | AUTHORS 2 | ------- 3 | 4 | 5 | Denis Morozov 6 | 7 | -------------------------------------------------------------------------------- /libdozor/README: -------------------------------------------------------------------------------- 1 | 2 | NightShift libdozor 3 | --------- 4 | 5 | provides C functions to unpack and pack Astra Dozor Security System 6 | messages. 7 | 8 | -- Denis Morozov 9 | -------------------------------------------------------------------------------- /Makefile.am: -------------------------------------------------------------------------------- 1 | AUTOMAKE_OPTIONS = foreign 2 | SUBDIRS = liblogger libdozor dozord tools 3 | DISTDIR = $(top_builddir)/dist 4 | ACLOCAL_AMFLAGS = -I m4 5 | 6 | clean-local: 7 | @echo: This will be run by "make clean" -------------------------------------------------------------------------------- /tools/Makefile.am: -------------------------------------------------------------------------------- 1 | AUTOMAKE_OPTS = gnu 2 | bin_PROGRAMS = parser 3 | 4 | parser_SOURCES = parser.c 5 | parser_LDADD = $(top_builddir)/liblogger/liblogger.la $(top_builddir)/libdozor/libdozor.la 6 | parser_CPPFLAGS = -I$(top_srcdir)/liblogger -I$(top_srcdir)/libdozor -------------------------------------------------------------------------------- /dozord/README: -------------------------------------------------------------------------------- 1 | 2 | NightShift daemon 3 | --------- 4 | 5 | dozord is an free implementation of the Astra Dozor Security 6 | System server to collect security events and control Astra 7 | Dozor Box. See more at https://github.com/frozer/nightshift 8 | 9 | -- Denis Morozov 10 | -------------------------------------------------------------------------------- /liblogger/Makefile.am: -------------------------------------------------------------------------------- 1 | liblogger_ladir = $(includedir)/liblogger 2 | 3 | lib_LTLIBRARIES = liblogger.la 4 | 5 | liblogger_la_SOURCES = liblogger.c liblogger.h 6 | liblogger_la_HEADERS = liblogger.h 7 | 8 | include_HEADERS = liblogger.h 9 | 10 | # Specify any additional flags or libraries needed 11 | AM_CFLAGS = -Wall -Wextra 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Makefile 2 | Makefile.in 3 | autom4te.cache 4 | .deps 5 | .libs 6 | aclocal.m4 7 | compile 8 | config.* 9 | depcomp 10 | *.lo 11 | *.la 12 | *.o 13 | install-sh 14 | libtool 15 | ltmain.sh 16 | missing 17 | stamp-h1 18 | *.tar.gz 19 | dozord/dozord 20 | tools/parser 21 | configure.in 22 | .aider* 23 | configure 24 | configure~ 25 | m4/ -------------------------------------------------------------------------------- /tools/README: -------------------------------------------------------------------------------- 1 | 2 | NightShift parser 3 | --------- 4 | 5 | Usage: 6 | 7 | ./parser message 8 | 9 | NightShift is a free implementation of the Astra Dozor Security 10 | System server to collect security events and control Astra 11 | Dozor Box. See more at https://github.com/frozer/nightshift 12 | 13 | -- Denis Morozov 14 | -------------------------------------------------------------------------------- /libdozor/Makefile.am: -------------------------------------------------------------------------------- 1 | AUTOMAKE_OPTIONS = gnu 2 | lib_LTLIBRARIES = libdozor.la 3 | 4 | libdozor_la_SOURCES = libdozor.c device-event.c dozor-crypto.c rc4.c utils.c event.c dozor-crypto.h event.h device-event.h rc4.h session.h utils.h 5 | libdozor_la_LIBADD = $(top_builddir)/liblogger/liblogger.la 6 | libdozor_la_CPPFLAGS = -I$(top_srcdir)/liblogger 7 | include_HEADERS = dozor.h 8 | 9 | libdozor_la_LDFLAGS = -version-info 0:0:0 -------------------------------------------------------------------------------- /contrib/systemd/nightshift.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Nightshift Daemon 3 | DefaultDependencies=no 4 | Wants=mosquitto.service 5 | After=network.target mosquitto.service 6 | 7 | [Service] 8 | Type=simple 9 | User=dim 10 | Group=dim 11 | Environment='DOZOR_SITE_ID=11' 'DOZOR_SITE_KEY=01234567890' 12 | ExecStart=/opt/nightshift/bin/dozord 13 | TimeoutStartSec=0 14 | RemainAfterExit=yes 15 | Restart=on-failure 16 | RestartSec=5 17 | 18 | [Install] 19 | WantedBy=default.target -------------------------------------------------------------------------------- /dozord/Makefile.am: -------------------------------------------------------------------------------- 1 | AUTOMAKE_OPTS = gnu 2 | bin_PROGRAMS = dozord 3 | 4 | dozord_SOURCES = main.c nightshift-mqtt.c socket-server.c command.c logger.c app-config.c command.h nightshift-mqtt.h logger.h socket-server.h app-config.h 5 | dozord_LDADD = $(top_builddir)/liblogger/liblogger.la $(top_builddir)/libdozor/libdozor.la -lpthread -lmosquitto 6 | dozord_CFLAGS = -pthread 7 | dozord_CPPFLAGS = -I$(top_srcdir)/liblogger -I$(top_srcdir)/libdozor 8 | 9 | man_MANS = dozord.8 10 | 11 | EXTRA_DIST = dozord.8 -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "nightshift-mqtt.h": "c", 4 | "answer.h": "c", 5 | "dozor.h": "c", 6 | "socket-server.h": "c", 7 | "signal.h": "c", 8 | "mosquitto.h": "c", 9 | "utils.h": "c", 10 | "command.h": "c", 11 | "logger.h": "c", 12 | "app-config.h": "c", 13 | "dozor-crypto.h": "c", 14 | "array": "c", 15 | "string": "c", 16 | "string_view": "c", 17 | "stdio.h": "c", 18 | "errno.h": "c", 19 | "cstdint": "c", 20 | "liblogger.h": "c", 21 | "time.h": "c" 22 | } 23 | } -------------------------------------------------------------------------------- /liblogger/liblogger.h: -------------------------------------------------------------------------------- 1 | #ifndef LIBLOGGER_H 2 | #define LIBLOGGER_H 3 | 4 | #include 5 | #include 6 | #include 7 | // Log levels 8 | typedef enum { 9 | LOG_LEVEL_DEBUG, 10 | LOG_LEVEL_INFO, 11 | LOG_LEVEL_WARN, 12 | LOG_LEVEL_ERROR 13 | } LogLevel; 14 | 15 | // Function prototypes 16 | void set_log_level(LogLevel level); 17 | LogLevel get_log_level(); 18 | char * logLevel2Str(LogLevel level); 19 | void logger(LogLevel level, const char* module, const char* format, ...); 20 | void blobToHexStr(char *res, const uint8_t *data, const int data_length); 21 | #endif // LIBLOGGER_H 22 | -------------------------------------------------------------------------------- /.github/workflows/c-cpp.yml: -------------------------------------------------------------------------------- 1 | name: C/C++ CI 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | jobs: 10 | 11 | build: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v4 17 | - name: configure 18 | run: | 19 | sudo apt update 20 | sudo apt-get update 21 | sudo apt-get -y install libmosquitto-dev libpthread-stubs0-dev 22 | autoreconf -i 23 | ./configure 24 | - name: make 25 | run: make 26 | - name: make check 27 | run: make check 28 | - name: make distcheck 29 | run: make distcheck 30 | -------------------------------------------------------------------------------- /dozord/app-config.h: -------------------------------------------------------------------------------- 1 | #ifndef APP_CONFIG_H 2 | #define APP_CONFIG_H 3 | 4 | #include 5 | #include "socket-server.h" 6 | #include "nightshift-mqtt.h" 7 | #include "logger.h" 8 | 9 | #define DEFAULT_PORT 1111 10 | #define AGENT_ID "80d7be61-d81d-4aac-9012-6729b6392a89" 11 | #define MQTT_HOST "127.0.0.1" 12 | #define MQTT_PORT 1883 13 | 14 | struct AppConfig { 15 | struct SocketConfig socketConfig; 16 | struct MQTTConfig mqttConfig; 17 | char pinCode[36]; 18 | unsigned int siteId; 19 | LogLevel logLevel; 20 | }; 21 | 22 | void initializeAppConfig(struct AppConfig *appConfig); 23 | void processCommandLineOptions(int argc, char **argv, struct AppConfig *appConfig); 24 | 25 | #endif // APP_CONFIG_H 26 | -------------------------------------------------------------------------------- /dozord/logger.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | #ifndef LOGGER_H 18 | #define LOGGER_H 19 | 20 | #include "liblogger.h" 21 | 22 | void prettyLogger(LogLevel level, const char* source, const char* message); 23 | 24 | #endif -------------------------------------------------------------------------------- /libdozor/session.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #ifndef CRYPTO_SESSION_H 19 | #define CRYPTO_SESSION_H 20 | 21 | typedef struct { 22 | unsigned short int pool[256]; 23 | unsigned short int iterator; 24 | unsigned short int pointer; 25 | } CryptoSession; 26 | 27 | #endif -------------------------------------------------------------------------------- /libdozor/utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #include 19 | #ifndef DOZOR_UTILS_H 20 | #define DOZOR_UTILS_H 21 | #define DATE_TIME_OFFSET 0x3A4FC880 22 | 23 | void char2utf8(wchar_t* dest, const unsigned char* src); 24 | char * getDateTime(const uint32_t t); 25 | 26 | #endif -------------------------------------------------------------------------------- /configure.ac: -------------------------------------------------------------------------------- 1 | m4_include([version.m4]) 2 | AC_INIT([nightshift],VERSION_NUMBER,[n.halcyon@gmail.com]) 3 | AM_INIT_AUTOMAKE 4 | 5 | LT_INIT 6 | 7 | # Checks for programs. 8 | AC_PROG_CC 9 | 10 | AC_PROG_MAKE_SET 11 | 12 | # Checks for libraries. 13 | AX_PTHREAD 14 | 15 | # Checks for libraries. 16 | AC_CHECK_LIB(mosquitto,mosquitto_publish, [], [ 17 | echo "Error! You need to have libmosquitto around." 18 | exit -1 19 | ]) 20 | 21 | # Checks for header files. 22 | AC_CHECK_HEADERS([arpa/inet.h inttypes.h stdint.h netinet/in.h stdlib.h string.h sys/socket.h unistd.h pthread.h byteswap.h mosquitto.h]) 23 | 24 | # Checks for typedefs, structures, and compiler characteristics. 25 | AC_TYPE_SIZE_T 26 | AC_TYPE_UINT16_T 27 | AC_TYPE_UINT32_T 28 | AC_TYPE_UINT64_T 29 | AC_TYPE_UINT8_T 30 | 31 | # Checks for library functions. 32 | AC_FUNC_MALLOC 33 | AC_CHECK_FUNCS([bzero socket strerror strtol]) 34 | 35 | AC_CONFIG_FILES([ 36 | dozord/Makefile 37 | libdozor/Makefile 38 | liblogger/Makefile 39 | tools/Makefile 40 | Makefile 41 | ]) 42 | AC_CONFIG_MACRO_DIRS([m4]) 43 | AC_OUTPUT 44 | -------------------------------------------------------------------------------- /dozord/dozord.8: -------------------------------------------------------------------------------- 1 | .TH DOZORD 8 "1 May 2020" "Free Software" "User Manuals" 2 | .SH NAME 3 | dozord \- Astra Dozor Security System protocol daemon 4 | .SH SYNOPSIS 5 | dozord -s -k [\-l 1111] [\-m 127.0.0.1] [\-p 1883] [\-d] [\h] 6 | 7 | .SH DESCRIPTION 8 | dozord is an free implementation of the Astra Dozor Security 9 | System server to collect security events and control Astra 10 | Dozor Box 11 | 12 | .SH "COMMAND-LINE OPTIONS" 13 | .IP -s 14 | Astra Box device ID 15 | .IP -k 16 | Astra Box device PIN code 17 | .IP -l 18 | listen specified port, 1111 by default 19 | .IP -m 20 | MQTT host to connect, 127.0.0.1 by default 21 | .IP -p 22 | MQTT port to connect, 1883 by default 23 | .IP -d 24 | runs in debug mode, highly verbose (will report 25 | every request and commands performed by the server) 26 | .IP -h 27 | displays help 28 | 29 | .SH "ENVIRONMENT VARIABLES" 30 | .IP DOZOR_SITE_ID 31 | Astra Box device ID 32 | .IP DOZOR_SITE_KEY 33 | Astra Box device PIN code 34 | 35 | .SH AUTHORS 36 | dozord was implemented and created by Denis Morozov 37 | . -------------------------------------------------------------------------------- /libdozor/rc4.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #ifndef RC4_H 19 | #define RC4_H 20 | 21 | #include 22 | #include 23 | #include 24 | #include "session.h" 25 | 26 | void codec(unsigned char* data, CryptoSession * crypto, 27 | const size_t msgLength); 28 | void getCryptoSession(CryptoSession * crypto, const uint8_t* key); 29 | static void swap(unsigned short int* pool, 30 | const unsigned short int src, const unsigned short int dst); 31 | 32 | #endif -------------------------------------------------------------------------------- /liblogger/liblogger.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "liblogger.h" 3 | 4 | static LogLevel currentLogLevel = LOG_LEVEL_DEBUG; 5 | 6 | // Set the minimum log level 7 | void set_log_level(LogLevel level) { 8 | currentLogLevel = level; 9 | } 10 | 11 | LogLevel get_log_level() { 12 | return currentLogLevel; 13 | } 14 | 15 | char * logLevel2Str(LogLevel level) { 16 | const char* levelStrings[] = { 17 | "DEBUG", 18 | "INFO", 19 | "WARN", 20 | "ERROR" 21 | }; 22 | return levelStrings[level]; 23 | } 24 | 25 | // Logger function 26 | void logger(LogLevel level, const char* module, const char* format, ...) { 27 | if (level < currentLogLevel) { 28 | return; 29 | } 30 | 31 | char logMessage[1024]; 32 | 33 | va_list args; 34 | va_start(args, format); 35 | vsnprintf(logMessage, sizeof(logMessage), format, args); 36 | va_end(args); 37 | 38 | printf("[%s] %s: %s\n", logLevel2Str(level), module, logMessage); 39 | } 40 | 41 | void blobToHexStr(char *res, const uint8_t *data, const int data_length) { 42 | int offset = 0; 43 | for (int i = 0; i < data_length; i++) { 44 | offset += snprintf(res + offset, 3, "%02x", data[i]); 45 | } 46 | 47 | // Ensure the string is null-terminated 48 | res[offset] = '\0'; 49 | } 50 | -------------------------------------------------------------------------------- /dozord/socket-server.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift. 3 | 4 | NightShift is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift. If not, see . 16 | */ 17 | #ifndef SOCKET_SERVER_CONFIG_H 18 | #define SOCKET_SERVER_CONFIG_H 19 | 20 | #define MAX_CONN 5 21 | 22 | typedef void (*on_message_t)(void *responsePayload, void *data, char *clientIp); 23 | 24 | struct SocketConfig { 25 | unsigned int port; 26 | on_message_t on_message; 27 | }; 28 | 29 | struct ConnectionPayload { 30 | int sockfd; 31 | char * clientIp[16]; 32 | on_message_t on_message; 33 | unsigned short int workerId; 34 | }; 35 | 36 | void startSocketService(struct SocketConfig * config); 37 | void stopSocketService(); 38 | 39 | #endif // SOCKET_SERVER_CONFIG_H -------------------------------------------------------------------------------- /dozord/command.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift. 3 | 4 | NightShift is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift. If not, see . 16 | */ 17 | 18 | #include 19 | 20 | #ifndef COMMAND_H 21 | #define COMMAND_H 22 | #define MAX_COMMAND_QUEUE_LENGTH 256 23 | 24 | typedef struct command { 25 | uint32_t id; 26 | unsigned short int done; 27 | char value[32]; 28 | } Command; 29 | 30 | typedef struct { 31 | Command items[MAX_COMMAND_QUEUE_LENGTH]; 32 | unsigned short int length; 33 | } Commands; 34 | 35 | short int getNextCommandIdx(Commands *); 36 | void readCommandsFromFile(Commands *, char * fn, const unsigned short int debugMode); 37 | void readCommandsFromString(Commands * commands, char * command); 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /libdozor/device-event.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #include 19 | 20 | #ifndef DOZOR_DEVICE_EVENT_H 21 | #define DOZOR_DEVICE_EVENT_H 22 | 23 | #define MAX_DEVICE_EVENT_DATA_SIZE 80 24 | #define MAX_EVENTS_PER_DEVICE 256 25 | // 4 bytes for date, 1 byte for event type id 26 | #define MESSAGE_ALIGN_SIZE 5 27 | 28 | typedef struct EVENT { 29 | uint8_t type; 30 | uint32_t time; 31 | uint8_t dataLength; 32 | uint8_t data[MAX_DEVICE_EVENT_DATA_SIZE]; 33 | } DeviceEvent; 34 | 35 | unsigned short int getDeviceEvents(const uint8_t * raw, long int bufSize, DeviceEvent * events); 36 | 37 | #endif -------------------------------------------------------------------------------- /libdozor/utils.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include "utils.h" 23 | 24 | void char2utf8(wchar_t* dest, const unsigned char* src) 25 | { 26 | short int new_length = strlen(src) + 1; 27 | short int index; 28 | 29 | mbstowcs(dest, src, new_length); 30 | } 31 | 32 | char * getDateTime(const uint32_t t) { 33 | time_t ot = t + DATE_TIME_OFFSET; 34 | struct tm *date = localtime(&ot); 35 | char *buffer = malloc(26); // Enough space for the formatted string 36 | if (buffer != NULL) { 37 | strftime(buffer, 26, "%a %b %d %H:%M:%S %Y", date); 38 | } 39 | return buffer; 40 | } 41 | -------------------------------------------------------------------------------- /dozord/command.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift. 3 | 4 | NightShift is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include "./command.h" 23 | 24 | short int getNextCommandIdx(Commands * commands) 25 | { 26 | unsigned short int index; 27 | short int found = -1; 28 | 29 | if (commands->length == 0) 30 | { 31 | return found; 32 | } 33 | 34 | for (index = 0; index < commands->length; index++) 35 | { 36 | if (commands->items[index].done == 0) 37 | { 38 | found = index; 39 | break; 40 | } 41 | } 42 | 43 | return found; 44 | } 45 | 46 | void readCommandsFromString(Commands * commands, char * command) 47 | { 48 | int i = commands->length; 49 | if (i >= MAX_COMMAND_QUEUE_LENGTH) 50 | { 51 | i = 0; 52 | } 53 | 54 | commands->length = i + 1; 55 | 56 | sprintf(commands->items[i].value, "%s", command); 57 | commands->items[i].done = 0; 58 | commands->items[i].id = i + 1; 59 | } -------------------------------------------------------------------------------- /libdozor/dozor.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #ifndef DOZOR_H 19 | #define DOZOR_H 20 | #include "session.h" 21 | #include "dozor-crypto.h" 22 | #include "event.h" 23 | 24 | #define DEFAULT_ANSWER "" 25 | #define END_OF_COMMAND "!" 26 | 27 | #define HANDLER_SOCKET_READ_ERROR -1 28 | #define HANDLER_UNABLE_TO_ALLOCATE_MEMORY_CRYPTO_SESSION -2 29 | #define HANDLER_CRYPTO_SESSION_NOT_INITIALIZED -4 30 | #define HANDLER_UNABLE_TO_ALLOCATE_MEMORY_REPORT -16 31 | #define HANDLER_UNABLE_TO_RECOGNIZE_MESSAGE -32 32 | 33 | #define BUFFERSIZE 1024 34 | 35 | typedef struct { 36 | int sock; 37 | char clientIp[16]; 38 | unsigned char pinCode[32]; 39 | } connectionInfo; 40 | 41 | typedef struct { 42 | DozorResponse response; 43 | unsigned short int responseLength; 44 | } CommandResponse; 45 | 46 | /* decrypt and unpack device messages from raw data packet */ 47 | Events * dozor_unpackV2(CryptoSession * crypto, uint8_t * raw, char * pinCode); 48 | 49 | /* encrypt command for device */ 50 | unsigned short int dozor_pack(CommandResponse * , CryptoSession *, unsigned int commandId, char * commandValue); 51 | 52 | 53 | #endif -------------------------------------------------------------------------------- /test/tcp_client.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | // Function to convert hex string to byte array 8 | void hexStringToByteArray(const char* hexString, unsigned char* byteArray, size_t* byteArrayLength) { 9 | size_t hexLength = strlen(hexString); 10 | *byteArrayLength = hexLength / 2; 11 | for (size_t i = 0; i < *byteArrayLength; i++) { 12 | sscanf(hexString + 2*i, "%2hhx", &byteArray[i]); 13 | } 14 | } 15 | 16 | int main(int argc, char *argv[]) { 17 | if (argc != 2) { 18 | fprintf(stderr, "Usage: %s \n", argv[0]); 19 | return EXIT_FAILURE; 20 | } 21 | 22 | const char* hexString = argv[1]; 23 | size_t byteArrayLength; 24 | unsigned char byteArray[1024]; // Buffer to hold the byte array 25 | 26 | hexStringToByteArray(hexString, byteArray, &byteArrayLength); 27 | 28 | int sockfd; 29 | struct sockaddr_in serverAddr; 30 | 31 | // Create socket 32 | if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { 33 | perror("Socket creation error"); 34 | return EXIT_FAILURE; 35 | } 36 | 37 | serverAddr.sin_family = AF_INET; 38 | serverAddr.sin_port = htons(1111); 39 | 40 | // Convert IPv4 and IPv6 addresses from text to binary form 41 | if (inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr) <= 0) { 42 | perror("Invalid address/ Address not supported"); 43 | return EXIT_FAILURE; 44 | } 45 | 46 | // Connect to the server 47 | if (connect(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) { 48 | perror("Connection failed"); 49 | return EXIT_FAILURE; 50 | } 51 | 52 | // Send the byte array to the server 53 | send(sockfd, byteArray, byteArrayLength, 0); 54 | printf("Data sent to server\n"); 55 | 56 | // Close the socket 57 | close(sockfd); 58 | 59 | return EXIT_SUCCESS; 60 | } 61 | -------------------------------------------------------------------------------- /dozord/nightshift-mqtt.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | #ifndef NIGHTSHIFT_MQTT_H 18 | #define NIGHTSHIFT_MQTT_H 19 | 20 | #define MQTT_KEEPALIVE_SEC 60 21 | #define MQTT_RECONNECT_SEC 3 22 | 23 | // publish 24 | #define ACK_TOPIC "/nightshift/notify" 25 | // publish 26 | #define REPORT_TOPIC "/nightshift/sites/%d/reports" 27 | // publish 28 | #define EVENT_TOPIC "/nightshift/sites/%d/events" 29 | // publish 30 | #define HEARBEAT_TOPIC "/nightshift/sites/%d/notify" 31 | // publish 32 | #define SECTION_TOPIC "/nightshift/sites/%d/sections/%s/events" 33 | // publish 34 | #define ZONE_TOPIC "/nightshift/sites/%d/zones/%s/events" 35 | // publish 36 | #define COMMAND_RESULT_TOPIC "/nightshift/sites/%d/commandresults" 37 | // publish 38 | #define DISCONNECTED_TOPIC "/nightshift/sites/%d/disconnected" 39 | // publish 40 | #define ARM_DISARM_TOPIC "/nightshift/sites/%d/status" 41 | 42 | // subscribe 43 | #define COMMAND_TOPIC "/nightshift/sites/%d/command" 44 | 45 | #define ACK_JSON "{\"name\":\"nightshift\",\"agentID\":\"%s\",\"siteId\":%d}" // {"name":"nightshift","agentId":"80d7be61-d81d-4aac-9012-6729b6392a89","siteId":4294967295} 46 | #define MESSAGE_JSON "{\"agentID\": \"%s\",\"message\": %s}" 47 | #define PAYLOAD_JSON "{\"deviceIp\":\"%s\",\"received\":\"%s\",\"payload\":%s}\n" 48 | 49 | #define WILL_MESSAGE "Guard device at site %d is offline" 50 | 51 | struct MQTTConfig { 52 | char host[50]; // MQTT_HOST 53 | unsigned int port; // MQTT_PORT 54 | unsigned int siteId; 55 | char agentId[36]; 56 | }; 57 | 58 | struct MQTTThreadPayload { 59 | struct MQTTConfig * mqttConfig; 60 | }; 61 | 62 | void initializeMQTT(struct MQTTConfig* mqttConfig, void (*on_message)); 63 | void disconnectMQTT(); 64 | void publish(char * topic, char * message, bool retainFlag); 65 | 66 | #endif 67 | 68 | -------------------------------------------------------------------------------- /dozord/logger.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include "liblogger.h" 23 | 24 | void getISODateTime(char* buffer, size_t bufferSize) { 25 | // Get current time 26 | struct timeval tv; 27 | gettimeofday(&tv, NULL); // Get time including microseconds 28 | 29 | time_t t = tv.tv_sec; 30 | struct tm tm = *localtime(&t); // Convert to local time 31 | 32 | // Get timezone offset in hours and minutes 33 | char timezoneSign = (tm.tm_gmtoff < 0) ? '-' : '+'; 34 | int timezoneHours = (int)(tm.tm_gmtoff / 3600); 35 | int timezoneMinutes = (int)((tm.tm_gmtoff % 3600) / 60); 36 | 37 | // Format the date and time as YYYY-MM-DDTHH:MM:SS.sss±hh:mm 38 | snprintf(buffer, bufferSize, 39 | "%04d-%02d-%02dT%02d:%02d:%02d.%03ld%c%02d:%02d", 40 | tm.tm_year + 1900, 41 | tm.tm_mon + 1, 42 | tm.tm_mday, 43 | tm.tm_hour, 44 | tm.tm_min, 45 | tm.tm_sec, 46 | tv.tv_usec / 1000, // Convert microseconds to milliseconds 47 | timezoneSign, 48 | timezoneHours, 49 | timezoneMinutes); 50 | } 51 | 52 | void prettyLogger(LogLevel level, const char* source, const char* message) { 53 | if (level < get_log_level()) { 54 | return; 55 | } 56 | 57 | char dateTimeBuffer[30]; // Buffer to hold the timestamp in ISO 8601 format 58 | getISODateTime(dateTimeBuffer, sizeof(dateTimeBuffer)); 59 | 60 | // Concatenate timestamp with the log message 61 | char logMessage[1024]; // Buffer for the final log message 62 | snprintf(logMessage, 1024, "[%s] %s [%s] %s", dateTimeBuffer, logLevel2Str(level), source, message); 63 | 64 | // Print the log message 65 | printf("%s\n", logMessage); 66 | } -------------------------------------------------------------------------------- /dozord/app-config.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "app-config.h" 6 | 7 | void displayHelp() 8 | { 9 | printf("dozord\nUsage: ./dozord -s -l -k -m -p -d\n"); 10 | } 11 | 12 | 13 | void processCommandLineOptions(int argc, char **argv, struct AppConfig *appConfig) { 14 | int opt; 15 | static const char *optString = "l:k:s:m:p:h?:d"; 16 | 17 | appConfig->logLevel = LOG_LEVEL_INFO; 18 | 19 | while ((opt = getopt(argc, argv, optString)) != -1) { 20 | switch (opt) { 21 | case 'l': 22 | appConfig->socketConfig.port = strtol(optarg, 0, 10); 23 | break; 24 | 25 | case 'k': 26 | strncpy(appConfig->pinCode, optarg, sizeof(appConfig->pinCode)); 27 | break; 28 | 29 | case 's': 30 | appConfig->mqttConfig.siteId = strtol(optarg, 0, 10); 31 | break; 32 | 33 | case 'm': 34 | strncpy(appConfig->mqttConfig.host, optarg, sizeof(appConfig->mqttConfig.host)); 35 | break; 36 | 37 | case 'p': 38 | appConfig->mqttConfig.port = strtol(optarg, 0, 10); 39 | break; 40 | 41 | case 'h': 42 | case '?': 43 | displayHelp(); 44 | exit(0); 45 | break; 46 | 47 | case 'd': 48 | appConfig->logLevel = LOG_LEVEL_DEBUG; 49 | break; 50 | 51 | default: 52 | abort(); 53 | } 54 | } 55 | } 56 | 57 | void initializeAppConfig(struct AppConfig *appConfig) { 58 | appConfig->socketConfig.port = DEFAULT_PORT; 59 | appConfig->siteId = 0; 60 | strncpy(appConfig->pinCode, "", sizeof(appConfig->pinCode)); 61 | appConfig->socketConfig.on_message = NULL; 62 | 63 | appConfig->mqttConfig.siteId = 0; 64 | strncpy(appConfig->mqttConfig.host, MQTT_HOST, sizeof(appConfig->mqttConfig.host)); 65 | appConfig->mqttConfig.port = MQTT_PORT; 66 | strncpy(appConfig->mqttConfig.agentId, AGENT_ID, sizeof(appConfig->mqttConfig.agentId)); 67 | 68 | // Check environment variables 69 | char* envSiteId = getenv("DOZOR_SITE_ID"); 70 | char* envSiteKey = getenv("DOZOR_SITE_KEY"); 71 | 72 | if (envSiteId != NULL) { 73 | appConfig->siteId = strtol(envSiteId, NULL, 10); 74 | appConfig->mqttConfig.siteId = appConfig->siteId; 75 | } 76 | 77 | if (envSiteKey != NULL) { 78 | strncpy(appConfig->pinCode, envSiteKey, sizeof(appConfig->pinCode)); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /libdozor/rc4.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include "rc4.h" 23 | #include "liblogger.h" 24 | 25 | #define POOL_SIZE 256 26 | 27 | void getCryptoSession(CryptoSession * crypto, const uint8_t* key) 28 | { 29 | const unsigned short int key_length = 16; 30 | unsigned short int i = 0; 31 | unsigned short int j = 0; 32 | unsigned short int temp = 0; 33 | 34 | for (i = 0; i < POOL_SIZE; i++) 35 | { 36 | crypto->pool[i] = i; 37 | } 38 | 39 | for (i=0; i < POOL_SIZE; i++) 40 | { 41 | j = (j + crypto->pool[i] + key[i % 16]) % POOL_SIZE; 42 | swap(crypto->pool, i, j); 43 | } 44 | } 45 | 46 | /** 47 | * encrypt/decrypt function 48 | */ 49 | void codec(unsigned char* data, CryptoSession * crypto, const size_t msgLength) 50 | { 51 | unsigned short int i = crypto->iterator; 52 | unsigned short int j = crypto->pointer; 53 | unsigned short int kword; 54 | unsigned short int data_index; 55 | unsigned char old; 56 | 57 | // logger(LOG_LEVEL_DEBUG, "rc4(codec)", "called for - %s\n", data); 58 | // logger(LOG_LEVEL_DEBUG, "rc4(codec)", "iterator %d\n", i); 59 | // logger(LOG_LEVEL_DEBUG, "rc4(codec)", "pointer %d\n", j); 60 | 61 | // convert data 62 | for (data_index = 0; data_index < msgLength; data_index++) { 63 | old = data[data_index]; 64 | i = (i + 1) % POOL_SIZE; 65 | j = (j + crypto->pool[i]) % POOL_SIZE; 66 | swap(crypto->pool, i, j); 67 | kword = crypto->pool[(crypto->pool[i] + crypto->pool[j]) % POOL_SIZE]; 68 | data[data_index] = old ^ kword; 69 | 70 | // logger(LOG_LEVEL_DEBUG, "rc4(codec)", "[%d] 0x%x -> 0x%x\n", data_index, old, data[data_index]); 71 | } 72 | 73 | crypto->iterator = i; 74 | crypto->pointer = j; 75 | } 76 | 77 | static void swap(unsigned short int* pool, const unsigned short int src, const unsigned short int dst) 78 | { 79 | unsigned short int temp = pool[src]; 80 | pool[src] = pool[dst]; 81 | pool[dst] = temp; 82 | } -------------------------------------------------------------------------------- /tools/parser.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift. 3 | 4 | NightShift is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include "dozor.h" 24 | #include "liblogger.h" 25 | 26 | #define BUFFERSIZE 1024 27 | 28 | union rawMessage { 29 | struct { 30 | char aLength[3]; 31 | uint8_t payload[BUFFERSIZE - sizeof(char) * 3]; 32 | } data; 33 | uint8_t raw[BUFFERSIZE]; 34 | }; 35 | 36 | void hexstr2char(char * dest, const char *hexstr, const size_t len) 37 | { 38 | int j; 39 | size_t i; 40 | 41 | for (i=0, j=0; j \n"); 59 | return 0; 60 | } 61 | 62 | msgLength = strlen(argv[2]); 63 | if (msgLength % 2 != 0) 64 | { 65 | fprintf(stderr, "Message length not odd\n"); 66 | return -1; 67 | } 68 | 69 | data = malloc(sizeof(char) * BUFFERSIZE); 70 | if (data == NULL) 71 | { 72 | fprintf(stderr, "Unable to allocate memory for data - %s\n", strerror(errno)); 73 | return -1; 74 | } 75 | 76 | hexstr2char(data, argv[2], msgLength / 2); 77 | 78 | memcpy(&packet, data, sizeof(char) * msgLength / 2); 79 | 80 | crypto = malloc(sizeof(CryptoSession)); 81 | if (crypto == NULL) 82 | { 83 | free(data); 84 | fprintf(stderr, "Unable to allocate memory for crypto session: %s\n", strerror(errno)); 85 | return -1; 86 | } 87 | 88 | set_log_level(LOG_LEVEL_INFO); 89 | 90 | Events * events = dozor_unpackV2(crypto, data, argv[1]); 91 | if (events != NULL && events->errorCode == 0) { 92 | for (int index = 0; index < events->length; index++) { 93 | logger(LOG_LEVEL_INFO, "parser", "%s", events->items[index].event); 94 | } 95 | 96 | free(data); 97 | free(crypto); 98 | return -1; 99 | } 100 | 101 | free(data); 102 | free(crypto); 103 | } -------------------------------------------------------------------------------- /libdozor/dozor-crypto.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #ifndef DEVICE_CRYPTO_H 19 | #define DEVICE_CRYPTO_H 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include "device-event.h" 27 | #include "session.h" 28 | 29 | // site position 30 | #define SITE 4 31 | // seed position 32 | #define SEED 6 33 | // closed part position 34 | #define CLOSED_START 10 35 | #define DEVICE_MESSAGE_LENGTH 4 36 | #define MAGIC_MESSAGE_START_FLAG 0x0d 37 | #define MAGIC_DECRYPTED_TAILEND 0x21 38 | 39 | #define ERROR_LENGTH_MISMATCH -1 40 | #define ERROR_NO_START_FLAG -2 41 | #define ERROR_DECRYPT_FAIL -3 42 | #define ERROR_MESSAGE_TOO_SHORT -4 43 | #define ERROR_CRYPTO_SESSION_NOT_INITIALIZED -5 44 | 45 | #define MAX_DEVICE_RECORDS 256 46 | 47 | typedef struct DEVICE_INFO { 48 | uint8_t tag; 49 | short unsigned int channel:4; 50 | short unsigned int sim: 4; 51 | uint8_t voltage; 52 | short unsigned int gsm_signal: 6; 53 | short unsigned int extra_index: 2; 54 | uint8_t extra_value; 55 | } DeviceInfo; 56 | 57 | typedef struct DOZOR_MESSAGE { 58 | struct { 59 | char alength[3]; 60 | char magic; 61 | uint16_t site; 62 | uint32_t seed; 63 | } opened; 64 | union { 65 | struct { 66 | DeviceInfo info; 67 | uint8_t messages[1]; 68 | }; 69 | // FIXME: absolutely random big number :-) 70 | uint8_t raw[1024]; 71 | } closed; 72 | } DozorMessage; 73 | 74 | typedef struct DOZOR_REPORT { 75 | uint8_t eventTotals; 76 | DeviceEvent events[MAX_DEVICE_RECORDS]; 77 | DeviceInfo info; 78 | uint16_t site; 79 | } DozorReport; 80 | 81 | typedef struct DOZOR_RESPONSE { 82 | uint32_t time; 83 | uint8_t unknownOne; 84 | uint8_t unknownTwo; 85 | unsigned char encrypted[124]; 86 | } DozorResponse; 87 | union PKEY 88 | { 89 | uint64_t x[2]; 90 | uint32_t y[4]; 91 | uint8_t z[16]; 92 | }; 93 | 94 | // Initialize connection state 95 | short int initializeDozorCrypto(CryptoSession * crypto, 96 | const unsigned char* userKey, const unsigned char * data, 97 | const size_t dataLength); 98 | 99 | // Return encrypted data 100 | short int encrypt(unsigned char* data, CryptoSession * crypto, const size_t dataLength); 101 | 102 | // Return decrypted device report 103 | short int getReport(DozorReport * report, CryptoSession * crypto, const unsigned char * data, const size_t dataLength); 104 | 105 | union PKEY getSeededKey(const wchar_t* key, const uint32_t seed, const uint16_t site); 106 | 107 | #endif -------------------------------------------------------------------------------- /libdozor/event.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #ifndef EVENT_H 19 | #define EVENT_H 20 | #include 21 | #include "device-event.h" 22 | #include "dozor-crypto.h" 23 | #include "utils.h" 24 | 25 | #define EVENT_COUNT 64 26 | #define EVENT_TIMESTAMP_LENGTH 25 27 | #define MAX_EVENT_NAME_LENGTH 25 28 | #define MAX_SECTION_LENGTH 22 // like, "[1, 2, 3, 4, 5, 7, 8]" 29 | #define COMMAND_RESULT_COUNT 8 30 | #define MAX_COMMAND_RESULT_NAME_LENGTH 32 31 | #define COMMON_EVENT_SCOPE "Common" 32 | #define AUTH_EVENT_SCOPE "Auth" 33 | #define USER_EVENT_SCOPE "User" 34 | #define SECURITY_EVENT_SCOPE "Security" 35 | #define KEEP_ALIVE_EVENT_SCOPE "KeepAlive" 36 | #define DEFAULT_DATA_POSITION 0 37 | #define REPORT_TEMP_DATA_POSITION 1 38 | #define USER_DATA_POSITION 3 39 | #define COMMAND_RESULT_DATA_POSITION 4 40 | #define VERSION_DATA_POSITION 1 41 | #define VERSION_MASK 0x7 42 | 43 | #define ENUM_EVENT_TYPE_COMMONEVENT 1 44 | #define ENUM_EVENT_TYPE_KEEPALIVE 2 45 | #define ENUM_EVENT_TYPE_COMMAND_RESPONSE 4 46 | #define ENUM_EVENT_TYPE_REPORT 8 47 | #define ENUM_EVENT_TYPE_ZONEINFO 16 48 | #define ENUM_EVENT_TYPE_SECTIONINFO 32 49 | #define ENUM_EVENT_TYPE_USERAUTHINFO 64 50 | #define ENUM_EVENT_TYPE_ARM_DISARM 96 51 | 52 | typedef struct { 53 | char event[1024]; 54 | // ENUM_EVENT_TYPE_* 55 | unsigned int eventType; 56 | // Event source id depends on event type, might be - zone, section, user 57 | char sourceId[4]; 58 | unsigned int siteId; 59 | } EventInfo; 60 | 61 | typedef struct COMMON_EVENT { 62 | uint8_t typeId; 63 | uint8_t site; 64 | char timestamp[EVENT_TIMESTAMP_LENGTH]; 65 | char data[256]; 66 | } CommonEvent; 67 | 68 | typedef struct EVENTS { 69 | EventInfo items[MAX_DEVICE_RECORDS]; 70 | uint8_t length; 71 | int errorCode; 72 | } Events; 73 | 74 | void getKeepAliveEvent(EventInfo* eventInfo, uint8_t site, DeviceInfo* info); 75 | void convertDeviceEventToCommon(EventInfo* eventInfo, uint8_t site, DeviceEvent* deviceEvent); 76 | static char * getFirmwareVersionEventData(uint8_t type, uint8_t * data, uint8_t len); 77 | static char * getCommandEventData(uint8_t type, uint8_t * data, uint8_t len); 78 | static char * getReportEventData(uint8_t type, uint8_t * data, uint8_t len); 79 | static char * getAuthEventData(uint8_t type, uint8_t * data, uint8_t len); 80 | static char * getSecurityEventData(uint8_t type, uint8_t * data, uint8_t len); 81 | static char * getCommonEventData(uint8_t type, uint8_t * data, uint8_t len, char * scope); 82 | static char * getZoneEventData(uint8_t type, uint8_t * data, uint8_t len); 83 | static char * getSectionEventData(uint8_t type, uint8_t * data, uint8_t len); 84 | static char * getData(uint8_t * data, uint8_t index, uint8_t len); 85 | static char * getEventNameByType(uint8_t type); 86 | #endif -------------------------------------------------------------------------------- /libdozor/device-event.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include "liblogger.h" 24 | #include "device-event.h" 25 | 26 | static const unsigned char MSGDATASIZE[68] = { 27 | // 0 - 4 28 | 0, 2, 2, 1, 1, 29 | // 5 - 9 30 | 1, 1, 1, 1, 1, 31 | // 10 - 14 32 | 1, 1, 1, 1, 1, 33 | // 15 - 19 34 | 1, 1, 4, 0, 0, 35 | // 20 - 24 36 | 0, 1, 1, 0, 0, 37 | // 25 - 29 38 | 0, 1, 1, 1, 1, 39 | // 30 - 34 40 | 1, 1, 1, 0, 2, 41 | // 35 - 39 42 | 2, 4, 4, 0, 16, 43 | // 40 - 44 44 | 1, 0, 17, 1, 1, 45 | // 45 - 49 46 | 1, 1, 1, 1, 1, 47 | // 50 - 54 48 | 1, 1, 1, 1, 1, 49 | // 55 - 59 50 | 1, 1, 4, 4, 1, 51 | // 60 - 64 52 | 1, 1, 1, 5, 3, 53 | // 65 - 68 54 | 37, 4, 73 }; 55 | 56 | static void getDeviceEvent(DeviceEvent * deviceEvent, const uint8_t * raw, unsigned short int eventDataSize) 57 | { 58 | deviceEvent->type = raw[0]; 59 | deviceEvent->dataLength = eventDataSize; 60 | 61 | memcpy(&deviceEvent->time, &raw[1], sizeof(deviceEvent->time)); 62 | memcpy(&deviceEvent->data, &raw[MESSAGE_ALIGN_SIZE], (size_t) eventDataSize); 63 | } 64 | 65 | unsigned short int getDeviceEvents(const uint8_t * raw, long int bufSize, DeviceEvent events[]) 66 | { 67 | long int totalLength = bufSize; 68 | unsigned short int index = 0; 69 | unsigned short int eventSize = 0; 70 | unsigned short int eventCount = 0; 71 | unsigned short int dataIndex = 0; 72 | 73 | DeviceEvent * deviceEvent = malloc(sizeof(DeviceEvent)); 74 | 75 | if (deviceEvent == NULL) 76 | { 77 | fprintf(stderr, "***device-event.c: Unable to allocate memory for device event: %s\n", strerror(errno)); 78 | return 0; 79 | } 80 | 81 | memset(deviceEvent, 0, sizeof(DeviceEvent)); 82 | 83 | if (bufSize == 0) 84 | { 85 | logger(LOG_LEVEL_DEBUG, "device-event(getDeviceEvents)", "No events\n"); 86 | 87 | free(deviceEvent); 88 | return 0; 89 | } 90 | 91 | while (totalLength > 0) 92 | { 93 | eventSize = MSGDATASIZE[raw[index]] + MESSAGE_ALIGN_SIZE; 94 | 95 | char *hexStr = (char *)malloc(eventSize * 2 + 1); 96 | if (hexStr) { 97 | 98 | blobToHexStr(hexStr, &raw[index], eventSize); 99 | 100 | logger(LOG_LEVEL_DEBUG, "device-event(getDeviceEvents)", "[%d] event id 0x%x: %s", eventCount, raw[index], hexStr); 101 | 102 | free(hexStr); 103 | } 104 | 105 | getDeviceEvent(deviceEvent, &raw[index], MSGDATASIZE[raw[index]]); 106 | memcpy(&events[eventCount], deviceEvent, sizeof(DeviceEvent)); 107 | 108 | eventCount += 1; 109 | index = index + eventSize; 110 | totalLength = totalLength - eventSize; 111 | } 112 | 113 | free(deviceEvent); 114 | return eventCount; 115 | } 116 | -------------------------------------------------------------------------------- /Roadmap.md: -------------------------------------------------------------------------------- 1 | # NightShift - свободная реализация сервера управления Астра Дозор 2 | 3 | ## План разработки 4 | 5 | * ~~0.9 - реализация базового MQTT-клиента (публикация событий в соответствующие топики, обработка команд, LWM на основе Heartbeat-сообщений)~~ 6 | * ~~0.9.5 - daemonize, корректное завершение по SIG_KILL, принудительное закрытие сокетов при выходе, логирование в syslog/отдельный файл~~ 7 | * 1.0 - вынос конфигурации в отдельный файл, реализация поддержки TLS и сертификатов для MQTT 8 | 9 | ## Wishlist 10 | * конфигурируемые топики подписки на команды и события 11 | 12 | ## Issues 13 | * неверная информация о дате для события типа SectionWarning: 14 | ```json 15 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 17:47:08 2022","payload":{"site":00,"typeId":13,"timestamp":"Sun Dec 4 17:47:07 2022","data":"1035","zone":16,"event":"ZoneDelayedAlarm","scope":"Zone"}} 16 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 17:47:08 2022","payload":{"site":00,"typeId":53,"timestamp":"Mon Mar 17 06:18:57 2003","data":"0621","section":6,"event":"SectionWarning","scope":"Section"}} 17 | ``` 18 | * SectionAlarm 19 | ```json 20 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 18:52:46 2022","payload":{"site":00,"typeId":15,"timestamp":"Sun Dec 4 18:52:46 2022","data":"0D37","zone":13,"event":"ZoneAlarm","scope":"Zone"}} 21 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 18:52:46 2022","payload":{"site":00,"typeId":55,"timestamp":"Sun Mar 27 12:51:29 2089","data":"0821","section":8,"event":"SectionAlarm","scope":"Section"}} 22 | ``` 23 | * SectionFail 24 | ```json 25 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 18:52:25 2022","payload":{"site":00,"typeId":12,"timestamp":"Sun Dec 4 18:52:25 2022","data":"0D34","zone":13,"event":"ZoneFail","scope":"Zone"}} 26 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 18:52:25 2022","payload":{"site":00,"typeId":52,"timestamp":"Wed Jan 19 17:26:41 2022","data":"0821","section":8,"event":"SectionFail","scope":"Section"}} 27 | ``` 28 | * Вход и выход из режима администрирования 29 | ```json 30 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 19:07:18 2022","payload":{"site":00,"typeId":59,"timestamp":"Thu May 20 21:34:25 1999","data":"0021","event":"SystemMaintenance","scope":"Security"}} 31 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 19:07:20 2022","payload":{"site":00,"typeId":37,"timestamp":"Sun Dec 12 21:12:49 2088","data":"0214000021","temp":20,"event":"Report","scope":"Common"}} 32 | 33 | 34 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 19:10:42 2022","payload":{"site":00,"typeId":59,"timestamp":"Tue Jan 27 02:24:17 2071","data":"0121","event":"SystemMaintenance","scope":"Security"}} 35 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 19:10:52 2022","payload":{"site":00,"typeId":59,"timestamp":"Tue Aug 8 03:02:41 2051","data":"0021","event":"SystemMaintenance","scope":"Security"}} 36 | 37 | 38 | // изменения работы зоны 13, use - no 39 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 19:22:26 2022","payload":{"site":00,"typeId":37,"timestamp":"Fri Jun 29 16:01:21 2063","data":"000C500021","temp":12,"event":"Report","scope":"Common"}} 40 | 41 | // изменения работы зоны 13, use - yes, section 8 42 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 19:48:15 2022","payload":{"site":00,"typeId":37,"timestamp":"Fri Jun 29 16:01:21 2063","data":"000C770021","temp":12,"event":"Report","scope":"Common"}} 43 | 44 | 45 | {"deviceIp":"aa.bb.cc.dd","received":"Sun Dec 4 20:06:50 2022","payload":{"site":00,"typeId":59,"timestamp":"Sun Mar 11 12:06:41 2040","data":"0021","event":"SystemMaintenance","scope":"Security"}} 46 | ``` 47 | 48 | * Странные события 49 | ```json 50 | {"site":00,"typeId":21,"timestamp":"Sat Jul 12 21:06:25 2087","data":"0021","event":"KeepAliveEvent","scope":"Common"} 51 | {"site":00,"typeId":22,"timestamp":"Mon Jan 1 03:00:33 2001","data":"0021","event":"KeepAliveEvent","scope":"Common"} 52 | {"site":00,"typeId":0,"timestamp":"Mon Jan 1 03:00:33 2001","data":"21","event":"UnknownEvent-0x0","scope":"Common"} 53 | {"site":00,"typeId":37,"timestamp":"Mon Jan 1 03:00:33 2001","data":"0210000021","temp":16,"event":"Report","scope":"Common"} 54 | ``` -------------------------------------------------------------------------------- /libdozor/dozor-crypto.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include "liblogger.h" 21 | #include "dozor-crypto.h" 22 | #include "utils.h" 23 | #include "rc4.h" 24 | 25 | short int initializeDozorCrypto(CryptoSession * crypto, 26 | const unsigned char* userKey, const unsigned char * data, 27 | const size_t dataLength 28 | ) 29 | { 30 | wchar_t key[strlen(userKey)]; 31 | union PKEY seededKey; 32 | uint32_t seed; 33 | uint8_t site; 34 | unsigned short int index; 35 | 36 | if (crypto == NULL) { 37 | return ERROR_CRYPTO_SESSION_NOT_INITIALIZED; 38 | } 39 | 40 | crypto->iterator = 0; 41 | crypto->pointer = 0; 42 | 43 | if (dataLength < SEED + 2) { 44 | logger(LOG_LEVEL_DEBUG, "dozor-crypto(initializeDozorCrypto)", "ERROR: message too short - %ld!", dataLength); 45 | return ERROR_MESSAGE_TOO_SHORT; 46 | } 47 | 48 | // convert string key to wchar[] 49 | char2utf8(key, userKey); 50 | 51 | memcpy(&seed, &data[SEED], sizeof(uint32_t)); 52 | memcpy(&site, &data[SITE], sizeof(uint8_t)); 53 | 54 | // enrich key with seed and site 55 | seededKey = getSeededKey(key, seed, site); 56 | 57 | getCryptoSession(crypto, (unsigned char*) &(seededKey.z)); 58 | 59 | 60 | logger(LOG_LEVEL_DEBUG, "dozor-crypto(initializeDozorCrypto)", "Enriched key START"); 61 | for (index = 0; index < 4; index++) 62 | { 63 | logger(LOG_LEVEL_DEBUG, "dozor-crypto(initializeDozorCrypto)", "[%d]: 0x%x", index, seededKey.y[index]); 64 | } 65 | logger(LOG_LEVEL_DEBUG, "dozor-crypto(initializeDozorCrypto)", "Enriched key END"); 66 | 67 | return 0; 68 | } 69 | 70 | short int encrypt(unsigned char* data, CryptoSession * crypto, const size_t dataLength) 71 | { 72 | if (crypto == NULL) 73 | { 74 | return ERROR_CRYPTO_SESSION_NOT_INITIALIZED; 75 | } 76 | 77 | codec(data, crypto, dataLength); 78 | return 0; 79 | } 80 | 81 | short int getReport(DozorReport * report, CryptoSession * crypto, const unsigned char * data, const size_t dataLength) 82 | { 83 | DozorMessage message; 84 | DeviceEvent events[MAX_EVENTS_PER_DEVICE]; 85 | unsigned short int index; 86 | long int actualDataLength = 0; 87 | long int closedLength = 0; 88 | 89 | if (crypto == NULL) 90 | { 91 | return ERROR_CRYPTO_SESSION_NOT_INITIALIZED; 92 | } 93 | 94 | // convert data to struct 95 | memcpy(&message.opened, &data[0], sizeof(message.opened)); 96 | memcpy(&message.opened.seed, &data[SEED], sizeof(message.opened.seed)); 97 | memcpy(&message.closed.raw, &data[CLOSED_START], sizeof(message.closed.raw)); 98 | 99 | actualDataLength = strtol(message.opened.alength, 0, 10); 100 | closedLength = actualDataLength - SEED; 101 | 102 | if (dataLength - DEVICE_MESSAGE_LENGTH != actualDataLength) 103 | { 104 | logger(LOG_LEVEL_ERROR, "dozor-crypto(getReport)", "Incoming message length not equal calculated length (%ld != %d)", actualDataLength, dataLength - DEVICE_MESSAGE_LENGTH != actualDataLength); 105 | 106 | return ERROR_LENGTH_MISMATCH; 107 | } 108 | 109 | if (message.opened.magic != MAGIC_MESSAGE_START_FLAG) 110 | { 111 | logger(LOG_LEVEL_ERROR, "dozor-crypto(getReport)", "Incoming message magic number not exists"); 112 | return ERROR_NO_START_FLAG; 113 | } 114 | 115 | logger(LOG_LEVEL_DEBUG, "dozor-crypto(getReport)", "New Dozor Message"); 116 | logger(LOG_LEVEL_DEBUG, "dozor-crypto(getReport)", "Total message length - %ld", dataLength); 117 | logger(LOG_LEVEL_DEBUG, "dozor-crypto(getReport)", "Length from message - %ld", actualDataLength); 118 | logger(LOG_LEVEL_DEBUG, "dozor-crypto(getReport)", "Magic field - %d", message.opened.magic); 119 | logger(LOG_LEVEL_DEBUG, "dozor-crypto(getReport)", "Site - %d", message.opened.site); 120 | logger(LOG_LEVEL_DEBUG, "dozor-crypto(getReport)", "Seed - 0x%x", message.opened.seed); 121 | 122 | codec((unsigned char*) &message.closed, crypto, closedLength); 123 | 124 | // check is decryption correct - last two bytes should be 0x21 125 | closedLength = closedLength - 2; 126 | 127 | for (index = 0; index < closedLength; index++) 128 | { 129 | char logRecord[10]; 130 | // sprintf(logRecord, "[%d]: 0x%x", index, message.closed.raw[index]); 131 | // logger(LOG_LEVEL_DEBUG, "dozor-crypto(getReport)", logRecord); 132 | } 133 | 134 | if (message.closed.raw[closedLength] != MAGIC_DECRYPTED_TAILEND) 135 | { 136 | logger(LOG_LEVEL_ERROR, "dozor-crypto(getReport)", "MAGIC_DECRYPTED_TAILEND #1 check %#x != %#x at position %ld", message.closed.raw[closedLength], MAGIC_DECRYPTED_TAILEND, closedLength); 137 | 138 | return ERROR_DECRYPT_FAIL; 139 | } 140 | 141 | if (message.closed.raw[closedLength + 1] != MAGIC_DECRYPTED_TAILEND) 142 | { 143 | logger(LOG_LEVEL_ERROR, "dozor-crypto(getReport)", "MAGIC_DECRYPTED_TAILEND #2 check %#x != %#x at position %ld", message.closed.raw[closedLength + 1], MAGIC_DECRYPTED_TAILEND, closedLength + 1); 144 | 145 | return ERROR_DECRYPT_FAIL; 146 | } 147 | 148 | report->eventTotals = getDeviceEvents(message.closed.messages, closedLength - 6, events); 149 | report->site = message.opened.site; 150 | 151 | memcpy(&(report->info), &message.closed.info, sizeof(message.closed.info)); 152 | memcpy(&(report->events), &events, sizeof(DeviceEvent) * report->eventTotals); 153 | 154 | return report->eventTotals; 155 | } 156 | 157 | union PKEY getSeededKey(const wchar_t* user_key, const uint32_t seed, const uint16_t site) 158 | { 159 | union PKEY preKey; 160 | unsigned short index; 161 | uint32_t x = seed >> 8; 162 | uint32_t s2 = seed >> 16; 163 | uint32_t s3 = seed >> 24; 164 | 165 | preKey.y[0] = seed; 166 | preKey.y[1] = user_key[0] | (uint32_t)user_key[1] << 8 | (uint32_t)user_key[2] << 16 | (uint32_t)user_key[3] << 24; 167 | preKey.y[2] = user_key[4] | (uint32_t)user_key[5] << 8 | (uint32_t)user_key[6] << 16 | (uint32_t)user_key[7] << 24; 168 | preKey.y[3] = (uint16_t) site; 169 | preKey.z[14] = (uint8_t) seed | x; 170 | preKey.z[15] = (uint8_t) s2 & s3; 171 | 172 | return preKey; 173 | } -------------------------------------------------------------------------------- /dozord/nightshift-mqtt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "nightshift-mqtt.h" 9 | #include "logger.h" 10 | 11 | bool GlobalMQTTConnected = false; 12 | bool shouldReconnect = false; 13 | pthread_t GlobalReconnectThread = 0; 14 | pthread_mutex_t GlobalMQTTConnectedLock; 15 | struct mosquitto * mosq = NULL; 16 | 17 | void publish(char * topic, char * message, bool retainFlag) { 18 | int rc = 0; 19 | char logMessage[2048]; 20 | 21 | if (GlobalMQTTConnected) { 22 | rc = mosquitto_publish(mosq, NULL, topic, strlen(message), message, 0, retainFlag); 23 | if (rc != MOSQ_ERR_SUCCESS) { 24 | snprintf(logMessage, sizeof(logMessage), "Failed to publish to topic \"%s\". Error code: %d", topic, rc); 25 | prettyLogger(LOG_LEVEL_ERROR, "MQTT", logMessage); 26 | } 27 | } else { 28 | // @todo build outgoing queue 29 | } 30 | } 31 | 32 | void* mqtt_thread_reconnect(void* args) 33 | { 34 | char logMessage[256]; 35 | int rc = 0; 36 | 37 | pthread_mutex_lock(&GlobalMQTTConnectedLock); 38 | if (!shouldReconnect) { 39 | pthread_mutex_unlock(&GlobalMQTTConnectedLock); 40 | pthread_exit(0); 41 | } 42 | pthread_mutex_unlock(&GlobalMQTTConnectedLock); 43 | 44 | int sleep_time = MQTT_RECONNECT_SEC; 45 | 46 | if(args == NULL) { 47 | pthread_exit(0); 48 | return 0; 49 | } 50 | 51 | if (mosq == NULL) { 52 | pthread_exit(0); 53 | return 0; 54 | } 55 | 56 | sleep_time += rand() % 20; 57 | 58 | snprintf(logMessage, sizeof(logMessage), "Connection lost. Reconnecting... %d sec", sleep_time); 59 | prettyLogger(LOG_LEVEL_INFO, "MQTT", logMessage); 60 | 61 | sleep(sleep_time); 62 | 63 | pthread_mutex_lock(&GlobalMQTTConnectedLock); 64 | if (!shouldReconnect) { 65 | pthread_mutex_unlock(&GlobalMQTTConnectedLock); 66 | pthread_exit(0); 67 | } 68 | 69 | if (!GlobalMQTTConnected) { 70 | pthread_mutex_unlock(&GlobalMQTTConnectedLock); 71 | 72 | rc = mosquitto_reconnect_async(mosq); 73 | if (rc != MOSQ_ERR_SUCCESS) { 74 | snprintf(logMessage, sizeof(logMessage), "Failed to reconnect. Error code: %d", rc); 75 | prettyLogger(LOG_LEVEL_ERROR, "MQTT", logMessage); 76 | } 77 | } 78 | 79 | pthread_mutex_unlock(&GlobalMQTTConnectedLock); 80 | pthread_exit(0); 81 | } 82 | 83 | void* mqtt_thread_connect(void* args) 84 | { 85 | struct MQTTConfig * mqttConfig = (struct MQTTConfig *) args; 86 | char agentInfo[90] = {0}; 87 | char commandTopic[100] = {0}; 88 | char logMessage[256]; 89 | int rc = 0; 90 | 91 | if (mqttConfig == NULL) { 92 | pthread_exit(0); 93 | return NULL; 94 | } 95 | 96 | snprintf(commandTopic, sizeof(commandTopic), COMMAND_TOPIC, mqttConfig->siteId); 97 | snprintf(agentInfo, sizeof(agentInfo), ACK_JSON, mqttConfig->agentId, mqttConfig->siteId); 98 | 99 | rc = mosquitto_subscribe(mosq, NULL, commandTopic, 0); 100 | if (rc != MOSQ_ERR_SUCCESS) { 101 | snprintf(logMessage, sizeof(logMessage), "Failed to subscribe to command topic \"%s\". Error code: %d", commandTopic, rc); 102 | prettyLogger(LOG_LEVEL_ERROR, "MQTT", logMessage); 103 | } else { 104 | snprintf(logMessage, sizeof(logMessage), "Command topic \"%s\" subscribed", commandTopic); 105 | prettyLogger(LOG_LEVEL_INFO, "MQTT", logMessage); 106 | } 107 | 108 | publish(ACK_TOPIC, agentInfo, false); 109 | 110 | pthread_exit(0); 111 | return NULL; 112 | } 113 | 114 | void mqtt_connect_callback(struct mosquitto *mosq, void *obj, int result) 115 | { 116 | char logMessage[256]; 117 | struct MQTTConfig * mqttConfig = (struct MQTTConfig *) obj; 118 | 119 | if (GlobalReconnectThread) { 120 | pthread_join(GlobalReconnectThread, NULL); 121 | GlobalReconnectThread = 0; 122 | } 123 | 124 | if (result == 0) 125 | { 126 | pthread_t conn = 0; 127 | 128 | snprintf(logMessage, sizeof(logMessage), "Connected %s:%d", mqttConfig->host, mqttConfig->port); 129 | prettyLogger(LOG_LEVEL_INFO, "MQTT", logMessage); 130 | 131 | pthread_mutex_lock(&GlobalMQTTConnectedLock); 132 | shouldReconnect = false; 133 | GlobalMQTTConnected = true; 134 | pthread_mutex_unlock(&GlobalMQTTConnectedLock); 135 | 136 | if (pthread_create(&conn, NULL, mqtt_thread_connect, mqttConfig) == 0) 137 | pthread_detach(conn); 138 | 139 | } else { 140 | 141 | prettyLogger(LOG_LEVEL_ERROR, "MQTT", "connection lost. Reconnecting..."); 142 | 143 | pthread_mutex_lock(&GlobalMQTTConnectedLock); 144 | shouldReconnect = true; 145 | GlobalMQTTConnected = false; 146 | pthread_mutex_unlock(&GlobalMQTTConnectedLock); 147 | 148 | if (pthread_create(&GlobalReconnectThread, NULL, mqtt_thread_reconnect, NULL) != 0) 149 | GlobalReconnectThread = 0; 150 | } 151 | } 152 | 153 | void initializeMQTT(struct MQTTConfig* mqttConfig, void (*on_message)) 154 | { 155 | char clientId[24] = {0}; 156 | char willTopic[36] = {0}; 157 | char willMessage[36] = {0}; 158 | bool retainFlag = true; 159 | char logMessage[256]; 160 | 161 | int rc = 0; 162 | 163 | pthread_mutex_init(&GlobalMQTTConnectedLock, NULL); 164 | 165 | mosquitto_lib_init(); 166 | 167 | sprintf(clientId, "nightshift_%d", getpid()); 168 | sprintf(willTopic, DISCONNECTED_TOPIC, mqttConfig->siteId); 169 | sprintf(willMessage, WILL_MESSAGE, mqttConfig->siteId); 170 | 171 | mosq = mosquitto_new(clientId, 1, mqttConfig); 172 | 173 | if (mosq != NULL) 174 | { 175 | mosquitto_connect_callback_set(mosq, mqtt_connect_callback); 176 | mosquitto_message_callback_set(mosq, on_message); 177 | 178 | mosquitto_will_set(mosq, willTopic, sizeof(willMessage), willMessage, 0, retainFlag); 179 | 180 | rc = mosquitto_loop_start(mosq); 181 | if (rc != MOSQ_ERR_SUCCESS) 182 | { 183 | snprintf(logMessage, sizeof(logMessage), "Unable to init MQTT %d", rc); 184 | prettyLogger(LOG_LEVEL_ERROR, "MQTT", logMessage); 185 | } 186 | 187 | rc = mosquitto_connect(mosq, mqttConfig->host, mqttConfig->port, MQTT_KEEPALIVE_SEC); 188 | 189 | if (rc != MOSQ_ERR_SUCCESS) 190 | { 191 | snprintf(logMessage, sizeof(logMessage), "Unable to connect %s:%d", mqttConfig->host, mqttConfig->port); 192 | prettyLogger(LOG_LEVEL_ERROR, "MQTT", logMessage); 193 | } 194 | 195 | } else { 196 | prettyLogger(LOG_LEVEL_ERROR, "MQTT", "Failed to create new Mosquitto instance."); 197 | mosquitto_lib_cleanup(); 198 | } 199 | } 200 | 201 | 202 | 203 | void disconnectMQTT() { 204 | int rc = 0; 205 | char logMessage[256]; 206 | 207 | prettyLogger(LOG_LEVEL_INFO, "MQTT", "Closing connection..."); 208 | 209 | if (GlobalReconnectThread) { 210 | pthread_join(GlobalReconnectThread, NULL); 211 | GlobalReconnectThread = 0; 212 | } 213 | 214 | if (mosq != NULL) { 215 | rc = mosquitto_disconnect(mosq); 216 | if (rc != MOSQ_ERR_SUCCESS) { 217 | if (rc == MOSQ_ERR_INVAL) { 218 | snprintf(logMessage, sizeof(logMessage), "Unable to disconnect. input parameters were invalid"); 219 | prettyLogger(LOG_LEVEL_ERROR, "MQTT", logMessage); 220 | } 221 | if (rc == MOSQ_ERR_NO_CONN) { 222 | snprintf(logMessage, sizeof(logMessage), "Unable to disconnect. client isnt connected to a broker"); 223 | prettyLogger(LOG_LEVEL_ERROR, "MQTT", logMessage); 224 | } 225 | } 226 | 227 | rc = mosquitto_loop_stop(mosq, true); 228 | if (rc != MOSQ_ERR_SUCCESS) { 229 | snprintf(logMessage, sizeof(logMessage), "Unable to stop loop. Error code: %d", rc); 230 | prettyLogger(LOG_LEVEL_ERROR, "MQTT", logMessage); 231 | } 232 | 233 | mosquitto_destroy(mosq); 234 | } 235 | 236 | mosquitto_lib_cleanup(); 237 | 238 | pthread_mutex_destroy(&GlobalMQTTConnectedLock); 239 | 240 | prettyLogger(LOG_LEVEL_INFO, "MQTT", "Closed."); 241 | } -------------------------------------------------------------------------------- /libdozor/libdozor.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include "dozor-crypto.h" 22 | #include "utils.h" 23 | #include "event.h" 24 | #include "dozor.h" 25 | #include "liblogger.h" 26 | 27 | union rawMessage { 28 | struct { 29 | char aLength[3]; 30 | uint8_t payload[BUFFERSIZE - sizeof(char) * 3]; 31 | } data; 32 | uint8_t raw[BUFFERSIZE]; 33 | }; 34 | 35 | Events * dozor_unpackV2(CryptoSession * crypto, uint8_t * raw, char * pinCode) 36 | { 37 | uint8_t * ptr; 38 | int c, n; 39 | int msgLength; 40 | unsigned short int index, dataIndex; 41 | short int result; 42 | union rawMessage packet; 43 | DozorReport * deviceReport; 44 | EventInfo * eventInfo; 45 | 46 | Events *events = malloc(sizeof(Events)); 47 | if (events == NULL) { 48 | fprintf(stderr, "Unable to allocate memory for events: %s\n", strerror(errno)); 49 | return NULL; // Return NULL on memory allocation failure 50 | } 51 | 52 | if (crypto == NULL) 53 | { 54 | fprintf(stderr, "Unable to allocate memory for crypto session: %s\n", strerror(errno)); 55 | events->errorCode = HANDLER_UNABLE_TO_ALLOCATE_MEMORY_CRYPTO_SESSION; 56 | return events; 57 | } 58 | 59 | memcpy(&packet, raw, BUFFERSIZE); 60 | 61 | msgLength = strtol(packet.data.aLength, 0, 10) + 4; 62 | 63 | short int initError = initializeDozorCrypto( 64 | crypto, 65 | (const unsigned char *) pinCode, 66 | (const unsigned char *) packet.raw, 67 | msgLength - 4 // strtol(packet.data.aLength, 0, 10) 68 | ); 69 | if (initError) 70 | { 71 | printf("Crypto session not initialized. Error - %d\n", initError); 72 | events->errorCode = initError; 73 | return events; 74 | } 75 | 76 | ptr = (uint8_t*) packet.raw; 77 | 78 | // Allocate memory for the hex string (2 characters per byte + 1 for null terminator) 79 | char *hexStr = (char *)malloc(msgLength * 2 + 1); 80 | if (!hexStr) { 81 | return NULL; // Return NULL if memory allocation fails 82 | } 83 | 84 | blobToHexStr(hexStr, ptr, msgLength); 85 | 86 | logger(LOG_LEVEL_DEBUG, "libdozor", "Incoming length - %d, message length - %d, %s", msgLength, msgLength - 4, hexStr); 87 | 88 | free(hexStr); 89 | 90 | deviceReport = malloc(sizeof(DozorReport)); 91 | if (deviceReport == NULL) 92 | { 93 | fprintf(stderr, "Unable to allocate memory for report: %s\n", strerror(errno)); 94 | events->errorCode = HANDLER_UNABLE_TO_ALLOCATE_MEMORY_REPORT; 95 | return events; 96 | } 97 | 98 | memset(deviceReport, 0, sizeof(DozorReport)); 99 | 100 | result = getReport(deviceReport, crypto, (const unsigned char *) packet.raw, msgLength); 101 | if ( result < 0) 102 | { 103 | fprintf(stderr, "ERROR: Unable to recognize message!!! Error - %d\n", result); 104 | free(deviceReport); 105 | events->errorCode = HANDLER_UNABLE_TO_RECOGNIZE_MESSAGE; 106 | return events; 107 | } 108 | 109 | logger(LOG_LEVEL_DEBUG, "libdozor", "Total %d events found", deviceReport->eventTotals); 110 | 111 | if (deviceReport->eventTotals == 0) 112 | { 113 | eventInfo = malloc(sizeof(EventInfo)); 114 | if (eventInfo == NULL) 115 | { 116 | fprintf(stderr, "Unable to allocate memory for event info structure: %s\n", strerror(errno)); 117 | return HANDLER_UNABLE_TO_ALLOCATE_MEMORY_REPORT; 118 | } 119 | 120 | memset(eventInfo, 0, sizeof(EventInfo)); 121 | 122 | getKeepAliveEvent(eventInfo, deviceReport->site, &(deviceReport->info)); 123 | 124 | logger(LOG_LEVEL_DEBUG, "libdozor", "[%d] %s", eventInfo->eventType, eventInfo->event); 125 | 126 | events->length = 1; 127 | events->errorCode = 0; 128 | memcpy(&(events->items[0]), eventInfo, sizeof(EventInfo)); 129 | 130 | free(eventInfo); 131 | free(deviceReport); 132 | 133 | return events; 134 | } 135 | 136 | 137 | for (index = 0; index < deviceReport->eventTotals; index++) 138 | { 139 | eventInfo = malloc(sizeof(EventInfo)); 140 | if (eventInfo == NULL) 141 | { 142 | fprintf(stderr, "Unable to allocate memory for event info structure: %s\n", strerror(errno)); 143 | return HANDLER_UNABLE_TO_ALLOCATE_MEMORY_REPORT; 144 | } 145 | 146 | memset(eventInfo, 0, sizeof(EventInfo)); 147 | 148 | convertDeviceEventToCommon(eventInfo, deviceReport->site, &(deviceReport->events[index])); 149 | 150 | logger(LOG_LEVEL_DEBUG, "libdozor", "[%d] %s", eventInfo->eventType, eventInfo->event); 151 | 152 | memcpy(&(events->items[index]), eventInfo, sizeof(EventInfo)); 153 | 154 | free(eventInfo); 155 | } 156 | 157 | events->length = deviceReport->eventTotals; 158 | events->errorCode = 0; 159 | 160 | free(deviceReport); 161 | 162 | return events; 163 | } 164 | 165 | unsigned short int dozor_pack( 166 | CommandResponse * command, 167 | CryptoSession * crypto, 168 | const unsigned int commandId, 169 | char * commandValue 170 | ) 171 | { 172 | 173 | unsigned short int answerLength; 174 | uint8_t * ptr; 175 | char * answer; 176 | char * cmdValue; 177 | 178 | if (crypto == NULL) 179 | { 180 | return -1; 181 | } 182 | 183 | DozorResponse * response = malloc(sizeof(DozorResponse)); 184 | if (response == NULL) 185 | { 186 | fprintf(stderr, "***libdozor.c: Unable to allocate memory for response: %s\n", strerror(errno)); 187 | return -1; 188 | } 189 | response->time = time(NULL) - DATE_TIME_OFFSET; 190 | response->unknownOne = 0; 191 | response->unknownTwo = 0x7c; 192 | 193 | cmdValue = malloc(sizeof(char) * 32); 194 | if (cmdValue == NULL) 195 | { 196 | free(response); 197 | fprintf(stderr, "***libdozor.c: Unable to allocate memory for cmdValue: %s\n", strerror(errno)); 198 | return -1; 199 | } 200 | 201 | if ((strlen(commandValue) > 1) && (commandId > 0)) 202 | { 203 | sprintf(cmdValue, "%s&%08x", commandValue, __builtin_bswap32(commandId)); 204 | logger(LOG_LEVEL_DEBUG, "libdozor", "New command - %s", cmdValue); 205 | } else { 206 | strncpy(cmdValue, DEFAULT_ANSWER, 31); 207 | cmdValue[31] = '\0'; 208 | } 209 | 210 | answerLength = strlen(cmdValue) + 2; 211 | answer = malloc(answerLength); 212 | 213 | if (answer == NULL) 214 | { 215 | free(cmdValue); 216 | free(response); 217 | fprintf(stderr, "***libdozor.c: Unable to allocate memory for command: %s\n", strerror(errno)); 218 | return -1; 219 | } 220 | 221 | snprintf(answer, answerLength, "%s!", cmdValue); 222 | free(cmdValue); 223 | 224 | logger(LOG_LEVEL_DEBUG, "libdozor", "command - %s (%d)", answer, answerLength); 225 | 226 | memcpy(response->encrypted, answer, sizeof(char) * answerLength); 227 | 228 | if (encrypt(response->encrypted, crypto, answerLength) != 0) 229 | { 230 | free(response); 231 | fprintf(stderr, "Unable to encrypt message:\"%s\" %s\n", answer, strerror(errno)); 232 | free(answer); 233 | return -1; 234 | } 235 | 236 | memcpy(&command->response, response, sizeof(DozorResponse)); 237 | command->responseLength = answerLength + 6; 238 | 239 | free(answer); 240 | logger(LOG_LEVEL_DEBUG, "libdozor", "answer freed"); 241 | 242 | free(response); 243 | logger(LOG_LEVEL_DEBUG, "libdozor", "response freed"); 244 | 245 | return 0; 246 | } -------------------------------------------------------------------------------- /dozord/socket-server.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift. 3 | 4 | NightShift is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift. If not, see . 16 | */ 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include "socket-server.h" 30 | #include "logger.h" 31 | 32 | pthread_t ServiceThreadId; 33 | pthread_t connectionWorkers[MAX_CONN] = {0}; 34 | unsigned int socketExitRequested = 0; 35 | pthread_mutex_t GlobaSocketLock; 36 | 37 | void log_incoming_data(const char *clientIp, uint8_t *data, int data_length) { 38 | char logMessage[BUFFERSIZE * 3]; 39 | int offset = 0; 40 | 41 | // Iterate over each byte of the data and append its hex representation to logMessage 42 | for (int i = 0; i < data_length; i++) { 43 | offset += snprintf(logMessage + offset, sizeof(logMessage) - offset, "%02x ", data[i]); 44 | if (offset >= sizeof(logMessage)) { 45 | break; // Prevent buffer overflow, stop if we exceed the buffer size 46 | } 47 | } 48 | 49 | // Ensure the string is null-terminated 50 | logMessage[offset - 1] = '\0'; // Replace the last space with a null terminator 51 | 52 | prettyLogger(LOG_LEVEL_DEBUG, clientIp, logMessage); 53 | } 54 | 55 | void * connectionCb(void * payload) { 56 | struct ConnectionPayload * connInfo = (struct ConnectionPayload *) payload; 57 | uint8_t data[BUFFERSIZE]; 58 | char logMessage[2048]; 59 | CommandResponse * responsePayload; 60 | 61 | int c = read(connInfo->sockfd, &data, BUFFERSIZE); 62 | if (c < 0) { 63 | fprintf(stderr, "ERROR reading from socket: %s\n", strerror(errno)); 64 | close(connInfo->sockfd); 65 | free(connInfo); 66 | pthread_exit(NULL); 67 | return -1; 68 | } 69 | 70 | log_incoming_data(&connInfo->clientIp, (uint8_t *)data, c); 71 | 72 | responsePayload = malloc(sizeof(CommandResponse)); 73 | if (responsePayload == NULL) { 74 | fprintf(stderr, "Unable to allocate memory for CommandResponse: %s\n", strerror(errno)); 75 | close(connInfo->sockfd); 76 | free(connInfo); 77 | pthread_exit(NULL); 78 | return -1; 79 | } 80 | 81 | responsePayload->responseLength = 0; 82 | 83 | // @todo handle return value, -1 - error 84 | connInfo->on_message(responsePayload, data, &connInfo->clientIp); 85 | 86 | if (responsePayload->responseLength > 0) { 87 | int n = 0; 88 | uint8_t * ptr = (uint8_t*) responsePayload; 89 | int written = 0; 90 | int toWrite = responsePayload->responseLength; 91 | 92 | while(responsePayload->responseLength > written) 93 | { 94 | n = send(connInfo->sockfd, ptr, (toWrite - written), 0x4000); 95 | if (n < 0) { 96 | free(responsePayload); 97 | fprintf(stderr, "Socket send failed: %s\n", strerror(errno)); 98 | close(connInfo->sockfd); 99 | free(connInfo); 100 | pthread_exit(NULL); 101 | return -1; 102 | } 103 | ptr += 1; 104 | written += n; 105 | } 106 | 107 | prettyLogger(LOG_LEVEL_DEBUG, "TCP", "Data sent."); 108 | } 109 | 110 | free(responsePayload); 111 | close(connInfo->sockfd); 112 | 113 | pthread_mutex_lock(&GlobaSocketLock); 114 | connectionWorkers[connInfo->workerId] = 0; 115 | pthread_mutex_unlock(&GlobaSocketLock); 116 | 117 | snprintf(logMessage, sizeof(logMessage), "%s closed", connInfo->clientIp); 118 | prettyLogger(LOG_LEVEL_DEBUG, "TCP", logMessage); 119 | 120 | free(connInfo); 121 | 122 | pthread_exit(NULL); 123 | } 124 | 125 | void * startSocketListener(void * args) { 126 | struct SocketConfig * socketConfig = (struct SocketConfig *) args; 127 | 128 | int sockfd, newsockfd, pid, rc; 129 | int port; 130 | char clientIp[INET_ADDRSTRLEN]; 131 | struct sockaddr_in servaddr; 132 | struct sockaddr_in cli; 133 | char logMessage[256]; 134 | struct ConnectionPayload infos[5]; 135 | socklen_t len; 136 | 137 | // socket create and verification 138 | sockfd = socket(AF_INET, SOCK_STREAM, 0); 139 | if (sockfd == -1) { 140 | fprintf(stderr, "Socket create failed: %s\n", strerror(errno)); 141 | exit(-1); 142 | } 143 | 144 | // set sock options 145 | if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) == -1) 146 | { 147 | fprintf(stderr, "Socket options setup failed: %s\n", strerror(errno)); 148 | exit(-1); 149 | } 150 | 151 | bzero(&servaddr, sizeof(servaddr)); 152 | 153 | // assign IP, PORT 154 | servaddr.sin_family = AF_INET; 155 | servaddr.sin_addr.s_addr = htonl(INADDR_ANY); 156 | servaddr.sin_port = htons(socketConfig->port); 157 | 158 | // Binding newly created socket to given IP and verification 159 | if ((bind(sockfd, (struct sockaddr *) &servaddr, (socklen_t) sizeof(servaddr))) != 0) { 160 | fprintf(stderr, "Socket bind failed: %s\n", strerror(errno)); 161 | exit(-1); 162 | } 163 | 164 | // Now server is ready to listen and verification 165 | if ((listen(sockfd, 5)) != 0) { 166 | fprintf(stderr, "Socket listen failed: %s\n", strerror(errno)); 167 | exit(-1); 168 | } 169 | 170 | snprintf(logMessage, sizeof(logMessage), "Listen *:%d", socketConfig->port); 171 | prettyLogger(LOG_LEVEL_INFO, "TCP", logMessage); 172 | 173 | while(!socketExitRequested) 174 | { 175 | int availableSlot = -1; 176 | for (int j = 0; j < MAX_CONN; j++) { 177 | if (connectionWorkers[j] == 0) { 178 | availableSlot = j; 179 | break; 180 | } 181 | } 182 | 183 | if (availableSlot >= 0) { 184 | struct ConnectionPayload *payload = malloc(sizeof(struct ConnectionPayload)); 185 | if (payload == NULL) { 186 | fprintf(stderr, "Memory allocation failed\n"); 187 | pthread_exit(-1); 188 | } 189 | 190 | // Accept the data packet from client and verification 191 | len = sizeof(cli); 192 | newsockfd = accept(sockfd, (struct sockaddr *) &cli, &len); 193 | 194 | if (newsockfd < 0) { 195 | fprintf(stderr, "Server accept failed: %s\n", strerror(errno)); 196 | free(payload); 197 | pthread_exit(NULL); 198 | exit(-1); 199 | } 200 | 201 | inet_ntop( AF_INET, &cli.sin_addr, clientIp, INET_ADDRSTRLEN ); 202 | 203 | strncpy(payload->clientIp, clientIp, sizeof(clientIp)); 204 | payload->sockfd = newsockfd; 205 | payload->on_message = socketConfig->on_message; 206 | payload->workerId = availableSlot; 207 | 208 | pthread_mutex_lock(&GlobaSocketLock); 209 | if (pthread_create(&connectionWorkers[availableSlot], NULL, connectionCb, (void *) payload) != 0) { 210 | free(payload); 211 | connectionWorkers[availableSlot] = 0; 212 | fprintf(stderr, "Connection workers init failed: %s\n", strerror(errno)); 213 | pthread_exit(-1); 214 | } 215 | pthread_mutex_unlock(&GlobaSocketLock); 216 | 217 | } else { 218 | prettyLogger(LOG_LEVEL_DEBUG, "TCP", "No more connections left..."); 219 | sleep(1); 220 | } 221 | } 222 | 223 | prettyLogger(LOG_LEVEL_INFO, "TCP", "Closing client connections..."); 224 | for (int j = 0; j < MAX_CONN; j++) { 225 | if (connectionWorkers[j]) { 226 | pthread_cancel(connectionWorkers[j]); 227 | pthread_join(connectionWorkers[j], NULL); 228 | 229 | pthread_mutex_lock(&GlobaSocketLock); 230 | connectionWorkers[j] = 0; 231 | pthread_mutex_unlock(&GlobaSocketLock); 232 | } 233 | } 234 | prettyLogger(LOG_LEVEL_INFO, "TCP", "Client connections closed."); 235 | 236 | close(sockfd); 237 | 238 | pthread_exit(0); 239 | 240 | return NULL; 241 | } 242 | 243 | void startSocketService(struct SocketConfig * config) { 244 | pthread_mutex_init(&GlobaSocketLock, NULL); 245 | 246 | if (pthread_create(&ServiceThreadId, NULL, startSocketListener, config) != 0) 247 | ServiceThreadId = 0; 248 | } 249 | 250 | void stopSocketService() { 251 | socketExitRequested = 1; 252 | 253 | if (ServiceThreadId) { 254 | pthread_join(ServiceThreadId, NULL); 255 | ServiceThreadId = 0; 256 | } 257 | 258 | pthread_mutex_destroy(&GlobaSocketLock); 259 | } -------------------------------------------------------------------------------- /dozord/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift. 3 | 4 | NightShift is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include "dozor.h" 30 | #include "command.h" 31 | #include "nightshift-mqtt.h" 32 | #include "logger.h" 33 | #include "app-config.h" 34 | #include "socket-server.h" 35 | 36 | #define SA struct sockaddr 37 | #define DEFAULT_ANSWER "" 38 | 39 | static const char * optString = "l:k:s:m:p:h?:d"; 40 | 41 | pthread_mutex_t commandsWriteLock; 42 | 43 | static struct AppConfig appConfig; 44 | static Commands * commands; 45 | 46 | volatile sig_atomic_t exitRequested = 0; 47 | 48 | void term(int signum) 49 | { 50 | exitRequested = 1; 51 | } 52 | 53 | struct Event { 54 | char * deviceIp; 55 | EventInfo * data; 56 | }; 57 | 58 | void * publishEvent(void * args) 59 | { 60 | struct Event * payload = (struct Event *) args; 61 | time_t ticks; 62 | char receivedTimestamp[25] = {0}; 63 | char eventReport[2048] = {0}; 64 | char report[3072] = {0}; 65 | char topic[256] = {0}; 66 | bool retainFlag = false; 67 | 68 | ticks = time(NULL); 69 | 70 | sprintf(receivedTimestamp, "%.24s", ctime(&ticks)); 71 | sprintf(eventReport, PAYLOAD_JSON, payload->deviceIp, receivedTimestamp, payload->data->event); 72 | sprintf(report, MESSAGE_JSON, AGENT_ID, eventReport); 73 | 74 | switch(payload->data->eventType) 75 | { 76 | case ENUM_EVENT_TYPE_REPORT: 77 | sprintf(topic, REPORT_TOPIC, payload->data->siteId); 78 | break; 79 | 80 | case ENUM_EVENT_TYPE_COMMAND_RESPONSE: 81 | sprintf(topic, COMMAND_RESULT_TOPIC, payload->data->siteId); 82 | break; 83 | 84 | case ENUM_EVENT_TYPE_KEEPALIVE: 85 | sprintf(topic, HEARBEAT_TOPIC, payload->data->siteId); 86 | retainFlag = true; 87 | break; 88 | 89 | case ENUM_EVENT_TYPE_ZONEINFO: 90 | sprintf(topic, ZONE_TOPIC, payload->data->siteId, payload->data->sourceId); 91 | retainFlag = true; 92 | break; 93 | 94 | case ENUM_EVENT_TYPE_SECTIONINFO: 95 | sprintf(topic, SECTION_TOPIC, payload->data->siteId, payload->data->sourceId); 96 | retainFlag = true; 97 | break; 98 | 99 | case ENUM_EVENT_TYPE_ARM_DISARM: 100 | sprintf(topic, ARM_DISARM_TOPIC, payload->data->siteId); 101 | retainFlag = true; 102 | break; 103 | 104 | default: 105 | sprintf(topic, EVENT_TOPIC, payload->data->siteId); 106 | } 107 | 108 | publish(topic, report, retainFlag); 109 | } 110 | 111 | void initCommandsStore() 112 | { 113 | commands = malloc(sizeof(Commands)); 114 | if (commands == NULL) 115 | { 116 | fprintf(stderr, "Unable to allocate memory for commands: %s\n", strerror(errno)); 117 | exit(-1); 118 | } 119 | 120 | commands->length = 0; 121 | } 122 | 123 | on_message_t socket_message_callback(CommandResponse * response, uint8_t * data, char * clientIp) { 124 | unsigned short int index = 0; 125 | short int res = -1; 126 | char logMessage[2048]; 127 | 128 | struct Event *payload = malloc(sizeof(struct Event)); 129 | if (payload == NULL) { 130 | fprintf(stderr, "Unable to allocate memory for Event: %s\n", strerror(errno)); 131 | return (void *) -1; 132 | } 133 | 134 | payload->deviceIp = malloc(16 * sizeof(char)); 135 | if (payload->deviceIp == NULL) { 136 | fprintf(stderr, "Unable to allocate memory for Event device ip: %s\n", strerror(errno)); 137 | free(payload); 138 | return (void *) -1; 139 | } 140 | 141 | payload->data = malloc(sizeof(EventInfo)); 142 | if (payload->data == NULL) { 143 | fprintf(stderr, "Unable to allocate memory for crypto session: %s\n", strerror(errno)); 144 | free(payload->deviceIp); 145 | free(payload); 146 | return (void *) -1; 147 | } 148 | 149 | CryptoSession * crypto = malloc(sizeof(CryptoSession)); 150 | if (crypto == NULL) 151 | { 152 | fprintf(stderr, "Unable to allocate memory for crypto session: %s\n", strerror(errno)); 153 | free(payload->deviceIp); 154 | free(payload->data); 155 | free(payload); 156 | return (void *) -1; 157 | } 158 | 159 | Events * events = dozor_unpackV2(crypto, data, appConfig.pinCode); 160 | 161 | if (events != NULL && events->errorCode == 0) { 162 | snprintf(logMessage, sizeof(logMessage), "Total events - %d", events->length); 163 | prettyLogger(LOG_LEVEL_DEBUG, clientIp, logMessage); 164 | 165 | for (index = 0; index < events->length; index++) { 166 | pthread_t publishThread = 0; 167 | 168 | // skip keep alive updates to being logged 169 | if (events->items[index].eventType != ENUM_EVENT_TYPE_KEEPALIVE) { 170 | snprintf(logMessage, sizeof(logMessage), "%s", events->items[index].event); 171 | prettyLogger(LOG_LEVEL_INFO, clientIp, logMessage); 172 | } 173 | 174 | strncpy(payload->deviceIp, clientIp, sizeof(char) * 16); 175 | memcpy(payload->data, &events->items[index], sizeof(EventInfo)); 176 | 177 | publishEvent(payload); 178 | } 179 | 180 | free(payload->deviceIp); 181 | free(payload->data); 182 | free(payload); 183 | 184 | free(events); 185 | 186 | 187 | short int found = getNextCommandIdx(commands); 188 | if (found != -1) { 189 | snprintf(logMessage, sizeof(logMessage), "Sending cmd - \"%s\"", commands->items[found].value); 190 | prettyLogger(LOG_LEVEL_INFO, clientIp, logMessage); 191 | res = dozor_pack(response, crypto, commands->items[found].id, commands->items[found].value); 192 | 193 | // @todo mark command as "sent", make it "done" once device returns command execution result 194 | pthread_mutex_lock(&commandsWriteLock); 195 | commands->items[found].done = 1; 196 | pthread_mutex_unlock(&commandsWriteLock); 197 | 198 | prettyLogger(LOG_LEVEL_DEBUG, "-", "Command encrypted"); 199 | } else { 200 | prettyLogger(LOG_LEVEL_DEBUG, "-", "No active command found, using default command"); 201 | res = dozor_pack(response, crypto, 1, DEFAULT_ANSWER); 202 | } 203 | 204 | if (response == NULL || res == -1) { 205 | prettyLogger(LOG_LEVEL_DEBUG, "-", "Unable to encrypt command! Freeing memory..."); 206 | 207 | free(payload->deviceIp); 208 | free(payload->data); 209 | free(payload); 210 | free(crypto); 211 | 212 | prettyLogger(LOG_LEVEL_DEBUG, "-", "Unable to encrypt command! Freeing memory...completed. Exiting..."); 213 | 214 | fprintf(stderr, "Unable to encrypt command!\n"); 215 | return (void *) -1; 216 | } 217 | } else { 218 | snprintf(logMessage, sizeof(logMessage), "Unable to unpack events! Error code - %d. Freeing memory...", events->errorCode); 219 | prettyLogger(LOG_LEVEL_INFO, clientIp, logMessage); 220 | 221 | // @todo handle error code value 222 | free(payload->deviceIp); 223 | free(payload->data); 224 | free(payload); 225 | free(crypto); 226 | 227 | prettyLogger(LOG_LEVEL_DEBUG, "-", "Unable to unpack events! Freeing memory...completed. Exiting..."); 228 | 229 | return (void *) events->errorCode; 230 | } 231 | 232 | 233 | prettyLogger(LOG_LEVEL_DEBUG, "-", "Freeing crypto..."); 234 | free(crypto); 235 | prettyLogger(LOG_LEVEL_DEBUG, "-", "Freeing crypto...completed. Exiting..."); 236 | 237 | return (void *) 0; 238 | } 239 | 240 | void * mqtt_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) 241 | { 242 | char logMessage[256]; 243 | snprintf(logMessage, sizeof(logMessage), "Command - %s", (char *) message->payload); 244 | prettyLogger(LOG_LEVEL_INFO, "MQTT", logMessage); 245 | 246 | pthread_mutex_lock(&commandsWriteLock); 247 | 248 | readCommandsFromString(commands, (char *)message->payload); 249 | 250 | pthread_mutex_unlock(&commandsWriteLock); 251 | } 252 | 253 | int main(int argc, char **argv) 254 | { 255 | // handle SIG 256 | struct sigaction action; 257 | memset(&action, 0, sizeof(action)); 258 | action.sa_handler = term; 259 | sigaction(SIGTERM, &action, NULL); 260 | 261 | appConfig.logLevel = LOG_LEVEL_INFO; 262 | 263 | initializeAppConfig(&appConfig); 264 | appConfig.socketConfig.on_message = socket_message_callback; 265 | 266 | processCommandLineOptions(argc, argv, &appConfig); 267 | 268 | set_log_level(appConfig.logLevel); 269 | 270 | if (appConfig.mqttConfig.siteId == 0) 271 | { 272 | prettyLogger(LOG_LEVEL_ERROR, "-", "Guard device ID is not set. Exiting."); 273 | return 0; 274 | } 275 | 276 | if (appConfig.pinCode == "") 277 | { 278 | prettyLogger(LOG_LEVEL_ERROR, "-", "Guard device pincode is not set. Exiting."); 279 | return 0; 280 | } 281 | 282 | char logMessage[256]; 283 | snprintf(logMessage, sizeof(logMessage), "Guard device ID %d", appConfig.mqttConfig.siteId); 284 | prettyLogger(LOG_LEVEL_INFO, "-", logMessage); 285 | 286 | pthread_mutex_init(&commandsWriteLock, NULL); 287 | 288 | initCommandsStore(); 289 | 290 | initializeMQTT(&appConfig.mqttConfig, mqtt_message_callback); 291 | 292 | startSocketService(&appConfig.socketConfig); 293 | 294 | while (!exitRequested) { 295 | sleep(1); 296 | } 297 | 298 | pthread_mutex_destroy(&commandsWriteLock); 299 | 300 | stopSocketService(); 301 | 302 | disconnectMQTT(); 303 | 304 | pthread_exit(NULL); 305 | 306 | free(&appConfig.mqttConfig); 307 | free(&appConfig.socketConfig); 308 | 309 | free(commands); 310 | 311 | return 0; 312 | } 313 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![CI/CD Status](https://github.com/frozer/nightshift/actions/workflows/c-cpp.yml/badge.svg) 2 | # NightShift - свободная реализация сервера управления Астра Дозор 3 | Выполняет роль сервера для приборов охранно-пожарной сигнализации Астра Дозор и реализует следующие функции: 4 | 5 | * логирование и разбор сообщений от прибора 6 | * передачу команд на прибор (список рабочих команд приведен ниже) 7 | * отправка сообщений по протоколу MQTT на настроенный брокер MQTT (список топиков см.ниже) 8 | 9 | ## Настройка прибора 10 | Настройка прибора выполняется согласно руководства пользователя. Указываются IP-адрес, порт на котором работает сервер и ключ связи для обеспечения шифрования сообщений. 11 | 12 | ## Использование 13 | Выполняется запуск демона dozord с параметрами: 14 | 15 | * -s - ИД устройства 16 | * -k - ключ связи 17 | * -l - порт сервера, по умолчанию - 1111 18 | * -m - адрес сервера MQTT, 127.0.0.1 19 | * -p - порт MQTT, 1883 20 | * -d - режим отладки 21 | * -h - вывод справки 22 | 23 | После подключения устройства выполняется вывод полученных сообщений на экран. Отправка команд осуществляется путем публикации сообщения с текстом команды в соответствующий топик 24 | 25 | ## Схема работы 26 | 27 | Клиент с установленным интервалом шлет Keep-Alive сообщения в сторону сервера. Если сервер имеет команды для устройства, то команды упаковываются и отсылаются в виде ответа. Если команд нет, то посылается пустой ответ, содержащий только текущее время сервера (видимо по нему выставляется время на устройстве). При отсутствии ответа от сервера устройство накапливает события у себя в буфере (но теряет дату(!) события). При появлении ответа сервера - на сервер отправляются накопленные события. 28 | 29 | Для шифрования сообщений используется общий ключ. Инициатором сообщений является устройство (обусловлено тем, что устройство может находиться за NAT/серой сетью и т.п.). Из этого следует, что отправить на устройство ничего нельзя пока устройство само не отправит сообщение. 30 | 31 | ## Формат сообщения от устройства 32 | Cостоит из открытой и закрытой части. 33 | 34 | ### Формат открытой части 35 | ```c 36 | struct opened { 37 | char msgLength[3]; 38 | char unknown; 39 | uint16_t site; 40 | uint32_t seed; 41 | }; 42 | ``` 43 | 44 | ### Формат закрытой части 45 | Закрытая часть зашифрована по алгоритму RC4 (реализация из Wikipedia - [RC4](https://ru.wikipedia.org/wiki/RC4)). Длина ключа - 16 байт. Ключ строится на основе соли из открытой части и ключа. 46 | 47 | Закрытая часть состоит в свою очередь из реквизитов объекта и характеристики устройства и блока сообщений. 48 | ```c 49 | struct closed { 50 | uint8_t tag; 51 | short unsigned int channel:4; 52 | short unsigned int sim: 4; 53 | uint8_t voltage; 54 | short unsigned int gsm_signal: 6; 55 | short unsigned int extra_index: 2; 56 | uint8_t extra_value; 57 | }; 58 | ``` 59 | Примечательно, что для получения уровня напряжения нужно значение в сообщении поделить на 10. Channel 0x0 - Ethernet 60 | 61 | ## Формат сообщения к устройству 62 | ```c 63 | struct message { 64 | uint32_t time; 65 | uint8_t unknownOne; 66 | uint8_t unknownTwo; 67 | uint8_t encrypted[] 68 | } 69 | ``` 70 | Перед шифрованием к сформированной строке команды добавляется символ "!" (0x21). В результирующем сообщении, в поле unknownOne устанавливается 0x0, в позицию unknownTwo - 0x7c. 71 | 72 | # Типы событий 73 | ## Классификатор событий 74 | #|Event Type ID|Event Type|Event Scope|Description| 75 | :---:|:---:|:---:|:---:|---| 76 | 1|0x1|DeviceConfiguration|ConfigurationEvent|Конфигурация устройства| 77 | 2|0x2|ManualReset|CommonEvent|Выполнен ручной сброс системы| 78 | 3|0x3|ZoneDisarm|ZoneEvent|Зона «Х» снята с охраны| 79 | 9|0x9|ZoneWarning|ZoneEvent|Внимание, сработали датчики в зоне «Х»| 80 | 10|0xa|ZoneArm|ZoneEvent|Зона «Х» поставлена на охрану| 81 | 11|0xb|ZoneGood|ZoneEvent|Отмена всех тревог зоны| 82 | 12|0xc|ZoneFail|ZoneEvent|Ошибка постановки на охрану зоны «X»| 83 | 13|0xd|ZoneDelayedAlarm|ZoneEvent|Тревога зоны «Х» после таймаута| 84 | 15|0xf|ZoneAlarm|ZoneEvent|Тревога зоны «Х»| 85 | 16|0x10|FallbackPowerRecovered|CommonEvent|Резервное питание восстановлено| 86 | 18|0x12|FactoryReset|CommonEvent|Выполнен сброс на заводские установки| 87 | 19|0x13|FirmwareUpgradeInProgress|CommonEvent|Производится обновление микропрограммы| 88 | 20|0x14|FirmwareUpgradeFail|CommonEvent|Сбой обновления микропрограммы| 89 | 21|0x15|TestEvent|CommonEvent|Тест| 90 | 22|0x16|TestEvent|CommonEvent|Тест| 91 | 23|0x17|CoverOpened|CommonEvent|Крышка прибора открыта| 92 | 24|0x18|CoverClosed|CommonEvent|Крышка прибора закрыта| 93 | 25|0x19|OffenceEvent|SecurityEvent|Действия под принуждением| 94 | 27|0x1b|UserAuth|AuthenticationEvent|Использован ключ пользователя «Х»| 95 | 29|0x1d|FallbackPowerFailed|CommonEvent|Сбой резервного питания| 96 | 30|0x1e|FailbackPowerActivated|CommonEvent|Выполняется переход на резервное питание| 97 | 31|0x1f|MainPowerFail|CommonEvent|Сбой основного питания| 98 | 32|0x20|PowerGood|CommonEvent|Восстановлено основное питание| 99 | 37|0x25|Report|ReportEvent|Ежедневный отчет| 100 | 38|0x26|FirmwareUpgradeRequest|CommonEvent|Запрос обновления встроенного ПО| 101 | 39|0x27|CardActivated|GSMEvent|Выполнена смена активной СИМ-карты| 102 | 40|0x28|CardRemoved|GSMEvent|Извлечена СИМ-карта| 103 | 41|0x29|CodeSeqAttack|SecurityEvent|Попытка подбора кода| 104 | 43|0x2b|SectionDisarm|SectionEvent|Раздел «Х» снят с охраны| 105 | 50|0x32|SectionArm|SectionEvent|Раздел «Х» поставлен на охрану| 106 | 51|0x33|SectionGood|SectionEvent|Отмена всех тревог раздела| 107 | 52|0x34|SectionFail|SectionEvent|Ошибка взятия раздела «Х»| 108 | 53|0x35|SectionWarning|SectionEvent|Внимание, раздел «Х»| 109 | 55|0x37|SectionAlarm|SectionEvent|Тревога раздела «Х»| 110 | 56|0x38|SystemFailure|CommonEvent|Неисправность системы| 111 | 57|0x39|SystemDisarm|SecurityEvent|Снятие с охраны| 112 | 58|0x3a|SystemArm|SecurityEvent|Постановка на охрану| 113 | 59|0x3b|SystemMaintenance|SecurityEvent|Введен инженерный код| 114 | 60|0x3c|SystemOverfreeze|ReportEvent|Переохлаждение оборудования| 115 | 62|0x3e|SystemOverheat|ReportEvent|Перегрев оборудования| 116 | 63|0x3f|RemoteCommandHandled|SystemEvent|Обработана внешняя команда| 117 | 118 | ## Длина сообщения в зависимости от типа события 119 | #|Event Type ID|Длина сообщения 120 | :---:|:---:|:---: 121 | |2|1|7 122 | |3|2|7 123 | |4|3|6 124 | |5|4|6 125 | |6|5|6 126 | |7|6|6 127 | |8|7|6 128 | |9|8|6 129 | |10|9|6 130 | |11|10|6 131 | |12|11|6 132 | |13|12|6 133 | |14|13|6 134 | |15|14|6 135 | |16|15|6 136 | |17|16|6 137 | |18|17|9 138 | |19|18|5 139 | |20|19|5 140 | |21|20|5 141 | |22|21|6 142 | |23|22|6 143 | |24|23|6 144 | |25|24|5 145 | |26|25|5 146 | |27|26|6 147 | |28|27|6 148 | |29|28|6 149 | |30|29|6 150 | |31|30|6 151 | |32|31|6 152 | |33|32|6 153 | |34|33|5 154 | |35|34|7 155 | |36|35|7 156 | |37|36|9 157 | |38|37|9 158 | |39|38|5 159 | |40|39|21 160 | |41|40|6 161 | |42|41|5 162 | |43|42|22 163 | |44|43|6 164 | |45|44|6 165 | |46|45|6 166 | |47|46|6 167 | |48|47|6 168 | |49|48|6 169 | |50|49|6 170 | |51|50|6 171 | |52|51|6 172 | |53|52|6 173 | |54|53|6 174 | |55|54|6 175 | |56|55|6 176 | |57|56|6 177 | |58|57|9 178 | |59|58|9 179 | |60|59|6 180 | |61|60|6 181 | |62|61|6 182 | |63|62|6 183 | |64|63|10 184 | |65|64|8 185 | |66|65|42 186 | |67|66|9 187 | |68|67|78 188 | 189 | ## Адреса данных для событий 190 | Данные обычно лежат в адресе "0". Приведена таблица для типов событий, использующих иные адреса 191 | #|Event Type ID|Event Type|Address|Description| 192 | :---:|:---:|:---:|:---:|---| 193 | 1|0x1|DeviceConfiguration|0 - минорная версия прошивки, 1 - мажорная версия|применить операцию AND 0x7 к мажорной версии 194 | 16|0x10|FallbackPowerRecovered||значение напряжения в вольтах 195 | 27|0x1b|UserAuth|3|ИД пользователя 196 | 29|0x1d|FallbackPowerFailed||значение напряжения в вольтах 197 | 30|0x1e|FailbackPowerActivated||значение напряжения в вольтах 198 | 31|0x1f|MainPowerFail||значение напряжения в вольтах 199 | 32|0x20|PowerGood||значение напряжения в вольтах 200 | 37|0x25|Report|1|если в позиции 0 значение "2", то значение текущей температуры в гр.Цельсия 201 | 57|0x39|SystemDisarm||значение в позиции "0" представляет снятые с охраны разделы в бинарной форме. Т.е. значение `ff` можно выразить как `1 1 1 1 1 1 1 1`.Т.е. все 8 разделов сняты с охраны 202 | 58|0x3a|SystemArm||значение в позиции "0" представляет поставленные на охрану разделы в бинарной форме. Т.е. значение `07` можно выразить как `0 0 0 0 0 1 1 1`.Т.е. первые 3 раздела поставлены на охрану 203 | 63|0x3f|RemoteCommandHandled|5|в позиции 0 - ИД команды, в позиции 5 - результат обработки 204 | 205 | ## Результаты обработки удаленных команд 206 | Result ID|Result Name 207 | :---:|---| 208 | 0x1|Success|Успешно 209 | 0x2|Not implemented 210 | 0x3|Incorrect parameter(s) 211 | 0x4|Busy 212 | 0x5|Unable to execute 213 | 0x6|Already executed 214 | 0x7|No access 215 | 216 | # Команды 217 | ## Проверены на версии 4.29 218 | * Постановка на сигнализацию - "ARM:" 219 | * Постановка на сигнализацию выбранного раздела "2" - "ARM:&2" 220 | * Снятие с сигнализации - "OFF:" 221 | * Снятие с сигнализации выбранного раздела "2" - "OFF:&2" 222 | * Перезагрузка устройства - "REBOOT:" 223 | * Включить зону - "ZON:11" 224 | * Выключить зону - "ZOFF:11" 225 | * Переключить реле - "OUT:1, 0|1|2", где (0 - выключить, 1 - включить, 2 - инвертировать) 226 | * Показать на экран сообщение - "SHOW: MessageToShow" 227 | 228 | ## Не работают в версии 4.29 229 | * Отправка уровня сигнала извещателей (упоминается в истории изменений для версии 4.25) - BRIMS 230 | * Запрос кадра из архива видеокадров (упоминается в истории изменений для версии 4.25) - CAM 231 | * Запрос состояния (упоминается в истории изменений для версии 4.25) - TEST 232 | 233 | # Поддержка MQTT 234 | ## Топики для публикации 235 | 236 | * /nightshift/notify - при подключении к брокеру MQTT. Формат сообщения: 237 | ``` 238 | {\"version\": \"%s\", \"name\": \"nightshift\", \"agentID\": \"%s\", \"siteId\": %d} 239 | ``` 240 | * /nightshift/sites/%d/reports - ежесуточный отчет устройстваю. Формат сообщения: 241 | ``` 242 | {"agentID": "80d7be61-d81d-4aac-9012-6729b6392a89", "message": {"deviceIp":"127.0.0.1","received":"Wed Jul 22 09:32:48 2020","payload":{"site":1,"typeId":37,"timestamp":"Thu Nov 28 09:00:00 2019","data":"0210000000","temp":16,"event":"Report","scope":"Common"}}} 243 | ``` 244 | * /nightshift/sites/%d/events - события от устройства. Формат сообщения: 245 | ``` 246 | {"agentID": "80d7be61-d81d-4aac-9012-6729b6392a89", "message": {"deviceIp":"127.0.0.1","received":"Wed Sep 9 12:42:19 2020","payload":{"site":1,"typeId":32,"timestamp":"Sun Dec 8 13:51:20 2019","data":"B71F","event":"PowerGood","scope":"Common"}} 247 | } 248 | {"agentID": "80d7be61-d81d-4aac-9012-6729b6392a89", "message": {"deviceIp":"127.0.0.1","received":"Wed Sep 9 12:42:19 2020","payload":{"site":1,"typeId":31,"timestamp":"Sun Dec 8 13:53:31 2019","data":"A710","event":"MainPowerFail","scope":"Common"}} 249 | } 250 | {"agentID": "80d7be61-d81d-4aac-9012-6729b6392a89", "message": {"deviceIp":"127.0.0.1","received":"Wed Sep 9 12:42:19 2020","payload":{"site":1,"typeId":16,"timestamp":"Sun Dec 8 13:54:48 2019","data":"0E1D","event":"FallbackPowerRecovered","scope":"Common"}} 251 | } 252 | {"agentID": "80d7be61-d81d-4aac-9012-6729b6392a89", "message": {"deviceIp":"127.0.0.1","received":"Wed Sep 9 12:42:19 2020","payload":{"site":1,"typeId":29,"timestamp":"Mon Jan 1 03:00:00 2001","data":"7F01","event":"FallbackPowerFailed","scope":"Common"}} 253 | } 254 | {"agentID": "80d7be61-d81d-4aac-9012-6729b6392a89", "message": {"deviceIp":"127.0.0.1","received":"Wed Sep 9 12:42:19 2020","payload":{"site":1,"typeId":1,"timestamp":"Mon Jan 1 03:00:00 2001","data":"1D043A","event":"DeviceConfiguration","scope":"Common","version":"4.29"}} 255 | ``` 256 | * /nightshift/sites/%d/status - состояние устройства на охране/снят с охраны 257 | ``` 258 | {"agentID": "80d7be61-d81d-4aac-9012-6729b6392a89", "message": {"deviceIp":"213.87.240.135","received":"Sat Sep 12 12:24:29 2020","payload":{"site":1,"typeId":57,"timestamp":"Sat Sep 12 12:24:28 2020","data":"F800000103","user":1,"event":"SystemDisarm","scope":"Security"}} 259 | {"agentID": "80d7be61-d81d-4aac-9012-6729b6392a89", "message": {"deviceIp":"213.87.240.135","received":"Sat Sep 12 12:24:29 2020","payload":{"site":1,"typeId":57,"timestamp":"Sat Sep 12 12:24:28 2020","data":"F800000103","user":1,"event":"SystemArm","scope":"Security"}} 260 | ``` 261 | * /nightshift/sites/%d/zones/%d/events - события от устройства по выбранной зоне 262 | ``` 263 | {"agentID": "80d7be61-d81d-4aac-9012-6729b6392a89", "message": {"deviceIp":"127.0.0.1","received":"Wed Sep 9 12:45:15 2020","payload":{"site":1,"typeId":10,"timestamp":"Mon Jan 1 03:00:00 2001","data":"1332","zone":19,"event":"ZoneArm","scope":"Zone"}} 264 | } 265 | ``` 266 | * /nightshift/sites/%d/sections/%d/events - события от устройства по выбранному разделу 267 | ``` 268 | {"agentID": "80d7be61-d81d-4aac-9012-6729b6392a89", "message": {"deviceIp":"127.0.0.1","received":"Wed Sep 9 12:46:11 2020","payload":{"site":1,"typeId":51,"timestamp":"Wed Dec 29 16:01:21 2038","data":"0121","section":1,"event":"SectionGood","scope":"Section"}} 269 | } 270 | ``` 271 | * /nightshift/sites/%d/notify - heartbeat-события от устройства 272 | ``` 273 | {"agentID": "80d7be61-d81d-4aac-9012-6729b6392a89", "message": {"deviceIp":"127.0.0.1","received":"Wed Jul 22 09:35:24 2020","payload":{ "site":1,"typeId":null,"event":"KeepAliveEvent","scope":"KeepAlive","channel":0,"sim":0,"voltage":17.00,"signal":0,"extraId":1,"extraValue":20,"data":"0000B2401400"}}} 274 | ``` 275 | * /nightshift/sites/%d/commandresults - результат выполнения команды 276 | * /nightshift/sites/%d/disconnnected - топик для публикации MQTT WILL сообщения 277 | 278 | ## Топик для управления 279 | 280 | * /nightshift/sites/%d/command - команда указывается в теле сообщения 281 | 282 | ## Типы сообщений с привязкой к топику 283 | #|Event Type ID|Event Type|Event Scope|Topic| 284 | :---:|:---:|:---:|:---:|---| 285 | 1|0x1|DeviceConfiguration|ConfigurationEvent|/nightshift/sites/%d/events| 286 | 2|0x2|ManualReset|CommonEvent|/nightshift/sites/%d/events| 287 | 3|0x3|ZoneDisarm|ZoneEvent|/nightshift/sites/%d/zones/%d/events| 288 | 9|0x9|ZoneWarning|ZoneEvent|/nightshift/sites/%d/zones/%d/events| 289 | 10|0xa|ZoneArm|ZoneEvent|/nightshift/sites/%d/zones/%d/events| 290 | 11|0xb|ZoneGood|ZoneEvent|/nightshift/sites/%d/zones/%d/events| 291 | 12|0xc|ZoneFail|ZoneEvent|/nightshift/sites/%d/zones/%d/events| 292 | 13|0xd|ZoneDelayedAlarm|ZoneEvent|/nightshift/sites/%d/zones/%d/events| 293 | 15|0xf|ZoneAlarm|ZoneEvent|/nightshift/sites/%d/zones/%d/events| 294 | 16|0x10|FallbackPowerRecovered|CommonEvent|/nightshift/sites/%d/events| 295 | 18|0x12|FactoryReset|CommonEvent|/nightshift/sites/%d/events| 296 | 19|0x13|FirmwareUpgradeInProgress|CommonEvent|/nightshift/sites/%d/events| 297 | 20|0x14|FirmwareUpgradeFail|CommonEvent|/nightshift/sites/%d/events| 298 | 21|0x15|TestEvent|CommonEvent|/nightshift/sites/%d/events| 299 | 22|0x16|TestEvent|CommonEvent|/nightshift/sites/%d/events| 300 | 23|0x17|CoverOpened|CommonEvent|/nightshift/sites/%d/events| 301 | 24|0x18|CoverClosed|CommonEvent|/nightshift/sites/%d/events| 302 | 25|0x19|OffenceEvent|SecurityEvent|/nightshift/sites/%d/events| 303 | 27|0x1b|UserAuth|AuthenticationEvent|/nightshift/sites/%d/events| 304 | 29|0x1d|FallbackPowerFailed|CommonEvent|/nightshift/sites/%d/events| 305 | 30|0x1e|FailbackPowerActivated|CommonEvent|/nightshift/sites/%d/events| 306 | 31|0x1f|MainPowerFail|CommonEvent|/nightshift/sites/%d/events| 307 | 32|0x20|PowerGood|CommonEvent|/nightshift/sites/%d/events| 308 | 37|0x25|Report|ReportEvent|/nightshift/sites/%d/reports| 309 | 38|0x26|FirmwareUpgradeRequest|CommonEvent|/nightshift/sites/%d/events| 310 | 39|0x27|CardActivated|GSMEvent|/nightshift/sites/%d/events| 311 | 40|0x28|CardRemoved|GSMEvent|/nightshift/sites/%d/events| 312 | 41|0x29|CodeSeqAttack|SecurityEvent|/nightshift/sites/%d/events| 313 | 43|0x2b|SectionDisarm|SectionEvent|/nightshift/sites/%d/sections/%d/events| 314 | 50|0x32|SectionArm|SectionEvent|/nightshift/sites/%d/sections/%d/events| 315 | 51|0x33|SectionGood|SectionEvent|/nightshift/sites/%d/sections/%d/events| 316 | 52|0x34|SectionFail|SectionEvent|/nightshift/sites/%d/sections/%d/events| 317 | 53|0x35|SectionWarning|SectionEvent|/nightshift/sites/%d/sections/%d/events| 318 | 55|0x37|SectionAlarm|SectionEvent|/nightshift/sites/%d/sections/%d/events| 319 | 56|0x38|SystemFailure|CommonEvent|/nightshift/sites/%d/events| 320 | 57|0x39|SystemDisarm|SecurityEvent|/nightshift/sites/%d/status| 321 | 58|0x3a|SystemArm|SecurityEvent|/nightshift/sites/%d/status| 322 | 59|0x3b|SystemMaintenance|SecurityEvent|/nightshift/sites/%d/events| 323 | 60|0x3c|SystemOverfreeze|ReportEvent|/nightshift/sites/%d/events| 324 | 62|0x3e|SystemOverheat|ReportEvent|/nightshift/sites/%d/events| 325 | 63|0x3f|RemoteCommandHandled|SystemEvent|/nightshift/sites/%d/commandresults| 326 | -------------------------------------------------------------------------------- /libdozor/event.c: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of NightShift Message Library. 3 | 4 | NightShift Message Library is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | 9 | NightShift Message Library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | GNU General Public License for more details. 13 | 14 | You should have received a copy of the GNU General Public License 15 | along with NightShift Message Library. If not, see . 16 | */ 17 | 18 | #include 19 | #include 20 | #include "event.h" 21 | #include "liblogger.h" 22 | 23 | const char events[EVENT_COUNT][MAX_EVENT_NAME_LENGTH] = { 24 | // 0x0 25 | "UnknownEvent-0x0", 26 | // 0x1 27 | "DeviceConfiguration", 28 | // 0x2 29 | "ManualReset", 30 | // 0x3 31 | "ZoneDisarm", 32 | // 0x4 33 | "UnknownEvent-0x4", 34 | // 0x5 35 | "UnknownEvent-0x5", 36 | // 0x6 37 | "UnknownEvent-0x6", 38 | // 0x7 39 | "UnknownEvent-0x7", 40 | // 0x8 41 | "UnknownEvent-0x8", 42 | // 0x9 43 | "ZoneWarning", 44 | // 0xa 45 | "ZoneArm", 46 | // 0xb 47 | "ZoneGood", 48 | // 0xc 49 | "ZoneFail", 50 | // 0xd 51 | "ZoneDelayedAlarm", 52 | // 0xe 53 | "UnknownEvent-0xe", 54 | // 0xf 55 | "ZoneAlarm", 56 | // 0x10 57 | "FallbackPowerRecovered", 58 | // 0x11 59 | "UnknownEvent-0x11", 60 | // 0x12 61 | "FactoryReset", 62 | // 0x13 63 | "FirmwareUpgradeInProgress", 64 | // 0x14 65 | "FirmwareUpgradeFail", 66 | // 0x15 67 | "KeepAliveEvent", 68 | // 0x16 69 | "KeepAliveEvent", 70 | // 0x17 71 | "CoverOpened", 72 | // 0x18 73 | "CoverClosed", 74 | // 0x19 75 | "OffenceEvent", 76 | // 0x1a 77 | "UnknownEvent-0x1a", 78 | // 0x1b 79 | "UserAuth", 80 | // 0x1c 81 | "UnknownEvent-0x1c", 82 | // 0x1d 83 | "FallbackPowerFailed", 84 | // 0x1e 85 | "FailbackPowerActivated", 86 | // 0x1f 87 | "MainPowerFail", 88 | // 0x20 89 | "PowerGood", 90 | // 0x21 91 | "UnknownEvent-0x21", 92 | // 0x22 93 | "UnknownEvent-0x22", 94 | // 0x23 95 | "UnknownEvent-0x23", 96 | // 0x24 97 | "UnknownEvent-0x24", 98 | // 0x25 99 | "Report", 100 | // 0x26 101 | "FirmwareUpgradeRequest", 102 | // 0x27 103 | "CardActivated", 104 | // 0x28 105 | "CardRemoved", 106 | // 0x29 107 | "CodeSeqAttack", 108 | // 0x2a 109 | "UnknownEvent-0x2a", 110 | // 0x2b 111 | "SectionDisarm", 112 | // 0x2c 113 | "UnknownEvent-0x2c", 114 | // 0x2d 115 | "UnknownEvent-0x2d", 116 | // 0x2e 117 | "UnknownEvent-0x2e", 118 | // 0x2f 119 | "UnknownEvent-0x2f", 120 | // 0x30 121 | "UnknownEvent-0x30", 122 | // 0x31 123 | "UnknownEvent-0x31", 124 | // 0x32 125 | "SectionArm", 126 | // 0x33 127 | "SectionGood", 128 | // 0x34 129 | "SectionFail", 130 | // 0x35 131 | "SectionWarning", 132 | // 0x36 133 | "UnknownEvent-0x36", 134 | // 0x37 135 | "SectionAlarm", 136 | // 0x38 137 | "SystemFailure", 138 | // 0x39 139 | "SystemDisarm", 140 | // 0x3a 141 | "SystemArm", 142 | // 0x3b 143 | "SystemMaintenance", 144 | // 0x3c 145 | "SystemOverfreeze", 146 | // 0x3d 147 | "UnknownEvent-0x3d", 148 | // 0x3e 149 | "SystemOverheat", 150 | // 0x3f 151 | "RemoteCommandHandled" 152 | }; 153 | 154 | const char cmdResults[COMMAND_RESULT_COUNT][MAX_COMMAND_RESULT_NAME_LENGTH] = { 155 | "Unknown", 156 | "Success", 157 | "Not implemented", 158 | "Incorrect parameter(s)", 159 | "Busy", 160 | "Unable to execute", 161 | "Already executed", 162 | "No access" 163 | }; 164 | 165 | void getKeepAliveEvent(EventInfo* eventInfo, uint8_t site, DeviceInfo* info) 166 | { 167 | if (eventInfo == NULL) { 168 | return; 169 | } 170 | 171 | const char * template = "{\ 172 | \"site\":%d,\"typeId\":null,\ 173 | \"event\":\"KeepAliveEvent\",\ 174 | \"scope\":\"%s\",\"channel\":%d,\"sim\":%d,\"voltage\":%.2f,\"signal\":%d,\ 175 | \"extraId\":%d,\"extraValue\":%d,\ 176 | \"data\":\""; 177 | char * res = malloc(sizeof(char) * 1024); 178 | unsigned short int index; 179 | uint8_t * ptr = (uint8_t*) info; 180 | char * temp = malloc(sizeof(char) * 3); 181 | float voltage = (unsigned short int) info->voltage / 10; 182 | 183 | sprintf(res, template, site, 184 | KEEP_ALIVE_EVENT_SCOPE, info->channel, info->sim, voltage, 185 | info->gsm_signal, info->extra_index, info->extra_value 186 | ); 187 | 188 | for(index = 0; index < 6; index++) 189 | { 190 | sprintf(temp, "%02X", *(ptr + index)); 191 | strcat(res, temp); 192 | } 193 | strcat(res, "\"}"); 194 | 195 | eventInfo->eventType = ENUM_EVENT_TYPE_KEEPALIVE; 196 | sprintf(eventInfo->event, "%s", res); 197 | eventInfo->siteId = site; 198 | 199 | free(temp); 200 | 201 | free(res); 202 | } 203 | 204 | void convertDeviceEventToCommon(EventInfo* eventInfo, uint8_t site, DeviceEvent* deviceEvent) 205 | { 206 | if (eventInfo == NULL) { 207 | return; 208 | } 209 | eventInfo->eventType = ENUM_EVENT_TYPE_COMMONEVENT; 210 | 211 | const char * template = "{\"site\":%d,\"typeId\":%d,\"timestamp\":\"%s\",\"data\":\""; 212 | char * timestamp = ""; 213 | char * res = malloc(sizeof(char) * 1024); 214 | unsigned short int index; 215 | char * temp = malloc(sizeof(char) * 3); 216 | 217 | uint8_t * ptr = (uint8_t*) deviceEvent->data; 218 | 219 | char * parsedEvent; 220 | char * parsedSubEvent; 221 | 222 | if (deviceEvent->time != 0x00000000) { 223 | timestamp = getDateTime(deviceEvent->time); 224 | } 225 | 226 | sprintf(res, template, site, deviceEvent->type, timestamp); 227 | 228 | for(index = 0; index < deviceEvent->dataLength; index++) 229 | { 230 | sprintf(temp, "%02X", *(ptr + index)); 231 | strcat(res, temp); 232 | } 233 | strcat(res, "\""); 234 | 235 | switch (deviceEvent->type) 236 | { 237 | // ZoneEvent 238 | case 0x3: 239 | case 0x9: 240 | case 0xa: 241 | case 0xb: 242 | case 0xc: 243 | case 0xd: 244 | case 0xf: 245 | logger(LOG_LEVEL_DEBUG, "event.c", "handle zone event"); 246 | parsedSubEvent = getZoneEventData(deviceEvent->type, deviceEvent->data, deviceEvent->dataLength); 247 | parsedEvent = getData(deviceEvent->data, DEFAULT_DATA_POSITION, deviceEvent->dataLength); 248 | 249 | strcat(res, parsedSubEvent); 250 | sprintf(eventInfo->sourceId, "%s", parsedEvent); 251 | eventInfo->eventType = ENUM_EVENT_TYPE_ZONEINFO; 252 | 253 | free(parsedSubEvent); 254 | free(parsedEvent); 255 | 256 | break; 257 | 258 | // SectionEvent 259 | case 0x2b: 260 | case 0x32: 261 | case 0x33: 262 | case 0x34: 263 | case 0x35: 264 | case 0x37: 265 | logger(LOG_LEVEL_DEBUG, "event.c", "handling section event\n"); 266 | parsedSubEvent = getSectionEventData(deviceEvent->type, deviceEvent->data, deviceEvent->dataLength); 267 | parsedEvent = getData(deviceEvent->data, DEFAULT_DATA_POSITION, deviceEvent->dataLength); 268 | 269 | strcat(res, parsedSubEvent); 270 | sprintf(eventInfo->sourceId, "%s", parsedEvent); 271 | eventInfo->eventType = ENUM_EVENT_TYPE_SECTIONINFO; 272 | 273 | free(parsedSubEvent); 274 | free(parsedEvent); 275 | 276 | break; 277 | 278 | // AuthenticationEvent 279 | case 0x1b: 280 | logger(LOG_LEVEL_DEBUG, "event.c", "handling authentication event"); 281 | parsedSubEvent = getAuthEventData(deviceEvent->type, deviceEvent->data, deviceEvent->dataLength); 282 | parsedEvent = getData(deviceEvent->data, DEFAULT_DATA_POSITION, deviceEvent->dataLength); 283 | 284 | strcat(res, parsedSubEvent); 285 | sprintf(eventInfo->sourceId, "%s", parsedEvent); 286 | 287 | free(parsedSubEvent); 288 | free(parsedEvent); 289 | 290 | break; 291 | 292 | // Arm / Disarm by user 293 | case 0x39: 294 | case 0x3a: 295 | logger(LOG_LEVEL_DEBUG, "event.c", "handling arm/disarm event"); 296 | parsedSubEvent = getSecurityEventData(deviceEvent->type, deviceEvent->data, deviceEvent->dataLength); 297 | parsedEvent = getData(deviceEvent->data, USER_DATA_POSITION, deviceEvent->dataLength); 298 | 299 | strcat(res, parsedSubEvent); 300 | sprintf(eventInfo->sourceId, "%s", parsedEvent); 301 | eventInfo->eventType = ENUM_EVENT_TYPE_ARM_DISARM; 302 | 303 | free(parsedSubEvent); 304 | free(parsedEvent); 305 | 306 | break; 307 | 308 | // SecurityEvent 309 | case 0x19: 310 | case 0x29: 311 | case 0x3b: 312 | logger(LOG_LEVEL_DEBUG, "event.c", "handling security event"); 313 | parsedEvent = getCommonEventData(deviceEvent->type, deviceEvent->data, deviceEvent->dataLength, SECURITY_EVENT_SCOPE); 314 | strcat(res, parsedEvent); 315 | 316 | free(parsedEvent); 317 | 318 | break; 319 | 320 | // ReportEvent 321 | case 0x25: 322 | logger(LOG_LEVEL_DEBUG, "event.c", "handling report event"); 323 | parsedEvent = getReportEventData(deviceEvent->type, deviceEvent->data, deviceEvent->dataLength); 324 | strcat(res, parsedEvent); 325 | 326 | eventInfo->eventType = ENUM_EVENT_TYPE_REPORT; 327 | 328 | free(parsedEvent); 329 | 330 | break; 331 | 332 | // Remote Command Executed 333 | case 0x3f: 334 | logger(LOG_LEVEL_DEBUG, "event.c", "handling command result event (%s...)", res); 335 | parsedEvent = getCommandEventData(deviceEvent->type, deviceEvent->data, deviceEvent->dataLength); 336 | strcat(res, parsedEvent); 337 | 338 | eventInfo->eventType = ENUM_EVENT_TYPE_COMMAND_RESPONSE; 339 | 340 | free(parsedEvent); 341 | 342 | break; 343 | 344 | case 0x1: 345 | logger(LOG_LEVEL_DEBUG, "event.c", "handling firmware version event"); 346 | parsedEvent = getFirmwareVersionEventData(deviceEvent->type, deviceEvent->data, deviceEvent->dataLength); 347 | strcat(res, parsedEvent); 348 | 349 | free(parsedEvent); 350 | 351 | break; 352 | 353 | default: 354 | logger(LOG_LEVEL_DEBUG, "event.c", "handling non-specific event"); 355 | parsedEvent = getCommonEventData(deviceEvent->type, deviceEvent->data, deviceEvent->dataLength, COMMON_EVENT_SCOPE); 356 | strcat(res, parsedEvent); 357 | 358 | free(parsedEvent); 359 | 360 | break; 361 | } 362 | 363 | strcat(res, "}"); 364 | 365 | sprintf(eventInfo->event, "%s", res); 366 | eventInfo->siteId = site; 367 | 368 | if (deviceEvent->time != 0x00000000) { 369 | free(timestamp); 370 | } 371 | 372 | free(temp); 373 | free(res); 374 | } 375 | 376 | static char * getFirmwareVersionEventData(uint8_t type, uint8_t * data, uint8_t len) 377 | { 378 | char * template = ",\"event\":\"%s\",\"scope\":\"Common\",\"version\":\"%ld.%s\""; 379 | char * res; 380 | char * subVersion = getData(data, DEFAULT_DATA_POSITION, len); 381 | char * subVersionData = getData(data, VERSION_DATA_POSITION, len); 382 | long int version = strtol(subVersionData, 0, 10) & VERSION_MASK; 383 | 384 | res = malloc(sizeof(char) * (strlen(template) + MAX_EVENT_NAME_LENGTH + 4)); 385 | sprintf(res, template, getEventNameByType(type), version, subVersion); 386 | 387 | free(subVersion); 388 | free(subVersionData); 389 | 390 | return res; 391 | } 392 | 393 | static char * getCommandEventData(uint8_t type, uint8_t * data, uint8_t len) 394 | { 395 | char * template = ",\"event\":\"%s\",\"scope\":\"Common\",\"commandId\":%s,\"commandResultId\":%s,\"commandResult\":\"%s\""; 396 | char * res; 397 | char * cmdResult = getData(data, COMMAND_RESULT_DATA_POSITION, len); 398 | logger(LOG_LEVEL_DEBUG, "event.c(getCommandEventData)", "command result %s, position - %d, length - %d", cmdResult, COMMAND_RESULT_DATA_POSITION, len); 399 | 400 | char * cmdResultName = (char *) cmdResults[strtol(cmdResult, 0, 10)]; 401 | logger(LOG_LEVEL_DEBUG, "event.c(getCommandEventData)", "command result name %s", cmdResultName); 402 | 403 | char * cmdId = getData(data, DEFAULT_DATA_POSITION, len); 404 | logger(LOG_LEVEL_DEBUG, "event.c(getCommandEventData)", "command id %s, position - %d, length - %d", cmdId, DEFAULT_DATA_POSITION, len); 405 | 406 | res = malloc(sizeof(char) * (strlen(template) + MAX_EVENT_NAME_LENGTH + MAX_COMMAND_RESULT_NAME_LENGTH + 4)); 407 | sprintf(res, template, getEventNameByType(type), cmdId, cmdResult, cmdResultName); 408 | 409 | free(cmdResult); 410 | free(cmdId); 411 | 412 | return res; 413 | } 414 | 415 | static char * getReportEventData(uint8_t type, uint8_t * data, uint8_t len) 416 | { 417 | char * temperatureReportTemplate = ",\"temp\":%s,\"event\":\"%s\",\"scope\":\"Common\""; 418 | char * unknownReportTemplate = ",\"temp\":null,\"event\":\"%s\",\"scope\":\"Common\""; 419 | char * res = malloc(sizeof(char) * (strlen(temperatureReportTemplate) + MAX_EVENT_NAME_LENGTH + 2)); 420 | 421 | if (data[0] == 2) { 422 | char * extractedData = getData(data, REPORT_TEMP_DATA_POSITION, len); 423 | sprintf(res, temperatureReportTemplate, extractedData, getEventNameByType(type)); 424 | 425 | free(extractedData); 426 | } else { 427 | sprintf(res, unknownReportTemplate, getEventNameByType(type)); 428 | } 429 | 430 | return res; 431 | } 432 | 433 | static char * getAuthEventData(uint8_t type, uint8_t * data, uint8_t len) 434 | { 435 | char * template = ",\"user\":%s,\"event\":\"%s\",\"scope\":\"Auth\""; 436 | char * res = malloc(sizeof(char) * (strlen(template) + MAX_EVENT_NAME_LENGTH + 2)); 437 | char * extractedData = getData(data, DEFAULT_DATA_POSITION, len); 438 | 439 | sprintf(res, template, extractedData, getEventNameByType(type)); 440 | 441 | free(extractedData); 442 | 443 | return res; 444 | } 445 | 446 | static char * getSecurityEventData(uint8_t type, uint8_t * data, uint8_t len) 447 | { 448 | char * template = ",\"user\":%s,\"event\":\"%s\",\"scope\":\"Security\",\"sections\":%s"; 449 | char * res = malloc(sizeof(char) * (strlen(template) + MAX_EVENT_NAME_LENGTH + MAX_SECTION_LENGTH + 2)); 450 | char * extractedData = getData(data, USER_DATA_POSITION, len); 451 | uint8_t state_byte = data[0]; 452 | char affectedSections[MAX_SECTION_LENGTH]; 453 | 454 | get_affected_sections(state_byte, affectedSections); 455 | 456 | sprintf(res, template, extractedData, getEventNameByType(type), affectedSections); 457 | 458 | free(extractedData); 459 | return res; 460 | } 461 | 462 | static char * getZoneEventData(uint8_t type, uint8_t * data, uint8_t len) 463 | { 464 | char * template = ",\"zone\":%s,\"event\":\"%s\",\"scope\":\"Zone\""; 465 | char * res = malloc(sizeof(char) * (strlen(template) + MAX_EVENT_NAME_LENGTH + 2)); 466 | char * extractedData = getData(data, DEFAULT_DATA_POSITION, len); 467 | sprintf(res, template, extractedData, getEventNameByType(type)); 468 | 469 | free(extractedData); 470 | return res; 471 | } 472 | 473 | static char * getSectionEventData(uint8_t type, uint8_t * data, uint8_t len) 474 | { 475 | char * template = ",\"section\":%s,\"event\":\"%s\",\"scope\":\"Section\""; 476 | char * res = malloc(sizeof(char) * (strlen(template) + MAX_EVENT_NAME_LENGTH + 2)); 477 | char * extractedData = getData(data, DEFAULT_DATA_POSITION, len); 478 | 479 | sprintf(res, template, extractedData, getEventNameByType(type)); 480 | 481 | free(extractedData); 482 | 483 | return res; 484 | } 485 | 486 | static char * getCommonEventData(uint8_t type, uint8_t * data, uint8_t len, char * scope) 487 | { 488 | char * template = ",\"event\":\"%s\",\"scope\":\"%s\""; 489 | char * res; 490 | 491 | res = malloc(sizeof(char) * (strlen(template) + MAX_EVENT_NAME_LENGTH + 1 + strlen(scope))); 492 | sprintf(res, template, getEventNameByType(type), scope); 493 | 494 | return res; 495 | } 496 | 497 | static char * getData(uint8_t * data, uint8_t index, uint8_t len) 498 | { 499 | char * res = malloc(sizeof(char) * 4); 500 | 501 | if (index < len) 502 | { 503 | sprintf(res, "%d", data[index]); 504 | return res; 505 | } 506 | 507 | return "null"; 508 | } 509 | 510 | static char * getEventNameByType(uint8_t type) 511 | { 512 | if (type < EVENT_COUNT) { 513 | return (char *) events[type]; 514 | } 515 | return "null"; 516 | } 517 | 518 | void get_affected_sections(uint8_t state_byte, char *result) { 519 | char temp[4]; // Temporary buffer for individual port numbers 520 | int first = 1; // Flag to track if it's the first port in the list 521 | 522 | strcpy(result, "["); // Initialize the result with the opening bracket 523 | 524 | // Iterate through each bit (8 ports) 525 | for (int i = 0; i < 8; i++) { 526 | if ((state_byte & (1 << i))) { // Check if the i-th bit is 1 (closed) 527 | if (!first) { 528 | strcat(result, ", "); // Add a comma and space for subsequent ports 529 | } 530 | snprintf(temp, sizeof(temp), "%d", i + 1); // Convert port number to string 531 | strcat(result, temp); // Append the port number to the result 532 | first = 0; // Clear the flag after the first port 533 | } 534 | } 535 | 536 | strcat(result, "]"); // Append the closing bracket 537 | } -------------------------------------------------------------------------------- /dozord/INSTALL: -------------------------------------------------------------------------------- 1 | Installation Instructions 2 | ************************* 3 | 4 | Copyright (C) 1994-1996, 1999-2002, 2004-2016 Free Software 5 | Foundation, Inc. 6 | 7 | Copying and distribution of this file, with or without modification, 8 | are permitted in any medium without royalty provided the copyright 9 | notice and this notice are preserved. This file is offered as-is, 10 | without warranty of any kind. 11 | 12 | Basic Installation 13 | ================== 14 | 15 | Briefly, the shell command './configure && make && make install' 16 | should configure, build, and install this package. The following 17 | more-detailed instructions are generic; see the 'README' file for 18 | instructions specific to this package. Some packages provide this 19 | 'INSTALL' file but do not implement all of the features documented 20 | below. The lack of an optional feature in a given package is not 21 | necessarily a bug. More recommendations for GNU packages can be found 22 | in *note Makefile Conventions: (standards)Makefile Conventions. 23 | 24 | The 'configure' shell script attempts to guess correct values for 25 | various system-dependent variables used during compilation. It uses 26 | those values to create a 'Makefile' in each directory of the package. 27 | It may also create one or more '.h' files containing system-dependent 28 | definitions. Finally, it creates a shell script 'config.status' that 29 | you can run in the future to recreate the current configuration, and a 30 | file 'config.log' containing compiler output (useful mainly for 31 | debugging 'configure'). 32 | 33 | It can also use an optional file (typically called 'config.cache' and 34 | enabled with '--cache-file=config.cache' or simply '-C') that saves the 35 | results of its tests to speed up reconfiguring. Caching is disabled by 36 | default to prevent problems with accidental use of stale cache files. 37 | 38 | If you need to do unusual things to compile the package, please try 39 | to figure out how 'configure' could check whether to do them, and mail 40 | diffs or instructions to the address given in the 'README' so they can 41 | be considered for the next release. If you are using the cache, and at 42 | some point 'config.cache' contains results you don't want to keep, you 43 | may remove or edit it. 44 | 45 | The file 'configure.ac' (or 'configure.in') is used to create 46 | 'configure' by a program called 'autoconf'. You need 'configure.ac' if 47 | you want to change it or regenerate 'configure' using a newer version of 48 | 'autoconf'. 49 | 50 | The simplest way to compile this package is: 51 | 52 | 1. 'cd' to the directory containing the package's source code and type 53 | './configure' to configure the package for your system. 54 | 55 | Running 'configure' might take a while. While running, it prints 56 | some messages telling which features it is checking for. 57 | 58 | 2. Type 'make' to compile the package. 59 | 60 | 3. Optionally, type 'make check' to run any self-tests that come with 61 | the package, generally using the just-built uninstalled binaries. 62 | 63 | 4. Type 'make install' to install the programs and any data files and 64 | documentation. When installing into a prefix owned by root, it is 65 | recommended that the package be configured and built as a regular 66 | user, and only the 'make install' phase executed with root 67 | privileges. 68 | 69 | 5. Optionally, type 'make installcheck' to repeat any self-tests, but 70 | this time using the binaries in their final installed location. 71 | This target does not install anything. Running this target as a 72 | regular user, particularly if the prior 'make install' required 73 | root privileges, verifies that the installation completed 74 | correctly. 75 | 76 | 6. You can remove the program binaries and object files from the 77 | source code directory by typing 'make clean'. To also remove the 78 | files that 'configure' created (so you can compile the package for 79 | a different kind of computer), type 'make distclean'. There is 80 | also a 'make maintainer-clean' target, but that is intended mainly 81 | for the package's developers. If you use it, you may have to get 82 | all sorts of other programs in order to regenerate files that came 83 | with the distribution. 84 | 85 | 7. Often, you can also type 'make uninstall' to remove the installed 86 | files again. In practice, not all packages have tested that 87 | uninstallation works correctly, even though it is required by the 88 | GNU Coding Standards. 89 | 90 | 8. Some packages, particularly those that use Automake, provide 'make 91 | distcheck', which can by used by developers to test that all other 92 | targets like 'make install' and 'make uninstall' work correctly. 93 | This target is generally not run by end users. 94 | 95 | Compilers and Options 96 | ===================== 97 | 98 | Some systems require unusual options for compilation or linking that 99 | the 'configure' script does not know about. Run './configure --help' 100 | for details on some of the pertinent environment variables. 101 | 102 | You can give 'configure' initial values for configuration parameters 103 | by setting variables in the command line or in the environment. Here is 104 | an example: 105 | 106 | ./configure CC=c99 CFLAGS=-g LIBS=-lposix 107 | 108 | *Note Defining Variables::, for more details. 109 | 110 | Compiling For Multiple Architectures 111 | ==================================== 112 | 113 | You can compile the package for more than one kind of computer at the 114 | same time, by placing the object files for each architecture in their 115 | own directory. To do this, you can use GNU 'make'. 'cd' to the 116 | directory where you want the object files and executables to go and run 117 | the 'configure' script. 'configure' automatically checks for the source 118 | code in the directory that 'configure' is in and in '..'. This is known 119 | as a "VPATH" build. 120 | 121 | With a non-GNU 'make', it is safer to compile the package for one 122 | architecture at a time in the source code directory. After you have 123 | installed the package for one architecture, use 'make distclean' before 124 | reconfiguring for another architecture. 125 | 126 | On MacOS X 10.5 and later systems, you can create libraries and 127 | executables that work on multiple system types--known as "fat" or 128 | "universal" binaries--by specifying multiple '-arch' options to the 129 | compiler but only a single '-arch' option to the preprocessor. Like 130 | this: 131 | 132 | ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ 133 | CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ 134 | CPP="gcc -E" CXXCPP="g++ -E" 135 | 136 | This is not guaranteed to produce working output in all cases, you 137 | may have to build one architecture at a time and combine the results 138 | using the 'lipo' tool if you have problems. 139 | 140 | Installation Names 141 | ================== 142 | 143 | By default, 'make install' installs the package's commands under 144 | '/usr/local/bin', include files under '/usr/local/include', etc. You 145 | can specify an installation prefix other than '/usr/local' by giving 146 | 'configure' the option '--prefix=PREFIX', where PREFIX must be an 147 | absolute file name. 148 | 149 | You can specify separate installation prefixes for 150 | architecture-specific files and architecture-independent files. If you 151 | pass the option '--exec-prefix=PREFIX' to 'configure', the package uses 152 | PREFIX as the prefix for installing programs and libraries. 153 | Documentation and other data files still use the regular prefix. 154 | 155 | In addition, if you use an unusual directory layout you can give 156 | options like '--bindir=DIR' to specify different values for particular 157 | kinds of files. Run 'configure --help' for a list of the directories 158 | you can set and what kinds of files go in them. In general, the default 159 | for these options is expressed in terms of '${prefix}', so that 160 | specifying just '--prefix' will affect all of the other directory 161 | specifications that were not explicitly provided. 162 | 163 | The most portable way to affect installation locations is to pass the 164 | correct locations to 'configure'; however, many packages provide one or 165 | both of the following shortcuts of passing variable assignments to the 166 | 'make install' command line to change installation locations without 167 | having to reconfigure or recompile. 168 | 169 | The first method involves providing an override variable for each 170 | affected directory. For example, 'make install 171 | prefix=/alternate/directory' will choose an alternate location for all 172 | directory configuration variables that were expressed in terms of 173 | '${prefix}'. Any directories that were specified during 'configure', 174 | but not in terms of '${prefix}', must each be overridden at install time 175 | for the entire installation to be relocated. The approach of makefile 176 | variable overrides for each directory variable is required by the GNU 177 | Coding Standards, and ideally causes no recompilation. However, some 178 | platforms have known limitations with the semantics of shared libraries 179 | that end up requiring recompilation when using this method, particularly 180 | noticeable in packages that use GNU Libtool. 181 | 182 | The second method involves providing the 'DESTDIR' variable. For 183 | example, 'make install DESTDIR=/alternate/directory' will prepend 184 | '/alternate/directory' before all installation names. The approach of 185 | 'DESTDIR' overrides is not required by the GNU Coding Standards, and 186 | does not work on platforms that have drive letters. On the other hand, 187 | it does better at avoiding recompilation issues, and works well even 188 | when some directory options were not specified in terms of '${prefix}' 189 | at 'configure' time. 190 | 191 | Optional Features 192 | ================= 193 | 194 | If the package supports it, you can cause programs to be installed 195 | with an extra prefix or suffix on their names by giving 'configure' the 196 | option '--program-prefix=PREFIX' or '--program-suffix=SUFFIX'. 197 | 198 | Some packages pay attention to '--enable-FEATURE' options to 199 | 'configure', where FEATURE indicates an optional part of the package. 200 | They may also pay attention to '--with-PACKAGE' options, where PACKAGE 201 | is something like 'gnu-as' or 'x' (for the X Window System). The 202 | 'README' should mention any '--enable-' and '--with-' options that the 203 | package recognizes. 204 | 205 | For packages that use the X Window System, 'configure' can usually 206 | find the X include and library files automatically, but if it doesn't, 207 | you can use the 'configure' options '--x-includes=DIR' and 208 | '--x-libraries=DIR' to specify their locations. 209 | 210 | Some packages offer the ability to configure how verbose the 211 | execution of 'make' will be. For these packages, running './configure 212 | --enable-silent-rules' sets the default to minimal output, which can be 213 | overridden with 'make V=1'; while running './configure 214 | --disable-silent-rules' sets the default to verbose, which can be 215 | overridden with 'make V=0'. 216 | 217 | Particular systems 218 | ================== 219 | 220 | On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC 221 | is not installed, it is recommended to use the following options in 222 | order to use an ANSI C compiler: 223 | 224 | ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" 225 | 226 | and if that doesn't work, install pre-built binaries of GCC for HP-UX. 227 | 228 | HP-UX 'make' updates targets which have the same time stamps as their 229 | prerequisites, which makes it generally unusable when shipped generated 230 | files such as 'configure' are involved. Use GNU 'make' instead. 231 | 232 | On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot 233 | parse its '' header file. The option '-nodtk' can be used as a 234 | workaround. If GNU CC is not installed, it is therefore recommended to 235 | try 236 | 237 | ./configure CC="cc" 238 | 239 | and if that doesn't work, try 240 | 241 | ./configure CC="cc -nodtk" 242 | 243 | On Solaris, don't put '/usr/ucb' early in your 'PATH'. This 244 | directory contains several dysfunctional programs; working variants of 245 | these programs are available in '/usr/bin'. So, if you need '/usr/ucb' 246 | in your 'PATH', put it _after_ '/usr/bin'. 247 | 248 | On Haiku, software installed for all users goes in '/boot/common', 249 | not '/usr/local'. It is recommended to use the following options: 250 | 251 | ./configure --prefix=/boot/common 252 | 253 | Specifying the System Type 254 | ========================== 255 | 256 | There may be some features 'configure' cannot figure out 257 | automatically, but needs to determine by the type of machine the package 258 | will run on. Usually, assuming the package is built to be run on the 259 | _same_ architectures, 'configure' can figure that out, but if it prints 260 | a message saying it cannot guess the machine type, give it the 261 | '--build=TYPE' option. TYPE can either be a short name for the system 262 | type, such as 'sun4', or a canonical name which has the form: 263 | 264 | CPU-COMPANY-SYSTEM 265 | 266 | where SYSTEM can have one of these forms: 267 | 268 | OS 269 | KERNEL-OS 270 | 271 | See the file 'config.sub' for the possible values of each field. If 272 | 'config.sub' isn't included in this package, then this package doesn't 273 | need to know the machine type. 274 | 275 | If you are _building_ compiler tools for cross-compiling, you should 276 | use the option '--target=TYPE' to select the type of system they will 277 | produce code for. 278 | 279 | If you want to _use_ a cross compiler, that generates code for a 280 | platform different from the build platform, you should specify the 281 | "host" platform (i.e., that on which the generated programs will 282 | eventually be run) with '--host=TYPE'. 283 | 284 | Sharing Defaults 285 | ================ 286 | 287 | If you want to set default values for 'configure' scripts to share, 288 | you can create a site shell script called 'config.site' that gives 289 | default values for variables like 'CC', 'cache_file', and 'prefix'. 290 | 'configure' looks for 'PREFIX/share/config.site' if it exists, then 291 | 'PREFIX/etc/config.site' if it exists. Or, you can set the 292 | 'CONFIG_SITE' environment variable to the location of the site script. 293 | A warning: not all 'configure' scripts look for a site script. 294 | 295 | Defining Variables 296 | ================== 297 | 298 | Variables not defined in a site shell script can be set in the 299 | environment passed to 'configure'. However, some packages may run 300 | configure again during the build, and the customized values of these 301 | variables may be lost. In order to avoid this problem, you should set 302 | them in the 'configure' command line, using 'VAR=value'. For example: 303 | 304 | ./configure CC=/usr/local2/bin/gcc 305 | 306 | causes the specified 'gcc' to be used as the C compiler (unless it is 307 | overridden in the site shell script). 308 | 309 | Unfortunately, this technique does not work for 'CONFIG_SHELL' due to an 310 | Autoconf limitation. Until the limitation is lifted, you can use this 311 | workaround: 312 | 313 | CONFIG_SHELL=/bin/bash ./configure CONFIG_SHELL=/bin/bash 314 | 315 | 'configure' Invocation 316 | ====================== 317 | 318 | 'configure' recognizes the following options to control how it 319 | operates. 320 | 321 | '--help' 322 | '-h' 323 | Print a summary of all of the options to 'configure', and exit. 324 | 325 | '--help=short' 326 | '--help=recursive' 327 | Print a summary of the options unique to this package's 328 | 'configure', and exit. The 'short' variant lists options used only 329 | in the top level, while the 'recursive' variant lists options also 330 | present in any nested packages. 331 | 332 | '--version' 333 | '-V' 334 | Print the version of Autoconf used to generate the 'configure' 335 | script, and exit. 336 | 337 | '--cache-file=FILE' 338 | Enable the cache: use and save the results of the tests in FILE, 339 | traditionally 'config.cache'. FILE defaults to '/dev/null' to 340 | disable caching. 341 | 342 | '--config-cache' 343 | '-C' 344 | Alias for '--cache-file=config.cache'. 345 | 346 | '--quiet' 347 | '--silent' 348 | '-q' 349 | Do not print messages saying which checks are being made. To 350 | suppress all normal output, redirect it to '/dev/null' (any error 351 | messages will still be shown). 352 | 353 | '--srcdir=DIR' 354 | Look for the package's source code in directory DIR. Usually 355 | 'configure' can determine that directory automatically. 356 | 357 | '--prefix=DIR' 358 | Use DIR as the installation prefix. *note Installation Names:: for 359 | more details, including other options available for fine-tuning the 360 | installation locations. 361 | 362 | '--no-create' 363 | '-n' 364 | Run the configure checks, but stop before creating any output 365 | files. 366 | 367 | 'configure' also accepts some other, not widely useful, options. Run 368 | 'configure --help' for more details. 369 | -------------------------------------------------------------------------------- /libdozor/INSTALL: -------------------------------------------------------------------------------- 1 | Installation Instructions 2 | ************************* 3 | 4 | Copyright (C) 1994-1996, 1999-2002, 2004-2016 Free Software 5 | Foundation, Inc. 6 | 7 | Copying and distribution of this file, with or without modification, 8 | are permitted in any medium without royalty provided the copyright 9 | notice and this notice are preserved. This file is offered as-is, 10 | without warranty of any kind. 11 | 12 | Basic Installation 13 | ================== 14 | 15 | Briefly, the shell command './configure && make && make install' 16 | should configure, build, and install this package. The following 17 | more-detailed instructions are generic; see the 'README' file for 18 | instructions specific to this package. Some packages provide this 19 | 'INSTALL' file but do not implement all of the features documented 20 | below. The lack of an optional feature in a given package is not 21 | necessarily a bug. More recommendations for GNU packages can be found 22 | in *note Makefile Conventions: (standards)Makefile Conventions. 23 | 24 | The 'configure' shell script attempts to guess correct values for 25 | various system-dependent variables used during compilation. It uses 26 | those values to create a 'Makefile' in each directory of the package. 27 | It may also create one or more '.h' files containing system-dependent 28 | definitions. Finally, it creates a shell script 'config.status' that 29 | you can run in the future to recreate the current configuration, and a 30 | file 'config.log' containing compiler output (useful mainly for 31 | debugging 'configure'). 32 | 33 | It can also use an optional file (typically called 'config.cache' and 34 | enabled with '--cache-file=config.cache' or simply '-C') that saves the 35 | results of its tests to speed up reconfiguring. Caching is disabled by 36 | default to prevent problems with accidental use of stale cache files. 37 | 38 | If you need to do unusual things to compile the package, please try 39 | to figure out how 'configure' could check whether to do them, and mail 40 | diffs or instructions to the address given in the 'README' so they can 41 | be considered for the next release. If you are using the cache, and at 42 | some point 'config.cache' contains results you don't want to keep, you 43 | may remove or edit it. 44 | 45 | The file 'configure.ac' (or 'configure.in') is used to create 46 | 'configure' by a program called 'autoconf'. You need 'configure.ac' if 47 | you want to change it or regenerate 'configure' using a newer version of 48 | 'autoconf'. 49 | 50 | The simplest way to compile this package is: 51 | 52 | 1. 'cd' to the directory containing the package's source code and type 53 | './configure' to configure the package for your system. 54 | 55 | Running 'configure' might take a while. While running, it prints 56 | some messages telling which features it is checking for. 57 | 58 | 2. Type 'make' to compile the package. 59 | 60 | 3. Optionally, type 'make check' to run any self-tests that come with 61 | the package, generally using the just-built uninstalled binaries. 62 | 63 | 4. Type 'make install' to install the programs and any data files and 64 | documentation. When installing into a prefix owned by root, it is 65 | recommended that the package be configured and built as a regular 66 | user, and only the 'make install' phase executed with root 67 | privileges. 68 | 69 | 5. Optionally, type 'make installcheck' to repeat any self-tests, but 70 | this time using the binaries in their final installed location. 71 | This target does not install anything. Running this target as a 72 | regular user, particularly if the prior 'make install' required 73 | root privileges, verifies that the installation completed 74 | correctly. 75 | 76 | 6. You can remove the program binaries and object files from the 77 | source code directory by typing 'make clean'. To also remove the 78 | files that 'configure' created (so you can compile the package for 79 | a different kind of computer), type 'make distclean'. There is 80 | also a 'make maintainer-clean' target, but that is intended mainly 81 | for the package's developers. If you use it, you may have to get 82 | all sorts of other programs in order to regenerate files that came 83 | with the distribution. 84 | 85 | 7. Often, you can also type 'make uninstall' to remove the installed 86 | files again. In practice, not all packages have tested that 87 | uninstallation works correctly, even though it is required by the 88 | GNU Coding Standards. 89 | 90 | 8. Some packages, particularly those that use Automake, provide 'make 91 | distcheck', which can by used by developers to test that all other 92 | targets like 'make install' and 'make uninstall' work correctly. 93 | This target is generally not run by end users. 94 | 95 | Compilers and Options 96 | ===================== 97 | 98 | Some systems require unusual options for compilation or linking that 99 | the 'configure' script does not know about. Run './configure --help' 100 | for details on some of the pertinent environment variables. 101 | 102 | You can give 'configure' initial values for configuration parameters 103 | by setting variables in the command line or in the environment. Here is 104 | an example: 105 | 106 | ./configure CC=c99 CFLAGS=-g LIBS=-lposix 107 | 108 | *Note Defining Variables::, for more details. 109 | 110 | Compiling For Multiple Architectures 111 | ==================================== 112 | 113 | You can compile the package for more than one kind of computer at the 114 | same time, by placing the object files for each architecture in their 115 | own directory. To do this, you can use GNU 'make'. 'cd' to the 116 | directory where you want the object files and executables to go and run 117 | the 'configure' script. 'configure' automatically checks for the source 118 | code in the directory that 'configure' is in and in '..'. This is known 119 | as a "VPATH" build. 120 | 121 | With a non-GNU 'make', it is safer to compile the package for one 122 | architecture at a time in the source code directory. After you have 123 | installed the package for one architecture, use 'make distclean' before 124 | reconfiguring for another architecture. 125 | 126 | On MacOS X 10.5 and later systems, you can create libraries and 127 | executables that work on multiple system types--known as "fat" or 128 | "universal" binaries--by specifying multiple '-arch' options to the 129 | compiler but only a single '-arch' option to the preprocessor. Like 130 | this: 131 | 132 | ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ 133 | CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ 134 | CPP="gcc -E" CXXCPP="g++ -E" 135 | 136 | This is not guaranteed to produce working output in all cases, you 137 | may have to build one architecture at a time and combine the results 138 | using the 'lipo' tool if you have problems. 139 | 140 | Installation Names 141 | ================== 142 | 143 | By default, 'make install' installs the package's commands under 144 | '/usr/local/bin', include files under '/usr/local/include', etc. You 145 | can specify an installation prefix other than '/usr/local' by giving 146 | 'configure' the option '--prefix=PREFIX', where PREFIX must be an 147 | absolute file name. 148 | 149 | You can specify separate installation prefixes for 150 | architecture-specific files and architecture-independent files. If you 151 | pass the option '--exec-prefix=PREFIX' to 'configure', the package uses 152 | PREFIX as the prefix for installing programs and libraries. 153 | Documentation and other data files still use the regular prefix. 154 | 155 | In addition, if you use an unusual directory layout you can give 156 | options like '--bindir=DIR' to specify different values for particular 157 | kinds of files. Run 'configure --help' for a list of the directories 158 | you can set and what kinds of files go in them. In general, the default 159 | for these options is expressed in terms of '${prefix}', so that 160 | specifying just '--prefix' will affect all of the other directory 161 | specifications that were not explicitly provided. 162 | 163 | The most portable way to affect installation locations is to pass the 164 | correct locations to 'configure'; however, many packages provide one or 165 | both of the following shortcuts of passing variable assignments to the 166 | 'make install' command line to change installation locations without 167 | having to reconfigure or recompile. 168 | 169 | The first method involves providing an override variable for each 170 | affected directory. For example, 'make install 171 | prefix=/alternate/directory' will choose an alternate location for all 172 | directory configuration variables that were expressed in terms of 173 | '${prefix}'. Any directories that were specified during 'configure', 174 | but not in terms of '${prefix}', must each be overridden at install time 175 | for the entire installation to be relocated. The approach of makefile 176 | variable overrides for each directory variable is required by the GNU 177 | Coding Standards, and ideally causes no recompilation. However, some 178 | platforms have known limitations with the semantics of shared libraries 179 | that end up requiring recompilation when using this method, particularly 180 | noticeable in packages that use GNU Libtool. 181 | 182 | The second method involves providing the 'DESTDIR' variable. For 183 | example, 'make install DESTDIR=/alternate/directory' will prepend 184 | '/alternate/directory' before all installation names. The approach of 185 | 'DESTDIR' overrides is not required by the GNU Coding Standards, and 186 | does not work on platforms that have drive letters. On the other hand, 187 | it does better at avoiding recompilation issues, and works well even 188 | when some directory options were not specified in terms of '${prefix}' 189 | at 'configure' time. 190 | 191 | Optional Features 192 | ================= 193 | 194 | If the package supports it, you can cause programs to be installed 195 | with an extra prefix or suffix on their names by giving 'configure' the 196 | option '--program-prefix=PREFIX' or '--program-suffix=SUFFIX'. 197 | 198 | Some packages pay attention to '--enable-FEATURE' options to 199 | 'configure', where FEATURE indicates an optional part of the package. 200 | They may also pay attention to '--with-PACKAGE' options, where PACKAGE 201 | is something like 'gnu-as' or 'x' (for the X Window System). The 202 | 'README' should mention any '--enable-' and '--with-' options that the 203 | package recognizes. 204 | 205 | For packages that use the X Window System, 'configure' can usually 206 | find the X include and library files automatically, but if it doesn't, 207 | you can use the 'configure' options '--x-includes=DIR' and 208 | '--x-libraries=DIR' to specify their locations. 209 | 210 | Some packages offer the ability to configure how verbose the 211 | execution of 'make' will be. For these packages, running './configure 212 | --enable-silent-rules' sets the default to minimal output, which can be 213 | overridden with 'make V=1'; while running './configure 214 | --disable-silent-rules' sets the default to verbose, which can be 215 | overridden with 'make V=0'. 216 | 217 | Particular systems 218 | ================== 219 | 220 | On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC 221 | is not installed, it is recommended to use the following options in 222 | order to use an ANSI C compiler: 223 | 224 | ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" 225 | 226 | and if that doesn't work, install pre-built binaries of GCC for HP-UX. 227 | 228 | HP-UX 'make' updates targets which have the same time stamps as their 229 | prerequisites, which makes it generally unusable when shipped generated 230 | files such as 'configure' are involved. Use GNU 'make' instead. 231 | 232 | On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot 233 | parse its '' header file. The option '-nodtk' can be used as a 234 | workaround. If GNU CC is not installed, it is therefore recommended to 235 | try 236 | 237 | ./configure CC="cc" 238 | 239 | and if that doesn't work, try 240 | 241 | ./configure CC="cc -nodtk" 242 | 243 | On Solaris, don't put '/usr/ucb' early in your 'PATH'. This 244 | directory contains several dysfunctional programs; working variants of 245 | these programs are available in '/usr/bin'. So, if you need '/usr/ucb' 246 | in your 'PATH', put it _after_ '/usr/bin'. 247 | 248 | On Haiku, software installed for all users goes in '/boot/common', 249 | not '/usr/local'. It is recommended to use the following options: 250 | 251 | ./configure --prefix=/boot/common 252 | 253 | Specifying the System Type 254 | ========================== 255 | 256 | There may be some features 'configure' cannot figure out 257 | automatically, but needs to determine by the type of machine the package 258 | will run on. Usually, assuming the package is built to be run on the 259 | _same_ architectures, 'configure' can figure that out, but if it prints 260 | a message saying it cannot guess the machine type, give it the 261 | '--build=TYPE' option. TYPE can either be a short name for the system 262 | type, such as 'sun4', or a canonical name which has the form: 263 | 264 | CPU-COMPANY-SYSTEM 265 | 266 | where SYSTEM can have one of these forms: 267 | 268 | OS 269 | KERNEL-OS 270 | 271 | See the file 'config.sub' for the possible values of each field. If 272 | 'config.sub' isn't included in this package, then this package doesn't 273 | need to know the machine type. 274 | 275 | If you are _building_ compiler tools for cross-compiling, you should 276 | use the option '--target=TYPE' to select the type of system they will 277 | produce code for. 278 | 279 | If you want to _use_ a cross compiler, that generates code for a 280 | platform different from the build platform, you should specify the 281 | "host" platform (i.e., that on which the generated programs will 282 | eventually be run) with '--host=TYPE'. 283 | 284 | Sharing Defaults 285 | ================ 286 | 287 | If you want to set default values for 'configure' scripts to share, 288 | you can create a site shell script called 'config.site' that gives 289 | default values for variables like 'CC', 'cache_file', and 'prefix'. 290 | 'configure' looks for 'PREFIX/share/config.site' if it exists, then 291 | 'PREFIX/etc/config.site' if it exists. Or, you can set the 292 | 'CONFIG_SITE' environment variable to the location of the site script. 293 | A warning: not all 'configure' scripts look for a site script. 294 | 295 | Defining Variables 296 | ================== 297 | 298 | Variables not defined in a site shell script can be set in the 299 | environment passed to 'configure'. However, some packages may run 300 | configure again during the build, and the customized values of these 301 | variables may be lost. In order to avoid this problem, you should set 302 | them in the 'configure' command line, using 'VAR=value'. For example: 303 | 304 | ./configure CC=/usr/local2/bin/gcc 305 | 306 | causes the specified 'gcc' to be used as the C compiler (unless it is 307 | overridden in the site shell script). 308 | 309 | Unfortunately, this technique does not work for 'CONFIG_SHELL' due to an 310 | Autoconf limitation. Until the limitation is lifted, you can use this 311 | workaround: 312 | 313 | CONFIG_SHELL=/bin/bash ./configure CONFIG_SHELL=/bin/bash 314 | 315 | 'configure' Invocation 316 | ====================== 317 | 318 | 'configure' recognizes the following options to control how it 319 | operates. 320 | 321 | '--help' 322 | '-h' 323 | Print a summary of all of the options to 'configure', and exit. 324 | 325 | '--help=short' 326 | '--help=recursive' 327 | Print a summary of the options unique to this package's 328 | 'configure', and exit. The 'short' variant lists options used only 329 | in the top level, while the 'recursive' variant lists options also 330 | present in any nested packages. 331 | 332 | '--version' 333 | '-V' 334 | Print the version of Autoconf used to generate the 'configure' 335 | script, and exit. 336 | 337 | '--cache-file=FILE' 338 | Enable the cache: use and save the results of the tests in FILE, 339 | traditionally 'config.cache'. FILE defaults to '/dev/null' to 340 | disable caching. 341 | 342 | '--config-cache' 343 | '-C' 344 | Alias for '--cache-file=config.cache'. 345 | 346 | '--quiet' 347 | '--silent' 348 | '-q' 349 | Do not print messages saying which checks are being made. To 350 | suppress all normal output, redirect it to '/dev/null' (any error 351 | messages will still be shown). 352 | 353 | '--srcdir=DIR' 354 | Look for the package's source code in directory DIR. Usually 355 | 'configure' can determine that directory automatically. 356 | 357 | '--prefix=DIR' 358 | Use DIR as the installation prefix. *note Installation Names:: for 359 | more details, including other options available for fine-tuning the 360 | installation locations. 361 | 362 | '--no-create' 363 | '-n' 364 | Run the configure checks, but stop before creating any output 365 | files. 366 | 367 | 'configure' also accepts some other, not widely useful, options. Run 368 | 'configure --help' for more details. 369 | -------------------------------------------------------------------------------- /tools/INSTALL: -------------------------------------------------------------------------------- 1 | Installation Instructions 2 | ************************* 3 | 4 | Copyright (C) 1994-1996, 1999-2002, 2004-2016 Free Software 5 | Foundation, Inc. 6 | 7 | Copying and distribution of this file, with or without modification, 8 | are permitted in any medium without royalty provided the copyright 9 | notice and this notice are preserved. This file is offered as-is, 10 | without warranty of any kind. 11 | 12 | Basic Installation 13 | ================== 14 | 15 | Briefly, the shell command './configure && make && make install' 16 | should configure, build, and install this package. The following 17 | more-detailed instructions are generic; see the 'README' file for 18 | instructions specific to this package. Some packages provide this 19 | 'INSTALL' file but do not implement all of the features documented 20 | below. The lack of an optional feature in a given package is not 21 | necessarily a bug. More recommendations for GNU packages can be found 22 | in *note Makefile Conventions: (standards)Makefile Conventions. 23 | 24 | The 'configure' shell script attempts to guess correct values for 25 | various system-dependent variables used during compilation. It uses 26 | those values to create a 'Makefile' in each directory of the package. 27 | It may also create one or more '.h' files containing system-dependent 28 | definitions. Finally, it creates a shell script 'config.status' that 29 | you can run in the future to recreate the current configuration, and a 30 | file 'config.log' containing compiler output (useful mainly for 31 | debugging 'configure'). 32 | 33 | It can also use an optional file (typically called 'config.cache' and 34 | enabled with '--cache-file=config.cache' or simply '-C') that saves the 35 | results of its tests to speed up reconfiguring. Caching is disabled by 36 | default to prevent problems with accidental use of stale cache files. 37 | 38 | If you need to do unusual things to compile the package, please try 39 | to figure out how 'configure' could check whether to do them, and mail 40 | diffs or instructions to the address given in the 'README' so they can 41 | be considered for the next release. If you are using the cache, and at 42 | some point 'config.cache' contains results you don't want to keep, you 43 | may remove or edit it. 44 | 45 | The file 'configure.ac' (or 'configure.in') is used to create 46 | 'configure' by a program called 'autoconf'. You need 'configure.ac' if 47 | you want to change it or regenerate 'configure' using a newer version of 48 | 'autoconf'. 49 | 50 | The simplest way to compile this package is: 51 | 52 | 1. 'cd' to the directory containing the package's source code and type 53 | './configure' to configure the package for your system. 54 | 55 | Running 'configure' might take a while. While running, it prints 56 | some messages telling which features it is checking for. 57 | 58 | 2. Type 'make' to compile the package. 59 | 60 | 3. Optionally, type 'make check' to run any self-tests that come with 61 | the package, generally using the just-built uninstalled binaries. 62 | 63 | 4. Type 'make install' to install the programs and any data files and 64 | documentation. When installing into a prefix owned by root, it is 65 | recommended that the package be configured and built as a regular 66 | user, and only the 'make install' phase executed with root 67 | privileges. 68 | 69 | 5. Optionally, type 'make installcheck' to repeat any self-tests, but 70 | this time using the binaries in their final installed location. 71 | This target does not install anything. Running this target as a 72 | regular user, particularly if the prior 'make install' required 73 | root privileges, verifies that the installation completed 74 | correctly. 75 | 76 | 6. You can remove the program binaries and object files from the 77 | source code directory by typing 'make clean'. To also remove the 78 | files that 'configure' created (so you can compile the package for 79 | a different kind of computer), type 'make distclean'. There is 80 | also a 'make maintainer-clean' target, but that is intended mainly 81 | for the package's developers. If you use it, you may have to get 82 | all sorts of other programs in order to regenerate files that came 83 | with the distribution. 84 | 85 | 7. Often, you can also type 'make uninstall' to remove the installed 86 | files again. In practice, not all packages have tested that 87 | uninstallation works correctly, even though it is required by the 88 | GNU Coding Standards. 89 | 90 | 8. Some packages, particularly those that use Automake, provide 'make 91 | distcheck', which can by used by developers to test that all other 92 | targets like 'make install' and 'make uninstall' work correctly. 93 | This target is generally not run by end users. 94 | 95 | Compilers and Options 96 | ===================== 97 | 98 | Some systems require unusual options for compilation or linking that 99 | the 'configure' script does not know about. Run './configure --help' 100 | for details on some of the pertinent environment variables. 101 | 102 | You can give 'configure' initial values for configuration parameters 103 | by setting variables in the command line or in the environment. Here is 104 | an example: 105 | 106 | ./configure CC=c99 CFLAGS=-g LIBS=-lposix 107 | 108 | *Note Defining Variables::, for more details. 109 | 110 | Compiling For Multiple Architectures 111 | ==================================== 112 | 113 | You can compile the package for more than one kind of computer at the 114 | same time, by placing the object files for each architecture in their 115 | own directory. To do this, you can use GNU 'make'. 'cd' to the 116 | directory where you want the object files and executables to go and run 117 | the 'configure' script. 'configure' automatically checks for the source 118 | code in the directory that 'configure' is in and in '..'. This is known 119 | as a "VPATH" build. 120 | 121 | With a non-GNU 'make', it is safer to compile the package for one 122 | architecture at a time in the source code directory. After you have 123 | installed the package for one architecture, use 'make distclean' before 124 | reconfiguring for another architecture. 125 | 126 | On MacOS X 10.5 and later systems, you can create libraries and 127 | executables that work on multiple system types--known as "fat" or 128 | "universal" binaries--by specifying multiple '-arch' options to the 129 | compiler but only a single '-arch' option to the preprocessor. Like 130 | this: 131 | 132 | ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ 133 | CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ 134 | CPP="gcc -E" CXXCPP="g++ -E" 135 | 136 | This is not guaranteed to produce working output in all cases, you 137 | may have to build one architecture at a time and combine the results 138 | using the 'lipo' tool if you have problems. 139 | 140 | Installation Names 141 | ================== 142 | 143 | By default, 'make install' installs the package's commands under 144 | '/usr/local/bin', include files under '/usr/local/include', etc. You 145 | can specify an installation prefix other than '/usr/local' by giving 146 | 'configure' the option '--prefix=PREFIX', where PREFIX must be an 147 | absolute file name. 148 | 149 | You can specify separate installation prefixes for 150 | architecture-specific files and architecture-independent files. If you 151 | pass the option '--exec-prefix=PREFIX' to 'configure', the package uses 152 | PREFIX as the prefix for installing programs and libraries. 153 | Documentation and other data files still use the regular prefix. 154 | 155 | In addition, if you use an unusual directory layout you can give 156 | options like '--bindir=DIR' to specify different values for particular 157 | kinds of files. Run 'configure --help' for a list of the directories 158 | you can set and what kinds of files go in them. In general, the default 159 | for these options is expressed in terms of '${prefix}', so that 160 | specifying just '--prefix' will affect all of the other directory 161 | specifications that were not explicitly provided. 162 | 163 | The most portable way to affect installation locations is to pass the 164 | correct locations to 'configure'; however, many packages provide one or 165 | both of the following shortcuts of passing variable assignments to the 166 | 'make install' command line to change installation locations without 167 | having to reconfigure or recompile. 168 | 169 | The first method involves providing an override variable for each 170 | affected directory. For example, 'make install 171 | prefix=/alternate/directory' will choose an alternate location for all 172 | directory configuration variables that were expressed in terms of 173 | '${prefix}'. Any directories that were specified during 'configure', 174 | but not in terms of '${prefix}', must each be overridden at install time 175 | for the entire installation to be relocated. The approach of makefile 176 | variable overrides for each directory variable is required by the GNU 177 | Coding Standards, and ideally causes no recompilation. However, some 178 | platforms have known limitations with the semantics of shared libraries 179 | that end up requiring recompilation when using this method, particularly 180 | noticeable in packages that use GNU Libtool. 181 | 182 | The second method involves providing the 'DESTDIR' variable. For 183 | example, 'make install DESTDIR=/alternate/directory' will prepend 184 | '/alternate/directory' before all installation names. The approach of 185 | 'DESTDIR' overrides is not required by the GNU Coding Standards, and 186 | does not work on platforms that have drive letters. On the other hand, 187 | it does better at avoiding recompilation issues, and works well even 188 | when some directory options were not specified in terms of '${prefix}' 189 | at 'configure' time. 190 | 191 | Optional Features 192 | ================= 193 | 194 | If the package supports it, you can cause programs to be installed 195 | with an extra prefix or suffix on their names by giving 'configure' the 196 | option '--program-prefix=PREFIX' or '--program-suffix=SUFFIX'. 197 | 198 | Some packages pay attention to '--enable-FEATURE' options to 199 | 'configure', where FEATURE indicates an optional part of the package. 200 | They may also pay attention to '--with-PACKAGE' options, where PACKAGE 201 | is something like 'gnu-as' or 'x' (for the X Window System). The 202 | 'README' should mention any '--enable-' and '--with-' options that the 203 | package recognizes. 204 | 205 | For packages that use the X Window System, 'configure' can usually 206 | find the X include and library files automatically, but if it doesn't, 207 | you can use the 'configure' options '--x-includes=DIR' and 208 | '--x-libraries=DIR' to specify their locations. 209 | 210 | Some packages offer the ability to configure how verbose the 211 | execution of 'make' will be. For these packages, running './configure 212 | --enable-silent-rules' sets the default to minimal output, which can be 213 | overridden with 'make V=1'; while running './configure 214 | --disable-silent-rules' sets the default to verbose, which can be 215 | overridden with 'make V=0'. 216 | 217 | Particular systems 218 | ================== 219 | 220 | On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC 221 | is not installed, it is recommended to use the following options in 222 | order to use an ANSI C compiler: 223 | 224 | ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" 225 | 226 | and if that doesn't work, install pre-built binaries of GCC for HP-UX. 227 | 228 | HP-UX 'make' updates targets which have the same time stamps as their 229 | prerequisites, which makes it generally unusable when shipped generated 230 | files such as 'configure' are involved. Use GNU 'make' instead. 231 | 232 | On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot 233 | parse its '' header file. The option '-nodtk' can be used as a 234 | workaround. If GNU CC is not installed, it is therefore recommended to 235 | try 236 | 237 | ./configure CC="cc" 238 | 239 | and if that doesn't work, try 240 | 241 | ./configure CC="cc -nodtk" 242 | 243 | On Solaris, don't put '/usr/ucb' early in your 'PATH'. This 244 | directory contains several dysfunctional programs; working variants of 245 | these programs are available in '/usr/bin'. So, if you need '/usr/ucb' 246 | in your 'PATH', put it _after_ '/usr/bin'. 247 | 248 | On Haiku, software installed for all users goes in '/boot/common', 249 | not '/usr/local'. It is recommended to use the following options: 250 | 251 | ./configure --prefix=/boot/common 252 | 253 | Specifying the System Type 254 | ========================== 255 | 256 | There may be some features 'configure' cannot figure out 257 | automatically, but needs to determine by the type of machine the package 258 | will run on. Usually, assuming the package is built to be run on the 259 | _same_ architectures, 'configure' can figure that out, but if it prints 260 | a message saying it cannot guess the machine type, give it the 261 | '--build=TYPE' option. TYPE can either be a short name for the system 262 | type, such as 'sun4', or a canonical name which has the form: 263 | 264 | CPU-COMPANY-SYSTEM 265 | 266 | where SYSTEM can have one of these forms: 267 | 268 | OS 269 | KERNEL-OS 270 | 271 | See the file 'config.sub' for the possible values of each field. If 272 | 'config.sub' isn't included in this package, then this package doesn't 273 | need to know the machine type. 274 | 275 | If you are _building_ compiler tools for cross-compiling, you should 276 | use the option '--target=TYPE' to select the type of system they will 277 | produce code for. 278 | 279 | If you want to _use_ a cross compiler, that generates code for a 280 | platform different from the build platform, you should specify the 281 | "host" platform (i.e., that on which the generated programs will 282 | eventually be run) with '--host=TYPE'. 283 | 284 | Sharing Defaults 285 | ================ 286 | 287 | If you want to set default values for 'configure' scripts to share, 288 | you can create a site shell script called 'config.site' that gives 289 | default values for variables like 'CC', 'cache_file', and 'prefix'. 290 | 'configure' looks for 'PREFIX/share/config.site' if it exists, then 291 | 'PREFIX/etc/config.site' if it exists. Or, you can set the 292 | 'CONFIG_SITE' environment variable to the location of the site script. 293 | A warning: not all 'configure' scripts look for a site script. 294 | 295 | Defining Variables 296 | ================== 297 | 298 | Variables not defined in a site shell script can be set in the 299 | environment passed to 'configure'. However, some packages may run 300 | configure again during the build, and the customized values of these 301 | variables may be lost. In order to avoid this problem, you should set 302 | them in the 'configure' command line, using 'VAR=value'. For example: 303 | 304 | ./configure CC=/usr/local2/bin/gcc 305 | 306 | causes the specified 'gcc' to be used as the C compiler (unless it is 307 | overridden in the site shell script). 308 | 309 | Unfortunately, this technique does not work for 'CONFIG_SHELL' due to an 310 | Autoconf limitation. Until the limitation is lifted, you can use this 311 | workaround: 312 | 313 | CONFIG_SHELL=/bin/bash ./configure CONFIG_SHELL=/bin/bash 314 | 315 | 'configure' Invocation 316 | ====================== 317 | 318 | 'configure' recognizes the following options to control how it 319 | operates. 320 | 321 | '--help' 322 | '-h' 323 | Print a summary of all of the options to 'configure', and exit. 324 | 325 | '--help=short' 326 | '--help=recursive' 327 | Print a summary of the options unique to this package's 328 | 'configure', and exit. The 'short' variant lists options used only 329 | in the top level, while the 'recursive' variant lists options also 330 | present in any nested packages. 331 | 332 | '--version' 333 | '-V' 334 | Print the version of Autoconf used to generate the 'configure' 335 | script, and exit. 336 | 337 | '--cache-file=FILE' 338 | Enable the cache: use and save the results of the tests in FILE, 339 | traditionally 'config.cache'. FILE defaults to '/dev/null' to 340 | disable caching. 341 | 342 | '--config-cache' 343 | '-C' 344 | Alias for '--cache-file=config.cache'. 345 | 346 | '--quiet' 347 | '--silent' 348 | '-q' 349 | Do not print messages saying which checks are being made. To 350 | suppress all normal output, redirect it to '/dev/null' (any error 351 | messages will still be shown). 352 | 353 | '--srcdir=DIR' 354 | Look for the package's source code in directory DIR. Usually 355 | 'configure' can determine that directory automatically. 356 | 357 | '--prefix=DIR' 358 | Use DIR as the installation prefix. *note Installation Names:: for 359 | more details, including other options available for fine-tuning the 360 | installation locations. 361 | 362 | '--no-create' 363 | '-n' 364 | Run the configure checks, but stop before creating any output 365 | files. 366 | 367 | 'configure' also accepts some other, not widely useful, options. Run 368 | 'configure --help' for more details. 369 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------