first commit

This commit is contained in:
pvvx 2017-04-22 16:54:00 +03:00
commit fa343db334
154 changed files with 18186 additions and 0 deletions

196
project/inc/web/web_srv.h Normal file
View file

@ -0,0 +1,196 @@
/*
* File: web_srv.h
* Description: The web server configration.
* Small WEB server ESP8266EX
* Author: PV`
*/
#ifndef _INCLUDE_WEB_SRV_H_
#define _INCLUDE_WEB_SRV_H_
#include "tcpsrv/tcp_srv_conn.h"
#ifdef WEBSOCKET_ENA
#include "websock.h"
#endif
#define WEB_SVERSION "0.2.0"
#define DEFAULT_WEB_PORT USE_WEB // 80
/****************************************************************************
Section:
Commands and Server Responses
***************************************************************************/
// File type definitions
typedef enum
{
HTTP_TXT = 0, // File is a text document
HTTP_HTML, // File is HTML (extension .htm)
HTTP_CGI, // File is HTML (extension .cgi)
HTTP_XML, // File is XML (extension .xml)
HTTP_CSS, // File is stylesheet (extension .css)
HTTP_ICO, // File is ICO vnd.microsoft.icon
HTTP_GIF, // File is GIF image (extension .gif)
HTTP_PNG, // File is PNG image (extension .png)
HTTP_JPG, // File is JPG image (extension .jpg)
HTTP_SVG, // File is SVG image (extension .svg)
HTTP_JAVA, // File is java (extension .js)
HTTP_SWF, // File is ShockWave-Flash (extension .swf)
HTTP_WAV, // File is audio (extension .wav)
HTTP_PDF, // File is PDF (extension .pdf)
HTTP_ZIP, // File is ZIP (extension .zip)
HTTP_BIN, // File is BIN (extension .bin)
HTTP_UNKNOWN // File type is unknown
} HTTP_FILE_TYPE;
// extended state data for each connection
#define FileNameSize 64
#define VarNameSize 64
#define CmdNameSize 32
typedef struct
{
uint16 httpStatus; // Request method/status
uint16 uri_len;
uint16 head_len;
uint16 cookie_len;
uint8 pFilename[FileNameSize];
uint8 *puri; // указатель на строку с переменными запроса к файлу
uint8 *phead; // HTTP Headers
uint8 *pcookie; // cookie
uint8 *pcontent; // content
uint32 content_len; //
uint8 httpver; // версия HTTP клиента в BCD (0x00 = неизвестен; 0x09 = HTTP/0.9; 0x10 = HTTP/1.0; 0x11 = HTTP/1.1)
uint8 fileType; // File type to return with Content-Type
} HTTP_CONN;
typedef void (* web_func_cb)(TCP_SERV_CONN *ts_conn);
typedef uint32 (* web_func_disc_cb)(uint32 flg); // отложенная функция, когда соединение закрыто
typedef struct
{
web_func_disc_cb fnk;
void * param;
} WEB_SRV_QFNK;
typedef struct
{
uint32 webflag; // флаги для http/web сервера
uint8 bffiles[4]; // четыре Files pointers для оработки вложенных файлов include
uint32 udata_start; // udata "start=0x..."
uint32 udata_stop; // udata "stop=0x..."
uint8 *msgbuf; // указатель на текущий буфер вывода
uint16 msgbuflen; // кол-во занятых байт в буфере msgbuf
uint16 msgbufsize; // размер буфера
web_func_cb func_web_cb; // calback функция у httpd для обработки приема/передачи кусками
uint32 content_len; // размер файла для передачи (GET/POST) или приема, если принимается внешний файл (POST + SCB_RXDATA)
web_func_disc_cb web_disc_cb; // функция вызываемая по закрытию соединения
uint32 web_disc_par; // параметры функции вызываемой по закрытию соединения
#ifdef WEBSOCKET_ENA
WS_FRSTAT ws; // параметры websoc
#endif
uint8 fileType; // File type to return with Content-Type (if SCB_FCALBACK)
} WEB_SRV_CONN;
typedef enum
{
WEBFS_MAX_HANDLE = 251,
WEBFS_NODISK_HANDLE,
WEBFS_WEBCGI_HANDLE,
WEBFS_UPLOAD_HANDLE
} WEBFS_NUM_HANDLE;
// webflag:
#define SCB_CLOSED 0x000001 // соединение закрыто
#define SCB_DISCONNECT 0x000002 // выход на DISCONNECT
#define SCB_FCLOSE 0x000004 // закрыть файлы
#define SCB_FOPEN 0x000008 // файл(ы) открыт(ы)
#define SCB_FCALBACK 0x000010 // file use ~calback~
#define SCB_FGZIP 0x000020 // файл GZIP
#define SCB_CHUNKED 0x000040 // передача шинковкой
#define SCB_RETRYCB 0x000080 // вызвать повтор CalBack
#define SCB_POST 0x000100 // POST
#define SCB_GET 0x000200 // GET
#define SCB_AUTH 0x000400 // необходима авторизация
#define SCB_FINDCB 0x000800 // используется парсингом ~calback~
#define SCB_RXDATA 0x001000 // прием данных (файла)
#define SCB_HEAD_OK 0x002000 // заголовок HTTP принят и обработан
#define SCB_BNDR 0x004000 // прилеплен Content-Type: multipart/form-data; boundary="..."
#define SCB_REDIR 0x008000 // Redirect 302
#define SCB_WEBSOC 0x010000 // WebSocket
#define SCB_WSDATA 0x020000 // WebSocket data
#define SCB_SYSSAVE 0x040000 // по закрытию соединения вызвать sys_write_cfg()
#define SCB_OPEN 0
#define SetSCB(a) web_conn->webflag |= a
#define FreeSCB() web_conn->webflag = SCB_FREE
#define SetNextFunSCB(a) web_conn->func_web_cb = a
#define ClrSCB(a) web_conn->webflag &= ~(a)
#define CheckSCB(a) (web_conn->webflag & (a))
#define FreeSCB() web_conn->webflag = SCB_FREE
#define OpenSCB() web_conn->webflag = SCB_OPEN
#define MAXLENBOUNDARY 64
typedef struct s_http_upload
{
uint16 status;
uint16 sizeboundary;
uint8 boundary[MAXLENBOUNDARY+1];
uint8 name[VarNameSize];
uint8 filename[VarNameSize];
#ifdef USE_OVERLAY
uint32 segs; // кол-во сегментов оверлея // пока в web_conn->web_disc_par
uint32 start; // адрес запуска оверлея
#endif
uint32 fsize;
uint32 faddr;
uint8 *pbndr;
uint8 *pnext;
} HTTP_UPLOAD;
typedef struct s_http_response
{
uint32 status;
uint32 flag;
const char * headers;
const char * default_content;
} HTTP_RESPONSE;
// HTTP_RESPONSE.flags:
#define HTTP_RESP_FLG_END 0x8000
#define HTTP_RESP_FLG_NONE 0x0000
#define HTTP_RESP_FLG_FINDFILE 0x0001
#define HTTP_RESP_FLG_REDIRECT 0x0002
#define tcp_put(a) web_conn->msgbuf[web_conn->msgbuflen++] = a
#define tcp_htmlstrcpy(str, len) web_conn->msgbuflen += htmlcode(&web_conn->msgbuf[web_conn->msgbuflen], str, web_conn->msgbufsize - web_conn->msgbuflen - 1, len)
//#define tcp_urlstrcpy(str, len) web_conn->msgbuflen += urlencode(&web_conn->msgbuf[web_conn->msgbuflen], str, web_conn->msgbufsize - web_conn->msgbuflen - 1, len)
#define tcp_puts(...) web_conn->msgbuflen += rtl_sprintf((char *)&web_conn->msgbuf[web_conn->msgbuflen], __VA_ARGS__)
#define tcp_puts_fd(...) web_conn->msgbuflen += rtl_sprintf((char *)&web_conn->msgbuf[web_conn->msgbuflen], __VA_ARGS__)
/*
#define tcp_puts_fd(fmt, ...) do { \
static const char flash_str[] ICACHE_RODATA_ATTR = fmt; \
web_conn->msgbuflen += rtl_sprintf((char *)&web_conn->msgbuf[web_conn->msgbuflen], (char *)flash_str, ##__VA_ARGS__); \
} while(0)
*/
//#define tcp_strcpy(a) web_conn->msgbuflen += ets_strlen((char *)ets_strcpy((char *)&web_conn->msgbuf[web_conn->msgbuflen], (char *)a))
#define tcp_strcpy(a) web_conn->msgbuflen += rom_xstrcpy((char *)&web_conn->msgbuf[web_conn->msgbuflen], (const char *)a)
#define tcp_strcpy_fd(a) web_conn->msgbuflen += rom_xstrcpy((char *)&web_conn->msgbuf[web_conn->msgbuflen], (const char *)a)
/*
#define tcp_strcpy_fd(fmt) do { \
static const char flash_str[] ICACHE_RODATA_ATTR = fmt; \
web_conn->msgbuflen += rom_xstrcpy((char *)&web_conn->msgbuf[web_conn->msgbuflen], (char *)flash_str); \
} while(0)
*/
uint32 ahextoul(uint8 *s);
err_t webserver_init(uint16 portn);
err_t webserver_close(uint16 portn);
err_t webserver_reinit(uint16 portn);
#endif /* _INCLUDE_WEB_SRV_H_ */

