├── src ├── utility │ ├── jsmn │ │ ├── .travis.yml │ │ ├── library.json │ │ ├── Makefile │ │ ├── LICENSE │ │ ├── jsmn.h │ │ ├── README.md │ │ └── jsmn.c │ ├── multihttpsclient │ │ ├── .gitmodules │ │ ├── README.md │ │ ├── multihttpsclient.h │ │ ├── multihttpsclient_hals │ │ │ ├── espidf │ │ │ │ ├── multihttpsclient_espidf.h │ │ │ │ └── multihttpsclient_espidf.cpp │ │ │ ├── arduino │ │ │ │ ├── multihttpsclient_arduino.h │ │ │ │ └── multihttpsclient_arduino.cpp │ │ │ └── generic │ │ │ │ ├── multihttpsclient_generic.h │ │ │ │ └── multihttpsclient_generic.cpp │ │ └── LICENSE │ └── get_update_libs └── utlgbotlib.h ├── library.properties ├── keywords.txt ├── library.json ├── beforebuild.py ├── res └── certs │ └── apitelegramorg.crt ├── examples ├── native_windows_linux │ └── echobot │ │ └── main.cpp ├── arduino │ ├── echo │ │ └── echo.ino │ ├── show_received_messages │ │ └── show_received_messages.ino │ └── commands_control_led │ │ └── commands_control_led.ino └── espidf │ └── echobot │ └── echobot.cpp ├── README.md └── LICENSE /src/utility/jsmn/.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | sudo: false 3 | script: 4 | - make test 5 | -------------------------------------------------------------------------------- /src/utility/multihttpsclient/.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "mbedtls"] 2 | path = mbedtls 3 | url = https://github.com/ARMmbed/mbedtls 4 | -------------------------------------------------------------------------------- /src/utility/multihttpsclient/README.md: -------------------------------------------------------------------------------- 1 | # multihttpsclient 2 | Multiplatform HTTPS Client (Implement basic HTTP requests HALs for differents devices and systems). 3 | -------------------------------------------------------------------------------- /src/utility/jsmn/library.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jsmn", 3 | "keywords": "json", 4 | "description": "Minimalistic JSON parser/tokenizer in C. It can be easily integrated into resource-limited or embedded projects", 5 | "repository": 6 | { 7 | "type": "git", 8 | "url": "https://github.com/zserge/jsmn.git" 9 | }, 10 | "frameworks": "*", 11 | "platforms": "*", 12 | "examples": [ 13 | "example/*.c" 14 | ], 15 | "exclude": "test" 16 | } 17 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=uTLGBotLib 2 | version=1.0.0 3 | author=JRios 4 | maintainer=JRios 5 | sentence=Universal Telegram Bot library for Arduino, ESP-IDF and Native (Windows and Linux) devices, that let you create Telegram Bots. 6 | paragraph=Universal Telegram Bot library for Arduino, ESP-IDF and Native (Windows and Linux) devices, that let you create Telegram Bots. You can use it with ESP8266 and ESP32 microcontrollers. 7 | category=Communication 8 | url=https://github.com/J-Rios/uTLGBotLib-arduino 9 | architectures=* 10 | -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | ########################################### 2 | # Syntax Coloring Map For uTLGBotLib 3 | ########################################### 4 | 5 | ########################################### 6 | # Datatypes (KEYWORD1) 7 | ########################################### 8 | 9 | uTLGBot KEYWORD1 10 | 11 | ########################################### 12 | # Methods and Functions (KEYWORD2) 13 | ########################################### 14 | 15 | connect KEYWORD2 16 | disconnect KEYWORD2 17 | is_connected KEYWORD2 18 | getMe KEYWORD2 19 | sendMessage KEYWORD2 20 | getUpdates KEYWORD2 21 | -------------------------------------------------------------------------------- /library.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "uTLGBotLib", 3 | "keywords": "arduino, espidf, esp8266, esp32, telegram, bot", 4 | "description": "Universal Telegram Bot library for Arduino, ESP-IDF and Native (Windows and Linux) devices, that let you create Telegram Bots. You can use it with ESP8266 and ESP32 microcontrollers.", 5 | "authors": { 6 | "name": "JRios", 7 | "url": "https://github.com/J-Rios" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "https://github.com/J-Rios/uTLGBotLib-arduino" 12 | }, 13 | "version": "1.0", 14 | "frameworks": ["arduino", "espidf", "native"], 15 | "platforms": ["espressif8266", "espressif32"], 16 | "build": { 17 | "libCompatMode": "off", 18 | "extraScript": "beforebuild.py" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/utility/get_update_libs: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Description: 3 | # This Script get/update lastest uTLGBotLib depending libraries from lastest 4 | # 5 | 6 | echo "" 7 | echo " Trying to get/update uTLGBotLib depending libraries from lastest." 8 | echo "" 9 | 10 | echo " Downloading multihttpsclient repository..." 11 | rm -rf multihttpsclient 12 | git clone --recurse-submodules https://github.com/J-Rios/multihttpsclient 13 | if [[ $? != 0 ]]; then 14 | echo " Error: Can't clone multihttpsclient library." 15 | echo "" 16 | exit 1 17 | fi 18 | 19 | echo " Downloading jsmn repository..." 20 | rm -rf jsmn 21 | git clone --recurse-submodules https://github.com/zserge/jsmn 22 | if [[ $? != 0 ]]; then 23 | echo " Error: Can't clone jsmn library." 24 | echo "" 25 | exit 1 26 | fi 27 | cd jsmn 28 | git checkout 18e9fe42cbfe21d65076f5c77ae2be379ad1270f 29 | cd .. 30 | 31 | echo "" 32 | echo " Process completed." 33 | 34 | exit 0 35 | -------------------------------------------------------------------------------- /src/utility/jsmn/Makefile: -------------------------------------------------------------------------------- 1 | # You can put your build options here 2 | -include config.mk 3 | 4 | all: libjsmn.a 5 | 6 | libjsmn.a: jsmn.o 7 | $(AR) rc $@ $^ 8 | 9 | %.o: %.c jsmn.h 10 | $(CC) -c $(CFLAGS) $< -o $@ 11 | 12 | test: test_default test_strict test_links test_strict_links 13 | test_default: test/tests.c 14 | $(CC) $(CFLAGS) $(LDFLAGS) $< -o test/$@ 15 | ./test/$@ 16 | test_strict: test/tests.c 17 | $(CC) -DJSMN_STRICT=1 $(CFLAGS) $(LDFLAGS) $< -o test/$@ 18 | ./test/$@ 19 | test_links: test/tests.c 20 | $(CC) -DJSMN_PARENT_LINKS=1 $(CFLAGS) $(LDFLAGS) $< -o test/$@ 21 | ./test/$@ 22 | test_strict_links: test/tests.c 23 | $(CC) -DJSMN_STRICT=1 -DJSMN_PARENT_LINKS=1 $(CFLAGS) $(LDFLAGS) $< -o test/$@ 24 | ./test/$@ 25 | 26 | jsmn_test.o: jsmn_test.c libjsmn.a 27 | 28 | simple_example: example/simple.o libjsmn.a 29 | $(CC) $(LDFLAGS) $^ -o $@ 30 | 31 | jsondump: example/jsondump.o libjsmn.a 32 | $(CC) $(LDFLAGS) $^ -o $@ 33 | 34 | clean: 35 | rm -f *.o example/*.o 36 | rm -f *.a *.so 37 | rm -f simple_example 38 | rm -f jsondump 39 | 40 | .PHONY: all clean test 41 | 42 | -------------------------------------------------------------------------------- /src/utility/jsmn/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010 Serge A. Zaitsev 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | 21 | -------------------------------------------------------------------------------- /beforebuild.py: -------------------------------------------------------------------------------- 1 | 2 | # Import Build Environment 3 | Import("env") 4 | 5 | #################################################################################################### 6 | 7 | # Callback function to skip and ignore file from a build process 8 | def skip_file_from_build(node): 9 | '''Skip and ignore file from a build process.''' 10 | return None 11 | 12 | #################################################################################################### 13 | 14 | # Get used PIO Framework (Doesn't exists in Native) 15 | build_framework = [] 16 | if "PIOFRAMEWORK" in env: 17 | build_framework = env["PIOFRAMEWORK"] 18 | print("Build framework - {}".format(build_framework)) 19 | 20 | # Check build and ignore custom mbedtls for ESP32 (To avoid conflict with esp-idf mbedtls component) 21 | if ("arduino" in build_framework) or ("espidf" in build_framework): 22 | print("ESP32 Build detected, ignoring multihttpsclient/mbedtls.") 23 | env.AddBuildMiddleware(skip_file_from_build, "*multihttpsclient/mbedtls/*") 24 | else: 25 | print("Generic Native Build detected, using src/utility/multihttpsclient/mbedtls.") 26 | -------------------------------------------------------------------------------- /res/certs/apitelegramorg.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx 3 | EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT 4 | EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp 5 | ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz 6 | NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH 7 | EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE 8 | AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw 9 | DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD 10 | E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH 11 | /PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy 12 | DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh 13 | GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR 14 | tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA 15 | AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE 16 | FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX 17 | WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu 18 | 9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr 19 | gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo 20 | 2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO 21 | LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI 22 | 4uJEvlz36hz1 23 | -----END CERTIFICATE----- 24 | -------------------------------------------------------------------------------- /src/utility/jsmn/jsmn.h: -------------------------------------------------------------------------------- 1 | #ifndef __JSMN_H_ 2 | #define __JSMN_H_ 3 | 4 | #include 5 | 6 | #ifdef __cplusplus 7 | extern "C" { 8 | #endif 9 | 10 | /** 11 | * JSON type identifier. Basic types are: 12 | * o Object 13 | * o Array 14 | * o String 15 | * o Other primitive: number, boolean (true/false) or null 16 | */ 17 | typedef enum { 18 | JSMN_UNDEFINED = 0, 19 | JSMN_OBJECT = 1, 20 | JSMN_ARRAY = 2, 21 | JSMN_STRING = 3, 22 | JSMN_PRIMITIVE = 4 23 | } jsmntype_t; 24 | 25 | enum jsmnerr { 26 | /* Not enough tokens were provided */ 27 | JSMN_ERROR_NOMEM = -1, 28 | /* Invalid character inside JSON string */ 29 | JSMN_ERROR_INVAL = -2, 30 | /* The string is not a full JSON packet, more bytes expected */ 31 | JSMN_ERROR_PART = -3 32 | }; 33 | 34 | /** 35 | * JSON token description. 36 | * type type (object, array, string etc.) 37 | * start start position in JSON data string 38 | * end end position in JSON data string 39 | */ 40 | typedef struct { 41 | jsmntype_t type; 42 | int start; 43 | int end; 44 | int size; 45 | #ifdef JSMN_PARENT_LINKS 46 | int parent; 47 | #endif 48 | } jsmntok_t; 49 | 50 | /** 51 | * JSON parser. Contains an array of token blocks available. Also stores 52 | * the string being parsed now and current position in that string 53 | */ 54 | typedef struct { 55 | unsigned int pos; /* offset in the JSON string */ 56 | unsigned int toknext; /* next token to allocate */ 57 | int toksuper; /* superior token node, e.g parent object or array */ 58 | } jsmn_parser; 59 | 60 | /** 61 | * Create JSON parser over an array of tokens 62 | */ 63 | void jsmn_init(jsmn_parser *parser); 64 | 65 | /** 66 | * Run JSON parser. It parses a JSON data string into and array of tokens, each describing 67 | * a single JSON object. 68 | */ 69 | int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, 70 | jsmntok_t *tokens, unsigned int num_tokens); 71 | 72 | #ifdef __cplusplus 73 | } 74 | #endif 75 | 76 | #endif /* __JSMN_H_ */ 77 | -------------------------------------------------------------------------------- /src/utility/multihttpsclient/multihttpsclient.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // File: multihttpsclient.h 3 | // Description: Basic Multiplatform HTTPS Client (Implement network HALs for differents devices). 4 | // Created on: 04 may. 2019 5 | // Last modified date: 11 may. 2019 6 | // Version: 0.0.1 7 | /**************************************************************************************************/ 8 | 9 | /* Include Guard */ 10 | 11 | #ifndef MULTIHTTPSCLIENT_H_ 12 | #define MULTIHTTPSCLIENT_H_ 13 | 14 | /**************************************************************************************************/ 15 | 16 | /* Check Build System */ 17 | 18 | #if !defined(ARDUINO) && !defined(ESP_IDF) && !defined(WIN32) && !defined(_WIN32) && \ 19 | !defined(__linux__) 20 | #error Unsupported system (Supported: Windows, Linux and ESP32) 21 | #endif 22 | 23 | /**************************************************************************************************/ 24 | 25 | /* Libraries Configurations */ 26 | 27 | // Integer types macros 28 | //#define __STDC_LIMIT_MACROS // Could be needed for C++, and it must be before inttypes include 29 | //#define __STDC_CONSTANT_MACROS // Could be needed for C++, and it must be before inttypes include 30 | #define __STDC_FORMAT_MACROS // Could be needed for C++, and it must be before inttypes include 31 | 32 | /**************************************************************************************************/ 33 | 34 | /* Use Specific HAL for build system */ 35 | 36 | #if defined(ARDUINO) 37 | #include "multihttpsclient_hals/arduino/multihttpsclient_arduino.h" 38 | #elif defined(ESP_IDF) 39 | #include "multihttpsclient_hals/espidf/multihttpsclient_espidf.h" 40 | #else 41 | #include "multihttpsclient_hals/generic/multihttpsclient_generic.h" 42 | #endif 43 | 44 | /**************************************************************************************************/ 45 | 46 | #endif 47 | -------------------------------------------------------------------------------- /examples/native_windows_linux/echobot/main.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // Example: echobot 3 | // Description: 4 | // Bot that response to any received text message with the same text received (echo messages). 5 | // It gives you a basic idea of how to receive and send messages. 6 | // Created on: 21 apr. 2019 7 | // Last modified date: 21 apr. 2019 8 | // Version: 1.0.0 9 | /**************************************************************************************************/ 10 | 11 | /* Libraries */ 12 | 13 | // Standard C/C++ libraries 14 | #include 15 | 16 | // Custom libraries 17 | #include "utlgbotlib.h" 18 | 19 | /**************************************************************************************************/ 20 | 21 | // Telegram Bot Token (Get from Botfather) 22 | #define TLG_TOKEN "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 23 | 24 | /**************************************************************************************************/ 25 | 26 | #if defined(WIN32) || defined(_WIN32) // Windows 27 | #define _delay(x) do { Sleep(x); } while(0) 28 | #elif defined(__linux__) 29 | #define _delay(x) do { usleep(x*1000); } while(0) 30 | #endif 31 | 32 | /**************************************************************************************************/ 33 | 34 | /* Main Function */ 35 | 36 | int main(void) 37 | { 38 | // Create Bot object 39 | uTLGBot Bot(TLG_TOKEN); 40 | 41 | // Main loop 42 | while(1) 43 | { 44 | // Check and handle any received message 45 | while(Bot.getUpdates()) 46 | { 47 | printf("Message received from %s at %s, sending it back.\n", 48 | Bot.received_msg.from.first_name, Bot.received_msg.chat.title); 49 | Bot.sendMessage(Bot.received_msg.chat.id, Bot.received_msg.text); 50 | } 51 | 52 | // Wait 1s for next iteration 53 | _delay(1000); 54 | } 55 | } 56 | 57 | /**************************************************************************************************/ 58 | -------------------------------------------------------------------------------- /src/utility/multihttpsclient/multihttpsclient_hals/espidf/multihttpsclient_espidf.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // File: multihttpsclient_espidf.h 3 | // Description: Multiplatform HTTPS Client implementation for ESP32 ESPIDF Framework. 4 | // Created on: 11 may. 2019 5 | // Last modified date: 14 apr. 2020 6 | // Version: 1.0.4 7 | /**************************************************************************************************/ 8 | 9 | #if defined(ESP_IDF) 10 | 11 | /**************************************************************************************************/ 12 | 13 | /* Include Guard */ 14 | 15 | #ifndef MULTIHTTPSCLIENTESPIDF_H_ 16 | #define MULTIHTTPSCLIENTESPIDF_H_ 17 | 18 | /**************************************************************************************************/ 19 | 20 | /* Libraries */ 21 | 22 | #include "esp_tls.h" 23 | 24 | #include 25 | #include 26 | #include 27 | 28 | /**************************************************************************************************/ 29 | 30 | /* Constants */ 31 | 32 | // HTTP connection timeout 33 | #define HTTP_CONNECT_TIMEOUT 5000 34 | 35 | // HTTP response wait timeout (ms) 36 | #define HTTP_WAIT_RESPONSE_TIMEOUT 5000 37 | 38 | // HTTP response between bytes receptions timeout (ms) 39 | #define HTTP_RESPONSE_BETWEEN_BYTES_TIMEOUT 500 40 | 41 | // HTTP Request header max length 42 | #define HTTP_HEADER_MAX_LENGTH 256 43 | 44 | /**************************************************************************************************/ 45 | 46 | class MultiHTTPSClient 47 | { 48 | public: 49 | // Public Methods 50 | MultiHTTPSClient(void); 51 | void set_debug(const bool debug); 52 | void set_cert(const uint8_t* ca_pem_start, const uint8_t* ca_pem_end); 53 | int8_t connect(const char* host, uint16_t port); 54 | void disconnect(void); 55 | bool is_connected(void); 56 | uint8_t get(const char* uri, const char* host, char* response, const size_t response_len, 57 | const unsigned long response_timeout=HTTP_WAIT_RESPONSE_TIMEOUT); 58 | uint8_t post(const char* uri, const char* host, char* request_response, 59 | const size_t request_len, const size_t request_response_max_size, 60 | const unsigned long response_timeout=HTTP_WAIT_RESPONSE_TIMEOUT); 61 | 62 | private: 63 | // Private Attributtes 64 | char _http_header[HTTP_HEADER_MAX_LENGTH]; 65 | struct esp_tls* _tls; 66 | esp_tls_cfg_t* _tls_cfg; 67 | bool _connected; 68 | bool _debug; 69 | 70 | // Private Methods 71 | void release_tls_elements(void); 72 | size_t write(const char* request); 73 | size_t read(char* response, const size_t response_len); 74 | uint8_t read_response(char* response, const size_t response_max_len, 75 | const unsigned long response_timeout); 76 | }; 77 | 78 | /**************************************************************************************************/ 79 | 80 | #endif 81 | 82 | /**************************************************************************************************/ 83 | 84 | #endif 85 | -------------------------------------------------------------------------------- /src/utility/multihttpsclient/multihttpsclient_hals/arduino/multihttpsclient_arduino.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // File: multihttpsclient_arduino.h 3 | // Description: Multiplatform HTTPS Client implementation for ESP32 Arduino Framework. 4 | // Created on: 11 may. 2019 5 | // Last modified date: 14 apr. 2020 6 | // Version: 1.0.4 7 | /**************************************************************************************************/ 8 | 9 | #if defined(ARDUINO) 10 | 11 | /**************************************************************************************************/ 12 | 13 | /* Include Guard */ 14 | 15 | #ifndef MULTIHTTPSCLIENTARDUINO_H_ 16 | #define MULTIHTTPSCLIENTARDUINO_H_ 17 | 18 | /**************************************************************************************************/ 19 | 20 | /* Libraries */ 21 | 22 | #include 23 | #include 24 | 25 | #include 26 | #include 27 | #include 28 | 29 | /**************************************************************************************************/ 30 | 31 | /* Constants */ 32 | 33 | // HTTP response wait timeout (ms) 34 | #define HTTP_WAIT_RESPONSE_TIMEOUT 5000 35 | 36 | // HTTP response between bytes receptions timeout (ms) 37 | #define HTTP_RESPONSE_BETWEEN_BYTES_TIMEOUT 500 38 | 39 | // HTTP Request header max length 40 | #define HTTP_HEADER_MAX_LENGTH 256 41 | 42 | /**************************************************************************************************/ 43 | 44 | class MultiHTTPSClient 45 | { 46 | public: 47 | // Public Methods 48 | MultiHTTPSClient(void); 49 | void set_debug(const bool debug); 50 | void set_cert(const char* cert_https_server); 51 | void set_cert(const uint8_t* ca_pem_start, const uint8_t* ca_pem_end); 52 | int8_t connect(const char* host, uint16_t port); 53 | void disconnect(void); 54 | bool is_connected(void); 55 | uint8_t get(const char* uri, const char* host, char* response, const size_t response_len, 56 | const unsigned long response_timeout=HTTP_WAIT_RESPONSE_TIMEOUT); 57 | uint8_t post(const char* uri, const char* host, char* request_response, 58 | const size_t request_len, const size_t request_response_max_size, 59 | const unsigned long response_timeout=HTTP_WAIT_RESPONSE_TIMEOUT); 60 | 61 | private: 62 | // Private Attributtes 63 | char _http_header[HTTP_HEADER_MAX_LENGTH]; 64 | WiFiClientSecure* _client; 65 | #ifdef ESP8266 66 | X509List* _cert; 67 | #endif 68 | const char* _cert_https_server; 69 | bool _connected; 70 | bool _debug; 71 | 72 | // Private Methods 73 | void release_tls_elements(void); 74 | size_t write(const char* request); 75 | size_t read(char* response, const size_t response_len); 76 | uint8_t read_response(char* response, const size_t response_max_len, 77 | const unsigned long response_timeout); 78 | void setClock(void); 79 | }; 80 | 81 | /**************************************************************************************************/ 82 | 83 | #endif 84 | 85 | /**************************************************************************************************/ 86 | 87 | #endif 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # uTLGBotLib 2 | Universal Telegram Bot library for Arduino, ESP-IDF and Native (Windows and Linux) devices, that let you create Telegram Bots. You can use it with ESP8266 and ESP32 microcontrollers. 3 | 4 | Micro Telegram Bot Library is a lightweight C++ library implementation that use Telegram Bot API to create Bots. The library goal is to be compatible with multiples devices, from embedded microcontrollers, to Servers and PCs (Windows and Linux). Inside microcontrollers world, uTLGBotLib focus on Espressif ESP32 (support for ESP-IDF and Arduino frameworks) and ESP8266 (support for Arduino) microcontrollers. 5 | 6 | ## Notes 7 | 8 | - This is a specific Arduino library modified from original uTLGBotLib due Arduino IDE build restrictions. Main change is that mbedtls of multihttpsclient library has been removed to avoid compiling conflicts. If you want to use this library in platformio for ESP-IDF, Arduino or Native use, please go and use the original full library: 9 | https://github.com/J-Rios/uTLGBotLib 10 | 11 | - Due library target embedded devices such microcontrollers, it MUST be take a lot of care in memory usage, from library size to safety use. 12 | 13 | - To avoid ram memory fragmentation and stack-heap collisions, the library doesn't use dynamic memory in non Native (Windows/Linux) platforms (ESP8266 and ESP32). 14 | 15 | - The library uses [multihttpsclient](https://github.com/J-Rios/multihttpsclient) to implement all low level HTTP request specific for each device/system. 16 | 17 | - The library uses [jsmn library](https://github.com/zserge/jsmn) to parse JSON text in the safest (memory) way possible, because it just get a string and return the indexes where each json element ("token") start and end. 18 | 19 | - Sub-library multihttpsclient uses [mbedtls library](https://github.com/ARMmbed/mbedtls) to handle HTTPS requests in Native (Windows and Linux) systems. 20 | 21 | - uTLGBotLib is a generic library, for that reason, to add support of a new device/system, you just need to specify the expected print() macros in utlgbotlib.cpp and create specific files in multihttpsclient library to implement the HTTP requests for this device/system. 22 | 23 | - You can set debug levels from 0 to 2: 24 | ``` 25 | Bot.set_debug(0); // No debug msgs 26 | Bot.set_debug(1); // Bot debug msgs 27 | Bot.set_debug(2); // Bot+HTTPS debug msgs 28 | ``` 29 | 30 | - Global define "UTLGBOT_NO_DEBUG" to disable build debug prints and save some flash and sram memory usage. 31 | 32 | - Global define "UTLGBOT_MEMORY_LEVEL" with values 0 to 5, to set library build memory usage level. It allows to reduce library flash and sram memory needs by reducing HTTPS response buffer length and maximum telegram text messages length buffer. 33 | ``` 34 | -DUTLGBOT_MEMORY_LEVEL=0 // Max TLG msgs: 128 chars 35 | -DUTLGBOT_MEMORY_LEVEL=1 // Max TLG msgs: 256 chars 36 | -DUTLGBOT_MEMORY_LEVEL=2 // Max TLG msgs: 512 chars 37 | -DUTLGBOT_MEMORY_LEVEL=3 // Max TLG msgs: 1024 chars 38 | -DUTLGBOT_MEMORY_LEVEL=4 // Max TLG msgs: 2048 chars 39 | -DUTLGBOT_MEMORY_LEVEL=5 // Max TLG msgs: 4097 chars (telegram max msg length) 40 | ``` 41 | 42 | - Defines must be passed to compiler by flag (-DUTLGBOT_NO_DEBUG -DUTLGBOT_MEMORY_LEVEL=2). Note that define in source code won't work as expected due utlgbot.cpp is compiled independent of main.cpp and that cause different definitions of memory levels from each file compiled. 43 | 44 | - Recommended to use platformio. Arduino IDE doesn't support a simple way to use global defines, so don't expect this previous characteristics to be used on it (if you want to, maybe try to add them using "build.extra_flags" inside core specifica platform.txt file). 45 | -------------------------------------------------------------------------------- /src/utility/multihttpsclient/multihttpsclient_hals/generic/multihttpsclient_generic.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // File: multihttpsclient_generic.h 3 | // Description: Multiplatform HTTPS Client implementation for Generic systems (Windows and Linux). 4 | // Created on: 11 may. 2019 5 | // Last modified date: 14 apr. 2020 6 | // Version: 1.0.4 7 | /**************************************************************************************************/ 8 | 9 | #if defined(WIN32) || defined(_WIN32) || defined(__linux__) 10 | 11 | /**************************************************************************************************/ 12 | 13 | /* Include Guard */ 14 | 15 | #ifndef MULTIHTTPSCLIENTGENERIC_H_ 16 | #define MULTIHTTPSCLIENTGENERIC_H_ 17 | 18 | /**************************************************************************************************/ 19 | 20 | /* Libraries */ 21 | 22 | #if defined(WIN32) || defined(_WIN32) // Windows 23 | #include 24 | #endif 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | // MBEDTLS library 34 | #include "mbedtls/net.h" 35 | #include "mbedtls/ssl.h" 36 | #include "mbedtls/entropy.h" 37 | #include "mbedtls/ctr_drbg.h" 38 | #include "mbedtls/certs.h" 39 | #include "mbedtls/debug.h" 40 | #include "mbedtls/error.h" 41 | 42 | /**************************************************************************************************/ 43 | 44 | /* Constants */ 45 | 46 | // HTTP response wait timeout (ms) 47 | #define HTTP_WAIT_RESPONSE_TIMEOUT 5000 48 | 49 | // HTTP response between bytes receptions timeout (ms) 50 | #define HTTP_RESPONSE_BETWEEN_BYTES_TIMEOUT 500 51 | 52 | // HTTP Request header max length 53 | #define HTTP_HEADER_MAX_LENGTH 256 54 | 55 | /**************************************************************************************************/ 56 | 57 | class MultiHTTPSClient 58 | { 59 | public: 60 | // Public Methods 61 | MultiHTTPSClient(void); 62 | ~MultiHTTPSClient(void); 63 | void set_debug(const bool debug); 64 | void set_cert(const char* cert_https_server); 65 | void set_cert(const uint8_t* ca_pem_start, const uint8_t* ca_pem_end); 66 | int8_t connect(const char* host, uint16_t port); 67 | void disconnect(void); 68 | bool is_connected(void); 69 | uint8_t get(const char* uri, const char* host, char* response, const size_t response_len, 70 | const unsigned long response_timeout=HTTP_WAIT_RESPONSE_TIMEOUT); 71 | uint8_t post(const char* uri, const char* host, char* request_response, 72 | const size_t request_len, const size_t request_response_max_size, 73 | const unsigned long response_timeout=HTTP_WAIT_RESPONSE_TIMEOUT); 74 | 75 | private: 76 | // Private Attributtes 77 | char _http_header[HTTP_HEADER_MAX_LENGTH]; 78 | const char* _cert_https_server; 79 | mbedtls_net_context _server_fd; 80 | mbedtls_entropy_context _entropy; 81 | mbedtls_ctr_drbg_context _ctr_drbg; 82 | mbedtls_ssl_context _tls; 83 | mbedtls_ssl_config _tls_cfg; 84 | mbedtls_x509_crt _cacert; 85 | bool _connected; 86 | bool _debug; 87 | 88 | // Private Methods 89 | bool init(void); 90 | void release_tls_elements(void); 91 | size_t write(const char* request); 92 | size_t read(char* response, const size_t response_len); 93 | uint8_t read_response(char* response, const size_t response_max_len, 94 | const unsigned long response_timeout); 95 | }; 96 | 97 | /**************************************************************************************************/ 98 | 99 | #endif 100 | 101 | /**************************************************************************************************/ 102 | 103 | #endif 104 | -------------------------------------------------------------------------------- /examples/arduino/echo/echo.ino: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // Example: echobot 3 | // Description: 4 | // Bot that response to any received text message with the same text received (echo messages). 5 | // It gives you a basic idea of how to receive and send messages. 6 | // Created on: 21 apr. 2019 7 | // Last modified date: 21 apr. 2019 8 | // Version: 1.0.0 9 | /**************************************************************************************************/ 10 | 11 | /* Libraries */ 12 | 13 | // Standard C/C++ libraries 14 | #include 15 | 16 | // Device libraries (Arduino ESP32/ESP8266 Cores) 17 | #include 18 | #ifdef ESP8266 19 | #include 20 | #else 21 | #include 22 | #endif 23 | // Custom libraries 24 | #include 25 | 26 | /**************************************************************************************************/ 27 | 28 | // WiFi Parameters 29 | #define WIFI_SSID "mynet1234" 30 | #define WIFI_PASS "password1234" 31 | #define MAX_CONN_FAIL 50 32 | #define MAX_LENGTH_WIFI_SSID 31 33 | #define MAX_LENGTH_WIFI_PASS 63 34 | 35 | // Telegram Bot Token (Get from Botfather) 36 | #define TLG_TOKEN "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 37 | 38 | // Enable Bot debug level (0 - None; 1 - Bot Level; 2 - Bot+HTTPS Level) 39 | #define DEBUG_LEVEL_UTLGBOT 0 40 | 41 | /**************************************************************************************************/ 42 | 43 | /* Functions Prototypes */ 44 | 45 | void wifi_init_stat(void); 46 | bool wifi_handle_connection(void); 47 | 48 | /**************************************************************************************************/ 49 | 50 | /* Globals */ 51 | 52 | // Create Bot object 53 | uTLGBot Bot(TLG_TOKEN); 54 | 55 | /**************************************************************************************************/ 56 | 57 | /* Main Function */ 58 | 59 | void setup(void) 60 | { 61 | // Enable Bot debug 62 | Bot.set_debug(DEBUG_LEVEL_UTLGBOT); 63 | 64 | // Initialize Serial 65 | Serial.begin(115200); 66 | 67 | // Initialize WiFi station connection 68 | wifi_init_stat(); 69 | 70 | // Wait WiFi connection 71 | Serial.println("Waiting for WiFi connection."); 72 | while(!wifi_handle_connection()) 73 | { 74 | Serial.println("."); 75 | delay(1000); 76 | } 77 | 78 | // Bot getMe command 79 | Bot.getMe(); 80 | } 81 | 82 | void loop() 83 | { 84 | // Check if WiFi is connected 85 | if(!wifi_handle_connection()) 86 | { 87 | // Wait 100ms and check again 88 | delay(100); 89 | return; 90 | } 91 | 92 | // Test Bot getUpdate command and receive messages 93 | while(Bot.getUpdates()) 94 | { 95 | // Send an echo message back 96 | Bot.sendMessage(Bot.received_msg.chat.id, Bot.received_msg.text); 97 | 98 | // Feed the Watchdog 99 | yield(); 100 | } 101 | 102 | // Wait 1s for next iteration 103 | delay(1000); 104 | } 105 | 106 | /**************************************************************************************************/ 107 | 108 | /* Functions */ 109 | 110 | // Init WiFi interface 111 | void wifi_init_stat(void) 112 | { 113 | Serial.println("Initializing TCP-IP adapter..."); 114 | Serial.print("Wifi connecting to SSID: "); 115 | Serial.println(WIFI_SSID); 116 | 117 | WiFi.mode(WIFI_STA); 118 | WiFi.begin(WIFI_SSID, WIFI_PASS); 119 | 120 | Serial.println("TCP-IP adapter successfuly initialized."); 121 | } 122 | 123 | /**************************************************************************************************/ 124 | 125 | /* WiFi Change Event Handler */ 126 | 127 | bool wifi_handle_connection(void) 128 | { 129 | static bool wifi_connected = false; 130 | 131 | // Device is not connected 132 | if(WiFi.status() != WL_CONNECTED) 133 | { 134 | // Was connected 135 | if(wifi_connected) 136 | { 137 | Serial.println("WiFi disconnected."); 138 | wifi_connected = false; 139 | } 140 | 141 | return false; 142 | } 143 | // Device connected 144 | else 145 | { 146 | // Wasn't connected 147 | if(!wifi_connected) 148 | { 149 | Serial.println(""); 150 | Serial.println("WiFi connected"); 151 | Serial.print("IP address: "); 152 | Serial.println(WiFi.localIP()); 153 | 154 | wifi_connected = true; 155 | } 156 | 157 | return true; 158 | } 159 | } 160 | 161 | /**************************************************************************************************/ 162 | -------------------------------------------------------------------------------- /src/utility/jsmn/README.md: -------------------------------------------------------------------------------- 1 | JSMN 2 | ==== 3 | 4 | [![Build Status](https://travis-ci.org/zserge/jsmn.svg?branch=master)](https://travis-ci.org/zserge/jsmn) 5 | 6 | jsmn (pronounced like 'jasmine') is a minimalistic JSON parser in C. It can be 7 | easily integrated into resource-limited or embedded projects. 8 | 9 | You can find more information about JSON format at [json.org][1] 10 | 11 | Library sources are available at https://github.com/zserge/jsmn 12 | 13 | The web page with some information about jsmn can be found at 14 | [http://zserge.com/jsmn.html][2] 15 | 16 | Philosophy 17 | ---------- 18 | 19 | Most JSON parsers offer you a bunch of functions to load JSON data, parse it 20 | and extract any value by its name. jsmn proves that checking the correctness of 21 | every JSON packet or allocating temporary objects to store parsed JSON fields 22 | often is an overkill. 23 | 24 | JSON format itself is extremely simple, so why should we complicate it? 25 | 26 | jsmn is designed to be **robust** (it should work fine even with erroneous 27 | data), **fast** (it should parse data on the fly), **portable** (no superfluous 28 | dependencies or non-standard C extensions). And of course, **simplicity** is a 29 | key feature - simple code style, simple algorithm, simple integration into 30 | other projects. 31 | 32 | Features 33 | -------- 34 | 35 | * compatible with C89 36 | * no dependencies (even libc!) 37 | * highly portable (tested on x86/amd64, ARM, AVR) 38 | * about 200 lines of code 39 | * extremely small code footprint 40 | * API contains only 2 functions 41 | * no dynamic memory allocation 42 | * incremental single-pass parsing 43 | * library code is covered with unit-tests 44 | 45 | Design 46 | ------ 47 | 48 | The rudimentary jsmn object is a **token**. Let's consider a JSON string: 49 | 50 | '{ "name" : "Jack", "age" : 27 }' 51 | 52 | It holds the following tokens: 53 | 54 | * Object: `{ "name" : "Jack", "age" : 27}` (the whole object) 55 | * Strings: `"name"`, `"Jack"`, `"age"` (keys and some values) 56 | * Number: `27` 57 | 58 | In jsmn, tokens do not hold any data, but point to token boundaries in JSON 59 | string instead. In the example above jsmn will create tokens like: Object 60 | [0..31], String [3..7], String [12..16], String [20..23], Number [27..29]. 61 | 62 | Every jsmn token has a type, which indicates the type of corresponding JSON 63 | token. jsmn supports the following token types: 64 | 65 | * Object - a container of key-value pairs, e.g.: 66 | `{ "foo":"bar", "x":0.3 }` 67 | * Array - a sequence of values, e.g.: 68 | `[ 1, 2, 3 ]` 69 | * String - a quoted sequence of chars, e.g.: `"foo"` 70 | * Primitive - a number, a boolean (`true`, `false`) or `null` 71 | 72 | Besides start/end positions, jsmn tokens for complex types (like arrays 73 | or objects) also contain a number of child items, so you can easily follow 74 | object hierarchy. 75 | 76 | This approach provides enough information for parsing any JSON data and makes 77 | it possible to use zero-copy techniques. 78 | 79 | Install 80 | ------- 81 | 82 | To clone the repository you should have Git installed. Just run: 83 | 84 | $ git clone https://github.com/zserge/jsmn 85 | 86 | Repository layout is simple: jsmn.c and jsmn.h are library files, tests are in 87 | the jsmn\_test.c, you will also find README, LICENSE and Makefile files inside. 88 | 89 | To build the library, run `make`. It is also recommended to run `make test`. 90 | Let me know, if some tests fail. 91 | 92 | If build was successful, you should get a `libjsmn.a` library. 93 | The header file you should include is called `"jsmn.h"`. 94 | 95 | API 96 | --- 97 | 98 | Token types are described by `jsmntype_t`: 99 | 100 | typedef enum { 101 | JSMN_UNDEFINED = 0, 102 | JSMN_OBJECT = 1, 103 | JSMN_ARRAY = 2, 104 | JSMN_STRING = 3, 105 | JSMN_PRIMITIVE = 4 106 | } jsmntype_t; 107 | 108 | **Note:** Unlike JSON data types, primitive tokens are not divided into 109 | numbers, booleans and null, because one can easily tell the type using the 110 | first character: 111 | 112 | * 't', 'f' - boolean 113 | * 'n' - null 114 | * '-', '0'..'9' - number 115 | 116 | Token is an object of `jsmntok_t` type: 117 | 118 | typedef struct { 119 | jsmntype_t type; // Token type 120 | int start; // Token start position 121 | int end; // Token end position 122 | int size; // Number of child (nested) tokens 123 | } jsmntok_t; 124 | 125 | **Note:** string tokens point to the first character after 126 | the opening quote and the previous symbol before final quote. This was made 127 | to simplify string extraction from JSON data. 128 | 129 | All job is done by `jsmn_parser` object. You can initialize a new parser using: 130 | 131 | jsmn_parser parser; 132 | jsmntok_t tokens[10]; 133 | 134 | jsmn_init(&parser); 135 | 136 | // js - pointer to JSON string 137 | // tokens - an array of tokens available 138 | // 10 - number of tokens available 139 | jsmn_parse(&parser, js, strlen(js), tokens, 10); 140 | 141 | This will create a parser, and then it tries to parse up to 10 JSON tokens from 142 | the `js` string. 143 | 144 | A non-negative return value of `jsmn_parse` is the number of tokens actually 145 | used by the parser. 146 | Passing NULL instead of the tokens array would not store parsing results, but 147 | instead the function will return the value of tokens needed to parse the given 148 | string. This can be useful if you don't know yet how many tokens to allocate. 149 | 150 | If something goes wrong, you will get an error. Error will be one of these: 151 | 152 | * `JSMN_ERROR_INVAL` - bad token, JSON string is corrupted 153 | * `JSMN_ERROR_NOMEM` - not enough tokens, JSON string is too large 154 | * `JSMN_ERROR_PART` - JSON string is too short, expecting more JSON data 155 | 156 | If you get `JSMN_ERROR_NOMEM`, you can re-allocate more tokens and call 157 | `jsmn_parse` once more. If you read json data from the stream, you can 158 | periodically call `jsmn_parse` and check if return value is `JSMN_ERROR_PART`. 159 | You will get this error until you reach the end of JSON data. 160 | 161 | Other info 162 | ---------- 163 | 164 | This software is distributed under [MIT license](http://www.opensource.org/licenses/mit-license.php), 165 | so feel free to integrate it in your commercial products. 166 | 167 | [1]: http://www.json.org/ 168 | [2]: http://zserge.com/jsmn.html 169 | -------------------------------------------------------------------------------- /examples/arduino/show_received_messages/show_received_messages.ino: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // Example: echobot 3 | // Description: 4 | // Bot that shows all received messages data through Serial. 5 | // It shows you all data that is received and can be use from any received message. 6 | // Created on: 21 apr. 2019 7 | // Last modified date: 21 apr. 2019 8 | // Version: 1.0.0 9 | /**************************************************************************************************/ 10 | 11 | /* Libraries */ 12 | 13 | // Standard C/C++ libraries 14 | #include 15 | 16 | // Device libraries (Arduino ESP32/ESP8266 Cores) 17 | #include 18 | #ifdef ESP8266 19 | #include 20 | #else 21 | #include 22 | #endif 23 | // Custom libraries 24 | #include 25 | 26 | /**************************************************************************************************/ 27 | 28 | // WiFi Parameters 29 | #define WIFI_SSID "mynet1234" 30 | #define WIFI_PASS "password1234" 31 | #define MAX_CONN_FAIL 50 32 | #define MAX_LENGTH_WIFI_SSID 31 33 | #define MAX_LENGTH_WIFI_PASS 63 34 | 35 | // Telegram Bot Token (Get from Botfather) 36 | #define TLG_TOKEN "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 37 | 38 | // Enable Bot debug level (0 - None; 1 - Bot Level; 2 - Bot+HTTPS Level) 39 | #define DEBUG_LEVEL_UTLGBOT 0 40 | 41 | /**************************************************************************************************/ 42 | 43 | /* Functions Prototypes */ 44 | 45 | void wifi_init_stat(void); 46 | bool wifi_handle_connection(void); 47 | 48 | /**************************************************************************************************/ 49 | 50 | /* Globals */ 51 | 52 | // Create Bot object 53 | uTLGBot Bot(TLG_TOKEN); 54 | 55 | /**************************************************************************************************/ 56 | 57 | /* Main Function */ 58 | 59 | void setup(void) 60 | { 61 | // Enable Bot debug 62 | Bot.set_debug(DEBUG_LEVEL_UTLGBOT); 63 | 64 | // Initialize Serial 65 | Serial.begin(115200); 66 | 67 | // Initialize WiFi station connection 68 | wifi_init_stat(); 69 | 70 | // Wait WiFi connection 71 | Serial.println("Waiting for WiFi connection."); 72 | while(!wifi_handle_connection()) 73 | { 74 | Serial.println("."); 75 | delay(1000); 76 | } 77 | 78 | // Bot getMe command 79 | Bot.getMe(); 80 | } 81 | 82 | void loop() 83 | { 84 | // Check if WiFi is connected 85 | if(!wifi_handle_connection()) 86 | { 87 | // Wait 100ms and check again 88 | delay(100); 89 | return; 90 | } 91 | 92 | // Test Bot getUpdate command and receive messages 93 | while(Bot.getUpdates()) 94 | { 95 | Serial.println("\n-----------------------------------------"); 96 | Serial.println("Received message."); 97 | 98 | Serial.printf(" From chat ID: %s\n", Bot.received_msg.chat.id); 99 | Serial.printf(" From chat type: %s\n", Bot.received_msg.chat.type); 100 | Serial.printf(" From chat alias: %s\n", Bot.received_msg.chat.username); 101 | Serial.printf(" From chat name: %s %s\n", Bot.received_msg.chat.first_name, 102 | Bot.received_msg.chat.last_name); 103 | Serial.printf(" From chat title: %s\n", Bot.received_msg.chat.title); 104 | if(Bot.received_msg.chat.all_members_are_administrators) 105 | Serial.println(" From chat where all members are admins."); 106 | else 107 | Serial.println(" From chat where not all members are admins."); 108 | 109 | Serial.printf(" From user ID: %s\n", Bot.received_msg.from.id); 110 | Serial.printf(" From user alias: %s\n", Bot.received_msg.from.username); 111 | Serial.printf(" From user name: %s %s\n", Bot.received_msg.from.first_name, 112 | Bot.received_msg.from.last_name); 113 | Serial.printf(" From user with language code: %s\n", Bot.received_msg.from.language_code); 114 | if(Bot.received_msg.from.is_bot) 115 | Serial.println(" From user that is a Bot."); 116 | else 117 | Serial.println(" From user that is not a Bot."); 118 | 119 | Serial.printf(" Message ID: %d\n", Bot.received_msg.message_id); 120 | Serial.printf(" Message sent date (UNIX epoch time): %ul\n", Bot.received_msg.date); 121 | Serial.printf(" Text: %s\n", Bot.received_msg.text); 122 | Serial.printf("-----------------------------------------\n"); 123 | 124 | // Feed the Watchdog 125 | yield(); 126 | } 127 | 128 | // Wait 1s for next iteration 129 | delay(1000); 130 | } 131 | 132 | /**************************************************************************************************/ 133 | 134 | /* Functions */ 135 | 136 | // Init WiFi interface 137 | void wifi_init_stat(void) 138 | { 139 | Serial.println("Initializing TCP-IP adapter..."); 140 | Serial.print("Wifi connecting to SSID: "); 141 | Serial.println(WIFI_SSID); 142 | 143 | WiFi.mode(WIFI_STA); 144 | WiFi.begin(WIFI_SSID, WIFI_PASS); 145 | 146 | Serial.println("TCP-IP adapter successfuly initialized."); 147 | } 148 | 149 | /**************************************************************************************************/ 150 | 151 | /* WiFi Change Event Handler */ 152 | 153 | bool wifi_handle_connection(void) 154 | { 155 | static bool wifi_connected = false; 156 | 157 | // Device is not connected 158 | if(WiFi.status() != WL_CONNECTED) 159 | { 160 | // Was connected 161 | if(wifi_connected) 162 | { 163 | Serial.println("WiFi disconnected."); 164 | wifi_connected = false; 165 | } 166 | 167 | return false; 168 | } 169 | // Device connected 170 | else 171 | { 172 | // Wasn't connected 173 | if(!wifi_connected) 174 | { 175 | Serial.println(""); 176 | Serial.println("WiFi connected"); 177 | Serial.print("IP address: "); 178 | Serial.println(WiFi.localIP()); 179 | 180 | wifi_connected = true; 181 | } 182 | 183 | return true; 184 | } 185 | } 186 | 187 | /**************************************************************************************************/ -------------------------------------------------------------------------------- /examples/espidf/echobot/echobot.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // Example: echobot 3 | // Description: 4 | // Bot that response to any received text message with the same text received (echo messages). 5 | // It gives you a basic idea of how to receive and send messages. 6 | // Created on: 21 apr. 2019 7 | // Last modified date: 21 apr. 2019 8 | // Version: 1.0.0 9 | /**************************************************************************************************/ 10 | 11 | /* Libraries */ 12 | 13 | // Standard C/C++ libraries 14 | #include 15 | 16 | // Device libraries (ESP-IDF) 17 | #include "sdkconfig.h" 18 | #include "nvs_flash.h" 19 | #include "esp_wifi.h" 20 | #include "esp_event_loop.h" 21 | 22 | // Custom libraries 23 | #include "utlgbotlib.h" 24 | 25 | /**************************************************************************************************/ 26 | 27 | // WiFi Parameters 28 | #define WIFI_SSID "mynet1234" 29 | #define WIFI_PASS "password1234" 30 | #define MAX_CONN_FAIL 50 31 | #define MAX_LENGTH_WIFI_SSID 31 32 | #define MAX_LENGTH_WIFI_PASS 63 33 | 34 | // Telegram Bot Token (Get from Botfather) 35 | #define TLG_TOKEN "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 36 | 37 | /**************************************************************************************************/ 38 | 39 | /* Functions Prototypes */ 40 | 41 | extern "C" { void app_main(void); } 42 | void nvs_init(void); 43 | void wifi_init_stat(void); 44 | static esp_err_t network_event_handler(void *ctx, system_event_t *e); 45 | 46 | /**************************************************************************************************/ 47 | 48 | /* Globals */ 49 | volatile bool wifi_connected = false; 50 | volatile bool wifi_has_ip = false; 51 | 52 | /**************************************************************************************************/ 53 | 54 | /* Main Function */ 55 | 56 | void app_main(void) 57 | { 58 | // Create Bot object 59 | uTLGBot Bot(TLG_TOKEN); 60 | 61 | // Initialize Non-Volatile-Storage and WiFi station connection 62 | nvs_init(); 63 | wifi_init_stat(); 64 | 65 | // Main loop 66 | while(1) 67 | { 68 | // Check if device is not connected 69 | if(!wifi_connected || !wifi_has_ip) 70 | { 71 | // Wait 100ms and check again 72 | vTaskDelay(100/portTICK_PERIOD_MS); 73 | continue; 74 | } 75 | 76 | // Check and handle any received message 77 | while(Bot.getUpdates()) 78 | { 79 | printf("Message received from %s, echo it back...\n", Bot.received_msg.from.first_name); 80 | if(!Bot.sendMessage(Bot.received_msg.chat.id, Bot.received_msg.text)) 81 | { 82 | printf("Send fail.\n"); 83 | continue; 84 | } 85 | printf("Send OK.\n\n"); 86 | } 87 | 88 | // Wait 1s for next iteration 89 | vTaskDelay(1000/portTICK_PERIOD_MS); 90 | } 91 | } 92 | 93 | /**************************************************************************************************/ 94 | 95 | /* Functions */ 96 | 97 | // Initialize Non-Volatile-Storage 98 | void nvs_init(void) 99 | { 100 | esp_err_t ret = nvs_flash_init(); 101 | if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) 102 | { 103 | ESP_ERROR_CHECK(nvs_flash_erase()); 104 | ret = nvs_flash_init(); 105 | } 106 | ESP_ERROR_CHECK(ret); 107 | } 108 | 109 | // Init WiFi interface 110 | void wifi_init_stat(void) 111 | { 112 | static wifi_init_config_t wifi_init_cfg; 113 | static wifi_config_t wifi_cfg; 114 | 115 | printf("Initializing TCP-IP adapter...\n"); 116 | 117 | tcpip_adapter_init(); 118 | 119 | wifi_init_cfg = WIFI_INIT_CONFIG_DEFAULT(); 120 | ESP_ERROR_CHECK(esp_wifi_init(&wifi_init_cfg)); 121 | esp_wifi_set_mode(WIFI_MODE_STA); 122 | 123 | // Set TCP-IP event handler callback 124 | ESP_ERROR_CHECK(esp_event_loop_init(network_event_handler, NULL)); 125 | 126 | // Create and launch WiFi Station 127 | memcpy(wifi_cfg.sta.ssid, WIFI_SSID, MAX_LENGTH_WIFI_SSID+1); 128 | memcpy(wifi_cfg.sta.password, WIFI_PASS, MAX_LENGTH_WIFI_PASS+1); 129 | ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_cfg)); 130 | ESP_ERROR_CHECK(esp_wifi_start()); 131 | 132 | printf("TCP-IP adapter successfuly initialized.\n"); 133 | } 134 | 135 | /**************************************************************************************************/ 136 | 137 | /* WiFi Change Event Handler */ 138 | 139 | static esp_err_t network_event_handler(void *ctx, system_event_t *e) 140 | { 141 | static uint8_t conn_fail_retries = 0; 142 | 143 | switch(e->event_id) 144 | { 145 | case SYSTEM_EVENT_STA_START: 146 | printf("WiFi Station interface Up.\n"); 147 | printf("Connecting...\n"); 148 | esp_wifi_connect(); 149 | break; 150 | 151 | case SYSTEM_EVENT_STA_CONNECTED: 152 | printf("WiFi connected.\n"); 153 | printf("Waiting for IP...\n"); 154 | wifi_connected = true; 155 | break; 156 | 157 | case SYSTEM_EVENT_STA_GOT_IP: 158 | printf("WiFi IPv4 received: %s\n", ip4addr_ntoa(&e->event_info.got_ip.ip_info.ip)); 159 | wifi_has_ip = true; 160 | break; 161 | 162 | case SYSTEM_EVENT_STA_LOST_IP: 163 | printf("WiFi IP lost.\n"); 164 | wifi_has_ip = false; 165 | break; 166 | 167 | case SYSTEM_EVENT_STA_DISCONNECTED: 168 | if(wifi_connected) 169 | { 170 | printf("WiFi disconnected\n"); 171 | conn_fail_retries = 0; 172 | } 173 | else 174 | { 175 | printf("Can't connect to AP, trying again...\n"); 176 | conn_fail_retries = conn_fail_retries + 1; 177 | } 178 | wifi_has_ip = false; 179 | wifi_connected = false; 180 | if(conn_fail_retries < MAX_CONN_FAIL) 181 | esp_wifi_connect(); 182 | else 183 | { 184 | printf("WiFi connection fail %d times.\n", MAX_CONN_FAIL); 185 | printf("Rebooting the system...\n\n"); 186 | esp_restart(); 187 | } 188 | break; 189 | 190 | case SYSTEM_EVENT_STA_STOP: 191 | printf("WiFi interface stopped\n"); 192 | conn_fail_retries = 0; 193 | wifi_has_ip = false; 194 | wifi_connected = false; 195 | break; 196 | 197 | default: 198 | break; 199 | } 200 | 201 | return ESP_OK; 202 | } 203 | 204 | /**************************************************************************************************/ 205 | -------------------------------------------------------------------------------- /examples/arduino/commands_control_led/commands_control_led.ino: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // Example: echobot 3 | // Description: 4 | // Bot to control a LED through telegram commands. 5 | // It gives you an idea of how to detect specific words from user message and response to it. 6 | // Commands implemented are /start /help /ledon /ledoff /ledstatus 7 | // Created on: 21 apr. 2019 8 | // Last modified date: 21 apr. 2019 9 | // Version: 1.0.0 10 | /**************************************************************************************************/ 11 | 12 | /* Libraries */ 13 | 14 | // Standard C/C++ libraries 15 | #include 16 | 17 | // Device libraries (Arduino ESP32/ESP8266 Cores) 18 | #include 19 | #ifdef ESP8266 20 | #include 21 | #else 22 | #include 23 | #endif 24 | // Custom libraries 25 | #include 26 | 27 | /**************************************************************************************************/ 28 | 29 | // WiFi Parameters 30 | #define WIFI_SSID "mynet1234" 31 | #define WIFI_PASS "password1234" 32 | 33 | #define MAX_CONN_FAIL 50 34 | #define MAX_LENGTH_WIFI_SSID 31 35 | #define MAX_LENGTH_WIFI_PASS 63 36 | 37 | // Telegram Bot Token (Get from Botfather) 38 | #define TLG_TOKEN "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 39 | 40 | // Enable Bot debug level (0 - None; 1 - Bot Level; 2 - Bot+HTTPS Level) 41 | #define DEBUG_LEVEL_UTLGBOT 0 42 | 43 | // Board Led Pin 44 | #define PIN_LED 13 45 | 46 | // Telegram Bot /start text message 47 | const char TEXT_START[] = 48 | "Hello, im a Bot running in an ESP microcontroller that let you turn on/off a LED/light.\n" 49 | "\n" 50 | "Check /help command to see how to use me."; 51 | 52 | // Telegram Bot /help text message 53 | const char TEXT_HELP[] = 54 | "Available Commands:\n" 55 | "\n" 56 | "/start - Show start text.\n" 57 | "/help - Show actual text.\n" 58 | "/ledon - Turn on the LED.\n" 59 | "/ledoff - Turn off the LED.\n" 60 | "/ledstatus - Show actual LED status."; 61 | 62 | /**************************************************************************************************/ 63 | 64 | /* Functions Prototypes */ 65 | 66 | void wifi_init_stat(void); 67 | bool wifi_handle_connection(void); 68 | 69 | /**************************************************************************************************/ 70 | 71 | /* Globals */ 72 | 73 | // Create Bot object 74 | uTLGBot Bot(TLG_TOKEN); 75 | 76 | // LED status 77 | uint8_t led_status; 78 | 79 | /**************************************************************************************************/ 80 | 81 | /* Main Function */ 82 | 83 | void setup(void) 84 | { 85 | // Enable Bot debug 86 | Bot.set_debug(DEBUG_LEVEL_UTLGBOT); 87 | 88 | // Initialize Serial 89 | Serial.begin(115200); 90 | 91 | // Initialize LED pin as digital output 92 | digitalWrite(PIN_LED, LOW); 93 | pinMode(PIN_LED, OUTPUT); 94 | led_status = 0; 95 | 96 | // Initialize WiFi station connection 97 | wifi_init_stat(); 98 | 99 | // Wait for WiFi connection 100 | Serial.println("Waiting for WiFi connection."); 101 | while(!wifi_handle_connection()) 102 | { 103 | Serial.print("."); 104 | delay(500); 105 | } 106 | 107 | // Get Bot account info 108 | Bot.getMe(); 109 | } 110 | 111 | void loop() 112 | { 113 | // Check if WiFi is connected 114 | if(!wifi_handle_connection()) 115 | { 116 | // Wait 100ms and check again 117 | delay(100); 118 | return; 119 | } 120 | 121 | // Check for Bot received messages 122 | while(Bot.getUpdates()) 123 | { 124 | // Show received message text 125 | Serial.println(""); 126 | Serial.println("Received message:"); 127 | Serial.println(Bot.received_msg.text); 128 | Serial.println(""); 129 | 130 | // If /start command was received 131 | if(strncmp(Bot.received_msg.text, "/start", strlen("/start")) == 0) 132 | { 133 | // Send a Telegram message for start 134 | Bot.sendMessage(Bot.received_msg.chat.id, TEXT_START); 135 | } 136 | 137 | // If /help command was received 138 | else if(strncmp(Bot.received_msg.text, "/help", strlen("/help")) == 0) 139 | { 140 | // Send a Telegram message for start 141 | Bot.sendMessage(Bot.received_msg.chat.id, TEXT_HELP); 142 | } 143 | 144 | // If /ledon command was received 145 | else if(strncmp(Bot.received_msg.text, "/ledon", strlen("/ledon")) == 0) 146 | { 147 | // Turn on LED 148 | led_status = 1; 149 | digitalWrite(PIN_LED, HIGH); 150 | 151 | // Show command reception through Serial 152 | Serial.println("Command /ledon received."); 153 | Serial.println("Turning on the LED."); 154 | 155 | // Send a Telegram message to notify that the LED has been turned on 156 | Bot.sendMessage(Bot.received_msg.chat.id, "Led turned on."); 157 | } 158 | 159 | // If /ledoff command was received 160 | else if(strncmp(Bot.received_msg.text, "/ledoff", strlen("/ledoff")) == 0) 161 | { 162 | // Turn off LED 163 | led_status = 0; 164 | digitalWrite(PIN_LED, LOW); 165 | 166 | // Show command reception through Serial 167 | Serial.println("Command /ledoff received."); 168 | Serial.println("Turning off the LED."); 169 | 170 | // Send a Telegram message to notify that the LED has been turned off 171 | Bot.sendMessage(Bot.received_msg.chat.id, "Led turned off."); 172 | } 173 | 174 | // If /ledstatus command was received 175 | else if(strncmp(Bot.received_msg.text, "/ledstatus", strlen("/ledstatus")) == 0) 176 | { 177 | // Send a Telegram message to notify actual LED status 178 | if(led_status) 179 | Bot.sendMessage(Bot.received_msg.chat.id, "The LED is on."); 180 | else 181 | Bot.sendMessage(Bot.received_msg.chat.id, "The LED is off."); 182 | } 183 | 184 | // Feed the Watchdog 185 | yield(); 186 | } 187 | 188 | // Wait 1s for next iteration 189 | delay(1000); 190 | } 191 | 192 | /**************************************************************************************************/ 193 | 194 | /* Functions */ 195 | 196 | // Init WiFi interface 197 | void wifi_init_stat(void) 198 | { 199 | Serial.println("Initializing TCP-IP adapter..."); 200 | Serial.print("Wifi connecting to SSID: "); 201 | Serial.println(WIFI_SSID); 202 | 203 | WiFi.mode(WIFI_STA); 204 | WiFi.begin(WIFI_SSID, WIFI_PASS); 205 | 206 | Serial.println("TCP-IP adapter successfuly initialized."); 207 | } 208 | 209 | /**************************************************************************************************/ 210 | 211 | /* WiFi Change Event Handler */ 212 | 213 | bool wifi_handle_connection(void) 214 | { 215 | static bool wifi_connected = false; 216 | 217 | // Device is not connected 218 | if(WiFi.status() != WL_CONNECTED) 219 | { 220 | // Was connected 221 | if(wifi_connected) 222 | { 223 | Serial.println("WiFi disconnected."); 224 | wifi_connected = false; 225 | } 226 | 227 | return false; 228 | } 229 | // Device connected 230 | else 231 | { 232 | // Wasn't connected 233 | if(!wifi_connected) 234 | { 235 | Serial.println(""); 236 | Serial.println("WiFi connected"); 237 | Serial.print("IP address: "); 238 | Serial.println(WiFi.localIP()); 239 | 240 | wifi_connected = true; 241 | } 242 | 243 | return true; 244 | } 245 | } 246 | 247 | /**************************************************************************************************/ -------------------------------------------------------------------------------- /src/utility/jsmn/jsmn.c: -------------------------------------------------------------------------------- 1 | #include "jsmn.h" 2 | 3 | /** 4 | * Allocates a fresh unused token from the token pool. 5 | */ 6 | static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, 7 | jsmntok_t *tokens, size_t num_tokens) { 8 | jsmntok_t *tok; 9 | if (parser->toknext >= num_tokens) { 10 | return NULL; 11 | } 12 | tok = &tokens[parser->toknext++]; 13 | tok->start = tok->end = -1; 14 | tok->size = 0; 15 | #ifdef JSMN_PARENT_LINKS 16 | tok->parent = -1; 17 | #endif 18 | return tok; 19 | } 20 | 21 | /** 22 | * Fills token type and boundaries. 23 | */ 24 | static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type, 25 | int start, int end) { 26 | token->type = type; 27 | token->start = start; 28 | token->end = end; 29 | token->size = 0; 30 | } 31 | 32 | /** 33 | * Fills next available token with JSON primitive. 34 | */ 35 | static int jsmn_parse_primitive(jsmn_parser *parser, const char *js, 36 | size_t len, jsmntok_t *tokens, size_t num_tokens) { 37 | jsmntok_t *token; 38 | int start; 39 | 40 | start = parser->pos; 41 | 42 | for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { 43 | switch (js[parser->pos]) { 44 | #ifndef JSMN_STRICT 45 | /* In strict mode primitive must be followed by "," or "}" or "]" */ 46 | case ':': 47 | #endif 48 | case '\t' : case '\r' : case '\n' : case ' ' : 49 | case ',' : case ']' : case '}' : 50 | goto found; 51 | } 52 | if (js[parser->pos] < 32 || js[parser->pos] >= 127) { 53 | parser->pos = start; 54 | return JSMN_ERROR_INVAL; 55 | } 56 | } 57 | #ifdef JSMN_STRICT 58 | /* In strict mode primitive must be followed by a comma/object/array */ 59 | parser->pos = start; 60 | return JSMN_ERROR_PART; 61 | #endif 62 | 63 | found: 64 | if (tokens == NULL) { 65 | parser->pos--; 66 | return 0; 67 | } 68 | token = jsmn_alloc_token(parser, tokens, num_tokens); 69 | if (token == NULL) { 70 | parser->pos = start; 71 | return JSMN_ERROR_NOMEM; 72 | } 73 | jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); 74 | #ifdef JSMN_PARENT_LINKS 75 | token->parent = parser->toksuper; 76 | #endif 77 | parser->pos--; 78 | return 0; 79 | } 80 | 81 | /** 82 | * Fills next token with JSON string. 83 | */ 84 | static int jsmn_parse_string(jsmn_parser *parser, const char *js, 85 | size_t len, jsmntok_t *tokens, size_t num_tokens) { 86 | jsmntok_t *token; 87 | 88 | int start = parser->pos; 89 | 90 | parser->pos++; 91 | 92 | /* Skip starting quote */ 93 | for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { 94 | char c = js[parser->pos]; 95 | 96 | /* Quote: end of string */ 97 | if (c == '\"') { 98 | if (tokens == NULL) { 99 | return 0; 100 | } 101 | token = jsmn_alloc_token(parser, tokens, num_tokens); 102 | if (token == NULL) { 103 | parser->pos = start; 104 | return JSMN_ERROR_NOMEM; 105 | } 106 | jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos); 107 | #ifdef JSMN_PARENT_LINKS 108 | token->parent = parser->toksuper; 109 | #endif 110 | return 0; 111 | } 112 | 113 | /* Backslash: Quoted symbol expected */ 114 | if (c == '\\' && parser->pos + 1 < len) { 115 | int i; 116 | parser->pos++; 117 | switch (js[parser->pos]) { 118 | /* Allowed escaped symbols */ 119 | case '\"': case '/' : case '\\' : case 'b' : 120 | case 'f' : case 'r' : case 'n' : case 't' : 121 | break; 122 | /* Allows escaped symbol \uXXXX */ 123 | case 'u': 124 | parser->pos++; 125 | for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) { 126 | /* If it isn't a hex character we have an error */ 127 | if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ 128 | (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ 129 | (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */ 130 | parser->pos = start; 131 | return JSMN_ERROR_INVAL; 132 | } 133 | parser->pos++; 134 | } 135 | parser->pos--; 136 | break; 137 | /* Unexpected symbol */ 138 | default: 139 | parser->pos = start; 140 | return JSMN_ERROR_INVAL; 141 | } 142 | } 143 | } 144 | parser->pos = start; 145 | return JSMN_ERROR_PART; 146 | } 147 | 148 | /** 149 | * Parse JSON string and fill tokens. 150 | */ 151 | int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, 152 | jsmntok_t *tokens, unsigned int num_tokens) { 153 | int r; 154 | int i; 155 | jsmntok_t *token; 156 | int count = parser->toknext; 157 | 158 | for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { 159 | char c; 160 | jsmntype_t type; 161 | 162 | c = js[parser->pos]; 163 | switch (c) { 164 | case '{': case '[': 165 | count++; 166 | if (tokens == NULL) { 167 | break; 168 | } 169 | token = jsmn_alloc_token(parser, tokens, num_tokens); 170 | if (token == NULL) 171 | return JSMN_ERROR_NOMEM; 172 | if (parser->toksuper != -1) { 173 | tokens[parser->toksuper].size++; 174 | #ifdef JSMN_PARENT_LINKS 175 | token->parent = parser->toksuper; 176 | #endif 177 | } 178 | token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); 179 | token->start = parser->pos; 180 | parser->toksuper = parser->toknext - 1; 181 | break; 182 | case '}': case ']': 183 | if (tokens == NULL) 184 | break; 185 | type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); 186 | #ifdef JSMN_PARENT_LINKS 187 | if (parser->toknext < 1) { 188 | return JSMN_ERROR_INVAL; 189 | } 190 | token = &tokens[parser->toknext - 1]; 191 | for (;;) { 192 | if (token->start != -1 && token->end == -1) { 193 | if (token->type != type) { 194 | return JSMN_ERROR_INVAL; 195 | } 196 | token->end = parser->pos + 1; 197 | parser->toksuper = token->parent; 198 | break; 199 | } 200 | if (token->parent == -1) { 201 | if(token->type != type || parser->toksuper == -1) { 202 | return JSMN_ERROR_INVAL; 203 | } 204 | break; 205 | } 206 | token = &tokens[token->parent]; 207 | } 208 | #else 209 | for (i = parser->toknext - 1; i >= 0; i--) { 210 | token = &tokens[i]; 211 | if (token->start != -1 && token->end == -1) { 212 | if (token->type != type) { 213 | return JSMN_ERROR_INVAL; 214 | } 215 | parser->toksuper = -1; 216 | token->end = parser->pos + 1; 217 | break; 218 | } 219 | } 220 | /* Error if unmatched closing bracket */ 221 | if (i == -1) return JSMN_ERROR_INVAL; 222 | for (; i >= 0; i--) { 223 | token = &tokens[i]; 224 | if (token->start != -1 && token->end == -1) { 225 | parser->toksuper = i; 226 | break; 227 | } 228 | } 229 | #endif 230 | break; 231 | case '\"': 232 | r = jsmn_parse_string(parser, js, len, tokens, num_tokens); 233 | if (r < 0) return r; 234 | count++; 235 | if (parser->toksuper != -1 && tokens != NULL) 236 | tokens[parser->toksuper].size++; 237 | break; 238 | case '\t' : case '\r' : case '\n' : case ' ': 239 | break; 240 | case ':': 241 | parser->toksuper = parser->toknext - 1; 242 | break; 243 | case ',': 244 | if (tokens != NULL && parser->toksuper != -1 && 245 | tokens[parser->toksuper].type != JSMN_ARRAY && 246 | tokens[parser->toksuper].type != JSMN_OBJECT) { 247 | #ifdef JSMN_PARENT_LINKS 248 | parser->toksuper = tokens[parser->toksuper].parent; 249 | #else 250 | for (i = parser->toknext - 1; i >= 0; i--) { 251 | if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) { 252 | if (tokens[i].start != -1 && tokens[i].end == -1) { 253 | parser->toksuper = i; 254 | break; 255 | } 256 | } 257 | } 258 | #endif 259 | } 260 | break; 261 | #ifdef JSMN_STRICT 262 | /* In strict mode primitives are: numbers and booleans */ 263 | case '-': case '0': case '1' : case '2': case '3' : case '4': 264 | case '5': case '6': case '7' : case '8': case '9': 265 | case 't': case 'f': case 'n' : 266 | /* And they must not be keys of the object */ 267 | if (tokens != NULL && parser->toksuper != -1) { 268 | jsmntok_t *t = &tokens[parser->toksuper]; 269 | if (t->type == JSMN_OBJECT || 270 | (t->type == JSMN_STRING && t->size != 0)) { 271 | return JSMN_ERROR_INVAL; 272 | } 273 | } 274 | #else 275 | /* In non-strict mode every unquoted value is a primitive */ 276 | default: 277 | #endif 278 | r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens); 279 | if (r < 0) return r; 280 | count++; 281 | if (parser->toksuper != -1 && tokens != NULL) 282 | tokens[parser->toksuper].size++; 283 | break; 284 | 285 | #ifdef JSMN_STRICT 286 | /* Unexpected char in strict mode */ 287 | default: 288 | return JSMN_ERROR_INVAL; 289 | #endif 290 | } 291 | } 292 | 293 | if (tokens != NULL) { 294 | for (i = parser->toknext - 1; i >= 0; i--) { 295 | /* Unmatched opened object or array */ 296 | if (tokens[i].start != -1 && tokens[i].end == -1) { 297 | return JSMN_ERROR_PART; 298 | } 299 | } 300 | } 301 | 302 | return count; 303 | } 304 | 305 | /** 306 | * Creates a new parser based over a given buffer with an array of tokens 307 | * available. 308 | */ 309 | void jsmn_init(jsmn_parser *parser) { 310 | parser->pos = 0; 311 | parser->toknext = 0; 312 | parser->toksuper = -1; 313 | } 314 | 315 | -------------------------------------------------------------------------------- /src/utlgbotlib.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // Project: uTLGBotLib 3 | // File: utlgbotlib.h 4 | // Description: Lightweight library to implement Telegram Bots. 5 | // Created on: 19 mar. 2019 6 | // Last modified date: 12 apr. 2020 7 | // Version: 1.0.3 8 | /**************************************************************************************************/ 9 | 10 | /* Include Guard */ 11 | 12 | #ifndef UTLGBOTLIB_H_ 13 | #define UTLGBOTLIB_H_ 14 | 15 | /**************************************************************************************************/ 16 | 17 | /* Libraries Configurations */ 18 | 19 | // If uTLGBot library without debug was set, disable debug in Multihttpsclient library too 20 | #ifdef UTLGBOT_NO_DEBUG 21 | #define MULTIHTTPSCLIENT_NO_DEBUG 22 | #endif 23 | 24 | // Set default and limit memory usage level 25 | #ifndef UTLGBOT_MEMORY_LEVEL 26 | #define UTLGBOT_MEMORY_LEVEL 5 27 | #endif 28 | #if UTLGBOT_MEMORY_LEVEL < 0 29 | #undef UTLGBOT_MEMORY_LEVEL 30 | #define UTLGBOT_MEMORY_LEVEL 0 31 | #endif 32 | #if UTLGBOT_MEMORY_LEVEL > 5 33 | #undef UTLGBOT_MEMORY_LEVEL 34 | #define UTLGBOT_MEMORY_LEVEL 5 35 | #endif 36 | 37 | // Integer types macros 38 | //#define __STDC_LIMIT_MACROS // Could be needed for C++, and it must be before inttypes include 39 | //#define __STDC_CONSTANT_MACROS // Could be needed for C++, and it must be before inttypes include 40 | #define __STDC_FORMAT_MACROS // Could be needed for C++, and it must be before inttypes include 41 | 42 | /**************************************************************************************************/ 43 | 44 | /* Libraries Inclusion */ 45 | 46 | #if defined(ARDUINO) // Arduino Framework 47 | #include 48 | #endif 49 | 50 | #include 51 | #include 52 | #include 53 | 54 | #include "utility/multihttpsclient/multihttpsclient.h" 55 | #include "utility/jsmn/jsmn.h" 56 | 57 | /**************************************************************************************************/ 58 | 59 | /* Constants */ 60 | 61 | // Telegram HTTPS Server Port 62 | #define HTTPS_PORT 443 63 | 64 | // Telegram Server address and address lenght 65 | #define TELEGRAM_SERVER "https://api.telegram.org" 66 | #define TELEGRAM_HOST "api.telegram.org" 67 | #define TELEGRAM_SERVER_LENGTH 28 68 | 69 | // Bot token max lenght (Note: Actual token lenght is 46, but it seems was increased in the past, 70 | // so we set it to 64) 71 | #define TOKEN_LENGTH 64 72 | 73 | // Telegram API address lenght 74 | #define TELEGRAM_API_LENGTH (TELEGRAM_SERVER_LENGTH + TOKEN_LENGTH) 75 | 76 | // Default Telegram getUpdate Long Poll value (s) 77 | #define DEFAULT_TELEGRAM_LONG_POLL_S 1 78 | 79 | // Telegram data types Max values length 80 | #define MAX_ID_LENGTH 24 81 | #define MAX_USER_LENGTH 32 82 | #define MAX_USERNAME_LENGTH 32 83 | #define MAX_LANGUAGE_CODE_LENGTH 8 84 | #define MAX_CHAT_TYPE_LENGTH 16 85 | #define MAX_CHAT_TITLE_LENGTH 32 86 | #define MAX_CHAT_DESCRIPTION_LENGTH 128 87 | #define MAX_URL_LENGTH 64 88 | #define MAX_STICKER_NAME 32 89 | #define MAX_TEXT_LENGTH 4097 // Yes, it is 4097 instead 4096 (telegram big brain) 90 | 91 | // Memory usage level apply 92 | #undef MAX_TEXT_LENGTH 93 | #if UTLGBOT_MEMORY_LEVEL == 0 94 | #warning "Info: uTLGBotLib memory level 0 select." 95 | #define MAX_TEXT_LENGTH 128 96 | #elif UTLGBOT_MEMORY_LEVEL == 1 97 | #warning "Info: uTLGBotLib memory level 1 select." 98 | #define MAX_TEXT_LENGTH 256 99 | #elif UTLGBOT_MEMORY_LEVEL == 2 100 | #warning "Info: uTLGBotLib memory level 2 select." 101 | #define MAX_TEXT_LENGTH 512 102 | #elif UTLGBOT_MEMORY_LEVEL == 3 103 | #warning "Info: uTLGBotLib memory level 3 select." 104 | #define MAX_TEXT_LENGTH 1024 105 | #elif UTLGBOT_MEMORY_LEVEL == 4 106 | #warning "Info: uTLGBotLib memory level 4 select." 107 | #define MAX_TEXT_LENGTH 2048 108 | #elif UTLGBOT_MEMORY_LEVEL == 5 109 | #warning "Info: uTLGBotLib memory level 5 select." 110 | #define MAX_TEXT_LENGTH 4097 111 | #else 112 | #warning "Info: uTLGBotLib invalid memory level selected." 113 | #define MAX_TEXT_LENGTH 4097 114 | #endif 115 | 116 | // Maximum HTTP GET and POST data lenght 117 | #define HTTP_MAX_URI_LENGTH 128 118 | #define HTTP_MAX_RES_LENGTH MAX_TEXT_LENGTH + 1024 119 | 120 | // JSON Max values length 121 | #define MAX_JSON_STR_LEN MAX_TEXT_LENGTH 122 | #define MAX_JSON_SUBVAL_STR_LEN 512 123 | #define MAX_JSON_ELEMENTS 64 124 | #define MAX_JSON_SUBELEMENTS 32 125 | 126 | // Others 127 | #define MAX_KEYBOARD_MARKUP_LENGTH 128 128 | #define MAX_TMP_BUFFER_LENGTH MAX_KEYBOARD_MARKUP_LENGTH*2 129 | 130 | /**************************************************************************************************/ 131 | 132 | /* Telegram API Commands and Contents */ 133 | 134 | // Commands 135 | #define API_CMD_GET_ME "getMe" 136 | #define API_CMD_SEND_MSG "sendMessage" 137 | #define API_CMD_GET_UPDATES "getUpdates" 138 | 139 | /**************************************************************************************************/ 140 | 141 | /* Telegram Data Types (Not all of them are implemented) */ 142 | 143 | // User: https://core.telegram.org/bots/api#user 144 | typedef struct tlg_type_user 145 | { 146 | char id[MAX_ID_LENGTH]; 147 | bool is_bot; 148 | char first_name[MAX_USER_LENGTH]; 149 | char last_name[MAX_USER_LENGTH]; 150 | char username[MAX_USERNAME_LENGTH]; 151 | char language_code[MAX_LANGUAGE_CODE_LENGTH]; 152 | } tlg_type_user; 153 | 154 | // Chat: https://core.telegram.org/bots/api#chat 155 | typedef struct tlg_type_chat 156 | { 157 | char id[MAX_ID_LENGTH]; 158 | char type[MAX_CHAT_TYPE_LENGTH]; 159 | char title[MAX_CHAT_TITLE_LENGTH]; 160 | char username[MAX_USERNAME_LENGTH]; 161 | char first_name[MAX_USER_LENGTH]; 162 | char last_name[MAX_USER_LENGTH]; 163 | bool all_members_are_administrators; 164 | //tlg_chatphoto_entity photo; // Uninplemented 165 | //char description[MAX_CHAT_DESCRIPTION_LENGTH]; // Uninplemented 166 | //char invite_link[MAX_URL_LENGTH]; // Uninplemented 167 | //tlg_type_message pinned_message; // Uninplemented 168 | //char sticker_set_name[MAX_STICKER_NAME]; // Uninplemented 169 | //bool can_set_sticker_set; // Uninplemented 170 | } tlg_type_chat; 171 | 172 | // Message: https://core.telegram.org/bots/api#message 173 | typedef struct tlg_type_message 174 | { 175 | int64_t message_id; 176 | tlg_type_user from; 177 | uint32_t date; 178 | tlg_type_chat chat; 179 | char text[MAX_TEXT_LENGTH]; 180 | //tlg_type_user forward_from; 181 | //tlg_type_chat forward_from_chat; 182 | //int32_t forward_from_message_id; 183 | //... 184 | } tlg_type_message; 185 | 186 | /**************************************************************************************************/ 187 | 188 | class uTLGBot 189 | { 190 | public: 191 | // Public Attributtes 192 | tlg_type_message received_msg; 193 | 194 | // Public Methods 195 | uTLGBot(const char* token, const bool dont_keep_connection=false); 196 | #if defined(WIN32) || defined(_WIN32) || defined(__linux__) // Native (Windows, Linux) 197 | ~uTLGBot(void); 198 | #endif 199 | void set_debug(const uint8_t debug_level); 200 | void set_token(const char* token); 201 | void set_cert(const uint8_t* ca_pem_start, const uint8_t* ca_pem_end=NULL); 202 | void set_polling_timeout(const uint8_t seconds); 203 | char* get_token(void); 204 | uint8_t get_polling_timeout(void); 205 | uint8_t connect(void); 206 | void disconnect(void); 207 | bool is_connected(void); 208 | uint8_t getMe(void); 209 | uint8_t sendMessage(const char* chat_id, const char* text, const char* parse_mode="", 210 | bool disable_web_page_preview=false, bool disable_notification=false, 211 | uint64_t reply_to_message_id=0, const char* reply_markup=""); 212 | uint8_t sendReplyKeyboardMarkup(const char* chat_id, const char* text, 213 | const char* keyboard); 214 | uint8_t getUpdates(void); 215 | 216 | private: 217 | // Private Attributtes 218 | MultiHTTPSClient* _client; 219 | const uint8_t* _tlg_api_ca_pem_start; 220 | const uint8_t* _tlg_api_ca_pem_end; 221 | uint8_t _long_poll_timeout; 222 | char _token[TOKEN_LENGTH]; 223 | char _tlg_api[TELEGRAM_API_LENGTH]; 224 | char _buffer[HTTP_MAX_RES_LENGTH]; 225 | jsmntok_t _json_elements[MAX_JSON_ELEMENTS]; 226 | jsmntok_t _json_subelements[MAX_JSON_SUBELEMENTS]; 227 | char _json_value_str[MAX_JSON_STR_LEN]; 228 | char _json_subvalue_str[MAX_JSON_SUBVAL_STR_LEN]; 229 | char json_keyboard[MAX_KEYBOARD_MARKUP_LENGTH]; 230 | uint64_t _last_received_msg; 231 | bool _dont_keep_connection; 232 | uint8_t _debug_level; 233 | 234 | // Private Methods 235 | uint8_t tlg_get(const char* command, char* response, const size_t response_len, 236 | const unsigned long response_timeout=HTTP_WAIT_RESPONSE_TIMEOUT); 237 | uint8_t tlg_post(const char* command, char* request_response, const size_t request_len, 238 | const size_t request_response_max_size, 239 | const unsigned long response_timeout=HTTP_WAIT_RESPONSE_TIMEOUT); 240 | 241 | void clear_msg_data(void); 242 | void cant_create_send_msg(const char* msg); 243 | uint32_t json_parse_str(const char* json_str, const size_t json_str_len, 244 | jsmntok_t* json_tokens, const uint32_t json_tokens_len); 245 | uint32_t json_has_key(const char* json_str, jsmntok_t* json_tokens, 246 | const uint32_t num_tokens, const char* key); 247 | void json_get_element_string(const char* json_str, jsmntok_t* token, char* converted_str, 248 | const uint32_t converted_str_len); 249 | uint8_t json_get_key_value(const char* key, const char* json_str, jsmntok_t* tokens, 250 | const uint32_t num_tokens, char* converted_str, const uint32_t converted_str_len); 251 | int32_t cstr_get_substr_pos_end(char* str, const size_t str_len, const char* substr, 252 | const size_t substr_len); 253 | void cstr_rm_char(char* str, const size_t str_len, const char c_remove); 254 | bool cstr_strncat(char* dest, const size_t dest_max_size, const char* src, 255 | const size_t src_len); 256 | }; 257 | 258 | /**************************************************************************************************/ 259 | 260 | #endif 261 | -------------------------------------------------------------------------------- /src/utility/multihttpsclient/multihttpsclient_hals/arduino/multihttpsclient_arduino.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // File: multihttpsclient_arduino.cpp 3 | // Description: Multiplatform HTTPS Client implementation for ESP32 Arduino Framework. 4 | // Created on: 11 may. 2019 5 | // Last modified date: 14 apr. 2020 6 | // Version: 1.0.4 7 | /**************************************************************************************************/ 8 | 9 | #if defined(ARDUINO) 10 | 11 | /**************************************************************************************************/ 12 | 13 | /* Libraries */ 14 | 15 | #include "multihttpsclient_arduino.h" 16 | 17 | /**************************************************************************************************/ 18 | 19 | /* Macros */ 20 | 21 | #ifndef MULTIHTTPSCLIENT_NO_DEBUG 22 | #define _print(x) do { if(_debug) Serial.print(x); } while(0) 23 | #define _println(x) do { if(_debug) Serial.println(x); } while(0) 24 | #define _printf(...) do { if(_debug) Serial.printf(__VA_ARGS__); } while(0) 25 | #else 26 | #define _print(x) 27 | #define _println(x) 28 | #define _printf(...) 29 | #endif 30 | 31 | #define sscanf_P(...) do { sscanf(__VA_ARGS__); } while(0) 32 | 33 | #define _millis_setup() 34 | #define _millis() millis() 35 | #define _delay(x) delay(x) 36 | #define _yield() yield() 37 | 38 | /**************************************************************************************************/ 39 | 40 | /* Constructor */ 41 | 42 | // MultiHTTPSClient constructor, initialize and setup secure client 43 | MultiHTTPSClient::MultiHTTPSClient(void) 44 | { 45 | _debug = false; 46 | _connected = false; 47 | _http_header[0] = '\0'; 48 | _cert_https_server = NULL; 49 | _client = new WiFiClientSecure(); 50 | #ifdef ESP8266 51 | _cert = NULL; 52 | #endif 53 | set_cert(_cert_https_server); 54 | } 55 | 56 | /**************************************************************************************************/ 57 | 58 | /* Public Methods */ 59 | 60 | // Enable/Disable Debug Prints 61 | void MultiHTTPSClient::set_debug(const bool debug) 62 | { 63 | _debug = debug; 64 | } 65 | 66 | // Setup Server Certificate 67 | void MultiHTTPSClient::set_cert(const uint8_t* ca_pem_start, const uint8_t* ca_pem_end) 68 | { 69 | set_cert((const char*)ca_pem_start); 70 | } 71 | 72 | // Setup Server Certificate 73 | void MultiHTTPSClient::set_cert(const char* cert_https_server) 74 | { 75 | _cert_https_server = cert_https_server; 76 | 77 | #ifdef ESP8266 78 | // ESP8266 doesn't have a hardware element for SSL/TLS acceleration 79 | // Note for users: Don't set a cert to ignore server authenticy and trust verification 80 | // to get a faster response 81 | if(_cert_https_server != NULL) 82 | { 83 | if(_cert != NULL) 84 | delete(_cert); 85 | _cert = new X509List(_cert_https_server); 86 | _client->setTrustAnchors(_cert); 87 | } 88 | else 89 | _client->setInsecure(); 90 | #else 91 | // ESP32 has a hardware element for SSL/TLS acceleration, so it could be use 92 | if(_cert_https_server != NULL) 93 | _client->setCACert(_cert_https_server); 94 | #endif 95 | } 96 | 97 | // Make HTTPS client connection to server 98 | int8_t MultiHTTPSClient::connect(const char* host, uint16_t port) 99 | { 100 | int8_t conn_result = _client->connect(host, port); 101 | if(conn_result) 102 | _connected = true; 103 | else 104 | { 105 | // Connection fail, if we are in ESP8266 and cert is configured 106 | #ifdef ESP8266 107 | if(_cert_https_server != NULL) 108 | { 109 | // Set system clock from a NTP server to verify certs 110 | setClock(); 111 | conn_result = _client->connect(host, port); 112 | if(conn_result) 113 | _connected = true; 114 | } 115 | #endif 116 | } 117 | return conn_result; 118 | } 119 | 120 | // HTTPS client disconnect from server 121 | void MultiHTTPSClient::disconnect(void) 122 | { 123 | _client->stop(); 124 | _connected = false; 125 | } 126 | 127 | // Check if HTTPS client is connected 128 | bool MultiHTTPSClient::is_connected(void) 129 | { 130 | _connected = _client->connected(); 131 | return _connected; 132 | } 133 | 134 | // Make and send a HTTP GET request 135 | uint8_t MultiHTTPSClient::get(const char* uri, const char* host, char* response, 136 | const size_t response_len, const unsigned long response_timeout) 137 | { 138 | // Lets use response buffer for make the request first (for the sake of save memory) 139 | char* request = response; 140 | uint8_t rc = 1; 141 | 142 | // Create header request 143 | snprintf_P(request, HTTP_HEADER_MAX_LENGTH, PSTR("GET %s HTTP/1.1\r\nHost: %s\r\n" \ 144 | "User-Agent: MultiHTTPSClient\r\nAccept: text/html,application/xml,application/json" \ 145 | "\r\n\r\n"), uri, host); 146 | 147 | // Send request 148 | _println(F("HTTP GET request to send: ")); 149 | _println(request); 150 | _println(); 151 | if(write(request) != strlen(request)) 152 | { 153 | _println(F("[HTTPS] Error: Incomplete HTTP request sent (sent less bytes than expected).")); 154 | return 1; 155 | } 156 | _println(F("[HTTPS] GET request successfully sent.")); 157 | memset(response, '\0', response_len); 158 | 159 | // Wait and read response 160 | _println(F("[HTTPS] Waiting for response...")); 161 | rc = read_response(response, response_len, response_timeout); 162 | _printf("[HTTPS] Response: %s\n\n", response); 163 | 164 | return rc; 165 | } 166 | 167 | // Make and send a HTTP POST request 168 | // Provide HTTP body in request_response argument 169 | // Argument request_response will be modified and returned as request response 170 | uint8_t MultiHTTPSClient::post(const char* uri, const char* host, char* request_response, 171 | const size_t request_len, const size_t request_response_max_size, 172 | const unsigned long response_timeout) 173 | { 174 | uint8_t rc = 1; 175 | 176 | // Create header request 177 | snprintf_P(_http_header, HTTP_HEADER_MAX_LENGTH, PSTR("POST %s HTTP/1.1\r\nHost: %s\r\n" \ 178 | "User-Agent: MultiHTTPSClient\r\nAccept: text/html,application/xml,application/json" \ 179 | "\r\nContent-Type: application/json\r\nContent-Length: %" PRIu64 "\r\n\r\n"), uri, 180 | host, (uint64_t)request_len); 181 | 182 | // Send request 183 | _println(F("HTTP POST request to send: ")); 184 | _println(_http_header); 185 | _println(request_response); 186 | _println(); 187 | if(write(_http_header) != strlen(_http_header)) 188 | { 189 | _println(F("[HTTPS] Error: Incomplete HTTP request sent (sent less bytes than expected).")); 190 | return 1; 191 | } 192 | if(write(request_response) != strlen(request_response)) 193 | { 194 | _println(F("[HTTPS] Error: Incomplete HTTP request sent (sent less bytes than expected).")); 195 | return 1; 196 | } 197 | _println(F("[HTTPS] POST request successfully sent.")); 198 | memset(request_response, '\0', request_response_max_size); 199 | 200 | // Wait and read response 201 | _println(F("[HTTPS] Waiting for response...")); 202 | rc = read_response(request_response, request_response_max_size, response_timeout); 203 | _printf("[HTTPS] Response: %s\n\n", request_response); 204 | 205 | return rc; 206 | } 207 | 208 | /**************************************************************************************************/ 209 | 210 | /* Private Methods */ 211 | 212 | // Release all mbedtls context 213 | void MultiHTTPSClient::release_tls_elements(void) 214 | { 215 | /* Not release in microcontrollers */ 216 | } 217 | 218 | // HTTPS Write 219 | size_t MultiHTTPSClient::write(const char* request) 220 | { 221 | return _client->print(request); 222 | } 223 | 224 | // HTTPS Read 225 | size_t MultiHTTPSClient::read(char* response, const size_t response_len) 226 | { 227 | char c; 228 | size_t i = 0; 229 | 230 | while(_client->available()) 231 | { 232 | c = _client->read(); 233 | if(i < response_len-1) 234 | { 235 | response[i] = c; 236 | i = i + 1; 237 | } 238 | 239 | _yield(); 240 | } 241 | 242 | return i; 243 | } 244 | 245 | // HTTP Read Response 246 | uint8_t MultiHTTPSClient::read_response(char* response, const size_t response_max_len, 247 | const unsigned long response_timeout) 248 | { 249 | unsigned long t0 = 0, t1 = 0, t2 = 0; 250 | size_t num_bytes_read = 0; 251 | size_t total_bytes_read = 0; 252 | size_t response_len = response_max_len; 253 | 254 | t0 = _millis(); 255 | while(true) 256 | { 257 | t1 = _millis(); 258 | 259 | // Check for overflow 260 | // Note: Due Arduino millis() return an unsigned long instead specific size type, lets just 261 | // handle overflow by reseting counter (this time the timeout can be < 2*expected_timeout) 262 | if(t1 < t0) 263 | { 264 | t0 = 0; 265 | continue; 266 | } 267 | 268 | // Check for timeout 269 | if(t1-t0 >= response_timeout) 270 | { 271 | _println(F("[HTTPS] Error: No response from server (timeout).")); 272 | return 2; // Timeout response 273 | } 274 | 275 | // Check for response 276 | num_bytes_read = read(response, response_len); 277 | total_bytes_read = total_bytes_read + num_bytes_read; 278 | if(total_bytes_read >= response_max_len) 279 | { 280 | _println(F("[HTTPS] Response read buffer full.")); 281 | return 3; 282 | } 283 | if(num_bytes_read == 0) 284 | { 285 | // Check for timeout without any incomming byte 286 | if(t2 != 0) 287 | { 288 | t1 = _millis(); 289 | if(t1 < t2) 290 | t2 = t1; 291 | if(t1-t2 >= HTTP_RESPONSE_BETWEEN_BYTES_TIMEOUT) 292 | { 293 | // Assume full reception 294 | _println(F("[HTTPS] Response successfully received.")); 295 | break; 296 | } 297 | } 298 | } 299 | else 300 | { 301 | _println(F("[HTTPS] Something partially received:")); 302 | _println(response); 303 | response = response + num_bytes_read; 304 | response_len = response_len - num_bytes_read; 305 | t2 = _millis(); 306 | } 307 | 308 | _yield(); 309 | } 310 | 311 | return 0; 312 | } 313 | 314 | // Set time via NTP, as required for x.509 validation 315 | void MultiHTTPSClient::setClock(void) 316 | { 317 | #ifdef ESP8266 318 | time_t now; 319 | struct tm timeinfo; 320 | 321 | configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov"); 322 | Serial.println("Waiting for NTP time sync."); 323 | now = time(nullptr); 324 | while(now < 8*3600*2) 325 | { 326 | delay(500); 327 | Serial.println("..."); 328 | now = time(nullptr); 329 | } 330 | gmtime_r(&now, &timeinfo); 331 | Serial.print("Current time: "); 332 | Serial.print(asctime(&timeinfo)); 333 | #endif 334 | } 335 | 336 | /**************************************************************************************************/ 337 | 338 | #endif 339 | -------------------------------------------------------------------------------- /src/utility/multihttpsclient/multihttpsclient_hals/espidf/multihttpsclient_espidf.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // File: multihttpsclient_espidf.cpp 3 | // Description: Multiplatform HTTPS Client implementation for ESP32 ESPIDF Framework. 4 | // Created on: 11 may. 2019 5 | // Last modified date: 14 apr. 2020 6 | // Version: 1.0.4 7 | /**************************************************************************************************/ 8 | 9 | #if defined(ESP_IDF) 10 | 11 | /**************************************************************************************************/ 12 | 13 | /* Libraries */ 14 | 15 | #include "multihttpsclient_espidf.h" 16 | 17 | /**************************************************************************************************/ 18 | 19 | /* Macros */ 20 | 21 | #ifndef MULTIHTTPSCLIENT_NO_DEBUG 22 | #define _print(x) do { if(_debug) printf("%s", x); } while(0) 23 | #define _println(x) do { if(_debug) printf("%s\n", x); } while(0) 24 | #define _printf(...) do { if(_debug) printf(__VA_ARGS__); } while(0) 25 | #else 26 | #define _print(x) 27 | #define _println(x) 28 | #define _printf(...) 29 | #endif 30 | 31 | #define F(x) x 32 | #define PSTR(x) x 33 | #define snprintf_P(...) do { snprintf(__VA_ARGS__); } while(0) 34 | #define sscanf_P(...) do { sscanf(__VA_ARGS__); } while(0) 35 | 36 | #define _millis_setup() 37 | #define _millis() (unsigned long)(esp_timer_get_time()/1000) 38 | #define _delay(x) do { vTaskDelay(x/portTICK_PERIOD_MS); } while(0) 39 | #define _yield() do { taskYIELD(); } while(0) 40 | 41 | #define PROGMEM 42 | 43 | /**************************************************************************************************/ 44 | 45 | /* Constructor */ 46 | 47 | // MultiHTTPSClient constructor, initialize and setup secure client 48 | MultiHTTPSClient::MultiHTTPSClient(void) 49 | { 50 | _debug = false; 51 | _connected = false; 52 | _http_header[0] = '\0'; 53 | _tls = NULL; 54 | _tls_cfg = NULL; 55 | set_cert(NULL, NULL); 56 | } 57 | 58 | /**************************************************************************************************/ 59 | 60 | /* Public Methods */ 61 | 62 | // Enable/Disable Debug Prints 63 | void MultiHTTPSClient::set_debug(const bool debug) 64 | { 65 | _debug = debug; 66 | } 67 | 68 | // Setup Server Certificate 69 | void MultiHTTPSClient::set_cert(const uint8_t* ca_pem_start, const uint8_t* ca_pem_end) 70 | { 71 | static esp_tls_cfg_t tls_cfg; 72 | 73 | tls_cfg.alpn_protos = NULL; 74 | tls_cfg.cacert_pem_buf = ca_pem_start; 75 | tls_cfg.cacert_pem_bytes = ca_pem_end - ca_pem_start; 76 | tls_cfg.non_block = true; 77 | _tls_cfg = &tls_cfg; 78 | _println(F("[HTTPS] Server Certificate setup.")); 79 | } 80 | 81 | // Make HTTPS client connection to server 82 | int8_t MultiHTTPSClient::connect(const char* host, uint16_t port) 83 | { 84 | unsigned long t0, t1; 85 | int conn_status; 86 | 87 | // Reserve memory for TLS (Warning, here we are dynamically reserving some memory in HEAP) 88 | _tls = (esp_tls*)calloc(1, sizeof(esp_tls_t)); 89 | if(!_tls) 90 | { 91 | _println(F("[HTTPS] Error: Cannot reserve memory for TLS.")); 92 | return false; 93 | } 94 | 95 | t0 = _millis(); 96 | conn_status = 0; 97 | while(conn_status == 0) 98 | { 99 | t1 = _millis(); 100 | 101 | // Check for overflow 102 | // Note: Due Arduino millis() return an unsigned long instead specific size type, 103 | // lets just handle overflow by reseting counter (this time the timeout can 104 | // be < 2*expected_timeout) 105 | if(t1 < t0) 106 | { 107 | t0 = 0; 108 | continue; 109 | } 110 | 111 | // Check for timeout 112 | if(t1-t0 >= HTTP_CONNECT_TIMEOUT) 113 | { 114 | _println(F("[HTTPS] Error: Can't connect to server (connection timeout).")); 115 | break; 116 | } 117 | 118 | // Check connection 119 | conn_status = esp_tls_conn_new_async(host, strlen(host), port, _tls_cfg, _tls); 120 | if(conn_status == 0) // Connection in progress 121 | continue; 122 | else if(conn_status == -1) // Connection Fail 123 | { 124 | _println(F("[HTTPS] Error: Can't connect to server (connection fail).")); 125 | break; 126 | } 127 | else if(conn_status == 1) // Connection Success 128 | break; 129 | 130 | // Release CPU usage 131 | _delay(10); 132 | } 133 | 134 | _connected = is_connected(); 135 | return _connected; 136 | } 137 | 138 | // HTTPS client disconnect from server 139 | void MultiHTTPSClient::disconnect(void) 140 | { 141 | if(_tls != NULL) 142 | { 143 | esp_tls_conn_delete(_tls); 144 | _tls = NULL; 145 | } 146 | _connected = false; 147 | } 148 | 149 | // Check if HTTPS client is connected 150 | bool MultiHTTPSClient::is_connected(void) 151 | { 152 | if(_tls != NULL) 153 | { 154 | if(_tls->conn_state == ESP_TLS_DONE) 155 | _connected = true; 156 | else 157 | _connected = false; 158 | } 159 | else 160 | _connected = false; 161 | 162 | return _connected; 163 | } 164 | 165 | // Make and send a HTTP GET request 166 | uint8_t MultiHTTPSClient::get(const char* uri, const char* host, char* response, 167 | const size_t response_len, const unsigned long response_timeout) 168 | { 169 | // Lets use response buffer for make the request first (for the sake of save memory) 170 | char* request = response; 171 | uint8_t rc = 1; 172 | 173 | // Create header request 174 | snprintf_P(request, HTTP_HEADER_MAX_LENGTH, PSTR("GET %s HTTP/1.1\r\nHost: %s\r\n" \ 175 | "User-Agent: MultiHTTPSClient\r\nAccept: text/html,application/xml,application/json" \ 176 | "\r\n\r\n"), uri, host); 177 | 178 | // Send request 179 | _printf("HTTP GET request to send:\n%s\n", request); 180 | if(write(request) != strlen(request)) 181 | { 182 | _println(F("[HTTPS] Error: Incomplete HTTP request sent (sent less bytes than expected).")); 183 | return 1; 184 | } 185 | _println(F("[HTTPS] GET request successfully sent.")); 186 | memset(response, '\0', response_len); 187 | 188 | // Wait and read response 189 | _println(F("[HTTPS] Waiting for response...")); 190 | rc = read_response(response, response_len, response_timeout); 191 | _printf("[HTTPS] Response: %s\n\n", response); 192 | 193 | return rc; 194 | } 195 | 196 | // Make and send a HTTP POST request 197 | // Provide HTTP body in request_response argument 198 | // Argument request_response will be modified and returned as request response 199 | uint8_t MultiHTTPSClient::post(const char* uri, const char* host, char* request_response, 200 | const size_t request_len, const size_t request_response_max_size, 201 | const unsigned long response_timeout) 202 | { 203 | uint8_t rc = 1; 204 | 205 | // Create header request 206 | snprintf_P(_http_header, HTTP_HEADER_MAX_LENGTH, PSTR("POST %s HTTP/1.1\r\nHost: %s\r\n" \ 207 | "User-Agent: MultiHTTPSClient\r\nAccept: text/html,application/xml,application/json" \ 208 | "\r\nContent-Type: application/json\r\nContent-Length: %" PRIu64 "\r\n\r\n"), uri, 209 | host, (uint64_t)request_len); 210 | 211 | // Send request 212 | _printf("HTTP POST request to send:\n%s%s\n", _http_header, request_response); 213 | if(write(_http_header) != strlen(_http_header)) 214 | { 215 | _println(F("[HTTPS] Error: Incomplete HTTP request sent (sent less bytes than expected).")); 216 | return 1; 217 | } 218 | if(write(request_response) != strlen(request_response)) 219 | { 220 | _println(F("[HTTPS] Error: Incomplete HTTP request sent (sent less bytes than expected).")); 221 | return 1; 222 | } 223 | _println(F("[HTTPS] POST request successfully sent.")); 224 | memset(request_response, '\0', request_response_max_size); 225 | 226 | // Wait and read response 227 | _println(F("[HTTPS] Waiting for response...")); 228 | rc = read_response(request_response, request_response_max_size, response_timeout); 229 | _printf("[HTTPS] Response: %s\n\n", request_response); 230 | 231 | return rc; 232 | } 233 | 234 | /**************************************************************************************************/ 235 | 236 | /* Private Methods */ 237 | 238 | // Release all mbedtls context 239 | void MultiHTTPSClient::release_tls_elements(void) 240 | { 241 | /* Not release in microcontrollers */ 242 | } 243 | 244 | // HTTPS Write 245 | size_t MultiHTTPSClient::write(const char* request) 246 | { 247 | size_t written_bytes = 0; 248 | int ret; 249 | 250 | do 251 | { 252 | ret = esp_tls_conn_write(_tls, request + written_bytes, strlen(request) - 253 | written_bytes); 254 | if(ret > 0) 255 | written_bytes += ret; 256 | else if(ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) 257 | { 258 | _printf(F("[HTTPS] Client write error 0x%x\n"), ret); 259 | break; 260 | } 261 | } while(written_bytes < strlen(request)); 262 | 263 | return written_bytes; 264 | } 265 | 266 | // HTTPS Read 267 | size_t MultiHTTPSClient::read(char* response, const size_t response_len) 268 | { 269 | ssize_t ret; 270 | 271 | ret = esp_tls_conn_read(_tls, response, response_len); 272 | 273 | if(ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) 274 | return 0; 275 | if(ret < 0) 276 | { 277 | _printf(F("[HTTPS] Client read error -0x%x\n"), -ret); 278 | return 0; 279 | } 280 | if(ret == 0) 281 | { 282 | _printf(F("[HTTPS] Lost connection while client was reading.\n")); 283 | return 0; 284 | } 285 | 286 | return ret; 287 | } 288 | 289 | // HTTP Read Response 290 | uint8_t MultiHTTPSClient::read_response(char* response, const size_t response_max_len, 291 | const unsigned long response_timeout) 292 | { 293 | unsigned long t0 = 0, t1 = 0, t2 = 0; 294 | size_t num_bytes_read = 0; 295 | size_t total_bytes_read = 0; 296 | size_t response_len = response_max_len; 297 | 298 | t0 = _millis(); 299 | while(true) 300 | { 301 | t1 = _millis(); 302 | 303 | // Check for overflow 304 | // Note: Due Arduino millis() return an unsigned long instead specific size type, lets just 305 | // handle overflow by reseting counter (this time the timeout can be < 2*expected_timeout) 306 | if(t1 < t0) 307 | { 308 | t0 = 0; 309 | continue; 310 | } 311 | 312 | // Check for timeout 313 | if(t1-t0 >= response_timeout) 314 | { 315 | _println(F("[HTTPS] Error: No response from server (timeout).")); 316 | return 2; // Timeout response 317 | } 318 | 319 | // Check for response 320 | num_bytes_read = read(response, response_len); 321 | total_bytes_read = total_bytes_read + num_bytes_read; 322 | if(total_bytes_read >= response_max_len) 323 | { 324 | _println(F("[HTTPS] Response read buffer full.")); 325 | return 3; 326 | } 327 | if(num_bytes_read == 0) 328 | { 329 | // Check for timeout without any incomming byte 330 | if(t2 != 0) 331 | { 332 | t1 = _millis(); 333 | if(t1 < t2) 334 | t2 = t1; 335 | if(t1-t2 >= HTTP_RESPONSE_BETWEEN_BYTES_TIMEOUT) 336 | { 337 | // Assume full reception 338 | _println(F("[HTTPS] Response successfully received.")); 339 | break; 340 | } 341 | } 342 | } 343 | else 344 | { 345 | _println(F("[HTTPS] Something partially received:")); 346 | _println(response); 347 | response = response + num_bytes_read; 348 | response_len = response_len - num_bytes_read; 349 | t2 = _millis(); 350 | } 351 | 352 | _yield(); 353 | } 354 | 355 | return 0; 356 | } 357 | 358 | /**************************************************************************************************/ 359 | 360 | #endif 361 | -------------------------------------------------------------------------------- /src/utility/multihttpsclient/multihttpsclient_hals/generic/multihttpsclient_generic.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************************************/ 2 | // File: multihttpsclient_generic.cpp 3 | // Description: Multiplatform HTTPS Client implementation for Generic systems (Windows and Linux). 4 | // Created on: 11 may. 2019 5 | // Last modified date: 11 apr. 2020 6 | // Version: 1.0.3 7 | /**************************************************************************************************/ 8 | 9 | #if defined(WIN32) || defined(_WIN32) || defined(__linux__) 10 | 11 | /**************************************************************************************************/ 12 | 13 | /* Libraries */ 14 | 15 | #include "multihttpsclient_generic.h" 16 | 17 | /**************************************************************************************************/ 18 | 19 | /* Macros */ 20 | 21 | #ifndef MULTIHTTPSCLIENT_NO_DEBUG 22 | #define _print(x) do { if(_debug) printf("%s", x); } while(0) 23 | #define _println(x) do { if(_debug) printf("%s\n", x); } while(0) 24 | #define _printf(...) do { if(_debug) printf(__VA_ARGS__); } while(0) 25 | #else 26 | #define _print(x) 27 | #define _println(x) 28 | #define _printf(...) 29 | #endif 30 | 31 | #define F(x) x 32 | #define PSTR(x) x 33 | #define snprintf_P(...) do { snprintf(__VA_ARGS__); } while(0) 34 | #define sscanf_P(...) do { sscanf(__VA_ARGS__); } while(0) 35 | 36 | #define PROGMEM 37 | #define _yield() 38 | 39 | // Initialize millis (just usefull for Generic) 40 | clock_t _millis_t0 = clock(); 41 | #define _millis() (unsigned long)((clock() - ::_millis_t0)*1000.0/CLOCKS_PER_SEC) 42 | 43 | #if defined(WIN32) || defined(_WIN32) // Windows 44 | #define _delay(x) do { Sleep(x); } while(0) 45 | #elif defined(__linux__) 46 | #define _delay(x) do { usleep(x*1000); } while(0) 47 | #endif 48 | 49 | /**************************************************************************************************/ 50 | 51 | /* Constructor & Destructor */ 52 | 53 | // MultiHTTPSClient constructor, initialize and setup secure client with the certificate 54 | MultiHTTPSClient::MultiHTTPSClient(void) 55 | { 56 | _debug = false; 57 | _connected = false; 58 | _http_header[0] = '\0'; 59 | _cert_https_server = NULL; 60 | 61 | init(); 62 | } 63 | 64 | // MultiHTTPSClient destructor, free mbedtls resources 65 | MultiHTTPSClient::~MultiHTTPSClient(void) 66 | { 67 | // Release all mbedtls context 68 | release_tls_elements(); 69 | } 70 | 71 | /**************************************************************************************************/ 72 | 73 | /* Public Methods */ 74 | 75 | // Enable/Disable Debug Prints 76 | void MultiHTTPSClient::set_debug(const bool debug) 77 | { 78 | _debug = debug; 79 | } 80 | 81 | // Setup Server Certificate 82 | void MultiHTTPSClient::set_cert(const uint8_t* ca_pem_start, const uint8_t* ca_pem_end) 83 | { 84 | set_cert((const char*)ca_pem_start); 85 | } 86 | 87 | // Setup Server Certificate 88 | void MultiHTTPSClient::set_cert(const char* cert_https_server) 89 | { 90 | _cert_https_server = cert_https_server; 91 | 92 | // Release all mbedtls context 93 | release_tls_elements(); 94 | 95 | // Initialize again the mbedtls context 96 | init(); 97 | } 98 | 99 | // Make HTTPS client connection to server 100 | int8_t MultiHTTPSClient::connect(const char* host, uint16_t port) 101 | { 102 | int ret; 103 | 104 | // Start connection 105 | char str_port[6]; 106 | snprintf(str_port, 6, "%d", port); 107 | if((ret = mbedtls_net_connect(&_server_fd, host, str_port, MBEDTLS_NET_PROTO_TCP)) != 0) 108 | { 109 | _printf("[HTTPS] Error: Can't connect to server. "); 110 | _printf("Start connection fail (mbedtls_net_connect returned %d).\n", ret); 111 | return 0; 112 | } 113 | 114 | // Set SSL/TLS configuration 115 | if((ret = mbedtls_ssl_config_defaults(&_tls_cfg, MBEDTLS_SSL_IS_CLIENT, 116 | MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) 117 | { 118 | _printf("[HTTPS] Error: Can't connect to server "); 119 | _printf("Default SSL/TLS configuration fail "); 120 | _printf("(mbedtls_ssl_config_defaults returned %d).\n", ret); 121 | return 0; 122 | } 123 | mbedtls_ssl_conf_authmode(&_tls_cfg, MBEDTLS_SSL_VERIFY_OPTIONAL); 124 | mbedtls_ssl_conf_ca_chain(&_tls_cfg, &_cacert, NULL); 125 | mbedtls_ssl_conf_rng(&_tls_cfg, mbedtls_ctr_drbg_random, &_ctr_drbg); 126 | mbedtls_ssl_conf_read_timeout(&_tls_cfg, HTTP_WAIT_RESPONSE_TIMEOUT); 127 | //mbedtls_ssl_conf_dbg(&_tls_cfg, my_debug, stdout); 128 | 129 | // SSL/TLS Server, Hostname and Bio setup 130 | if((ret = mbedtls_ssl_setup( &_tls, &_tls_cfg)) != 0) 131 | { 132 | _printf("[HTTPS] Error: Can't connect to server "); 133 | _printf("SSL/TLS setup fail (mbedtls_ssl_setup returned %d).\n", ret); 134 | return 0; 135 | } 136 | if((ret = mbedtls_ssl_set_hostname(&_tls, host)) != 0) 137 | { 138 | _printf("[HTTPS] Error: Can't connect to server. "); 139 | _printf("Hostname setup fail (mbedtls_ssl_set_hostname returned %d).\n", ret); 140 | return 0; 141 | } 142 | mbedtls_ssl_set_bio(&_tls, &_server_fd, mbedtls_net_send, mbedtls_net_recv, NULL); 143 | 144 | // Perform SSL/TLS Handshake 145 | while((ret = mbedtls_ssl_handshake(&_tls)) != 0) 146 | { 147 | if((ret != MBEDTLS_ERR_SSL_WANT_READ) && (ret != MBEDTLS_ERR_SSL_WANT_WRITE)) 148 | { 149 | _printf("[HTTPS] Error: Can't connect to server "); 150 | _printf("SSL/TLS handshake fail (mbedtls_ssl_handshake returned -0x%x).\n", -ret); 151 | return 0; 152 | } 153 | } 154 | 155 | // Verify server certificate 156 | uint32_t flags; 157 | if(_cert_https_server != NULL) 158 | { 159 | if((flags = mbedtls_ssl_get_verify_result(&_tls)) != 0) 160 | { 161 | char vrfy_buf[512]; 162 | mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), " ! ", flags); 163 | _printf("[HTTPS] Warning: Invalid Server Certificate.\n%s\n", vrfy_buf); 164 | return -1; 165 | } 166 | } 167 | 168 | // Connection stablished and certificate verified 169 | _connected = true; 170 | return 1; 171 | } 172 | 173 | // HTTPS client disconnect from server 174 | void MultiHTTPSClient::disconnect(void) 175 | { 176 | // Close connection 177 | int ret = mbedtls_ssl_close_notify(&_tls); 178 | if((ret != 0) && (ret != MBEDTLS_ERR_SSL_WANT_READ) && (ret != MBEDTLS_ERR_SSL_WANT_WRITE)) 179 | mbedtls_ssl_session_reset(&_tls); 180 | 181 | // Release all mbedtls context 182 | release_tls_elements(); 183 | 184 | // Initialize again the mbedtls context 185 | init(); 186 | 187 | _connected = false; 188 | } 189 | 190 | // Check if HTTPS client is connected 191 | bool MultiHTTPSClient::is_connected(void) 192 | { 193 | return _connected; 194 | } 195 | 196 | // Make and send a HTTP GET request 197 | uint8_t MultiHTTPSClient::get(const char* uri, const char* host, char* response, 198 | const size_t response_len, const unsigned long response_timeout) 199 | { 200 | // Lets use response buffer for make the request first (for the sake of save memory) 201 | char* request = response; 202 | uint8_t rc = 0; 203 | 204 | // Create header request 205 | snprintf_P(request, HTTP_HEADER_MAX_LENGTH, PSTR("GET %s HTTP/1.1\r\nHost: %s\r\n" \ 206 | "User-Agent: MultiHTTPSClient\r\nAccept: text/html,application/xml,application/json" \ 207 | "\r\n\r\n"), uri, host); 208 | 209 | // Send request 210 | _printf("HTTP GET request to send:\n%s", request); 211 | if(write(request) != strlen(request)) 212 | { 213 | _println(F("[HTTPS] Error: Incomplete HTTP request sent (sent less bytes than expected).")); 214 | return 1; 215 | } 216 | _println(F("[HTTPS] GET request successfully sent.")); 217 | memset(response, '\0', response_len); 218 | 219 | // Wait and read response 220 | _println(F("[HTTPS] Waiting for response...")); 221 | rc = read_response(response, response_len, response_timeout); 222 | _printf("[HTTPS] Response: %s\n\n", response); 223 | 224 | return rc; 225 | } 226 | 227 | // Make and send a HTTP POST request 228 | // Provide HTTP body in request_response argument 229 | // Argument request_response will be modified and returned as request response 230 | uint8_t MultiHTTPSClient::post(const char* uri, const char* host, char* request_response, 231 | const size_t request_len, const size_t request_response_max_size, 232 | const unsigned long response_timeout) 233 | { 234 | uint8_t rc = 0; 235 | 236 | // Create header request 237 | snprintf_P(_http_header, HTTP_HEADER_MAX_LENGTH, PSTR("POST %s HTTP/1.1\r\nHost: %s\r\n" \ 238 | "User-Agent: MultiHTTPSClient\r\nAccept: text/html,application/xml,application/json" \ 239 | "\r\nContent-Type: application/json\r\nContent-Length: %" PRIu64 "\r\n\r\n"), uri, 240 | host, (uint64_t)request_len); 241 | 242 | // Send request 243 | _printf("HTTP POST request to send:\n%s%s\n", _http_header, request_response); 244 | if(write(_http_header) != strlen(_http_header)) 245 | { 246 | _println(F("[HTTPS] Error: Incomplete HTTP request sent (sent less bytes than expected).")); 247 | return 1; 248 | } 249 | if(write(request_response) != strlen(request_response)) 250 | { 251 | _println(F("[HTTPS] Error: Incomplete HTTP request sent (sent less bytes than expected).")); 252 | return 1; 253 | } 254 | _println(F("[HTTPS] POST request successfully sent.")); 255 | memset(request_response, '\0', request_response_max_size); 256 | 257 | // Wait and read response 258 | _println(F("[HTTPS] Waiting for response...")); 259 | rc = read_response(request_response, request_response_max_size, response_timeout); 260 | _printf("[HTTPS] Response: %s\n\n", request_response); 261 | 262 | return rc; 263 | } 264 | 265 | /**************************************************************************************************/ 266 | 267 | /* Private Methods */ 268 | 269 | bool MultiHTTPSClient::init(void) 270 | { 271 | static const char* entropy_generation_key = "tls_client\0"; 272 | int ret = 1; 273 | 274 | // Initialization 275 | mbedtls_net_init(&_server_fd); 276 | mbedtls_ssl_init(&_tls); 277 | mbedtls_ssl_config_init(&_tls_cfg); 278 | mbedtls_x509_crt_init(&_cacert); 279 | mbedtls_ctr_drbg_init(&_ctr_drbg); 280 | mbedtls_entropy_init(&_entropy); 281 | if((ret = mbedtls_ctr_drbg_seed(&_ctr_drbg, mbedtls_entropy_func, &_entropy, 282 | (const unsigned char*)entropy_generation_key, strlen(entropy_generation_key))) != 0) 283 | { 284 | printf("[HTTPS] Error: Cannot initialize HTTPS client. "); 285 | printf("mbedtls_ctr_drbg_seed returned %d\n", ret); 286 | return false; 287 | } 288 | 289 | // Load Certificate 290 | if(_cert_https_server != NULL) 291 | { 292 | ret = mbedtls_x509_crt_parse(&_cacert, (const unsigned char*)_cert_https_server, 293 | strlen(_cert_https_server)+1); 294 | if(ret < 0) 295 | { 296 | printf("[HTTPS] Error: Cannot initialize HTTPS client. "); 297 | printf("mbedtls_x509_crt_parse returned -0x%x\n\n", -ret); 298 | return false; 299 | } 300 | } 301 | 302 | return true; 303 | } 304 | 305 | // Release all mbedtls context 306 | void MultiHTTPSClient::release_tls_elements(void) 307 | { 308 | mbedtls_net_free(&_server_fd); 309 | mbedtls_x509_crt_free(&_cacert); 310 | mbedtls_ssl_free(&_tls); 311 | mbedtls_ssl_config_free(&_tls_cfg); 312 | mbedtls_ctr_drbg_free(&_ctr_drbg); 313 | mbedtls_entropy_free(&_entropy); 314 | } 315 | 316 | // HTTPS Write 317 | size_t MultiHTTPSClient::write(const char* request) 318 | { 319 | size_t written_bytes = 0; 320 | int ret; 321 | 322 | written_bytes = strlen(request); 323 | while((ret = mbedtls_ssl_write(&_tls, (const unsigned char*)request, written_bytes)) <= 0) 324 | { 325 | if((ret != MBEDTLS_ERR_SSL_WANT_READ) && (ret != MBEDTLS_ERR_SSL_WANT_WRITE)) 326 | { 327 | _printf(F("[HTTPS] Client write error -0x%x\n"), -ret); 328 | return 0; 329 | } 330 | } 331 | written_bytes = ret; 332 | 333 | return written_bytes; 334 | } 335 | 336 | // HTTPS Read 337 | size_t MultiHTTPSClient::read(char* response, const size_t response_len) 338 | { 339 | int ret; 340 | _printf("Reading\n"); 341 | ret = mbedtls_ssl_read(&_tls, (unsigned char*)response, response_len); 342 | _printf("OK\n"); 343 | 344 | if(ret == MBEDTLS_ERR_SSL_WANT_READ || ret == MBEDTLS_ERR_SSL_WANT_WRITE) 345 | return 0; 346 | 347 | if(ret < 0) 348 | { 349 | _printf(F("[HTTPS] Client read error -0x%x\n"), -ret); 350 | return 0; 351 | } 352 | if(ret == 0) 353 | { 354 | _printf(F("[HTTPS] Lost connection while client was reading.\n")); 355 | return 0; 356 | } 357 | 358 | return (size_t)ret; 359 | } 360 | 361 | 362 | // HTTP Read Response 363 | uint8_t MultiHTTPSClient::read_response(char* response, const size_t response_max_len, 364 | const unsigned long response_timeout) 365 | { 366 | size_t rc = 0; 367 | 368 | rc = read(response, response_max_len); 369 | if(rc > 0) 370 | return 0; 371 | else 372 | return 1; 373 | } 374 | 375 | /**************************************************************************************************/ 376 | 377 | #endif 378 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/utility/multihttpsclient/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 | --------------------------------------------------------------------------------