updated codestyle
Prepare Build and Testing executable binary / Prepare-Build-Testing-With-Make-Without-sqlite3 (push) Successful in 6s
Prepare Build and Testing executable binary / Prepare-Build-Testing-With-CMake-Without-sqlite3 (push) Successful in 9s
Prepare Build and Testing executable binary / Prepare-Build-Testing-With-Meson-Without-sqlite3 (push) Successful in 7s

This commit is contained in:
wt committed 2025-11-18 11:48:46 +07:00
1 parent 193779bd13
commit 36aa1bea2a
10 files changed
+15836 -1416

No files matched your search

+695 -1021
View File
File diff suppressed because it is too large. Load diff
+181 -92
View File
@@ -24,23 +24,27 @@
#define cJSON__h #define cJSON__h
#ifdef __cplusplus #ifdef __cplusplus
extern "C" extern "C" {
{
#endif #endif
#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) #if !defined(__WINDOWS__) && \
(defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
#define __WINDOWS__ #define __WINDOWS__
#endif #endif
#ifdef __WINDOWS__ #ifdef __WINDOWS__
/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: /* When compiling for windows, we specify a specific calling convention to avoid
issues where we are being called from a project with a different default calling
convention. For windows you have 3 define options:
CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) dllexport symbols CJSON_EXPORT_SYMBOLS - Define this on library build when you
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol want to dllexport symbols (default) CJSON_IMPORT_SYMBOLS - Define this if you
want to dllimport symbol
For *nix builds that support visibility attribute, you can define similar behavior by For *nix builds that support visibility attribute, you can define similar
behavior by
setting default visibility to hidden by adding setting default visibility to hidden by adding
-fvisibility=hidden (for gcc) -fvisibility=hidden (for gcc)
@@ -48,15 +52,18 @@ or
-xldscope=hidden (for sun cc) -xldscope=hidden (for sun cc)
to CFLAGS to CFLAGS
then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way
CJSON_EXPORT_SYMBOLS does
*/ */
#define CJSON_CDECL __cdecl #define CJSON_CDECL __cdecl
#define CJSON_STDCALL __stdcall #define CJSON_STDCALL __stdcall
/* export symbols by default, this is necessary for copy pasting the C and header file */ /* export symbols by default, this is necessary for copy pasting the C and
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) * header file */
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && \
!defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_EXPORT_SYMBOLS #define CJSON_EXPORT_SYMBOLS
#endif #endif
@@ -71,7 +78,8 @@ then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJ
#define CJSON_CDECL #define CJSON_CDECL
#define CJSON_STDCALL #define CJSON_STDCALL
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) #if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined(__SUNPRO_C)) && \
defined(CJSON_API_VISIBILITY)
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type #define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
#else #else
#define CJSON_PUBLIC(type) type #define CJSON_PUBLIC(type) type
@@ -100,12 +108,13 @@ then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJ
#define cJSON_StringIsConst 512 #define cJSON_StringIsConst 512
/* The cJSON structure: */ /* The cJSON structure: */
typedef struct cJSON typedef struct cJSON {
{ /* next/prev allow you to walk array/object chains. Alternatively, use
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ * GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *next; struct cJSON *next;
struct cJSON *prev; struct cJSON *prev;
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ /* An array or object item will have a child pointer pointing to a chain of
* the items in the array/object. */
struct cJSON *child; struct cJSON *child;
/* The type of the item, as above. */ /* The type of the item, as above. */
@@ -118,27 +127,29 @@ typedef struct cJSON
/* The item's number, if type==cJSON_Number */ /* The item's number, if type==cJSON_Number */
double valuedouble; double valuedouble;
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ /* The item's name string, if this item is the child of, or is in the list of
* subitems of an object. */
char *string; char *string;
} cJSON; } cJSON;
typedef struct cJSON_Hooks typedef struct cJSON_Hooks {
{ /* malloc/free are CDECL on Windows regardless of the default calling
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ * convention of the compiler, so ensure the hooks allow passing those
* functions directly. */
void *(CJSON_CDECL *malloc_fn)(size_t sz); void *(CJSON_CDECL *malloc_fn)(size_t sz);
void(CJSON_CDECL *free_fn)(void *ptr); void(CJSON_CDECL *free_fn)(void *ptr);
} cJSON_Hooks; } cJSON_Hooks;
typedef int cJSON_bool; typedef int cJSON_bool;
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. /* Limits how deeply nested arrays/objects can be before cJSON rejects to parse
* This is to prevent stack overflows. */ * them. This is to prevent stack overflows. */
#ifndef CJSON_NESTING_LIMIT #ifndef CJSON_NESTING_LIMIT
#define CJSON_NESTING_LIMIT 1000 #define CJSON_NESTING_LIMIT 1000
#endif #endif
/* Limits the length of circular references can be before cJSON rejects to parse them. /* Limits the length of circular references can be before cJSON rejects to parse
* This is to prevent stack overflows. */ * them. This is to prevent stack overflows. */
#ifndef CJSON_CIRCULAR_LIMIT #ifndef CJSON_CIRCULAR_LIMIT
#define CJSON_CIRCULAR_LIMIT 10000 #define CJSON_CIRCULAR_LIMIT 10000
#endif #endif
@@ -149,36 +160,64 @@ CJSON_PUBLIC(const char*) cJSON_Version(void);
/* Supply malloc, realloc and free functions to cJSON */ /* Supply malloc, realloc and free functions to cJSON */
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks *hooks); CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks *hooks);
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ /* Memory Management: the caller is always responsible to free the results from
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ * all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib
* free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is
* cJSON_PrintPreallocated, where the caller has full responsibility of the
* buffer. */
/* Supply a block of JSON, and this returns a cJSON object you can interrogate.
*/
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); CJSON_PUBLIC(cJSON *)
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ cJSON_ParseWithLength(const char *value, size_t buffer_length);
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ /* ParseWithOpts allows you to require (and check) that the JSON is null
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); * terminated, and to retrieve the pointer to the final byte parsed. */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); /* If you supply a ptr in return_parse_end and parsing fails, then
* return_parse_end will contain a pointer to the error so will match
* cJSON_GetErrorPtr(). */
CJSON_PUBLIC(cJSON *)
cJSON_ParseWithOpts(const char *value, const char **return_parse_end,
cJSON_bool require_null_terminated);
CJSON_PUBLIC(cJSON *)
cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length,
const char **return_parse_end,
cJSON_bool require_null_terminated);
/* Render a cJSON entity to text for transfer/storage. */ /* Render a cJSON entity to text for transfer/storage. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. */ /* Render a cJSON entity to text for transfer/storage without any formatting. */
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ /* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); * at the final size. guessing well reduces reallocation. fmt=0 gives
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ * unformatted, =1 gives formatted */
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ CJSON_PUBLIC(char *)
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
/* Render a cJSON entity to text using a buffer already allocated in memory with
* given length. Returns 1 on success and 0 on failure. */
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will
* use, so to be safe allocate 5 bytes more than you actually need */
CJSON_PUBLIC(cJSON_bool)
cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length,
const cJSON_bool format);
/* Delete a cJSON entity and all subentities. */ /* Delete a cJSON entity and all subentities. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
/* Returns the number of items in an array (or object). */ /* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ /* Retrieve item number "index" from array "array". Returns NULL if
* unsuccessful. */
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */ /* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); cJSON_GetObjectItem(const cJSON *const object, const char *const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); CJSON_PUBLIC(cJSON *)
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ cJSON_GetObjectItemCaseSensitive(const cJSON *const object,
const char *const string);
CJSON_PUBLIC(cJSON_bool)
cJSON_HasObjectItem(const cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error.
* You'll probably need to look a few chars back to make sense of it. Defined
* when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
/* Check item type and return its value */ /* Check item type and return its value */
@@ -218,84 +257,134 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
/* These utilities create an Array of count items. /* These utilities create an Array of count items.
* The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ * The parameter count cannot be greater than the number of elements in the
* number array, otherwise array access will be out of bounds.*/
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); CJSON_PUBLIC(cJSON *)
cJSON_CreateStringArray(const char *const *strings, int count);
/* Append item to the specified array/object. */ /* Append item to the specified array/object. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); CJSON_PUBLIC(cJSON_bool)
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before /* Use this when string is definitely const (i.e. a literal, or as good as), and
* writing to `item->string` */ * will definitely survive the cJSON object. WARNING: When this function was
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); * used, make sure to always check that (item->type & cJSON_StringIsConst) is
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ * zero before writing to `item->string` */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); CJSON_PUBLIC(cJSON_bool)
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
/* Append reference to item to the specified array/object. Use this when you
* want to add an existing cJSON to a new cJSON, but don't want to corrupt your
* existing cJSON. */
CJSON_PUBLIC(cJSON_bool)
cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool)
cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
/* Remove/Detach items from Arrays/Objects. */ /* Remove/Detach items from Arrays/Objects. */
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); CJSON_PUBLIC(cJSON *)
cJSON_DetachItemViaPointer(cJSON *parent, cJSON *const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void)
cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void)
cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
/* Update array items. */ /* Update array items. */
CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ CJSON_PUBLIC(cJSON_bool)
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); cJSON_InsertItemInArray(
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); cJSON *array, int which,
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); CJSON_PUBLIC(cJSON_bool)
cJSON_ReplaceItemViaPointer(cJSON *const parent, cJSON *const item,
cJSON *replacement);
CJSON_PUBLIC(cJSON_bool)
cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(cJSON_bool)
cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem);
CJSON_PUBLIC(cJSON_bool)
cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string,
cJSON *newitem);
/* Duplicate a cJSON item */ /* Duplicate a cJSON item */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will /* Duplicate will create a new, identical cJSON item to the one you pass, in new
* need to be released. With recurse!=0, it will duplicate any children connected to the item. * memory that will need to be released. With recurse!=0, it will duplicate any
* The item->next and ->prev pointers are always zero on return from Duplicate. */ * children connected to the item. The item->next and ->prev pointers are always
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. * zero on return from Duplicate. */
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ /* Recursively compare two cJSON items for equality. If either a or b is NULL or
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); * invalid, they will be considered unequal. case_sensitive determines if object
* keys are treated case sensitive (1) or case insensitive (0) */
CJSON_PUBLIC(cJSON_bool)
cJSON_Compare(const cJSON *const a, const cJSON *const b,
const cJSON_bool case_sensitive);
/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. /* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from
* The input pointer json cannot point to a read-only address area, such as a string constant, * strings. The input pointer json cannot point to a read-only address area,
* but should point to a readable and writable address area. */ * such as a string constant, but should point to a readable and writable
* address area. */
CJSON_PUBLIC(void) cJSON_Minify(char *json); CJSON_PUBLIC(void) cJSON_Minify(char *json);
/* Helper functions for creating and adding items to an object at the same time. /* Helper functions for creating and adding items to an object at the same time.
* They return the added item or NULL on failure. */ * They return the added item or NULL on failure. */
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); cJSON_AddNullToObject(cJSON *const object, const char *const name);
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); cJSON_AddTrueToObject(cJSON *const object, const char *const name);
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); cJSON_AddFalseToObject(cJSON *const object, const char *const name);
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); cJSON_AddBoolToObject(cJSON *const object, const char *const name,
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); const cJSON_bool boolean);
CJSON_PUBLIC(cJSON *)
cJSON_AddNumberToObject(cJSON *const object, const char *const name,
const double number);
CJSON_PUBLIC(cJSON *)
cJSON_AddStringToObject(cJSON *const object, const char *const name,
const char *const string);
CJSON_PUBLIC(cJSON *)
cJSON_AddRawToObject(cJSON *const object, const char *const name,
const char *const raw);
CJSON_PUBLIC(cJSON *)
cJSON_AddObjectToObject(cJSON *const object, const char *const name);
CJSON_PUBLIC(cJSON *)
cJSON_AddArrayToObject(cJSON *const object, const char *const name);
/* When assigning an integer value, it needs to be propagated to valuedouble too. */ /* When assigning an integer value, it needs to be propagated to valuedouble
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) * too. */
#define cJSON_SetIntValue(object, number) \
((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
/* helper for the cJSON_SetNumberValue macro */ /* helper for the cJSON_SetNumberValue macro */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) #define cJSON_SetNumberValue(object, number) \
/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); /* Change the valuestring of a cJSON_String object, only takes effect when type
* of object is cJSON_String */
CJSON_PUBLIC(char *)
cJSON_SetValuestring(cJSON *object, const char *valuestring);
/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ /* If the object is not a boolean type this does nothing and returns
#define cJSON_SetBoolValue(object, boolValue) ( \ * cJSON_Invalid else it returns the new type*/
(object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ #define cJSON_SetBoolValue(object, boolValue) \
(object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ ((object != NULL && ((object)->type & (cJSON_False | cJSON_True))) \
cJSON_Invalid\ ? (object)->type = ((object)->type & (~(cJSON_False | cJSON_True))) | \
) ((boolValue) ? cJSON_True : cJSON_False) \
: cJSON_Invalid)
/* Macro for iterating over an array or object */ /* Macro for iterating over an array or object */
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) #define cJSON_ArrayForEach(element, array) \
for (element = (array != NULL) ? (array)->child : NULL; element != NULL; \
element = element->next)
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ /* malloc/free objects using the malloc/free functions that have been set with
* cJSON_InitHooks */
CJSON_PUBLIC(void *) cJSON_malloc(size_t size); CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
CJSON_PUBLIC(void) cJSON_free(void *object); CJSON_PUBLIC(void) cJSON_free(void *object);
+39 -22
View File
@@ -1,13 +1,13 @@
#include "terminal.h"
#include <cJSON.h>
#include <errno.h>
#include <mongoose.h>
#include <signal.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <errno.h> #include <sys/wait.h>
#include <mongoose.h>
#include <cJSON.h>
#include "terminal.h"
#define HTTP_PORT "8888" #define HTTP_PORT "8888"
#define STATIC_DIR "./static/" #define STATIC_DIR "./static/"
@@ -28,7 +28,8 @@ static void log_request(struct mg_connection *c, struct mg_http_message *hm) {
// Проверяем, жив ли дочерний процесс // Проверяем, жив ли дочерний процесс
static bool is_process_alive(pid_t pid) { static bool is_process_alive(pid_t pid) {
if (pid <= 0) return false; if (pid <= 0)
return false;
int status; int status;
pid_t result = waitpid(pid, &status, WNOHANG); pid_t result = waitpid(pid, &status, WNOHANG);
@@ -50,8 +51,10 @@ static bool is_process_alive(pid_t pid) {
} }
// Перезапускаем терминальную сессию // Перезапускаем терминальную сессию
static void restart_terminal_session(struct mg_connection *c, struct client_data *cd) { static void restart_terminal_session(struct mg_connection *c,
if (!cd) return; struct client_data *cd) {
if (!cd)
return;
printf("Restarting terminal session...\n"); printf("Restarting terminal session...\n");
@@ -62,20 +65,25 @@ static void restart_terminal_session(struct mg_connection *c, struct client_data
// Создаем новую сессию // Создаем новую сессию
const char *shell = getenv("SHELL"); const char *shell = getenv("SHELL");
if (!shell) shell = "/bin/bash"; if (!shell)
shell = "/bin/bash";
if (create_terminal_session(&cd->term, shell) == 0) { if (create_terminal_session(&cd->term, shell) == 0) {
cd->terminal_ready = true; cd->terminal_ready = true;
mg_ws_send(c, "\r\n*** Terminal restarted ***\r\n", 29, WEBSOCKET_OP_TEXT); mg_ws_send(c, "\r\n*** Terminal restarted ***\r\n", 29, WEBSOCKET_OP_TEXT);
} else { } else {
mg_ws_send(c, "\r\n*** Failed to restart terminal ***\r\n", 37, WEBSOCKET_OP_TEXT); mg_ws_send(c, "\r\n*** Failed to restart terminal ***\r\n", 37,
WEBSOCKET_OP_TEXT);
cd->terminal_ready = false; cd->terminal_ready = false;
} }
} }
// Обработчик WebSocket сообщений // Обработчик WebSocket сообщений
static void handle_websocket_message(struct mg_connection *c, struct mg_ws_message *wm, struct client_data *cd) { static void handle_websocket_message(struct mg_connection *c,
if (!cd) return; struct mg_ws_message *wm,
struct client_data *cd) {
if (!cd)
return;
if (wm->data.len == 0) { if (wm->data.len == 0) {
return; return;
@@ -119,7 +127,8 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (mg_match(hm->uri, mg_str("/ws"), nullptr)) { if (mg_match(hm->uri, mg_str("/ws"), nullptr)) {
// Проверяем, нет ли уже активного соединения // Проверяем, нет ли уже активного соединения
if (c->fn_data != NULL) { if (c->fn_data != NULL) {
printf("WebSocket connection already exists for this connection, cleaning up...\n"); printf("WebSocket connection already exists for this connection, "
"cleaning up...\n");
struct client_data *old_cd = (struct client_data *)c->fn_data; struct client_data *old_cd = (struct client_data *)c->fn_data;
destroy_terminal_session(&old_cd->term); destroy_terminal_session(&old_cd->term);
free(old_cd); free(old_cd);
@@ -129,17 +138,20 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
// Upgrade до WebSocket // Upgrade до WebSocket
struct client_data *cd = calloc(1, sizeof(struct client_data)); struct client_data *cd = calloc(1, sizeof(struct client_data));
if (!cd) { if (!cd) {
mg_http_reply(c, 500, "Content-Type: text/plain\r\n", "Memory allocation failed"); mg_http_reply(c, 500, "Content-Type: text/plain\r\n",
"Memory allocation failed");
return; return;
} }
// Создаем терминальную сессию // Создаем терминальную сессию
const char *shell = getenv("SHELL"); const char *shell = getenv("SHELL");
if (!shell) shell = "/bin/bash"; if (!shell)
shell = "/bin/bash";
printf("Creating new terminal session with shell: %s\n", shell); printf("Creating new terminal session with shell: %s\n", shell);
if (create_terminal_session(&cd->term, shell) != 0) { if (create_terminal_session(&cd->term, shell) != 0) {
mg_http_reply(c, 500, "Content-Type: text/plain\r\n", "Failed to create terminal session"); mg_http_reply(c, 500, "Content-Type: text/plain\r\n",
"Failed to create terminal session");
free(cd); free(cd);
return; return;
} }
@@ -148,7 +160,8 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
c->fn_data = cd; c->fn_data = cd;
// Upgrade to WebSocket // Upgrade to WebSocket
struct mg_str *ws_proto = mg_http_get_header(hm, "Sec-WebSocket-Protocol"); struct mg_str *ws_proto =
mg_http_get_header(hm, "Sec-WebSocket-Protocol");
if (ws_proto != NULL) { if (ws_proto != NULL) {
mg_ws_upgrade(c, hm, ws_proto->buf); mg_ws_upgrade(c, hm, ws_proto->buf);
} else { } else {
@@ -185,7 +198,8 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
printf("WebSocket connection opened\n"); printf("WebSocket connection opened\n");
struct client_data *cd = (struct client_data *)c->fn_data; struct client_data *cd = (struct client_data *)c->fn_data;
if (cd) { if (cd) {
mg_ws_send(c, "Terminal ready - type 'exit' to restart session\r\n", 49, WEBSOCKET_OP_TEXT); mg_ws_send(c, "Terminal ready - type 'exit' to restart session\r\n", 49,
WEBSOCKET_OP_TEXT);
} }
} else if (ev == MG_EV_WS_MSG) { } else if (ev == MG_EV_WS_MSG) {
// Сообщение от WebSocket клиента // Сообщение от WebSocket клиента
@@ -205,7 +219,8 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
// Проверяем данные от терминала и отправляем через WebSocket // Проверяем данные от терминала и отправляем через WebSocket
struct mg_connection *conn; struct mg_connection *conn;
for (conn = mgr.conns; conn != NULL; conn = conn->next) { for (conn = mgr.conns; conn != NULL; conn = conn->next) {
if (!conn->is_websocket) continue; if (!conn->is_websocket)
continue;
struct client_data *cd = (struct client_data *)conn->fn_data; struct client_data *cd = (struct client_data *)conn->fn_data;
if (cd && cd->terminal_ready) { if (cd && cd->terminal_ready) {
@@ -218,7 +233,8 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
// Читаем данные из терминала // Читаем данные из терминала
char buffer[1024]; char buffer[1024];
ssize_t bytes_read = read_from_terminal(&cd->term, buffer, sizeof(buffer)); ssize_t bytes_read =
read_from_terminal(&cd->term, buffer, sizeof(buffer));
if (bytes_read > 0) { if (bytes_read > 0) {
mg_ws_send(conn, buffer, bytes_read, WEBSOCKET_OP_BINARY); mg_ws_send(conn, buffer, bytes_read, WEBSOCKET_OP_BINARY);
} else if (bytes_read == 0) { } else if (bytes_read == 0) {
@@ -271,7 +287,8 @@ int main(void) {
// Проверяем существование статической директории // Проверяем существование статической директории
if (!directory_exists(STATIC_DIR)) { if (!directory_exists(STATIC_DIR)) {
fprintf(stderr, "Static directory '%s' not found! Creating it...\n", STATIC_DIR); fprintf(stderr, "Static directory '%s' not found! Creating it...\n",
STATIC_DIR);
if (mkdir(STATIC_DIR, 0755) != 0) { if (mkdir(STATIC_DIR, 0755) != 0) {
fprintf(stderr, "Failed to create static directory\n"); fprintf(stderr, "Failed to create static directory\n");
return 1; return 1;
+45 -217
View File
@@ -26,7 +26,6 @@
extern "C" { extern "C" {
#endif #endif
#define MG_ARCH_CUSTOM 0 // User creates its own mongoose_config.h #define MG_ARCH_CUSTOM 0 // User creates its own mongoose_config.h
#define MG_ARCH_UNIX 1 // Linux, BSD, Mac, ... #define MG_ARCH_UNIX 1 // Linux, BSD, Mac, ...
#define MG_ARCH_WIN32 2 // Windows #define MG_ARCH_WIN32 2 // Windows
@@ -60,28 +59,13 @@ extern "C" {
#endif #endif
#if !defined(MG_ARCH) #if !defined(MG_ARCH)
#error "MG_ARCH is not specified and we couldn't guess it. Define MG_ARCH=... in mongoose_config.h" #error \
"MG_ARCH is not specified and we couldn't guess it. Define MG_ARCH=... in mongoose_config.h"
#endif #endif
// http://esr.ibiblio.org/?p=5095 // http://esr.ibiblio.org/?p=5095
#define MG_BIG_ENDIAN (*(uint16_t *)"\0\xff" < 0x100) #define MG_BIG_ENDIAN (*(uint16_t *)"\0\xff" < 0x100)
#if MG_ARCH == MG_ARCH_ARMCGT #if MG_ARCH == MG_ARCH_ARMCGT
#include <ctype.h> #include <ctype.h>
@@ -100,7 +84,6 @@ extern "C" {
#endif #endif
#if MG_ARCH == MG_ARCH_ARMGCC #if MG_ARCH == MG_ARCH_ARMGCC
#define _POSIX_TIMERS #define _POSIX_TIMERS
@@ -123,7 +106,6 @@ extern "C" {
#endif #endif
#if MG_ARCH == MG_ARCH_CUBE #if MG_ARCH == MG_ARCH_CUBE
#include <ctype.h> #include <ctype.h>
@@ -159,7 +141,8 @@ extern "C" {
#define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack #define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack
#endif #endif
#if MG_ENABLE_TCPIP && !defined(MG_ENABLE_DRIVER_STM32F) && !defined(MG_ENABLE_DRIVER_STM32H) #if MG_ENABLE_TCPIP && !defined(MG_ENABLE_DRIVER_STM32F) && \
!defined(MG_ENABLE_DRIVER_STM32H)
#if defined(STM32F1) || defined(STM32F2) || defined(STM32F4) || defined(STM32F7) #if defined(STM32F1) || defined(STM32F2) || defined(STM32F4) || defined(STM32F7)
#define MG_ENABLE_DRIVER_STM32F 1 #define MG_ENABLE_DRIVER_STM32F 1
#elif defined(STM32H5) || defined(STM32H7) #elif defined(STM32H5) || defined(STM32H7)
@@ -173,7 +156,8 @@ extern "C" {
#define MG_TLS MG_TLS_BUILTIN #define MG_TLS MG_TLS_BUILTIN
#endif #endif
#if !defined(MG_OTA) && defined(STM32F1) || defined(STM32F2) || defined(STM32F4) || defined(STM32F7) #if !defined(MG_OTA) && defined(STM32F1) || defined(STM32F2) || \
defined(STM32F4) || defined(STM32F7)
#define MG_OTA MG_OTA_STM32F #define MG_OTA MG_OTA_STM32F
#elif !defined(MG_OTA) && defined(STM32H5) #elif !defined(MG_OTA) && defined(STM32H5)
#define MG_OTA MG_OTA_STM32H5 #define MG_OTA MG_OTA_STM32H5
@@ -195,20 +179,21 @@ extern "C" {
#define MG_SET_MAC_ADDRESS(mac) \ #define MG_SET_MAC_ADDRESS(mac) \
do { \ do { \
int icache_enabled_ = HAL_ICACHE_IsEnabled(); \ int icache_enabled_ = HAL_ICACHE_IsEnabled(); \
if (icache_enabled_) HAL_ICACHE_Disable(); \ if (icache_enabled_) \
HAL_ICACHE_Disable(); \
mac[0] = 42; \ mac[0] = 42; \
mac[1] = ((MGUID[0] >> 0) & 255) ^ ((MGUID[2] >> 19) & 255); \ mac[1] = ((MGUID[0] >> 0) & 255) ^ ((MGUID[2] >> 19) & 255); \
mac[2] = ((MGUID[0] >> 10) & 255) ^ ((MGUID[1] >> 10) & 255); \ mac[2] = ((MGUID[0] >> 10) & 255) ^ ((MGUID[1] >> 10) & 255); \
mac[3] = (MGUID[0] >> 19) & 255; \ mac[3] = (MGUID[0] >> 19) & 255; \
mac[4] = ((MGUID[1] >> 0) & 255) ^ ((MGUID[2] >> 10) & 255); \ mac[4] = ((MGUID[1] >> 0) & 255) ^ ((MGUID[2] >> 10) & 255); \
mac[5] = ((MGUID[2] >> 0) & 255) ^ ((MGUID[1] >> 19) & 255); \ mac[5] = ((MGUID[2] >> 0) & 255) ^ ((MGUID[1] >> 19) & 255); \
if (icache_enabled_) HAL_ICACHE_Enable(); \ if (icache_enabled_) \
HAL_ICACHE_Enable(); \
} while (0) } while (0)
#endif #endif
#endif #endif
#if MG_ARCH == MG_ARCH_ESP32 #if MG_ARCH == MG_ARCH_ESP32
#include <ctype.h> #include <ctype.h>
@@ -241,7 +226,6 @@ extern "C" {
#endif #endif
#if MG_ARCH == MG_ARCH_ESP8266 #if MG_ARCH == MG_ARCH_ESP8266
#include <ctype.h> #include <ctype.h>
@@ -267,7 +251,6 @@ extern "C" {
#endif #endif
#if MG_ARCH == MG_ARCH_FREERTOS #if MG_ARCH == MG_ARCH_FREERTOS
#include <ctype.h> #include <ctype.h>
@@ -295,14 +278,13 @@ extern "C" {
#define MG_ENABLE_CUSTOM_CALLOC 1 #define MG_ENABLE_CUSTOM_CALLOC 1
static inline void mg_free(void *ptr) { static inline void mg_free(void *ptr) { vPortFree(ptr); }
vPortFree(ptr);
}
// Re-route calloc/free to the FreeRTOS's functions, don't use stdlib // Re-route calloc/free to the FreeRTOS's functions, don't use stdlib
static inline void *mg_calloc(size_t cnt, size_t size) { static inline void *mg_calloc(size_t cnt, size_t size) {
void *p = pvPortMalloc(cnt * size); void *p = pvPortMalloc(cnt * size);
if (p != NULL) memset(p, 0, size * cnt); if (p != NULL)
memset(p, 0, size * cnt);
return p; return p;
} }
@@ -317,7 +299,6 @@ static inline int mg_mkdir(const char *path, mode_t mode) {
#endif // MG_ARCH == MG_ARCH_FREERTOS #endif // MG_ARCH == MG_ARCH_FREERTOS
#if MG_ARCH == MG_ARCH_PICOSDK #if MG_ARCH == MG_ARCH_PICOSDK
#if !defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP #if !defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP
#include <errno.h> #include <errno.h>
@@ -330,8 +311,8 @@ static inline int mg_mkdir(const char *path, mode_t mode) {
#include <string.h> #include <string.h>
#include <time.h> #include <time.h>
#include <pico/stdlib.h>
#include <pico/rand.h> #include <pico/rand.h>
#include <pico/stdlib.h>
int mkdir(const char *, mode_t); int mkdir(const char *, mode_t);
#if MG_OTA == MG_OTA_PICOSDK #if MG_OTA == MG_OTA_PICOSDK
@@ -341,21 +322,20 @@ int mkdir(const char *, mode_t);
#endif #endif
#if MG_ARCH == MG_ARCH_RTTHREAD #if MG_ARCH == MG_ARCH_RTTHREAD
#include <rtthread.h>
#include <ctype.h> #include <ctype.h>
#include <errno.h> #include <errno.h>
#include <fcntl.h> #include <fcntl.h>
#include <sys/socket.h> #include <rtthread.h>
#include <sys/select.h>
#include <stdarg.h> #include <stdarg.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdint.h> #include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h> #include <sys/types.h>
#include <time.h> #include <time.h>
@@ -365,10 +345,10 @@ int mkdir(const char *, mode_t);
#endif // MG_ARCH == MG_ARCH_RTTHREAD #endif // MG_ARCH == MG_ARCH_RTTHREAD
#if MG_ARCH == MG_ARCH_ARMCC || MG_ARCH == MG_ARCH_CMSIS_RTOS1 || \ #if MG_ARCH == MG_ARCH_ARMCC || MG_ARCH == MG_ARCH_CMSIS_RTOS1 || \
MG_ARCH == MG_ARCH_CMSIS_RTOS2 MG_ARCH == MG_ARCH_CMSIS_RTOS2
#include <alloca.h>
#include <ctype.h> #include <ctype.h>
#include <errno.h> #include <errno.h>
#include <stdarg.h> #include <stdarg.h>
@@ -377,7 +357,6 @@ int mkdir(const char *, mode_t);
#include <stdint.h> #include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <alloca.h>
#include <string.h> #include <string.h>
#include <time.h> #include <time.h>
#if MG_ARCH == MG_ARCH_CMSIS_RTOS1 #if MG_ARCH == MG_ARCH_CMSIS_RTOS1
@@ -410,7 +389,6 @@ static inline int mg_mkdir(const char *path, mode_t mode) {
#endif #endif
#if MG_ARCH == MG_ARCH_THREADX #if MG_ARCH == MG_ARCH_THREADX
#include <stdarg.h> #include <stdarg.h>
@@ -453,15 +431,14 @@ static inline int mg_mkdir(const char *path, mode_t mode) {
#endif #endif
#if MG_ARCH == MG_ARCH_TIRTOS #if MG_ARCH == MG_ARCH_TIRTOS
#include <stdlib.h>
#include <ctype.h> #include <ctype.h>
#include <stdarg.h> #include <stdarg.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdint.h> #include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h> #include <string.h>
#include <time.h> #include <time.h>
@@ -472,7 +449,6 @@ static inline int mg_mkdir(const char *path, mode_t mode) {
#endif #endif
#if MG_ARCH == MG_ARCH_UNIX #if MG_ARCH == MG_ARCH_UNIX
#define _DARWIN_UNLIMITED_SELECT 1 // No limit on file descriptors #define _DARWIN_UNLIMITED_SELECT 1 // No limit on file descriptors
@@ -539,7 +515,6 @@ static inline int mg_mkdir(const char *path, mode_t mode) {
#endif #endif
#if MG_ARCH == MG_ARCH_WIN32 #if MG_ARCH == MG_ARCH_WIN32
// Avoid name clashing; (macro expansion producing 'defined' has undefined // Avoid name clashing; (macro expansion producing 'defined' has undefined
@@ -717,7 +692,6 @@ typedef int socklen_t;
#endif #endif
#if MG_ARCH == MG_ARCH_ZEPHYR #if MG_ARCH == MG_ARCH_ZEPHYR
#include <zephyr/kernel.h> #include <zephyr/kernel.h>
@@ -725,9 +699,6 @@ typedef int socklen_t;
#include <ctype.h> #include <ctype.h>
#include <errno.h> #include <errno.h>
#include <zephyr/net/socket.h>
#include <zephyr/posix/fcntl.h>
#include <zephyr/posix/sys/select.h>
#include <stdarg.h> #include <stdarg.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdint.h> #include <stdint.h>
@@ -736,6 +707,9 @@ typedef int socklen_t;
#include <string.h> #include <string.h>
#include <sys/types.h> #include <sys/types.h>
#include <time.h> #include <time.h>
#include <zephyr/net/socket.h>
#include <zephyr/posix/fcntl.h>
#include <zephyr/posix/sys/select.h>
#define MG_PUTCHAR(x) printk("%c", x) #define MG_PUTCHAR(x) printk("%c", x)
#ifndef strdup #ifndef strdup
@@ -758,7 +732,6 @@ int sscanf(const char *, const char *, ...);
#endif #endif
#if defined(MG_ENABLE_FREERTOS_TCP) && MG_ENABLE_FREERTOS_TCP #if defined(MG_ENABLE_FREERTOS_TCP) && MG_ENABLE_FREERTOS_TCP
#include <limits.h> #include <limits.h>
@@ -827,7 +800,6 @@ static inline int mg_getpeername(MG_SOCKET_TYPE fd, void *buf, socklen_t *len) {
} }
#endif #endif
#if defined(MG_ENABLE_LWIP) && MG_ENABLE_LWIP #if defined(MG_ENABLE_LWIP) && MG_ENABLE_LWIP
#if defined(__GNUC__) && !defined(__ARMCC_VERSION) #if defined(__GNUC__) && !defined(__ARMCC_VERSION)
@@ -855,7 +827,6 @@ struct timeval {
#endif #endif
#endif #endif
#if defined(MG_ENABLE_RL) && MG_ENABLE_RL #if defined(MG_ENABLE_RL) && MG_ENABLE_RL
#include <rl_net.h> #include <rl_net.h>
@@ -880,7 +851,6 @@ struct timeval {
#define socklen_t int #define socklen_t int
#endif #endif
#ifndef MG_ENABLE_LOG #ifndef MG_ENABLE_LOG
#define MG_ENABLE_LOG 1 #define MG_ENABLE_LOG 1
#endif #endif
@@ -1028,7 +998,8 @@ struct timeval {
#define MG_EPOLL_MOD(c, wr) \ #define MG_EPOLL_MOD(c, wr) \
do { \ do { \
struct epoll_event ev = {EPOLLIN | EPOLLERR | EPOLLHUP, {c}}; \ struct epoll_event ev = {EPOLLIN | EPOLLERR | EPOLLHUP, {c}}; \
if (wr) ev.events |= EPOLLOUT; \ if (wr) \
ev.events |= EPOLLOUT; \
epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_MOD, (int)(size_t)c->fd, &ev); \ epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_MOD, (int)(size_t)c->fd, &ev); \
} while (0) } while (0)
#else #else
@@ -1072,8 +1043,6 @@ struct timeval {
#define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN #define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN
#endif #endif
// Macros to record timestamped events that happens with a connection. // Macros to record timestamped events that happens with a connection.
// They are saved into a c->prof IO buffer, each event is a name and a 32-bit // They are saved into a c->prof IO buffer, each event is a name and a 32-bit
// timestamp in milliseconds since connection init time. // timestamp in milliseconds since connection init time.
@@ -1146,9 +1115,6 @@ struct mg_profitem {
#define MG_PROF_DUMP(c) #define MG_PROF_DUMP(c)
#endif #endif
// Describes an arbitrary chunk of memory // Describes an arbitrary chunk of memory
struct mg_str { struct mg_str {
char *buf; // String data char *buf; // String data
@@ -1169,9 +1135,6 @@ bool mg_span(struct mg_str s, struct mg_str *a, struct mg_str *b, char delim);
bool mg_str_to_num(struct mg_str, int base, void *val, size_t val_len); bool mg_str_to_num(struct mg_str, int base, void *val, size_t val_len);
// Single producer, single consumer non-blocking queue // Single producer, single consumer non-blocking queue
struct mg_queue { struct mg_queue {
@@ -1187,20 +1150,12 @@ void mg_queue_add(struct mg_queue *, size_t); // Add new message
size_t mg_queue_next(struct mg_queue *, char **); // Get oldest message size_t mg_queue_next(struct mg_queue *, char **); // Get oldest message
void mg_queue_del(struct mg_queue *, size_t); // Delete oldest message void mg_queue_del(struct mg_queue *, size_t); // Delete oldest message
typedef void (*mg_pfn_t)(char, void *); // Output function typedef void (*mg_pfn_t)(char, void *); // Output function
typedef size_t (*mg_pm_t)(mg_pfn_t, void *, va_list *); // %M printer typedef size_t (*mg_pm_t)(mg_pfn_t, void *, va_list *); // %M printer
size_t mg_vxprintf(void (*)(char, void *), void *, const char *fmt, va_list *); size_t mg_vxprintf(void (*)(char, void *), void *, const char *fmt, va_list *);
size_t mg_xprintf(void (*fn)(char, void *), void *, const char *fmt, ...); size_t mg_xprintf(void (*fn)(char, void *), void *, const char *fmt, ...);
// Convenience wrappers around mg_xprintf // Convenience wrappers around mg_xprintf
size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list *ap); size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list *ap);
size_t mg_snprintf(char *, size_t, const char *fmt, ...); size_t mg_snprintf(char *, size_t, const char *fmt, ...);
@@ -1226,11 +1181,6 @@ void mg_pfn_stdout(char c, void *param); // param: ignored
// A helper macro for printing JSON: mg_snprintf(buf, len, "%m", MG_ESC("hi")) // A helper macro for printing JSON: mg_snprintf(buf, len, "%m", MG_ESC("hi"))
#define MG_ESC(str) mg_print_esc, 0, (str) #define MG_ESC(str) mg_print_esc, 0, (str)
enum { MG_LL_NONE, MG_LL_ERROR, MG_LL_INFO, MG_LL_DEBUG, MG_LL_VERBOSE }; enum { MG_LL_NONE, MG_LL_ERROR, MG_LL_INFO, MG_LL_DEBUG, MG_LL_VERBOSE };
extern int mg_log_level; // Current log level, one of MG_LL_* extern int mg_log_level; // Current log level, one of MG_LL_*
@@ -1253,7 +1203,8 @@ void mg_log_set_fn(mg_pfn_t fn, void *param);
#else #else
#define MG_LOG(level, args) \ #define MG_LOG(level, args) \
do { \ do { \
if (0) mg_log args; \ if (0) \
mg_log args; \
} while (0) } while (0)
#endif #endif
@@ -1262,9 +1213,6 @@ void mg_log_set_fn(mg_pfn_t fn, void *param);
#define MG_DEBUG(args) MG_LOG(MG_LL_DEBUG, args) #define MG_DEBUG(args) MG_LOG(MG_LL_DEBUG, args)
#define MG_VERBOSE(args) MG_LOG(MG_LL_VERBOSE, args) #define MG_VERBOSE(args) MG_LOG(MG_LL_VERBOSE, args)
struct mg_timer { struct mg_timer {
uint64_t period_ms; // Timer period in milliseconds uint64_t period_ms; // Timer period in milliseconds
uint64_t expire; // Expiration timestamp in milliseconds uint64_t expire; // Expiration timestamp in milliseconds
@@ -1286,10 +1234,6 @@ void mg_timer_free(struct mg_timer **head, struct mg_timer *);
void mg_timer_poll(struct mg_timer **head, uint64_t new_ms); void mg_timer_poll(struct mg_timer **head, uint64_t new_ms);
bool mg_timer_expired(uint64_t *expiration, uint64_t period, uint64_t now); bool mg_timer_expired(uint64_t *expiration, uint64_t period, uint64_t now);
enum { MG_FS_READ = 1, MG_FS_WRITE = 2, MG_FS_DIR = 4 }; enum { MG_FS_READ = 1, MG_FS_WRITE = 2, MG_FS_DIR = 4 };
// Filesystem API functions // Filesystem API functions
@@ -1336,12 +1280,6 @@ const char *mg_unpack(const char *path, size_t *size, time_t *mtime);
const char *mg_unlist(size_t no); // Get no'th packed filename const char *mg_unlist(size_t no); // Get no'th packed filename
struct mg_str mg_unpacked(const char *path); // Packed file as mg_str struct mg_str mg_unpacked(const char *path); // Packed file as mg_str
#if MG_ENABLE_ASSERT #if MG_ENABLE_ASSERT
#include <assert.h> #include <assert.h>
#elif !defined(assert) #elif !defined(assert)
@@ -1454,19 +1392,19 @@ int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip);
#define LIST_ADD_TAIL(type_, head_, elem_) \ #define LIST_ADD_TAIL(type_, head_, elem_) \
do { \ do { \
type_ **h = head_; \ type_ **h = head_; \
while (*h != NULL) h = &(*h)->next; \ while (*h != NULL) \
h = &(*h)->next; \
*h = (elem_); \ *h = (elem_); \
} while (0) } while (0)
#define LIST_DELETE(type_, head_, elem_) \ #define LIST_DELETE(type_, head_, elem_) \
do { \ do { \
type_ **h = head_; \ type_ **h = head_; \
while (*h != (elem_)) h = &(*h)->next; \ while (*h != (elem_)) \
h = &(*h)->next; \
*h = (elem_)->next; \ *h = (elem_)->next; \
} while (0) } while (0)
unsigned short mg_url_port(const char *url); unsigned short mg_url_port(const char *url);
int mg_url_is_ssl(const char *url); int mg_url_is_ssl(const char *url);
struct mg_str mg_url_host(const char *url); struct mg_str mg_url_host(const char *url);
@@ -1474,9 +1412,6 @@ struct mg_str mg_url_user(const char *url);
struct mg_str mg_url_pass(const char *url); struct mg_str mg_url_pass(const char *url);
const char *mg_url_uri(const char *url); const char *mg_url_uri(const char *url);
struct mg_iobuf { struct mg_iobuf {
unsigned char *buf; // Pointer to stored data unsigned char *buf; // Pointer to stored data
size_t size; // Total size available size_t size; // Total size available
@@ -1490,15 +1425,11 @@ void mg_iobuf_free(struct mg_iobuf *);
size_t mg_iobuf_add(struct mg_iobuf *, size_t, const void *, size_t); size_t mg_iobuf_add(struct mg_iobuf *, size_t, const void *, size_t);
size_t mg_iobuf_del(struct mg_iobuf *, size_t ofs, size_t len); size_t mg_iobuf_del(struct mg_iobuf *, size_t ofs, size_t len);
size_t mg_base64_update(unsigned char input_byte, char *buf, size_t len); size_t mg_base64_update(unsigned char input_byte, char *buf, size_t len);
size_t mg_base64_final(char *buf, size_t len); size_t mg_base64_final(char *buf, size_t len);
size_t mg_base64_encode(const unsigned char *p, size_t n, char *buf, size_t); size_t mg_base64_encode(const unsigned char *p, size_t n, char *buf, size_t);
size_t mg_base64_decode(const char *src, size_t n, char *dst, size_t); size_t mg_base64_decode(const char *src, size_t n, char *dst, size_t);
typedef struct { typedef struct {
uint32_t buf[4]; uint32_t buf[4];
uint32_t bits[2]; uint32_t bits[2];
@@ -1509,9 +1440,6 @@ void mg_md5_init(mg_md5_ctx *c);
void mg_md5_update(mg_md5_ctx *c, const unsigned char *data, size_t len); void mg_md5_update(mg_md5_ctx *c, const unsigned char *data, size_t len);
void mg_md5_final(mg_md5_ctx *c, unsigned char[16]); void mg_md5_final(mg_md5_ctx *c, unsigned char[16]);
typedef struct { typedef struct {
uint32_t state[5]; uint32_t state[5];
uint32_t count[2]; uint32_t count[2];
@@ -1527,10 +1455,6 @@ void mg_sha1_final(unsigned char digest[20], mg_sha1_ctx *);
// Details: Defines the API for the corresponding SHA1 implementation. // Details: Defines the API for the corresponding SHA1 implementation.
// Copyright: public domain // Copyright: public domain
typedef struct { typedef struct {
uint32_t state[8]; uint32_t state[8];
uint64_t bits; uint64_t bits;
@@ -1538,7 +1462,6 @@ typedef struct {
unsigned char buffer[64]; unsigned char buffer[64];
} mg_sha256_ctx; } mg_sha256_ctx;
void mg_sha256_init(mg_sha256_ctx *); void mg_sha256_init(mg_sha256_ctx *);
void mg_sha256_update(mg_sha256_ctx *, const unsigned char *data, size_t len); void mg_sha256_update(mg_sha256_ctx *, const unsigned char *data, size_t len);
void mg_sha256_final(unsigned char digest[32], mg_sha256_ctx *); void mg_sha256_final(unsigned char digest[32], mg_sha256_ctx *);
@@ -1557,8 +1480,6 @@ void mg_sha384_update(mg_sha384_ctx *ctx, const uint8_t *data, size_t len);
void mg_sha384_final(uint8_t digest[48], mg_sha384_ctx *ctx); void mg_sha384_final(uint8_t digest[48], mg_sha384_ctx *ctx);
void mg_sha384(uint8_t dst[48], uint8_t *data, size_t datasz); void mg_sha384(uint8_t dst[48], uint8_t *data, size_t datasz);
struct mg_connection; struct mg_connection;
typedef void (*mg_event_handler_t)(struct mg_connection *, int ev, typedef void (*mg_event_handler_t)(struct mg_connection *, int ev,
void *ev_data); void *ev_data);
@@ -1589,15 +1510,6 @@ enum {
MG_EV_USER // Starting ID for user events MG_EV_USER // Starting ID for user events
}; };
struct mg_dns { struct mg_dns {
const char *url; // DNS server URL const char *url; // DNS server URL
struct mg_connection *c; // DNS server connection struct mg_connection *c; // DNS server connection
@@ -1699,13 +1611,6 @@ struct mg_connection *mg_connect_svc(struct mg_mgr *mgr, const char *url,
mg_event_handler_t fn, void *fn_data, mg_event_handler_t fn, void *fn_data,
mg_event_handler_t pfn, void *pfn_data); mg_event_handler_t pfn, void *pfn_data);
struct mg_http_header { struct mg_http_header {
struct mg_str name; // Header name struct mg_str name; // Header name
struct mg_str value; // Header value struct mg_str value; // Header value
@@ -1764,11 +1669,9 @@ struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v);
size_t mg_http_next_multipart(struct mg_str, size_t, struct mg_http_part *); size_t mg_http_next_multipart(struct mg_str, size_t, struct mg_http_part *);
int mg_http_status(const struct mg_http_message *hm); int mg_http_status(const struct mg_http_message *hm);
void mg_http_serve_ssi(struct mg_connection *c, const char *root, void mg_http_serve_ssi(struct mg_connection *c, const char *root,
const char *fullpath); const char *fullpath);
#define MG_TLS_NONE 0 // No TLS support #define MG_TLS_NONE 0 // No TLS support
#define MG_TLS_MBED 1 // mbedTLS #define MG_TLS_MBED 1 // mbedTLS
#define MG_TLS_OPENSSL 2 // OpenSSL #define MG_TLS_OPENSSL 2 // OpenSSL
@@ -1780,10 +1683,6 @@ void mg_http_serve_ssi(struct mg_connection *c, const char *root,
#define MG_TLS MG_TLS_NONE #define MG_TLS MG_TLS_NONE
#endif #endif
struct mg_tls_opts { struct mg_tls_opts {
struct mg_str ca; // PEM or DER struct mg_str ca; // PEM or DER
struct mg_str cert; // PEM or DER struct mg_str cert; // PEM or DER
@@ -1811,15 +1710,12 @@ long mg_io_recv(struct mg_connection *c, void *buf, size_t len);
#ifndef TLS_X15519_H #ifndef TLS_X15519_H
#define TLS_X15519_H #define TLS_X15519_H
#define X25519_BYTES 32 #define X25519_BYTES 32
extern const uint8_t X25519_BASE_POINT[X25519_BYTES]; extern const uint8_t X25519_BASE_POINT[X25519_BYTES];
int mg_tls_x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES], int mg_tls_x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES],
const uint8_t x1[X25519_BYTES], int clamp); const uint8_t x1[X25519_BYTES], int clamp);
#endif /* TLS_X15519_H */ #endif /* TLS_X15519_H */
/****************************************************************************** /******************************************************************************
* *
@@ -1857,7 +1753,6 @@ typedef struct {
uint32_t buf[68]; // key expansion buffer uint32_t buf[68]; // key expansion buffer
} aes_context; } aes_context;
#define GCM_AUTH_FAILURE 0x55555555 // authentication failure #define GCM_AUTH_FAILURE 0x55555555 // authentication failure
/****************************************************************************** /******************************************************************************
@@ -1888,8 +1783,6 @@ int mg_aes_gcm_decrypt(unsigned char *output, const unsigned char *input,
// End of aes128 PD // End of aes128 PD
#define MG_UECC_SUPPORTS_secp256r1 1 #define MG_UECC_SUPPORTS_secp256r1 1
/* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */ /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
@@ -2547,10 +2440,6 @@ int mg_uecc_generate_random_int(mg_uecc_word_t *random,
// Contains poly1305-donna e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781 (Public // Contains poly1305-donna e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781 (Public
// Domain) // Domain)
#if MG_TLS == MG_TLS_BUILTIN #if MG_TLS == MG_TLS_BUILTIN
#ifndef __PORTABLE_8439_H #ifndef __PORTABLE_8439_H
#define __PORTABLE_8439_H #define __PORTABLE_8439_H
@@ -2657,17 +2546,12 @@ PORTABLE_8439_DECL size_t mg_chacha20_poly1305_decrypt(
#ifndef TLS_RSA_H #ifndef TLS_RSA_H
#define TLS_RSA_H #define TLS_RSA_H
int mg_rsa_mod_pow(const uint8_t *mod, size_t modsz, const uint8_t *exp,
int mg_rsa_mod_pow(const uint8_t *mod, size_t modsz, const uint8_t *exp, size_t expsz, const uint8_t *msg, size_t msgsz, uint8_t *out, size_t outsz); size_t expsz, const uint8_t *msg, size_t msgsz, uint8_t *out,
size_t outsz);
#endif // TLS_RSA_H #endif // TLS_RSA_H
#if MG_TLS == MG_TLS_MBED #if MG_TLS == MG_TLS_MBED
#include <mbedtls/debug.h> #include <mbedtls/debug.h>
#include <mbedtls/error.h> #include <mbedtls/error.h>
@@ -2697,7 +2581,6 @@ struct mg_tls {
}; };
#endif #endif
#if MG_TLS == MG_TLS_OPENSSL || MG_TLS == MG_TLS_WOLFSSL #if MG_TLS == MG_TLS_OPENSSL || MG_TLS == MG_TLS_WOLFSSL
#include <openssl/err.h> #include <openssl/err.h>
@@ -2710,7 +2593,6 @@ struct mg_tls {
}; };
#endif #endif
#define WEBSOCKET_OP_CONTINUE 0 #define WEBSOCKET_OP_CONTINUE 0
#define WEBSOCKET_OP_TEXT 1 #define WEBSOCKET_OP_TEXT 1
#define WEBSOCKET_OP_BINARY 2 #define WEBSOCKET_OP_BINARY 2
@@ -2718,8 +2600,6 @@ struct mg_tls {
#define WEBSOCKET_OP_PING 9 #define WEBSOCKET_OP_PING 9
#define WEBSOCKET_OP_PONG 10 #define WEBSOCKET_OP_PONG 10
struct mg_ws_message { struct mg_ws_message {
struct mg_str data; // Websocket message data struct mg_str data; // Websocket message data
uint8_t flags; // Websocket message flags uint8_t flags; // Websocket message flags
@@ -2736,9 +2616,6 @@ size_t mg_ws_printf(struct mg_connection *c, int op, const char *fmt, ...);
size_t mg_ws_vprintf(struct mg_connection *c, int op, const char *fmt, size_t mg_ws_vprintf(struct mg_connection *c, int op, const char *fmt,
va_list *); va_list *);
struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url, struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url,
mg_event_handler_t fn, void *fn_data); mg_event_handler_t fn, void *fn_data);
void mg_sntp_request(struct mg_connection *c); void mg_sntp_request(struct mg_connection *c);
@@ -2746,10 +2623,6 @@ int64_t mg_sntp_parse(const unsigned char *buf, size_t len);
uint64_t mg_now(void); // Return milliseconds since Epoch uint64_t mg_now(void); // Return milliseconds since Epoch
#define MQTT_CMD_CONNECT 1 #define MQTT_CMD_CONNECT 1
#define MQTT_CMD_CONNACK 2 #define MQTT_CMD_CONNACK 2
#define MQTT_CMD_PUBLISH 3 #define MQTT_CMD_PUBLISH 3
@@ -2860,10 +2733,6 @@ void mg_mqtt_disconnect(struct mg_connection *, const struct mg_mqtt_opts *);
size_t mg_mqtt_next_prop(struct mg_mqtt_message *, struct mg_mqtt_prop *, size_t mg_mqtt_next_prop(struct mg_mqtt_message *, struct mg_mqtt_prop *,
size_t ofs); size_t ofs);
// Mongoose sends DNS queries that contain only one question: // Mongoose sends DNS queries that contain only one question:
// either A (IPv4) or AAAA (IPv6) address lookup. // either A (IPv4) or AAAA (IPv6) address lookup.
// Therefore, we expect zero or one answer. // Therefore, we expect zero or one answer.
@@ -2900,10 +2769,6 @@ size_t mg_dns_parse_rr(const uint8_t *buf, size_t len, size_t ofs,
struct mg_connection *mg_mdns_listen(struct mg_mgr *mgr, char *name); struct mg_connection *mg_mdns_listen(struct mg_mgr *mgr, char *name);
#ifndef MG_JSON_MAX_DEPTH #ifndef MG_JSON_MAX_DEPTH
#define MG_JSON_MAX_DEPTH 30 #define MG_JSON_MAX_DEPTH 30
#endif #endif
@@ -2924,9 +2789,6 @@ bool mg_json_unescape(struct mg_str str, char *buf, size_t len);
size_t mg_json_next(struct mg_str obj, size_t ofs, struct mg_str *key, size_t mg_json_next(struct mg_str obj, size_t ofs, struct mg_str *key,
struct mg_str *val); struct mg_str *val);
// JSON-RPC request descriptor // JSON-RPC request descriptor
struct mg_rpc_req { struct mg_rpc_req {
struct mg_rpc **head; // RPC handlers list head struct mg_rpc **head; // RPC handlers list head
@@ -2959,10 +2821,6 @@ void mg_rpc_list(struct mg_rpc_req *r);
// Copyright (c) 2023 Cesanta Software Limited // Copyright (c) 2023 Cesanta Software Limited
// All rights reserved // All rights reserved
#define MG_OTA_NONE 0 // No OTA support #define MG_OTA_NONE 0 // No OTA support
#define MG_OTA_STM32H5 1 // STM32 H5 #define MG_OTA_STM32H5 1 // STM32 H5
#define MG_OTA_STM32H7 2 // STM32 H7 #define MG_OTA_STM32H7 2 // STM32 H7
@@ -2999,8 +2857,6 @@ bool mg_ota_begin(size_t new_firmware_size); // Start writing
bool mg_ota_write(const void *buf, size_t len); // Write chunk, aligned to 1k bool mg_ota_write(const void *buf, size_t len); // Write chunk, aligned to 1k
bool mg_ota_end(void); // Stop writing bool mg_ota_end(void); // Stop writing
#if MG_OTA != MG_OTA_NONE && MG_OTA != MG_OTA_CUSTOM #if MG_OTA != MG_OTA_NONE && MG_OTA != MG_OTA_CUSTOM
struct mg_flash { struct mg_flash {
@@ -3018,11 +2874,6 @@ bool mg_ota_flash_end(struct mg_flash *flash);
#endif #endif
struct mg_wifi_scan_bss_data { struct mg_wifi_scan_bss_data {
struct mg_str SSID; struct mg_str SSID;
char *BSSID; char *BSSID;
@@ -3040,19 +2891,12 @@ struct mg_wifi_scan_bss_data {
unsigned has_n : 1; unsigned has_n : 1;
}; };
bool mg_wifi_scan(void); bool mg_wifi_scan(void);
bool mg_wifi_connect(char *ssid, char *pass); bool mg_wifi_connect(char *ssid, char *pass);
bool mg_wifi_disconnect(void); bool mg_wifi_disconnect(void);
bool mg_wifi_ap_start(char *ssid, char *pass, unsigned int channel); bool mg_wifi_ap_start(char *ssid, char *pass, unsigned int channel);
bool mg_wifi_ap_stop(void); bool mg_wifi_ap_stop(void);
#if MG_ENABLE_TCPIP #if MG_ENABLE_TCPIP
struct mg_tcpip_if; // Mongoose TCP/IP network interface struct mg_tcpip_if; // Mongoose TCP/IP network interface
@@ -3073,14 +2917,15 @@ enum {
MG_TCPIP_EV_DHCP_SNTP, // DHCP SNTP assignment uint32_t *ipaddr MG_TCPIP_EV_DHCP_SNTP, // DHCP SNTP assignment uint32_t *ipaddr
MG_TCPIP_EV_ARP, // Got ARP packet struct mg_str * MG_TCPIP_EV_ARP, // Got ARP packet struct mg_str *
MG_TCPIP_EV_TIMER_1S, // 1 second timer NULL MG_TCPIP_EV_TIMER_1S, // 1 second timer NULL
MG_TCPIP_EV_WIFI_SCAN_RESULT, // Wi-Fi scan results struct mg_wifi_scan_bss_data * MG_TCPIP_EV_WIFI_SCAN_RESULT, // Wi-Fi scan results struct
// mg_wifi_scan_bss_data *
MG_TCPIP_EV_WIFI_SCAN_END, // Wi-Fi scan has finished NULL MG_TCPIP_EV_WIFI_SCAN_END, // Wi-Fi scan has finished NULL
MG_TCPIP_EV_WIFI_CONNECT_ERR, // Wi-Fi connect has failed driver and chip specific MG_TCPIP_EV_WIFI_CONNECT_ERR, // Wi-Fi connect has failed driver and
// chip specific
MG_TCPIP_EV_DRIVER, // Driver event driver specific MG_TCPIP_EV_DRIVER, // Driver event driver specific
MG_TCPIP_EV_USER // Starting ID for user events MG_TCPIP_EV_USER // Starting ID for user events
}; };
// Network interface // Network interface
struct mg_tcpip_if { struct mg_tcpip_if {
uint8_t mac[6]; // MAC address. Must be set to a valid MAC uint8_t mac[6]; // MAC address. Must be set to a valid MAC
@@ -3152,10 +2997,8 @@ struct mg_tcpip_spi {
uint8_t (*txn)(void *, uint8_t); // SPI transaction: write 1 byte, read reply uint8_t (*txn)(void *, uint8_t); // SPI transaction: write 1 byte, read reply
}; };
#endif #endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS
#include "Driver_ETH_MAC.h" // keep this include #include "Driver_ETH_MAC.h" // keep this include
@@ -3163,7 +3006,6 @@ struct mg_tcpip_spi {
#endif #endif
#if MG_ENABLE_TCPIP && \ #if MG_ENABLE_TCPIP && \
((defined(MG_ENABLE_DRIVER_CYW) && MG_ENABLE_DRIVER_CYW) || \ ((defined(MG_ENABLE_DRIVER_CYW) && MG_ENABLE_DRIVER_CYW) || \
(defined(MG_ENABLE_DRIVER_CYW_SDIO) && MG_ENABLE_DRIVER_CYW_SDIO)) (defined(MG_ENABLE_DRIVER_CYW_SDIO) && MG_ENABLE_DRIVER_CYW_SDIO))
@@ -3195,8 +3037,10 @@ struct mg_tcpip_driver_cyw_data {
uint8_t security; // TBD uint8_t security; // TBD
uint8_t apsecurity; // TBD uint8_t apsecurity; // TBD
uint8_t apchannel; uint8_t apchannel;
bool apmode; // start in AP mode; 'false' starts connection to 'ssid' if not NULL bool apmode; // start in AP mode; 'false' starts connection to 'ssid' if not
bool hs; // use chip "high-speed" mode; otherwise SPI CPOL0 CPHA0 (DS 4.2.3 Table 6) // NULL
bool hs; // use chip "high-speed" mode; otherwise SPI CPOL0 CPHA0 (DS 4.2.3
// Table 6)
}; };
#if 0 #if 0
@@ -3219,7 +3063,6 @@ struct mg_tcpip_driver_cyw_data {
#endif #endif
#if MG_ENABLE_TCPIP && \ #if MG_ENABLE_TCPIP && \
(defined(MG_ENABLE_DRIVER_IMXRT10) && MG_ENABLE_DRIVER_IMXRT10) || \ (defined(MG_ENABLE_DRIVER_IMXRT10) && MG_ENABLE_DRIVER_IMXRT10) || \
(defined(MG_ENABLE_DRIVER_IMXRT11) && MG_ENABLE_DRIVER_IMXRT11) (defined(MG_ENABLE_DRIVER_IMXRT11) && MG_ENABLE_DRIVER_IMXRT11)
@@ -3267,9 +3110,6 @@ struct mg_tcpip_driver_imxrt_data {
#endif #endif
struct mg_phy { struct mg_phy {
uint16_t (*read_reg)(uint8_t addr, uint8_t reg); uint16_t (*read_reg)(uint8_t addr, uint8_t reg);
void (*write_reg)(uint8_t addr, uint8_t reg, uint16_t value); void (*write_reg)(uint8_t addr, uint8_t reg, uint16_t value);
@@ -3289,7 +3129,6 @@ void mg_phy_init(struct mg_phy *, uint8_t addr, uint8_t config);
bool mg_phy_up(struct mg_phy *, uint8_t addr, bool *full_duplex, bool mg_phy_up(struct mg_phy *, uint8_t addr, bool *full_duplex,
uint8_t *speed); uint8_t *speed);
#if MG_ENABLE_TCPIP && MG_ARCH == MG_ARCH_PICOSDK && \ #if MG_ENABLE_TCPIP && MG_ARCH == MG_ARCH_PICOSDK && \
defined(MG_ENABLE_DRIVER_PICO_W) && MG_ENABLE_DRIVER_PICO_W defined(MG_ENABLE_DRIVER_PICO_W) && MG_ENABLE_DRIVER_PICO_W
@@ -3305,7 +3144,8 @@ struct mg_tcpip_driver_pico_w_data {
uint8_t security; // TBD uint8_t security; // TBD
uint8_t apsecurity; // TBD uint8_t apsecurity; // TBD
uint8_t apchannel; uint8_t apchannel;
bool apmode; // start in AP mode; 'false' starts connection to 'ssid' if not NULL bool apmode; // start in AP mode; 'false' starts connection to 'ssid' if not
// NULL
}; };
#define MG_TCPIP_DRIVER_INIT(mgr) \ #define MG_TCPIP_DRIVER_INIT(mgr) \
@@ -3326,7 +3166,6 @@ struct mg_tcpip_driver_pico_w_data {
#endif #endif
struct mg_tcpip_driver_ppp_data { struct mg_tcpip_driver_ppp_data {
void *uart; // Opaque UART bus descriptor void *uart; // Opaque UART bus descriptor
void (*reset)(void *); // Modem hardware reset void (*reset)(void *); // Modem hardware reset
@@ -3337,7 +3176,6 @@ struct mg_tcpip_driver_ppp_data {
uint64_t deadline; // AT command deadline in ms uint64_t deadline; // AT command deadline in ms
}; };
#if MG_ENABLE_TCPIP && \ #if MG_ENABLE_TCPIP && \
(defined(MG_ENABLE_DRIVER_RA6) && MG_ENABLE_DRIVER_RA6) || \ (defined(MG_ENABLE_DRIVER_RA6) && MG_ENABLE_DRIVER_RA6) || \
(defined(MG_ENABLE_DRIVER_RA8) && MG_ENABLE_DRIVER_RA8) (defined(MG_ENABLE_DRIVER_RA8) && MG_ENABLE_DRIVER_RA8)
@@ -3380,7 +3218,6 @@ struct mg_tcpip_driver_ra_data {
#endif #endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RW612) && MG_ENABLE_DRIVER_RW612 #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RW612) && MG_ENABLE_DRIVER_RW612
struct mg_tcpip_driver_rw612_data { struct mg_tcpip_driver_rw612_data {
@@ -3426,7 +3263,6 @@ struct mg_tcpip_driver_rw612_data {
#endif #endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_SAME54) && \ #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_SAME54) && \
MG_ENABLE_DRIVER_SAME54 MG_ENABLE_DRIVER_SAME54
@@ -3461,7 +3297,6 @@ struct mg_tcpip_driver_same54_data {
#endif #endif
#if MG_ENABLE_TCPIP && \ #if MG_ENABLE_TCPIP && \
(defined(MG_ENABLE_DRIVER_CYW_SDIO) && MG_ENABLE_DRIVER_CYW_SDIO) (defined(MG_ENABLE_DRIVER_CYW_SDIO) && MG_ENABLE_DRIVER_CYW_SDIO)
@@ -3500,7 +3335,6 @@ bool mg_sdio_transfer(struct mg_tcpip_sdio *sdio, bool write, unsigned int f,
#endif #endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \ #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \
MG_ENABLE_DRIVER_STM32F MG_ENABLE_DRIVER_STM32F
@@ -3554,7 +3388,6 @@ struct mg_tcpip_driver_stm32f_data {
#endif #endif
#if MG_ENABLE_TCPIP #if MG_ENABLE_TCPIP
#if !defined(MG_ENABLE_DRIVER_STM32H) #if !defined(MG_ENABLE_DRIVER_STM32H)
#define MG_ENABLE_DRIVER_STM32H 0 #define MG_ENABLE_DRIVER_STM32H 0
@@ -3622,7 +3455,6 @@ struct mg_tcpip_driver_stm32h_data {
#endif #endif
#endif #endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C
struct mg_tcpip_driver_tm4c_data { struct mg_tcpip_driver_tm4c_data {
@@ -3659,8 +3491,8 @@ struct mg_tcpip_driver_tm4c_data {
#endif #endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TMS570) && \
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TMS570) && MG_ENABLE_DRIVER_TMS570 MG_ENABLE_DRIVER_TMS570
struct mg_tcpip_driver_tms570_data { struct mg_tcpip_driver_tms570_data {
int mdc_cr; int mdc_cr;
int phy_addr; int phy_addr;
@@ -3691,8 +3523,6 @@ struct mg_tcpip_driver_tms570_data {
} while (0) } while (0)
#endif #endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC7) && MG_ENABLE_DRIVER_XMC7 #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC7) && MG_ENABLE_DRIVER_XMC7
struct mg_tcpip_driver_xmc7_data { struct mg_tcpip_driver_xmc7_data {
@@ -3726,8 +3556,6 @@ struct mg_tcpip_driver_xmc7_data {
#endif #endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC) && MG_ENABLE_DRIVER_XMC #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC) && MG_ENABLE_DRIVER_XMC
struct mg_tcpip_driver_xmc_data { struct mg_tcpip_driver_xmc_data {
+14 -14
View File
@@ -1,17 +1,18 @@
#include "terminal.h" #include "terminal.h"
#include <errno.h>
#include <fcntl.h>
#include <pty.h>
#include <signal.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <pty.h> #include <unistd.h>
#include <utmp.h> #include <utmp.h>
#include <signal.h>
#include <errno.h>
int create_terminal_session(struct terminal_session *session, const char *shell) { int create_terminal_session(struct terminal_session *session,
const char *shell) {
// Создаем pty // Создаем pty
int master, slave; int master, slave;
char slave_name[64]; char slave_name[64];
@@ -100,7 +101,8 @@ void destroy_terminal_session(struct terminal_session *session) {
printf("Terminal session destroyed\n"); printf("Terminal session destroyed\n");
} }
ssize_t read_from_terminal(struct terminal_session *session, char *buffer, size_t size) { ssize_t read_from_terminal(struct terminal_session *session, char *buffer,
size_t size) {
if (!session || !session->active) { if (!session || !session->active) {
return -1; return -1;
} }
@@ -123,7 +125,8 @@ ssize_t read_from_terminal(struct terminal_session *session, char *buffer, size_
return bytes_read; return bytes_read;
} }
ssize_t write_to_terminal(struct terminal_session *session, const char *data, size_t size) { ssize_t write_to_terminal(struct terminal_session *session, const char *data,
size_t size) {
if (!session || !session->active) { if (!session || !session->active) {
return -1; return -1;
} }
@@ -137,17 +140,14 @@ ssize_t write_to_terminal(struct terminal_session *session, const char *data, si
return bytes_written; return bytes_written;
} }
int resize_terminal(struct terminal_session *session, uint16_t rows, uint16_t cols) { int resize_terminal(struct terminal_session *session, uint16_t rows,
uint16_t cols) {
if (!session || !session->active) { if (!session || !session->active) {
return -1; return -1;
} }
struct winsize ws = { struct winsize ws = {
.ws_row = rows, .ws_row = rows, .ws_col = cols, .ws_xpixel = 0, .ws_ypixel = 0};
.ws_col = cols,
.ws_xpixel = 0,
.ws_ypixel = 0
};
if (ioctl(session->master_pty, TIOCSWINSZ, &ws) == -1) { if (ioctl(session->master_pty, TIOCSWINSZ, &ws) == -1) {
perror("ioctl TIOCSWINSZ failed"); perror("ioctl TIOCSWINSZ failed");
+10 -6
View File
@@ -1,10 +1,10 @@
#ifndef TERMINAL_H #ifndef TERMINAL_H
#define TERMINAL_H #define TERMINAL_H
#include <signal.h>
#include <stdbool.h>
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include <stdbool.h>
#include <signal.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include <sys/types.h> #include <sys/types.h>
@@ -16,10 +16,14 @@ struct terminal_session {
}; };
// Функции для работы с терминалом // Функции для работы с терминалом
int create_terminal_session(struct terminal_session *session, const char *shell); int create_terminal_session(struct terminal_session *session,
const char *shell);
void destroy_terminal_session(struct terminal_session *session); void destroy_terminal_session(struct terminal_session *session);
ssize_t read_from_terminal(struct terminal_session *session, char *buffer, size_t size); ssize_t read_from_terminal(struct terminal_session *session, char *buffer,
ssize_t write_to_terminal(struct terminal_session *session, const char *data, size_t size); size_t size);
int resize_terminal(struct terminal_session *session, uint16_t rows, uint16_t cols); ssize_t write_to_terminal(struct terminal_session *session, const char *data,
size_t size);
int resize_terminal(struct terminal_session *session, uint16_t rows,
uint16_t cols);
#endif #endif
+49 -30
View File
@@ -1,8 +1,8 @@
<!DOCTYPE html> <!doctype html>
<html> <html>
<head> <head>
<title>Web Terminal</title> <title>Web Terminal</title>
<link rel="stylesheet" href="xterm.css"> <link rel="stylesheet" href="xterm.css" />
<style> <style>
body { body {
margin: 0; margin: 0;
@@ -30,9 +30,15 @@
margin-bottom: 10px; margin-bottom: 10px;
} }
.connected { background-color: #2d5a2d; } .connected {
.disconnected { background-color: #5a2d2d; } background-color: #2d5a2d;
.connecting { background-color: #5a5a2d; } }
.disconnected {
background-color: #5a2d2d;
}
.connecting {
background-color: #5a5a2d;
}
</style> </style>
</head> </head>
<body> <body>
@@ -48,10 +54,10 @@
this.terminal = new Terminal({ this.terminal = new Terminal({
cursorBlink: true, cursorBlink: true,
theme: { theme: {
background: '#000000', background: "#000000",
foreground: '#ffffff', foreground: "#ffffff",
cursor: '#ffffff' cursor: "#ffffff",
} },
}); });
this.fitAddon = new FitAddon.FitAddon(); this.fitAddon = new FitAddon.FitAddon();
@@ -66,12 +72,13 @@
} }
init() { init() {
const terminalContainer = document.getElementById('terminal-container'); const terminalContainer =
document.getElementById("terminal-container");
this.terminal.open(terminalContainer); this.terminal.open(terminalContainer);
this.fitAddon.fit(); this.fitAddon.fit();
this.terminal.writeln('Welcome to Web Terminal'); this.terminal.writeln("Welcome to Web Terminal");
this.terminal.writeln('Connecting to server...'); this.terminal.writeln("Connecting to server...");
this.connect(); this.connect();
@@ -83,13 +90,13 @@
}); });
// Handle resize // Handle resize
window.addEventListener('resize', () => { window.addEventListener("resize", () => {
this.fitAddon.fit(); this.fitAddon.fit();
this.sendResize(); this.sendResize();
}); });
// Handle page unload // Handle page unload
window.addEventListener('beforeunload', () => { window.addEventListener("beforeunload", () => {
if (this.ws) { if (this.ws) {
this.ws.close(); this.ws.close();
} }
@@ -97,23 +104,24 @@
} }
connect() { connect() {
this.updateStatus('Connecting...', 'connecting'); this.updateStatus("Connecting...", "connecting");
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const protocol =
window.location.protocol === "https:" ? "wss:" : "ws:";
const wsUrl = `${protocol}//${window.location.host}/ws`; const wsUrl = `${protocol}//${window.location.host}/ws`;
this.ws = new WebSocket(wsUrl); this.ws = new WebSocket(wsUrl);
this.ws.onopen = () => { this.ws.onopen = () => {
console.log('WebSocket connected'); console.log("WebSocket connected");
this.reconnectAttempts = 0; this.reconnectAttempts = 0;
this.updateStatus('Connected', 'connected'); this.updateStatus("Connected", "connected");
this.terminal.clear(); this.terminal.clear();
this.sendResize(); this.sendResize();
}; };
this.ws.onmessage = (event) => { this.ws.onmessage = (event) => {
if (typeof event.data === 'string') { if (typeof event.data === "string") {
this.terminal.write(event.data); this.terminal.write(event.data);
} else { } else {
// Handle binary data // Handle binary data
@@ -127,25 +135,36 @@
}; };
this.ws.onclose = (event) => { this.ws.onclose = (event) => {
console.log('WebSocket disconnected:', event.code, event.reason); console.log(
this.updateStatus('Disconnected', 'disconnected'); "WebSocket disconnected:",
event.code,
event.reason,
);
this.updateStatus("Disconnected", "disconnected");
if (this.reconnectAttempts < this.maxReconnectAttempts) { if (
this.reconnectAttempts < this.maxReconnectAttempts
) {
this.reconnectAttempts++; this.reconnectAttempts++;
const delay = this.reconnectDelay * this.reconnectAttempts; const delay =
this.terminal.write(`\r\nConnection lost. Reconnecting in ${delay/1000}s...\r\n`); this.reconnectDelay * this.reconnectAttempts;
this.terminal.write(
`\r\nConnection lost. Reconnecting in ${delay / 1000}s...\r\n`,
);
setTimeout(() => { setTimeout(() => {
this.connect(); this.connect();
}, delay); }, delay);
} else { } else {
this.terminal.write('\r\nFailed to reconnect. Please refresh the page.\r\n'); this.terminal.write(
"\r\nFailed to reconnect. Please refresh the page.\r\n",
);
} }
}; };
this.ws.onerror = (error) => { this.ws.onerror = (error) => {
console.error('WebSocket error:', error); console.error("WebSocket error:", error);
this.updateStatus('Connection Error', 'disconnected'); this.updateStatus("Connection Error", "disconnected");
}; };
} }
@@ -154,21 +173,21 @@
const dimensions = this.terminal; const dimensions = this.terminal;
const resizeMsg = { const resizeMsg = {
cols: dimensions.cols, cols: dimensions.cols,
rows: dimensions.rows rows: dimensions.rows,
}; };
this.ws.send(JSON.stringify(resizeMsg)); this.ws.send(JSON.stringify(resizeMsg));
} }
} }
updateStatus(text, className) { updateStatus(text, className) {
const status = document.getElementById('status'); const status = document.getElementById("status");
status.textContent = text; status.textContent = text;
status.className = `status ${className}`; status.className = `status ${className}`;
} }
} }
// Initialize terminal when page loads // Initialize terminal when page loads
document.addEventListener('DOMContentLoaded', () => { document.addEventListener("DOMContentLoaded", () => {
new WebTerminal(); new WebTerminal();
}); });
</script> </script>
+72 -1
View File
@@ -1,2 +1,73 @@
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.FitAddon=t():e.FitAddon=t()}(self,(()=>(()=>{"use strict";var e={};return(()=>{var t=e;Object.defineProperty(t,"__esModule",{value:!0}),t.FitAddon=void 0,t.FitAddon=class{activate(e){this._terminal=e}dispose(){}fit(){const e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;const t=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal)return;if(!this._terminal.element||!this._terminal.element.parentElement)return;const e=this._terminal._core,t=e._renderService.dimensions;if(0===t.css.cell.width||0===t.css.cell.height)return;const r=0===this._terminal.options.scrollback?0:e.viewport.scrollBarWidth,i=window.getComputedStyle(this._terminal.element.parentElement),o=parseInt(i.getPropertyValue("height")),s=Math.max(0,parseInt(i.getPropertyValue("width"))),n=window.getComputedStyle(this._terminal.element),l=o-(parseInt(n.getPropertyValue("padding-top"))+parseInt(n.getPropertyValue("padding-bottom"))),a=s-(parseInt(n.getPropertyValue("padding-right"))+parseInt(n.getPropertyValue("padding-left")))-r;return{cols:Math.max(2,Math.floor(a/t.css.cell.width)),rows:Math.max(1,Math.floor(l/t.css.cell.height))}}}})(),e})())); !(function (e, t) {
"object" == typeof exports && "object" == typeof module
? (module.exports = t())
: "function" == typeof define && define.amd
? define([], t)
: "object" == typeof exports
? (exports.FitAddon = t())
: (e.FitAddon = t());
})(self, () =>
(() => {
"use strict";
var e = {};
return (
(() => {
var t = e;
(Object.defineProperty(t, "__esModule", { value: !0 }),
(t.FitAddon = void 0),
(t.FitAddon = class {
activate(e) {
this._terminal = e;
}
dispose() {}
fit() {
const e = this.proposeDimensions();
if (!e || !this._terminal || isNaN(e.cols) || isNaN(e.rows))
return;
const t = this._terminal._core;
(this._terminal.rows === e.rows &&
this._terminal.cols === e.cols) ||
(t._renderService.clear(),
this._terminal.resize(e.cols, e.rows));
}
proposeDimensions() {
if (!this._terminal) return;
if (
!this._terminal.element ||
!this._terminal.element.parentElement
)
return;
const e = this._terminal._core,
t = e._renderService.dimensions;
if (0 === t.css.cell.width || 0 === t.css.cell.height) return;
const r =
0 === this._terminal.options.scrollback
? 0
: e.viewport.scrollBarWidth,
i = window.getComputedStyle(
this._terminal.element.parentElement,
),
o = parseInt(i.getPropertyValue("height")),
s = Math.max(0, parseInt(i.getPropertyValue("width"))),
n = window.getComputedStyle(this._terminal.element),
l =
o -
(parseInt(n.getPropertyValue("padding-top")) +
parseInt(n.getPropertyValue("padding-bottom"))),
a =
s -
(parseInt(n.getPropertyValue("padding-right")) +
parseInt(n.getPropertyValue("padding-left"))) -
r;
return {
cols: Math.max(2, Math.floor(a / t.css.cell.width)),
rows: Math.max(1, Math.floor(l / t.css.cell.height)),
};
}
}));
})(),
e
);
})(),
);
//# sourceMappingURL=xterm-addon-fit.js.map //# sourceMappingURL=xterm-addon-fit.js.map
+34 -12
View File
@@ -79,7 +79,7 @@
.xterm .composition-view { .xterm .composition-view {
/* TODO: Composition position got messed up somewhere */ /* TODO: Composition position got messed up somewhere */
background: #000; background: #000;
color: #FFF; color: #fff;
display: none; display: none;
position: absolute; position: absolute;
white-space: nowrap; white-space: nowrap;
@@ -166,21 +166,41 @@
opacity: 1 !important; opacity: 1 !important;
} }
.xterm-underline-1 { text-decoration: underline; } .xterm-underline-1 {
.xterm-underline-2 { text-decoration: double underline; } text-decoration: underline;
.xterm-underline-3 { text-decoration: wavy underline; } }
.xterm-underline-4 { text-decoration: dotted underline; } .xterm-underline-2 {
.xterm-underline-5 { text-decoration: dashed underline; } text-decoration: double underline;
}
.xterm-underline-3 {
text-decoration: wavy underline;
}
.xterm-underline-4 {
text-decoration: dotted underline;
}
.xterm-underline-5 {
text-decoration: dashed underline;
}
.xterm-overline { .xterm-overline {
text-decoration: overline; text-decoration: overline;
} }
.xterm-overline.xterm-underline-1 { text-decoration: overline underline; } .xterm-overline.xterm-underline-1 {
.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; } text-decoration: overline underline;
.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; } }
.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; } .xterm-overline.xterm-underline-2 {
.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; } text-decoration: overline double underline;
}
.xterm-overline.xterm-underline-3 {
text-decoration: overline wavy underline;
}
.xterm-overline.xterm-underline-4 {
text-decoration: overline dotted underline;
}
.xterm-overline.xterm-underline-5 {
text-decoration: overline dashed underline;
}
.xterm-strikethrough { .xterm-strikethrough {
text-decoration: line-through; text-decoration: line-through;
@@ -191,7 +211,9 @@
position: absolute; position: absolute;
} }
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { .xterm-screen
.xterm-decoration-container
.xterm-decoration.xterm-decoration-top-layer {
z-index: 7; z-index: 7;
} }
+14697 -1
View File
File diff suppressed because it is too large. Load diff