View file

@ -0,0 +1,49 @@
/*
* File: web_srv_int.h
* Description: The web server configration.
* Small WEB server ESP8266EX
*
* Author: PV` 12/2014
*/
#ifndef _INCLUDE_WEB_SRV_INT_H_
#define _INCLUDE_WEB_SRV_INT_H_
#include "web_srv.h"
#define WEB_NAME_VERSION "PVs/0.2"
// #define WEBSOCKET_ENA 1
// lifetime (sec) of static responses as string 60*60*24*14=1209600"
#define FILE_CACHE_MAX_AGE_SEC 3600 // время для кеша файлов, ставить 0 пока тест!
#define MAX_HTTP_HEAD_BUF 3070 // максимальный размер HTTP запроса (GET)
#define RESCHKS_SEND_SIZE 16
#define RESCHKE_SEND_SIZE 8
#define RESCHK_SEND_SIZE (RESCHKS_SEND_SIZE + RESCHKE_SEND_SIZE)
#define MIN_SEND_SIZE (256 + RESCHK_SEND_SIZE) // минимальный размер буфера для передачи файла
#define MAX_SEND_SIZE ((TCP_MSS*4) + RESCHK_SEND_SIZE) // максимальный размер буфера для передачи 4*MSS = 5840 (MSS=1460)
#define HTTP_SEND_SIZE 384 // минимальный размер буфера для передачи заголовка HTTP
#define SCB_SEND_SIZE 128 // минимальный резерв в буфере для callback
#define webfile bffiles[0] // File pointer for main file
//-----------------------------------------------------------------------------
void web_int_vars(TCP_SERV_CONN *ts_conn, uint8 *pcmd, uint8 *pvar);
void web_int_cookie(HTTP_CONN *CurHTTP, TCP_SERV_CONN *ts_conn);
void web_int_callback(TCP_SERV_CONN *ts_conn, uint8 *cstr);
void web_hexdump(TCP_SERV_CONN *ts_conn);
bool web_inc_fopen(TCP_SERV_CONN *ts_conn, uint8 *cFile);
bool web_inc_fclose(WEB_SRV_CONN *web_conn);
bool web_trim_bufi(TCP_SERV_CONN *ts_conn, uint8 *pdata, uint32 data_len);
bool web_feee_bufi(TCP_SERV_CONN *ts_conn);
//uint8 * head_find_ctr(HTTP_CONN *CurHTTP, const uint8 * c, int clen, int dlen);
#endif /* _INCLUDE_WEB_SRV_INT_H_ */

View file

@ -0,0 +1,33 @@
/******************************************************************************
* FileName: web_utils.h
* Alternate SDK
* Author: PV`
* (c) PV` 2015
*******************************************************************************/
#ifndef _INCLUDE_WEB_UTILS_H_
#define _INCLUDE_WEB_UTILS_H_
int rom_atoi(const char *s);
void copy_align4(void *ptrd, void *ptrs, uint32 len);
uint32 hextoul(uint8 *s);
uint32 ahextoul(uint8 *s);
uint8 * cmpcpystr(uint8 *pbuf, uint8 *pstr, uint8 a, uint8 b, uint16 len);
uint8 * web_strnstr(const uint8* buffer, const uint8* token, int n);
bool base64decode(const uint8 *in, int len, uint8_t *out, int *outlen);
size_t base64encode(char* target, size_t target_len, const char* source, size_t source_len);
void strtomac(uint8 *s, uint8 *macaddr);
//uint32 strtoip(uint8 *s); // ipaddr_addr();
int urldecode(uint8 *d, uint8 *s, uint16 lend, uint16 lens);
//int urlencode(uint8 *d, uint8 *s, uint16 lend, uint16 lens);
int htmlcode(uint8 *d, uint8 *s, uint16 lend, uint16 lens);
void print_hex_dump(uint8 *buf, uint32 len, uint8 k);
// char* str_to_upper_case(char* text);
uint32 str_array(uint8 *s, uint32 *buf, uint32 max_buf);
uint32 str_array_w(uint8 *s, uint16 *buf, uint32 max_buf);
uint32 str_array_b(uint8 *s, uint8 *buf, uint32 max_buf);
char* word_to_lower_case(char* text);
int rom_xstrcmp(char * pd, const char * ps);
int rom_xstrcpy(char * pd, const char * ps);
#endif /* _INCLUDE_WEB_UTILS_H_ */

View file

@ -0,0 +1,17 @@
#ifndef _WEB_WEBSOCKET_H_
/******************************************************************************
* FileName: web_websocket.h
* Description: websocket for web ESP8266
* Author: PV`
* (c) PV` 2016
*******************************************************************************/
#define _WEB_WEBSOCKET_H_
#include "user_config.h"
#ifdef WEBSOCKET_ENA
#include "websock.h"
err_t websock_tx_close_err(TCP_SERV_CONN *ts_conn, uint32 err);
bool websock_rx_data(TCP_SERV_CONN *ts_conn);
#endif // WEBSOCKET_ENA
#endif /* _WEB_WEBSOCKET_H_ */

108
project/inc/web/websock.h Normal file
View file

@ -0,0 +1,108 @@
/*
* File: websock.h
* Small WEB server ESP8266EX
* Author: PV`
*/
#ifndef _WEBSOCK_H_
#define _WEBSOCK_H_
//#define WS_NONBLOCK 0x02
/*
0 1 2 3
7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| опкод |М| Длина тела | Расширенная длина тела |
|I|S|S|S|(4бита)|А| (7бит) | (2 байта) |
|N|V|V|V| |С| |(если длина тела==126 или 127) |
| |1|2|3| |К| | |
| | | | | |А| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
|4 5 6 7 |
| Продолжение расширенной длины тела, если длина тела = 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
|8 9 10 11 |
| | Ключ маски, если МАСКА = 1 |
+-------------------------------+-------------------------------+
|12 13 14 15 |
| Ключ маски (продолжение) | Данные фрейма ("тело") |
+-------------------------------- - - - - - - - - - - - - - - - +
|16 17 18 19 |
: Данные продолжаются ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Данные продолжаются ... |
+---------------------------------------------------------------+
*/
#define WS_FRAGMENT_FIN 0x80
//#define WS_RSVD_BITS (7 << 4)
#define WS_OPCODE_BITS 0x7F
#define WS_OPCODE_CONTINUE 0x0 // фрейм-продолжение для фрагментированного сообщения
#define WS_OPCODE_TEXT 0x1 // текстовый фрейм
#define WS_OPCODE_BINARY 0x2 // двоичный фрейм
#define WS_OPCODE_CLOSE 0x8 // закрытие соединения
#define WS_OPCODE_PING 0x9
#define WS_OPCODE_PONG 0xa
#define WS_MASK_FLG (1 << 7)
#define WS_SIZE1_BITS 0x7F
#define WS_CLOSE_NORMAL 1000
#define WS_CLOSE_GOING_AWAY 1001
#define WS_CLOSE_PROTOCOL_ERROR 1002
#define WS_CLOSE_NOT_ALLOWED 1003
#define WS_CLOSE_RESERVED 1004
#define WS_CLOSE_NO_CODE 1005
#define WS_CLOSE_DIRTY 1006
#define WS_CLOSE_WRONG_TYPE 1007
#define WS_CLOSE_POLICY_VIOLATION 1008
#define WS_CLOSE_MESSAGE_TOO_BIG 1009
#define WS_CLOSE_UNEXPECTED_ERROR 1011
typedef struct _WS_FRSTAT
{
uint32 frame_len; // размер данных в заголовке фрейма
uint32 cur_len; // счетчик обработанных данных
union {
unsigned char uc[4];
unsigned int ud;
} mask; // маска принимаемых данных
uint8 status;
uint8 flg;
uint8 head_len;
} WS_FRSTAT; // __attribute__((packed))
#define WS_FLG_MASK 0x01
#define WS_FLG_FIN 0x02
#define WS_FLG_CLOSE 0x04 // уже передано WS_CLOSE
enum WS_FRAME_STATE {
sw_frs_none = 0,
sw_frs_text,
sw_frs_binary,
sw_frs_close,
sw_frs_ping,
sw_frs_pong
};
extern const uint8 WebSocketHTTPOkKey[]; // ICACHE_RODATA_ATTR = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept:%s\r\n\r\n"
extern const uint8 WebSocketAddKey[]; // ICACHE_RODATA_ATTR = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
#define sizeWebSocketAddKey 36
#define maxsizeWebSocketKey 64
#define minsizeWebSocketKey 8
extern const uint8 *HTTPUpgrade; // = "Upgrade:";
#define sizeHTTPUpgrade 8
extern const uint8 *HTTPwebsocket; // = "websocket";
#define sizeHTTPwebsocket 9
extern const uint8 *HTTPSecWebSocketKey; // = "Sec-WebSocket-Key:";
#define sizeHTTPSecWebSocketKey 18
bool WebSocketAcceptKey(uint8* dkey, uint8* skey);
void WebsocketMask(WS_FRSTAT *ws, uint8 *raw_data, uint32 raw_len);
uint32 WebsocketHead(WS_FRSTAT *ws, uint8 *raw_data, uint32 raw_len);
err_t WebsocketTxFrame(TCP_SERV_CONN *ts_conn, uint32 opcode, uint8 *raw_data, uint32 raw_len);
#endif /* _WEBSOCK_H_ */