diff --git a/cores/esp32/HardwareSerial.cpp b/cores/esp32/HardwareSerial.cpp index 920e4abd..1871a4b5 100644 --- a/cores/esp32/HardwareSerial.cpp +++ b/cores/esp32/HardwareSerial.cpp @@ -3,8 +3,25 @@ #include #include +#include "pins_arduino.h" #include "HardwareSerial.h" +#ifndef RX1 +#define RX1 9 +#endif + +#ifndef TX1 +#define TX1 10 +#endif + +#ifndef RX2 +#define RX2 16 +#endif + +#ifndef TX2 +#define TX2 17 +#endif + #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL) HardwareSerial Serial(0); HardwareSerial Serial1(1); @@ -27,12 +44,12 @@ void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, in txPin = 1; } if(_uart_nr == 1 && rxPin < 0 && txPin < 0) { - rxPin = 9; - txPin = 10; + rxPin = RX1; + txPin = TX1; } if(_uart_nr == 2 && rxPin < 0 && txPin < 0) { - rxPin = 16; - txPin = 17; + rxPin = RX2; + txPin = TX2; } _uart = uartBegin(_uart_nr, baud, config, rxPin, txPin, 256, invert); } diff --git a/cores/esp32/apps/sntp/sntp.h b/cores/esp32/apps/sntp/sntp.h new file mode 100644 index 00000000..8a940f88 --- /dev/null +++ b/cores/esp32/apps/sntp/sntp.h @@ -0,0 +1 @@ +#include "lwip/apps/sntp.h" diff --git a/cores/esp32/esp32-hal-log.h b/cores/esp32/esp32-hal-log.h index 126ebf69..e1d4e56f 100644 --- a/cores/esp32/esp32-hal-log.h +++ b/cores/esp32/esp32-hal-log.h @@ -79,38 +79,50 @@ int log_printf(const char *fmt, ...); #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE #define log_v(format, ...) log_printf(ARDUHAL_LOG_FORMAT(V, format), ##__VA_ARGS__) +#define isr_log_v(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(V, format), ##__VA_ARGS__) #else #define log_v(format, ...) +#define isr_log_v(format, ...) #endif #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG #define log_d(format, ...) log_printf(ARDUHAL_LOG_FORMAT(D, format), ##__VA_ARGS__) +#define isr_log_d(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(D, format), ##__VA_ARGS__) #else #define log_d(format, ...) +#define isr_log_d(format, ...) #endif #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO #define log_i(format, ...) log_printf(ARDUHAL_LOG_FORMAT(I, format), ##__VA_ARGS__) +#define isr_log_i(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(I, format), ##__VA_ARGS__) #else #define log_i(format, ...) +#define isr_log_i(format, ...) #endif #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_WARN #define log_w(format, ...) log_printf(ARDUHAL_LOG_FORMAT(W, format), ##__VA_ARGS__) +#define isr_log_w(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(W, format), ##__VA_ARGS__) #else #define log_w(format, ...) +#define isr_log_w(format, ...) #endif #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_ERROR #define log_e(format, ...) log_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__) +#define isr_log_e(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__) #else #define log_e(format, ...) +#define isr_log_e(format, ...) #endif #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_NONE #define log_n(format, ...) log_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__) +#define isr_log_n(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__) #else #define log_n(format, ...) +#define isr_log_n(format, ...) #endif #include "esp_log.h" @@ -121,12 +133,22 @@ int log_printf(const char *fmt, ...); #undef ESP_LOGI #undef ESP_LOGD #undef ESP_LOGV +#undef ESP_EARLY_LOGE +#undef ESP_EARLY_LOGW +#undef ESP_EARLY_LOGI +#undef ESP_EARLY_LOGD +#undef ESP_EARLY_LOGV #define ESP_LOGE(tag, ...) log_e(__VA_ARGS__) #define ESP_LOGW(tag, ...) log_w(__VA_ARGS__) #define ESP_LOGI(tag, ...) log_i(__VA_ARGS__) #define ESP_LOGD(tag, ...) log_d(__VA_ARGS__) #define ESP_LOGV(tag, ...) log_v(__VA_ARGS__) +#define ESP_EARLY_LOGE(tag, ...) isr_log_e(__VA_ARGS__) +#define ESP_EARLY_LOGW(tag, ...) isr_log_w(__VA_ARGS__) +#define ESP_EARLY_LOGI(tag, ...) isr_log_i(__VA_ARGS__) +#define ESP_EARLY_LOGD(tag, ...) isr_log_d(__VA_ARGS__) +#define ESP_EARLY_LOGV(tag, ...) isr_log_v(__VA_ARGS__) #endif #ifdef __cplusplus diff --git a/cores/esp32/esp32-hal-time.c b/cores/esp32/esp32-hal-time.c index 176ac65c..1d171f27 100644 --- a/cores/esp32/esp32-hal-time.c +++ b/cores/esp32/esp32-hal-time.c @@ -13,7 +13,7 @@ // limitations under the License. #include "esp32-hal.h" -#include "apps/sntp/sntp.h" +#include "lwip/apps/sntp.h" static void setTimeZone(long offset, int daylight) { diff --git a/libraries/AsyncUDP/src/AsyncUDP.cpp b/libraries/AsyncUDP/src/AsyncUDP.cpp index 6fff201a..fcbc55f8 100644 --- a/libraries/AsyncUDP/src/AsyncUDP.cpp +++ b/libraries/AsyncUDP/src/AsyncUDP.cpp @@ -8,6 +8,7 @@ extern "C" { #include "lwip/igmp.h" #include "lwip/ip_addr.h" #include "lwip/mld6.h" +#include "lwip/prot/ethernet.h" #include #include } @@ -15,7 +16,7 @@ extern "C" { #include "lwip/priv/tcpip_priv.h" typedef struct { - struct tcpip_api_call call; + struct tcpip_api_call_data call; udp_pcb * pcb; const ip_addr_t *addr; uint16_t port; @@ -24,7 +25,7 @@ typedef struct { err_t err; } udp_api_call_t; -static err_t _udp_connect_api(struct tcpip_api_call *api_call_msg){ +static err_t _udp_connect_api(struct tcpip_api_call_data *api_call_msg){ udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; msg->err = udp_connect(msg->pcb, msg->addr, msg->port); return msg->err; @@ -35,11 +36,11 @@ static err_t _udp_connect(struct udp_pcb *pcb, const ip_addr_t *addr, u16_t port msg.pcb = pcb; msg.addr = addr; msg.port = port; - tcpip_api_call(_udp_connect_api, (struct tcpip_api_call*)&msg); + tcpip_api_call(_udp_connect_api, (struct tcpip_api_call_data*)&msg); return msg.err; } -static err_t _udp_disconnect_api(struct tcpip_api_call *api_call_msg){ +static err_t _udp_disconnect_api(struct tcpip_api_call_data *api_call_msg){ udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; msg->err = 0; udp_disconnect(msg->pcb); @@ -49,10 +50,10 @@ static err_t _udp_disconnect_api(struct tcpip_api_call *api_call_msg){ static void _udp_disconnect(struct udp_pcb *pcb){ udp_api_call_t msg; msg.pcb = pcb; - tcpip_api_call(_udp_disconnect_api, (struct tcpip_api_call*)&msg); + tcpip_api_call(_udp_disconnect_api, (struct tcpip_api_call_data*)&msg); } -static err_t _udp_remove_api(struct tcpip_api_call *api_call_msg){ +static err_t _udp_remove_api(struct tcpip_api_call_data *api_call_msg){ udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; msg->err = 0; udp_remove(msg->pcb); @@ -62,10 +63,10 @@ static err_t _udp_remove_api(struct tcpip_api_call *api_call_msg){ static void _udp_remove(struct udp_pcb *pcb){ udp_api_call_t msg; msg.pcb = pcb; - tcpip_api_call(_udp_remove_api, (struct tcpip_api_call*)&msg); + tcpip_api_call(_udp_remove_api, (struct tcpip_api_call_data*)&msg); } -static err_t _udp_bind_api(struct tcpip_api_call *api_call_msg){ +static err_t _udp_bind_api(struct tcpip_api_call_data *api_call_msg){ udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; msg->err = udp_bind(msg->pcb, msg->addr, msg->port); return msg->err; @@ -76,11 +77,11 @@ static err_t _udp_bind(struct udp_pcb *pcb, const ip_addr_t *addr, u16_t port){ msg.pcb = pcb; msg.addr = addr; msg.port = port; - tcpip_api_call(_udp_bind_api, (struct tcpip_api_call*)&msg); + tcpip_api_call(_udp_bind_api, (struct tcpip_api_call_data*)&msg); return msg.err; } -static err_t _udp_sendto_api(struct tcpip_api_call *api_call_msg){ +static err_t _udp_sendto_api(struct tcpip_api_call_data *api_call_msg){ udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; msg->err = udp_sendto(msg->pcb, msg->pb, msg->addr, msg->port); return msg->err; @@ -92,11 +93,11 @@ static err_t _udp_sendto(struct udp_pcb *pcb, struct pbuf *pb, const ip_addr_t * msg.addr = addr; msg.port = port; msg.pb = pb; - tcpip_api_call(_udp_sendto_api, (struct tcpip_api_call*)&msg); + tcpip_api_call(_udp_sendto_api, (struct tcpip_api_call_data*)&msg); return msg.err; } -static err_t _udp_sendto_if_api(struct tcpip_api_call *api_call_msg){ +static err_t _udp_sendto_if_api(struct tcpip_api_call_data *api_call_msg){ udp_api_call_t * msg = (udp_api_call_t *)api_call_msg; msg->err = udp_sendto_if(msg->pcb, msg->pb, msg->addr, msg->port, msg->netif); return msg->err; @@ -109,7 +110,7 @@ static err_t _udp_sendto_if(struct udp_pcb *pcb, struct pbuf *pb, const ip_addr_ msg.port = port; msg.pb = pb; msg.netif = netif; - tcpip_api_call(_udp_sendto_if_api, (struct tcpip_api_call*)&msg); + tcpip_api_call(_udp_sendto_if_api, (struct tcpip_api_call_data*)&msg); return msg.err; } @@ -292,19 +293,23 @@ AsyncUDPPacket::AsyncUDPPacket(AsyncUDP *udp, pbuf *pb, const ip_addr_t *raddr, _remoteIp.type = raddr->type; _localIp.type = _remoteIp.type; + eth_hdr* eth = NULL; udp_hdr* udphdr = reinterpret_cast(_data - UDP_HLEN); _localPort = ntohs(udphdr->dest); _remotePort = ntohs(udphdr->src); - + if (_remoteIp.type == IPADDR_TYPE_V4) { + eth = (eth_hdr *)(((uint8_t *)(pb->payload)) - UDP_HLEN - IP_HLEN - SIZEOF_ETH_HDR); struct ip_hdr * iphdr = (struct ip_hdr *)(((uint8_t *)(pb->payload)) - UDP_HLEN - IP_HLEN); _localIp.u_addr.ip4.addr = iphdr->dest.addr; _remoteIp.u_addr.ip4.addr = iphdr->src.addr; } else { + eth = (eth_hdr *)(((uint8_t *)(pb->payload)) - UDP_HLEN - IP6_HLEN - SIZEOF_ETH_HDR); struct ip6_hdr * ip6hdr = (struct ip6_hdr *)(((uint8_t *)(pb->payload)) - UDP_HLEN - IP6_HLEN); memcpy(&_localIp.u_addr.ip6.addr, (uint8_t *)ip6hdr->dest.addr, 16); memcpy(&_remoteIp.u_addr.ip6.addr, (uint8_t *)ip6hdr->src.addr, 16); } + memcpy(_remoteMac, eth->src.addr, 6); struct netif * netif = NULL; void * nif = NULL; @@ -415,6 +420,11 @@ uint16_t AsyncUDPPacket::remotePort() return _remotePort; } +void AsyncUDPPacket::remoteMac(uint8_t * mac) +{ + memcpy(mac, _remoteMac, 6); +} + bool AsyncUDPPacket::isIPv6() { return _localIp.type == IPADDR_TYPE_V6; @@ -452,16 +462,24 @@ size_t AsyncUDPPacket::send(AsyncUDPMessage &message) return write(message.data(), message.length()); } -AsyncUDP::AsyncUDP() -{ +bool AsyncUDP::_init(){ + if(_pcb){ + return true; + } _pcb = udp_new(); - _connected = false; - _handler = NULL; if(!_pcb){ - return; + return false; } //_lock = xSemaphoreCreateMutex(); udp_recv(_pcb, &_udp_recv, (void *) this); + return true; +} + +AsyncUDP::AsyncUDP() +{ + _pcb = NULL; + _connected = false; + _handler = NULL; } AsyncUDP::~AsyncUDP() @@ -483,8 +501,7 @@ void AsyncUDP::close() _udp_disconnect(_pcb); } _connected = false; - _pcb->multicast_ip.type = IPADDR_TYPE_V4; - _pcb->multicast_ip.u_addr.ip4.addr = 0; + //todo: unjoin multicast group } UDP_MUTEX_UNLOCK(); } @@ -495,7 +512,7 @@ bool AsyncUDP::connect(const ip_addr_t *addr, uint16_t port) log_e("failed to start task"); return false; } - if(_pcb == NULL) { + if(!_init()) { return false; } close(); @@ -516,7 +533,7 @@ bool AsyncUDP::listen(const ip_addr_t *addr, uint16_t port) log_e("failed to start task"); return false; } - if(_pcb == NULL) { + if(!_init()) { return false; } close(); @@ -534,57 +551,53 @@ bool AsyncUDP::listen(const ip_addr_t *addr, uint16_t port) return true; } +static esp_err_t joinMulticastGroup(const ip_addr_t *addr, bool join, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX) +{ + struct netif * netif = NULL; + if(tcpip_if < TCPIP_ADAPTER_IF_MAX){ + void * nif = NULL; + esp_err_t err = tcpip_adapter_get_netif(tcpip_if, &nif); + if (err) { + return ESP_ERR_INVALID_ARG; + } + netif = (struct netif *)nif; + } + + if (addr->type == IPADDR_TYPE_V4) { + if(join){ + if (igmp_joingroup_netif(netif, (const ip4_addr *)&(addr->u_addr.ip4))) { + return ESP_ERR_INVALID_STATE; + } + } else { + if (igmp_leavegroup_netif(netif, (const ip4_addr *)&(addr->u_addr.ip4))) { + return ESP_ERR_INVALID_STATE; + } + } + } else { + if(join){ + if (mld6_joingroup_netif(netif, &(addr->u_addr.ip6))) { + return ESP_ERR_INVALID_STATE; + } + } else { + if (mld6_leavegroup_netif(netif, &(addr->u_addr.ip6))) { + return ESP_ERR_INVALID_STATE; + } + } + } + return ESP_OK; +} + bool AsyncUDP::listenMulticast(const ip_addr_t *addr, uint16_t port, uint8_t ttl, tcpip_adapter_if_t tcpip_if) { if(!ip_addr_ismulticast(addr)) { return false; } - ip_addr_t multicast_if_addr; - uint8_t mode; - if(esp_wifi_get_mode((wifi_mode_t*)&mode)){ - mode = WIFI_MODE_NULL; - } - if(addr->type == IPADDR_TYPE_V6){ - multicast_if_addr.type = IPADDR_TYPE_V6; - - if((tcpip_if == TCPIP_ADAPTER_IF_STA && (mode & WIFI_MODE_STA)) - || (tcpip_if == TCPIP_ADAPTER_IF_AP && (mode & WIFI_MODE_AP)) - || (tcpip_if == TCPIP_ADAPTER_IF_ETH)) { - if(tcpip_adapter_get_ip6_linklocal(tcpip_if, &multicast_if_addr.u_addr.ip6)){ - return false; - } - } else { - return false; - } - - if (mld6_joingroup(&(multicast_if_addr.u_addr.ip6), &(addr->u_addr.ip6))) { - return false; - } - } else if(addr->type == IPADDR_TYPE_V4){ - tcpip_adapter_ip_info_t ifIpInfo; - - if((tcpip_if == TCPIP_ADAPTER_IF_STA && (mode & WIFI_MODE_STA)) - || (tcpip_if == TCPIP_ADAPTER_IF_AP && (mode & WIFI_MODE_AP)) - || (tcpip_if == TCPIP_ADAPTER_IF_ETH)) { - if(tcpip_adapter_get_ip_info(tcpip_if, &ifIpInfo)){ - return false; - } - } else { - return false; - } - - multicast_if_addr.type = IPADDR_TYPE_V4; - multicast_if_addr.u_addr.ip4.addr = ifIpInfo.ip.addr; - - if (igmp_joingroup((const ip4_addr *)&multicast_if_addr.u_addr.ip4, (const ip4_addr *)&addr->u_addr.ip4)!= ERR_OK) { - return false; - } - } else { + if (joinMulticastGroup(addr, true, tcpip_if)!= ERR_OK) { return false; } - if(!listen(&multicast_if_addr, port)) { + if(!listen(NULL, port)) { return false; } @@ -592,9 +605,7 @@ bool AsyncUDP::listenMulticast(const ip_addr_t *addr, uint16_t port, uint8_t ttl _pcb->mcast_ttl = ttl; _pcb->remote_port = port; ip_addr_copy(_pcb->remote_ip, *addr); - if(addr->type == IPADDR_TYPE_V4){ - ip_addr_copy(_pcb->multicast_ip, multicast_if_addr); - } + //ip_addr_copy(_pcb->remote_ip, ip_addr_any_type); UDP_MUTEX_UNLOCK(); return true; @@ -604,7 +615,7 @@ size_t AsyncUDP::writeTo(const uint8_t * data, size_t len, const ip_addr_t * add { if(!_pcb) { UDP_MUTEX_LOCK(); - _pcb = udp_new_ip_type(addr->type); + _pcb = udp_new(); UDP_MUTEX_UNLOCK(); if(_pcb == NULL) { return 0; @@ -619,7 +630,7 @@ size_t AsyncUDP::writeTo(const uint8_t * data, size_t len, const ip_addr_t * add uint8_t* dst = reinterpret_cast(pbt->payload); memcpy(dst, data, len); UDP_MUTEX_LOCK(); - if(tcpip_if != TCPIP_ADAPTER_IF_MAX){ + if(tcpip_if < TCPIP_ADAPTER_IF_MAX){ void * nif = NULL; tcpip_adapter_get_netif((tcpip_adapter_if_t)tcpip_if, &nif); if(!nif){ diff --git a/libraries/AsyncUDP/src/AsyncUDP.h b/libraries/AsyncUDP/src/AsyncUDP.h index f97381ca..2ac48a69 100644 --- a/libraries/AsyncUDP/src/AsyncUDP.h +++ b/libraries/AsyncUDP/src/AsyncUDP.h @@ -53,6 +53,7 @@ protected: uint16_t _localPort; ip_addr_t _remoteIp; uint16_t _remotePort; + uint8_t _remoteMac[6]; uint8_t *_data; size_t _len; size_t _index; @@ -74,6 +75,7 @@ public: IPAddress remoteIP(); IPv6Address remoteIPv6(); uint16_t remotePort(); + void remoteMac(uint8_t * mac); size_t send(AsyncUDPMessage &message); @@ -95,6 +97,7 @@ protected: bool _connected; AuPacketHandlerFunction _handler; + bool _init(); void _recv(udp_pcb *upcb, pbuf *pb, const ip_addr_t *addr, uint16_t port, struct netif * netif); public: @@ -109,9 +112,9 @@ public: bool listen(const IPv6Address addr, uint16_t port); bool listen(uint16_t port); - bool listenMulticast(const ip_addr_t *addr, uint16_t port, uint8_t ttl=1, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_STA); - bool listenMulticast(const IPAddress addr, uint16_t port, uint8_t ttl=1, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_STA); - bool listenMulticast(const IPv6Address addr, uint16_t port, uint8_t ttl=1, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_STA); + bool listenMulticast(const ip_addr_t *addr, uint16_t port, uint8_t ttl=1, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + bool listenMulticast(const IPAddress addr, uint16_t port, uint8_t ttl=1, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); + bool listenMulticast(const IPv6Address addr, uint16_t port, uint8_t ttl=1, tcpip_adapter_if_t tcpip_if=TCPIP_ADAPTER_IF_MAX); bool connect(const ip_addr_t *addr, uint16_t port); bool connect(const IPAddress addr, uint16_t port); diff --git a/libraries/BluetoothSerial/src/BluetoothSerial.cpp b/libraries/BluetoothSerial/src/BluetoothSerial.cpp index 97f18867..9bfe7a68 100644 --- a/libraries/BluetoothSerial/src/BluetoothSerial.cpp +++ b/libraries/BluetoothSerial/src/BluetoothSerial.cpp @@ -40,11 +40,115 @@ #include "esp32-hal-log.h" #endif -const char * _spp_server_name = "ESP32_SPP_SERVER"; +const char * _spp_server_name = "ESP32SPP"; -#define QUEUE_SIZE 256 +#define RX_QUEUE_SIZE 512 +#define TX_QUEUE_SIZE 32 static uint32_t _spp_client = 0; -static xQueueHandle _spp_queue = NULL; +static xQueueHandle _spp_rx_queue = NULL; +static xQueueHandle _spp_tx_queue = NULL; +static SemaphoreHandle_t _spp_tx_done = NULL; +static TaskHandle_t _spp_task_handle = NULL; +static EventGroupHandle_t _spp_event_group = NULL; + +#define SPP_RUNNING 0x01 +#define SPP_CONNECTED 0x02 +#define SPP_CONGESTED 0x04 + +typedef struct { + size_t len; + uint8_t data[]; +} spp_packet_t; + +static esp_err_t _spp_queue_packet(uint8_t *data, size_t len){ + if(!data || !len){ + log_w("No data provided"); + return ESP_OK; + } + spp_packet_t * packet = (spp_packet_t*)malloc(sizeof(spp_packet_t) + len); + if(!packet){ + log_e("SPP TX Packet Malloc Failed!"); + return ESP_FAIL; + } + packet->len = len; + memcpy(packet->data, data, len); + if (xQueueSend(_spp_tx_queue, &packet, portMAX_DELAY) != pdPASS) { + log_e("SPP TX Queue Send Failed!"); + free(packet); + return ESP_FAIL; + } + return ESP_OK; +} + +const uint16_t SPP_TX_MAX = 330; +static uint8_t _spp_tx_buffer[SPP_TX_MAX]; +static uint16_t _spp_tx_buffer_len = 0; + +static bool _spp_send_buffer(){ + if((xEventGroupWaitBits(_spp_event_group, SPP_CONGESTED, pdFALSE, pdTRUE, portMAX_DELAY) & SPP_CONGESTED)){ + esp_err_t err = esp_spp_write(_spp_client, _spp_tx_buffer_len, _spp_tx_buffer); + if(err != ESP_OK){ + log_e("SPP Write Failed! [0x%X]", err); + return false; + } + _spp_tx_buffer_len = 0; + if(xSemaphoreTake(_spp_tx_done, portMAX_DELAY) != pdTRUE){ + log_e("SPP Ack Failed!"); + return false; + } + return true; + } + return false; +} + +static void _spp_tx_task(void * arg){ + spp_packet_t *packet = NULL; + size_t len = 0, to_send = 0; + uint8_t * data = NULL; + for (;;) { + if(_spp_tx_queue && xQueueReceive(_spp_tx_queue, &packet, portMAX_DELAY) == pdTRUE && packet){ + if(packet->len <= (SPP_TX_MAX - _spp_tx_buffer_len)){ + memcpy(_spp_tx_buffer+_spp_tx_buffer_len, packet->data, packet->len); + _spp_tx_buffer_len+=packet->len; + free(packet); + packet = NULL; + if(SPP_TX_MAX == _spp_tx_buffer_len || uxQueueMessagesWaiting(_spp_tx_queue) == 0){ + _spp_send_buffer(); + } + } else { + len = packet->len; + data = packet->data; + to_send = SPP_TX_MAX - _spp_tx_buffer_len; + memcpy(_spp_tx_buffer+_spp_tx_buffer_len, data, to_send); + _spp_tx_buffer_len = SPP_TX_MAX; + data += to_send; + len -= to_send; + _spp_send_buffer(); + while(len >= SPP_TX_MAX){ + memcpy(_spp_tx_buffer, data, SPP_TX_MAX); + _spp_tx_buffer_len = SPP_TX_MAX; + data += SPP_TX_MAX; + len -= SPP_TX_MAX; + _spp_send_buffer(); + } + if(len){ + memcpy(_spp_tx_buffer, data, len); + _spp_tx_buffer_len += len; + free(packet); + packet = NULL; + if(uxQueueMessagesWaiting(_spp_tx_queue) == 0){ + _spp_send_buffer(); + } + } + } + } else { + log_e("Something went horribly wrong"); + } + } + vTaskDelete(NULL); + _spp_task_handle = NULL; +} + static void esp_spp_cb(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) { @@ -54,44 +158,66 @@ static void esp_spp_cb(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) log_i("ESP_SPP_INIT_EVT"); esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); esp_spp_start_srv(ESP_SPP_SEC_NONE, ESP_SPP_ROLE_SLAVE, 0, _spp_server_name); + xEventGroupSetBits(_spp_event_group, SPP_RUNNING); break; + + case ESP_SPP_SRV_OPEN_EVT://Server connection open + _spp_client = param->open.handle; + xEventGroupSetBits(_spp_event_group, SPP_CONNECTED); + log_i("ESP_SPP_SRV_OPEN_EVT"); + break; + + case ESP_SPP_CLOSE_EVT://Client connection closed + _spp_client = 0; + xEventGroupClearBits(_spp_event_group, SPP_CONNECTED); + log_i("ESP_SPP_CLOSE_EVT"); + break; + + case ESP_SPP_CONG_EVT://connection congestion status changed + if(param->cong.cong){ + xEventGroupClearBits(_spp_event_group, SPP_CONGESTED); + } else { + xEventGroupSetBits(_spp_event_group, SPP_CONGESTED); + } + log_v("ESP_SPP_CONG_EVT: %s", param->cong.cong?"CONGESTED":"FREE"); + break; + + case ESP_SPP_WRITE_EVT://write operation completed + if(param->write.cong){ + xEventGroupClearBits(_spp_event_group, SPP_CONGESTED); + } + xSemaphoreGive(_spp_tx_done);//we can try to send another packet + log_v("ESP_SPP_WRITE_EVT: %u %s", param->write.len, param->write.cong?"CONGESTED":"FREE"); + break; + + case ESP_SPP_DATA_IND_EVT://connection received data + log_v("ESP_SPP_DATA_IND_EVT len=%d handle=%d", param->data_ind.len, param->data_ind.handle); + //esp_log_buffer_hex("",param->data_ind.data,param->data_ind.len); //for low level debug + //ets_printf("r:%u\n", param->data_ind.len); + + if (_spp_rx_queue != NULL){ + for (int i = 0; i < param->data_ind.len; i++){ + if(xQueueSend(_spp_rx_queue, param->data_ind.data + i, (TickType_t)0) != pdTRUE){ + log_e("RX Full! Discarding %u bytes", param->data_ind.len - i); + break; + } + } + } + break; + + //should maybe delete those. case ESP_SPP_DISCOVERY_COMP_EVT://discovery complete log_i("ESP_SPP_DISCOVERY_COMP_EVT"); break; case ESP_SPP_OPEN_EVT://Client connection open log_i("ESP_SPP_OPEN_EVT"); break; - case ESP_SPP_CLOSE_EVT://Client connection closed - _spp_client = 0; - log_i("ESP_SPP_CLOSE_EVT"); - break; case ESP_SPP_START_EVT://server started log_i("ESP_SPP_START_EVT"); break; case ESP_SPP_CL_INIT_EVT://client initiated a connection log_i("ESP_SPP_CL_INIT_EVT"); break; - case ESP_SPP_DATA_IND_EVT://connection received data - log_v("ESP_SPP_DATA_IND_EVT len=%d handle=%d", param->data_ind.len, param->data_ind.handle); - //esp_log_buffer_hex("",param->data_ind.data,param->data_ind.len); //for low level debug - - if (_spp_queue != NULL){ - for (int i = 0; i < param->data_ind.len; i++) - xQueueSend(_spp_queue, param->data_ind.data + i, (TickType_t)0); - } else { - log_e("SerialQueueBT ERROR"); - } - break; - case ESP_SPP_CONG_EVT://connection congestion status changed - log_i("ESP_SPP_CONG_EVT"); - break; - case ESP_SPP_WRITE_EVT://write operation completed - log_v("ESP_SPP_WRITE_EVT"); - break; - case ESP_SPP_SRV_OPEN_EVT://Server connection open - _spp_client = param->open.handle; - log_i("ESP_SPP_SRV_OPEN_EVT"); - break; default: break; } @@ -99,41 +225,76 @@ static void esp_spp_cb(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) static bool _init_bt(const char *deviceName) { + if(!_spp_event_group){ + _spp_event_group = xEventGroupCreate(); + if(!_spp_event_group){ + log_e("SPP Event Group Create Failed!"); + return false; + } + xEventGroupClearBits(_spp_event_group, 0xFFFFFF); + xEventGroupSetBits(_spp_event_group, SPP_CONGESTED); + } + if (_spp_rx_queue == NULL){ + _spp_rx_queue = xQueueCreate(RX_QUEUE_SIZE, sizeof(uint8_t)); //initialize the queue + if (_spp_rx_queue == NULL){ + log_e("RX Queue Create Failed"); + return false; + } + } + if (_spp_tx_queue == NULL){ + _spp_tx_queue = xQueueCreate(TX_QUEUE_SIZE, sizeof(spp_packet_t*)); //initialize the queue + if (_spp_tx_queue == NULL){ + log_e("TX Queue Create Failed"); + return false; + } + } + if(_spp_tx_done == NULL){ + _spp_tx_done = xSemaphoreCreateBinary(); + if (_spp_tx_done == NULL){ + log_e("TX Semaphore Create Failed"); + return false; + } + xSemaphoreTake(_spp_tx_done, 0); + } + + if(!_spp_task_handle){ + xTaskCreate(_spp_tx_task, "spp_tx", 4096, NULL, 2, &_spp_task_handle); + if(!_spp_task_handle){ + log_e("Network Event Task Start Failed!"); + return false; + } + } + if (!btStarted() && !btStart()){ - log_e("%s initialize controller failed\n", __func__); + log_e("initialize controller failed"); return false; } esp_bluedroid_status_t bt_state = esp_bluedroid_get_status(); if (bt_state == ESP_BLUEDROID_STATUS_UNINITIALIZED){ if (esp_bluedroid_init()) { - log_e("%s initialize bluedroid failed\n", __func__); + log_e("initialize bluedroid failed"); return false; } } if (bt_state != ESP_BLUEDROID_STATUS_ENABLED){ if (esp_bluedroid_enable()) { - log_e("%s enable bluedroid failed\n", __func__); + log_e("enable bluedroid failed"); return false; } } if (esp_spp_register_callback(esp_spp_cb) != ESP_OK){ - log_e("%s spp register failed\n", __func__); + log_e("spp register failed"); return false; } if (esp_spp_init(ESP_SPP_MODE_CB) != ESP_OK){ - log_e("%s spp init failed\n", __func__); + log_e("spp init failed"); return false; } - _spp_queue = xQueueCreate(QUEUE_SIZE, sizeof(uint8_t)); //initialize the queue - if (_spp_queue == NULL){ - log_e("%s Queue creation error\n", __func__); - return false; - } esp_bt_dev_set_device_name(deviceName); // the default BTA_DM_COD_LOUDSPEAKER does not work with the macOS BT stack @@ -142,7 +303,7 @@ static bool _init_bt(const char *deviceName) cod.minor = 0b000100; cod.service = 0b00000010110; if (esp_bt_gap_set_cod(cod, ESP_BT_INIT_COD) != ESP_OK) { - log_e("%s set cod failed\n", __func__); + log_e("set cod failed"); return false; } @@ -159,6 +320,32 @@ static bool _stop_bt() esp_bluedroid_deinit(); btStop(); } + _spp_client = 0; + if(_spp_task_handle){ + vTaskDelete(_spp_task_handle); + _spp_task_handle = NULL; + } + if(_spp_event_group){ + vEventGroupDelete(_spp_event_group); + _spp_event_group = NULL; + } + if(_spp_rx_queue){ + vQueueDelete(_spp_rx_queue); + //ToDo: clear RX queue when in packet mode + _spp_rx_queue = NULL; + } + if(_spp_tx_queue){ + spp_packet_t *packet = NULL; + while(xQueueReceive(_spp_tx_queue, &packet, 0) == pdTRUE){ + free(packet); + } + vQueueDelete(_spp_tx_queue); + _spp_tx_queue = NULL; + } + if (_spp_tx_done) { + vSemaphoreDelete(_spp_tx_done); + _spp_tx_done = NULL; + } return true; } @@ -175,7 +362,6 @@ BluetoothSerial::BluetoothSerial() BluetoothSerial::~BluetoothSerial(void) { _stop_bt(); - vQueueDelete(_spp_queue); } bool BluetoothSerial::begin(String localName) @@ -188,60 +374,39 @@ bool BluetoothSerial::begin(String localName) int BluetoothSerial::available(void) { - if (!_spp_client || _spp_queue == NULL){ + if (_spp_rx_queue == NULL){ return 0; } - return uxQueueMessagesWaiting(_spp_queue); + return uxQueueMessagesWaiting(_spp_rx_queue); } int BluetoothSerial::peek(void) { - if (available()){ - if (!_spp_client || _spp_queue == NULL){ - return 0; - } - - uint8_t c; - if (xQueuePeek(_spp_queue, &c, 0)){ - return c; - } + uint8_t c; + if (_spp_rx_queue && xQueuePeek(_spp_rx_queue, &c, 0)){ + return c; } return -1; } bool BluetoothSerial::hasClient(void) { - if (_spp_client) - return true; - - return false; + return _spp_client > 0; } int BluetoothSerial::read(void) { - if (available()){ - if (!_spp_client || _spp_queue == NULL){ - return 0; - } - uint8_t c; - if (xQueueReceive(_spp_queue, &c, 0)){ - return c; - } + uint8_t c = 0; + if (_spp_rx_queue && xQueueReceive(_spp_rx_queue, &c, 0)){ + return c; } - return 0; + return -1; } size_t BluetoothSerial::write(uint8_t c) { - if (!_spp_client){ - return 0; - } - - uint8_t buffer[1]; - buffer[0] = c; - esp_err_t err = esp_spp_write(_spp_client, 1, buffer); - return (err == ESP_OK) ? 1 : 0; + return write(&c, 1); } size_t BluetoothSerial::write(const uint8_t *buffer, size_t size) @@ -249,24 +414,17 @@ size_t BluetoothSerial::write(const uint8_t *buffer, size_t size) if (!_spp_client){ return 0; } - - esp_err_t err = esp_spp_write(_spp_client, size, (uint8_t *)buffer); - return (err == ESP_OK) ? size : 0; + return (_spp_queue_packet((uint8_t *)buffer, size) == ESP_OK) ? size : 0; } void BluetoothSerial::flush() { - if (_spp_client){ - int qsize = available(); - uint8_t buffer[qsize]; - esp_spp_write(_spp_client, qsize, buffer); - } + while(read() >= 0){} } void BluetoothSerial::end() { _stop_bt(); - vQueueDelete(_spp_queue); } #endif diff --git a/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopbakc.ino b/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino similarity index 100% rename from libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopbakc.ino rename to libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino diff --git a/libraries/ESP32/examples/Timer/WatchdogTimer/WatchdogTimer.ino b/libraries/ESP32/examples/Timer/WatchdogTimer/WatchdogTimer.ino index bfe4a9f0..056cab96 100644 --- a/libraries/ESP32/examples/Timer/WatchdogTimer/WatchdogTimer.ino +++ b/libraries/ESP32/examples/Timer/WatchdogTimer/WatchdogTimer.ino @@ -6,7 +6,7 @@ hw_timer_t *timer = NULL; void IRAM_ATTR resetModule() { ets_printf("reboot\n"); - esp_restart_noos(); + esp_restart(); } void setup() { diff --git a/libraries/SD_MMC/src/SD_MMC.cpp b/libraries/SD_MMC/src/SD_MMC.cpp index 2f36eee7..4de46730 100644 --- a/libraries/SD_MMC/src/SD_MMC.cpp +++ b/libraries/SD_MMC/src/SD_MMC.cpp @@ -50,12 +50,13 @@ bool SDMMCFS::begin(const char * mountpoint, bool mode1bit) .init = &sdmmc_host_init, .set_bus_width = &sdmmc_host_set_bus_width, .get_bus_width = &sdmmc_host_get_slot_width, + .set_bus_ddr_mode = &sdmmc_host_set_bus_ddr_mode, .set_card_clk = &sdmmc_host_set_card_clk, .do_transaction = &sdmmc_host_do_transaction, .deinit = &sdmmc_host_deinit, - .io_int_enable = sdmmc_host_io_int_enable, - .io_int_wait = sdmmc_host_io_int_wait, - .command_timeout_ms = 0, + .io_int_enable = &sdmmc_host_io_int_enable, + .io_int_wait = &sdmmc_host_io_int_wait, + .command_timeout_ms = 0 }; host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; #ifdef BOARD_HAS_1BIT_SDMMC diff --git a/libraries/WiFi/src/WiFiAP.cpp b/libraries/WiFi/src/WiFiAP.cpp index f4a2fa54..8f96add9 100644 --- a/libraries/WiFi/src/WiFiAP.cpp +++ b/libraries/WiFi/src/WiFiAP.cpp @@ -37,7 +37,7 @@ extern "C" { #include #include #include -#include "apps/dhcpserver_options.h" +#include "dhcpserver/dhcpserver_options.h" } diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json index a03f2639..791dc307 100644 --- a/package/package_esp32_index.template.json +++ b/package/package_esp32_index.template.json @@ -38,7 +38,7 @@ { "packager": "esp32", "name": "esptool", - "version": "2.3.1" + "version": "2.5.0" }, { "packager": "esp32", @@ -85,42 +85,42 @@ }, { "name": "esptool", - "version": "2.3.1", + "version": "2.5.0", "systems": [ { "host": "i686-mingw32", - "url": "https://dl.espressif.com/dl/esptool-2.3.1-windows.zip", - "archiveFileName": "esptool-2.3.1-windows.zip", - "checksum": "SHA-256:c187763d0faac7da7c30a292a23c759bbc256fcd084dc8846ed284000cb0fe29", - "size": "3396085" + "url": "https://dl.espressif.com/dl/esptool-2.5.0-windows.zip", + "archiveFileName": "esptool-2.5.0-windows.zip", + "checksum": "SHA-256:576b8068b577cae0e6e937566a9d32a08ff7ff82963fb60400eacb6691f2fbfb", + "size": "3420959" }, { "host": "x86_64-apple-darwin", - "url": "https://dl.espressif.com/dl/esptool-2.3.1-macos.tar.gz", - "archiveFileName": "esptool-2.3.1-macos.tar.gz", - "checksum": "SHA-256:cd922418f02e0ca11dc066b36a22646a1b441da00d762b4464ca598c902c5ecb", - "size": "3810932" + "url": "https://dl.espressif.com/dl/esptool-2.5.0-macos.tar.gz", + "archiveFileName": "esptool-2.5.0-macos.tar.gz", + "checksum": "SHA-256:2da8ba3b83d99b5d808cab955a077e3e0738ec640b51de932d047cad7fac1157", + "size": "3835397" }, { "host": "x86_64-pc-linux-gnu", - "url": "https://dl.espressif.com/dl/esptool-2.3.1-linux.tar.gz", - "archiveFileName": "esptool-2.3.1-linux.tar.gz", - "checksum": "SHA-256:cff30841dad80ed5d7d2d58a31843b63afa57528979a9c839806568167691d8e", - "size": "39563" + "url": "https://dl.espressif.com/dl/esptool-2.5.0-linux.tar.gz", + "archiveFileName": "esptool-2.5.0-linux.tar.gz", + "checksum": "SHA-256:34d63b9a0bf2acb9b6fdac15f91a8756f4e722065de031e8fbce4e4abc369e54", + "size": "43468" }, { "host": "i686-pc-linux-gnu", - "url": "https://dl.espressif.com/dl/esptool-2.3.1-linux.tar.gz", - "archiveFileName": "esptool-2.3.1-linux.tar.gz", - "checksum": "SHA-256:cff30841dad80ed5d7d2d58a31843b63afa57528979a9c839806568167691d8e", - "size": "39563" + "url": "https://dl.espressif.com/dl/esptool-2.5.0-linux.tar.gz", + "archiveFileName": "esptool-2.5.0-linux.tar.gz", + "checksum": "SHA-256:34d63b9a0bf2acb9b6fdac15f91a8756f4e722065de031e8fbce4e4abc369e54", + "size": "43468" }, { "host": "arm-linux-gnueabihf", - "url": "https://dl.espressif.com/dl/esptool-2.3.1-linux.tar.gz", - "archiveFileName": "esptool-2.3.1-linux.tar.gz", - "checksum": "SHA-256:cff30841dad80ed5d7d2d58a31843b63afa57528979a9c839806568167691d8e", - "size": "39563" + "url": "https://dl.espressif.com/dl/esptool-2.5.0-linux.tar.gz", + "archiveFileName": "esptool-2.5.0-linux.tar.gz", + "checksum": "SHA-256:34d63b9a0bf2acb9b6fdac15f91a8756f4e722065de031e8fbce4e4abc369e54", + "size": "43468" } ] }, diff --git a/platform.txt b/platform.txt index cd6078df..5cb04a12 100644 --- a/platform.txt +++ b/platform.txt @@ -22,7 +22,7 @@ compiler.warning_flags.all=-Wall -Werror=all -Wextra compiler.path={runtime.tools.xtensa-esp32-elf-gcc.path}/bin/ compiler.sdk.path={runtime.platform.path}/tools/sdk -compiler.cpreprocessor.flags=-DESP_PLATFORM -DMBEDTLS_CONFIG_FILE="mbedtls/esp_config.h" -DHAVE_CONFIG_H "-I{compiler.sdk.path}/include/config" "-I{compiler.sdk.path}/include/bluedroid" "-I{compiler.sdk.path}/include/bluedroid/api" "-I{compiler.sdk.path}/include/app_trace" "-I{compiler.sdk.path}/include/app_update" "-I{compiler.sdk.path}/include/bootloader_support" "-I{compiler.sdk.path}/include/bt" "-I{compiler.sdk.path}/include/driver" "-I{compiler.sdk.path}/include/esp32" "-I{compiler.sdk.path}/include/esp_adc_cal" "-I{compiler.sdk.path}/include/esp_http_client" "-I{compiler.sdk.path}/include/esp-tls" "-I{compiler.sdk.path}/include/ethernet" "-I{compiler.sdk.path}/include/fatfs" "-I{compiler.sdk.path}/include/freertos" "-I{compiler.sdk.path}/include/heap" "-I{compiler.sdk.path}/include/jsmn" "-I{compiler.sdk.path}/include/log" "-I{compiler.sdk.path}/include/mdns" "-I{compiler.sdk.path}/include/mbedtls" "-I{compiler.sdk.path}/include/mbedtls_port" "-I{compiler.sdk.path}/include/newlib" "-I{compiler.sdk.path}/include/nvs_flash" "-I{compiler.sdk.path}/include/openssl" "-I{compiler.sdk.path}/include/spi_flash" "-I{compiler.sdk.path}/include/sdmmc" "-I{compiler.sdk.path}/include/smartconfig_ack" "-I{compiler.sdk.path}/include/spiffs" "-I{compiler.sdk.path}/include/tcpip_adapter" "-I{compiler.sdk.path}/include/ulp" "-I{compiler.sdk.path}/include/vfs" "-I{compiler.sdk.path}/include/wear_levelling" "-I{compiler.sdk.path}/include/xtensa-debug-module" "-I{compiler.sdk.path}/include/coap" "-I{compiler.sdk.path}/include/console" "-I{compiler.sdk.path}/include/expat" "-I{compiler.sdk.path}/include/json" "-I{compiler.sdk.path}/include/lwip" "-I{compiler.sdk.path}/include/newlib" "-I{compiler.sdk.path}/include/nghttp" "-I{compiler.sdk.path}/include/soc" "-I{compiler.sdk.path}/include/wpa_supplicant" +compiler.cpreprocessor.flags=-DESP_PLATFORM -DMBEDTLS_CONFIG_FILE="mbedtls/esp_config.h" -DHAVE_CONFIG_H "-I{compiler.sdk.path}/include/config" "-I{compiler.sdk.path}/include/bluedroid" "-I{compiler.sdk.path}/include/bluedroid/api" "-I{compiler.sdk.path}/include/app_trace" "-I{compiler.sdk.path}/include/app_update" "-I{compiler.sdk.path}/include/bootloader_support" "-I{compiler.sdk.path}/include/bt" "-I{compiler.sdk.path}/include/driver" "-I{compiler.sdk.path}/include/esp32" "-I{compiler.sdk.path}/include/esp_adc_cal" "-I{compiler.sdk.path}/include/esp_http_client" "-I{compiler.sdk.path}/include/esp_https_ota" "-I{compiler.sdk.path}/include/esp-mqtt" "-I{compiler.sdk.path}/include/esp-tls" "-I{compiler.sdk.path}/include/ethernet" "-I{compiler.sdk.path}/include/fatfs" "-I{compiler.sdk.path}/include/freertos" "-I{compiler.sdk.path}/include/heap" "-I{compiler.sdk.path}/include/http_server" "-I{compiler.sdk.path}/include/jsmn" "-I{compiler.sdk.path}/include/log" "-I{compiler.sdk.path}/include/mdns" "-I{compiler.sdk.path}/include/mbedtls" "-I{compiler.sdk.path}/include/mbedtls_port" "-I{compiler.sdk.path}/include/newlib" "-I{compiler.sdk.path}/include/nvs_flash" "-I{compiler.sdk.path}/include/openssl" "-I{compiler.sdk.path}/include/spi_flash" "-I{compiler.sdk.path}/include/sdmmc" "-I{compiler.sdk.path}/include/smartconfig_ack" "-I{compiler.sdk.path}/include/spiffs" "-I{compiler.sdk.path}/include/tcpip_adapter" "-I{compiler.sdk.path}/include/tcp_transport" "-I{compiler.sdk.path}/include/ulp" "-I{compiler.sdk.path}/include/vfs" "-I{compiler.sdk.path}/include/wear_levelling" "-I{compiler.sdk.path}/include/xtensa-debug-module" "-I{compiler.sdk.path}/include/lwip" "-I{compiler.sdk.path}/include/coap" "-I{compiler.sdk.path}/include/console" "-I{compiler.sdk.path}/include/expat" "-I{compiler.sdk.path}/include/json" "-I{compiler.sdk.path}/include/newlib" "-I{compiler.sdk.path}/include/nghttp" "-I{compiler.sdk.path}/include/soc" "-I{compiler.sdk.path}/include/wpa_supplicant" compiler.c.cmd=xtensa-esp32-elf-gcc compiler.c.flags=-std=gnu99 -Os -g3 -fstack-protector -ffunction-sections -fdata-sections -fstrict-volatile-bitfields -mlongcalls -nostdlib -Wpointer-arith {compiler.warning_flags} -Wno-error=unused-function -Wno-error=unused-but-set-variable -Wno-error=unused-variable -Wno-error=deprecated-declarations -Wno-unused-parameter -Wno-sign-compare -Wno-old-style-declaration -MMD -c @@ -35,7 +35,7 @@ compiler.S.flags=-c -g3 -x assembler-with-cpp -MMD -mlongcalls compiler.c.elf.cmd=xtensa-esp32-elf-gcc compiler.c.elf.flags=-nostdlib "-L{compiler.sdk.path}/lib" "-L{compiler.sdk.path}/ld" -T esp32_out.ld -T esp32.common.ld -T esp32.rom.ld -T esp32.peripherals.ld -T esp32.rom.spiram_incompatible_fns.ld -u ld_include_panic_highint_hdl -u call_user_start_cpu0 -Wl,--gc-sections -Wl,-static -Wl,--undefined=uxTopUsedPriority -u __cxa_guard_dummy -u __cxx_fatal_exception -compiler.c.elf.libs=-lgcc -lopenssl -lbtdm_app -lfatfs -lwps -lcoexist -lwear_levelling -lesp_http_client -lhal -lnewlib -ldriver -lbootloader_support -lpp -lmesh -lsmartconfig -ljsmn -lwpa -lethernet -lphy -lapp_trace -lconsole -lulp -lwpa_supplicant -lfreertos -lbt -lmicro-ecc -lcxx -lxtensa-debug-module -lmdns -lvfs -lsoc -lcore -lsdmmc -lcoap -ltcpip_adapter -lc_nano -lesp-tls -lrtc -lspi_flash -lwpa2 -lesp32 -lapp_update -lnghttp -lspiffs -lespnow -lnvs_flash -lesp_adc_cal -llog -lsmartconfig_ack -lexpat -lm -lc -lheap -lmbedtls -llwip -lnet80211 -lpthread -ljson -lstdc++ +compiler.c.elf.libs=-lgcc -lopenssl -lbtdm_app -lfatfs -lwps -lhttp_server -lcoexist -lwear_levelling -lesp_http_client -lhal -lnewlib -ldriver -lbootloader_support -lpp -lmesh -lsmartconfig -ljsmn -lwpa -lethernet -lphy -lapp_trace -lconsole -lulp -lwpa_supplicant -lfreertos -lbt -lmicro-ecc -lcxx -lxtensa-debug-module -ltcp_transport -lmdns -lvfs -lesp_ringbuf -lsoc -lcore -lsdmmc -lcoap -ltcpip_adapter -lc_nano -lesp-tls -lasio -lrtc -lspi_flash -lwpa2 -lesp32 -lapp_update -lnghttp -lspiffs -lespnow -lnvs_flash -lesp_adc_cal -llog -lsmartconfig_ack -lexpat -lm -lmqtt -lc -lheap -lmbedtls -llwip -lnet80211 -lpthread -ljson -lesp_https_ota -lstdc++ compiler.as.cmd=xtensa-esp32-elf-as diff --git a/tools/esptool.py b/tools/esptool.py index 36f95002..bd89a7ff 100755 --- a/tools/esptool.py +++ b/tools/esptool.py @@ -20,6 +20,7 @@ from __future__ import division, print_function import argparse import base64 +import binascii import copy import hashlib import inspect @@ -30,10 +31,27 @@ import struct import sys import time import zlib +import string +import serial.tools.list_ports as list_ports import serial -__version__ = "2.3.1" +# check 'serial' is 'pyserial' and not 'serial' https://github.com/espressif/esptool/issues/269 +try: + if "serialization" in serial.__doc__ and "deserialization" in serial.__doc__: + raise ImportError(""" +esptool.py depends on pyserial, but there is a conflict with a currently installed package named 'serial'. + +You may be able to work around this by 'pip uninstall serial; pip install pyserial' \ +but this may break other installed Python software that depends on 'serial'. + +There is no good fix for this right now, apart from configuring virtualenvs. \ +See https://github.com/espressif/esptool/issues/269#issuecomment-385298196 for discussion of the underlying issue(s).""") +except TypeError: + pass # __doc__ returns None for pyserial + + +__version__ = "2.5.0" MAX_UINT32 = 0xffffffff MAX_UINT24 = 0xffffff @@ -45,6 +63,8 @@ MAX_TIMEOUT = CHIP_ERASE_TIMEOUT * 2 # longest any command can run SYNC_TIMEOUT = 0.1 # timeout for syncing with bootloader MD5_TIMEOUT_PER_MB = 8 # timeout (per megabyte) for calculating md5sum ERASE_REGION_TIMEOUT_PER_MB = 30 # timeout (per megabyte) for erasing a region +MEM_END_ROM_TIMEOUT = 0.05 # special short timeout for ESP_MEM_END, as it may never respond +DEFAULT_SERIAL_WRITE_TIMEOUT = 10 # timeout for serial port write def timeout_per_mb(seconds_per_mb, size_bytes): @@ -112,7 +132,7 @@ def esp8266_function_only(func): class ESPLoader(object): - """ Base class providing access to ESP ROM & softtware stub bootloaders. + """ Base class providing access to ESP ROM & software stub bootloaders. Subclasses provide ESP8266 & ESP32 specific functionality. Don't instantiate this base class directly, either instantiate a subclass or @@ -200,6 +220,8 @@ class ESPLoader(object): # https://github.com/espressif/esptool/issues/44#issuecomment-107094446 self._set_port_baudrate(baud) self._trace_enabled = trace_enabled + # set write timeout, to prevent esptool blocked at write forever. + self._port.write_timeout = DEFAULT_SERIAL_WRITE_TIMEOUT def _set_port_baudrate(self, baud): try: @@ -243,7 +265,7 @@ class ESPLoader(object): buf = b'\xc0' \ + (packet.replace(b'\xdb',b'\xdb\xdd').replace(b'\xc0',b'\xdb\xdc')) \ + b'\xc0' - self.trace("Write %d bytes: %r", len(buf), buf) + self.trace("Write %d bytes: %s", len(buf), HexFormatter(buf)) self._port.write(buf) def trace(self, message, *format_args): @@ -278,8 +300,8 @@ class ESPLoader(object): try: if op is not None: - self.trace("command op=0x%02x data len=%s wait_response=%d timeout=%.3f data=%r", - op, len(data), 1 if wait_response else 0, timeout, data) + self.trace("command op=0x%02x data len=%s wait_response=%d timeout=%.3f data=%s", + op, len(data), 1 if wait_response else 0, timeout, HexFormatter(data)) pkt = struct.pack(b' start: + raise FatalError(("Software loader is resident at 0x%08x-0x%08x. " + + "Can't load binary at overlapping address range 0x%08x-0x%08x. " + + "Either change binary loading address, or use the --no-stub " + + "option to disable the software loader.") % (start, end, load_start, load_end)) + return self.check_command("enter RAM download mode", self.ESP_MEM_BEGIN, struct.pack('LOW + self._setRTS(True) # EN->LOW time.sleep(0.1) - self._port.setRTS(False) + self._setRTS(False) def soft_reset(self, stay_in_bootloader): if not self.IS_STUB: @@ -892,7 +952,7 @@ class ESP8266ROM(ESPLoader): return "ESP8285" if is_8285 else "ESP8266EX" def get_chip_features(self): - features = [ "WiFi" ] + features = ["WiFi"] if self.get_chip_description() == "ESP8285": features += ["Embedded Flash"] return features @@ -911,7 +971,7 @@ class ESP8266ROM(ESPLoader): super(ESP8266ROM, self).flash_set_parameters(size) def chip_id(self): - """ Read Chip ID from OTP ROM - see http://esp8266-re.foogod.com/wiki/System_get_chip_id_%28IoT_RTOS_SDK_0.9.9%29 """ + """ Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() function """ id0 = self.read_reg(self.ESP_OTP_MAC0) id1 = self.read_reg(self.ESP_OTP_MAC1) return (id0 >> 24) | ((id1 & MAX_UINT24) << 8) @@ -950,6 +1010,9 @@ class ESP8266ROM(ESPLoader): else: return (num_sectors - head_sectors) * sector_size + def override_vddsdio(self, new_voltage): + raise NotImplementedInROMError("Overriding VDDSDIO setting only applies to ESP32") + class ESP8266StubLoader(ESP8266ROM): """ Access class for ESP8266 stub loader, runs on top of ROM. @@ -1002,17 +1065,13 @@ class ESP32ROM(ESPLoader): BOOTLOADER_FLASH_OFFSET = 0x1000 + OVERRIDE_VDDSDIO_CHOICES = ["1.8V", "1.9V", "OFF"] + def get_chip_description(self): word3 = self.read_efuse(3) - chip_version = (word3 >> 12) & 0xF + chip_ver_rev1 = (word3 >> 15) & 0x1 pkg_version = (word3 >> 9) & 0x07 - silicon_rev = { - 0x0: "0", - 0x8: "1", - 0xc: "1", # Silicon rev 1 w/ BLK3_PART_RESERVE bit set - }.get(chip_version, "(unknown 0x%x)" % chip_version) - chip_name = { 0: "ESP32D0WDQ6", 1: "ESP32D0WDQ5", @@ -1020,27 +1079,41 @@ class ESP32ROM(ESPLoader): 5: "ESP32-PICO-D4", }.get(pkg_version, "unknown ESP32") - return "%s (revision %s)" % (chip_name, silicon_rev) + return "%s (revision %d)" % (chip_name, chip_ver_rev1) def get_chip_features(self): features = ["WiFi"] word3 = self.read_efuse(3) - if word3 & (1 << 1) == 0: # RD_CHIP_VER_DIS_BT + # names of variables in this section are lowercase + # versions of EFUSE names as documented in TRM and + # ESP-IDF efuse_reg.h + + chip_ver_dis_bt = word3 & (1 << 1) + if chip_ver_dis_bt == 0: features += ["BT"] - if word3 & (1 << 0): # RD_CHIP_VER_DIS_APP_CPU + chip_ver_dis_app_cpu = word3 & (1 << 0) + if chip_ver_dis_app_cpu: features += ["Single Core"] else: features += ["Dual Core"] + chip_cpu_freq_rated = word3 & (1 << 13) + if chip_cpu_freq_rated: + chip_cpu_freq_low = word3 & (1 << 12) + if chip_cpu_freq_low: + features += ["160MHz"] + else: + features += ["240MHz"] + pkg_version = (word3 >> 9) & 0x07 - if pkg_version != 0: + if pkg_version in [2, 4, 5]: features += ["Embedded Flash"] word4 = self.read_efuse(4) - vref = (word4 >> 8) & 0x1F - if vref != 0: + adc_vref = (word4 >> 8) & 0x1F + if adc_vref: features += ["VRef calibration in efuse"] return features @@ -1050,9 +1123,7 @@ class ESP32ROM(ESPLoader): return self.read_reg(self.EFUSE_REG_BASE + (4 * n)) def chip_id(self): - word16 = self.read_efuse(1) - word17 = self.read_efuse(2) - return ((word17 & MAX_UINT24) << 24) | (word16 >> 8) & MAX_UINT24 + raise NotSupportedError(self, "chip_id") def read_mac(self): """ Read MAC from EFUSE region """ @@ -1067,6 +1138,28 @@ class ESP32ROM(ESPLoader): def get_erase_size(self, offset, size): return size + def override_vddsdio(self, new_voltage): + new_voltage = new_voltage.upper() + if new_voltage not in self.OVERRIDE_VDDSDIO_CHOICES: + raise FatalError("The only accepted VDDSDIO overrides are '1.8V', '1.9V' and 'OFF'") + RTC_CNTL_SDIO_CONF_REG = 0x3ff48074 + RTC_CNTL_XPD_SDIO_REG = (1 << 31) + RTC_CNTL_DREFH_SDIO_M = (3 << 29) + RTC_CNTL_DREFM_SDIO_M = (3 << 27) + RTC_CNTL_DREFL_SDIO_M = (3 << 25) + # RTC_CNTL_SDIO_TIEH = (1 << 23) # not used here, setting TIEH=1 would set 3.3V output, not safe for esptool.py to do + RTC_CNTL_SDIO_FORCE = (1 << 22) + RTC_CNTL_SDIO_PD_EN = (1 << 21) + + reg_val = RTC_CNTL_SDIO_FORCE # override efuse setting + reg_val |= RTC_CNTL_SDIO_PD_EN + if new_voltage != "OFF": + reg_val |= RTC_CNTL_XPD_SDIO_REG # enable internal LDO + if new_voltage == "1.9V": + reg_val |= (RTC_CNTL_DREFH_SDIO_M | RTC_CNTL_DREFM_SDIO_M | RTC_CNTL_DREFL_SDIO_M) # boost voltage + self.write_reg(RTC_CNTL_SDIO_CONF_REG, reg_val) + print("VDDSDIO regulator set to %s" % new_voltage) + class ESP32StubLoader(ESP32ROM): """ Access class for ESP32 stub loader, runs on top of ROM. @@ -1096,20 +1189,20 @@ class ESPBOOTLOADER(object): def LoadFirmwareImage(chip, filename): """ Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are - original ROM firmware images (ESPFirmwareImage) or "v2" OTA bootloader images. + original ROM firmware images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images. - Returns a BaseFirmwareImage subclass, either ESPFirmwareImage (v1) or OTAFirmwareImage (v2). + Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwareImage (v1) or ESP8266V2FirmwareImage (v2). """ with open(filename, 'rb') as f: - if chip == 'esp32': + if chip.lower() == 'esp32': return ESP32FirmwareImage(f) else: # Otherwise, ESP8266 so look at magic to determine the image type magic = ord(f.read(1)) f.seek(0) if magic == ESPLoader.ESP_IMAGE_MAGIC: - return ESPFirmwareImage(f) + return ESP8266ROMFirmwareImage(f) elif magic == ESPBOOTLOADER.IMAGE_V2_MAGIC: - return OTAFirmwareImage(f) + return ESP8266V2FirmwareImage(f) else: raise FatalError("Invalid image magic number: %d" % magic) @@ -1119,10 +1212,11 @@ class ImageSegment(object): (very similar to a section in an ELFImage also) """ def __init__(self, addr, data, file_offs=None): self.addr = addr - # pad all ImageSegments to at least 4 bytes length - self.data = pad_to(data, 4, b'\x00') + self.data = data self.file_offs = file_offs self.include_in_checksum = True + if self.addr != 0: + self.pad_to_alignment(4) # pad all "real" ImageSegments 4 byte aligned length def copy_with_new_addr(self, new_addr): """ Return a new ImageSegment with same data, but mapped at @@ -1147,6 +1241,9 @@ class ImageSegment(object): r += " file_offs 0x%08x" % (self.file_offs) return r + def pad_to_alignment(self, alignment): + self.data = pad_to(self.data, alignment, b'\x00') + class ELFSection(ImageSegment): """ Wrapper class for a section in an ELF image, has a section @@ -1243,13 +1340,13 @@ class BaseFirmwareImage(object): return [s for s in self.segments if s != irom_segment] -class ESPFirmwareImage(BaseFirmwareImage): +class ESP8266ROMFirmwareImage(BaseFirmwareImage): """ 'Version 1' firmware image, segments loaded directly by the ROM bootloader. """ ROM_LOADER = ESP8266ROM def __init__(self, load_file=None): - super(ESPFirmwareImage, self).__init__() + super(ESP8266ROMFirmwareImage, self).__init__() self.flash_mode = 0 self.flash_size_freq = 0 self.version = 1 @@ -1283,7 +1380,7 @@ class ESPFirmwareImage(BaseFirmwareImage): self.append_checksum(f, checksum) -class OTAFirmwareImage(BaseFirmwareImage): +class ESP8266V2FirmwareImage(BaseFirmwareImage): """ 'Version 2' firmware image, segments loaded by software bootloader stub (ie Espressif bootloader or rboot) """ @@ -1291,7 +1388,7 @@ class OTAFirmwareImage(BaseFirmwareImage): ROM_LOADER = ESP8266ROM def __init__(self, load_file=None): - super(OTAFirmwareImage, self).__init__() + super(ESP8266V2FirmwareImage, self).__init__() self.version = 2 if load_file is not None: segments = self.load_common_header(load_file, ESPBOOTLOADER.IMAGE_V2_MAGIC) @@ -1304,8 +1401,7 @@ class OTAFirmwareImage(BaseFirmwareImage): # the file is saved in the image with a zero load address # in the header, so we need to calculate a load address irom_segment = self.load_segment(load_file, True) - # for actual mapped addr, add ESP8266ROM.IROM_MAP_START + flashing_Addr + 8 - irom_segment.addr = 0 + irom_segment.addr = 0 # for actual mapped addr, add ESP8266ROM.IROM_MAP_START + flashing_addr + 8 irom_segment.include_in_checksum = False first_flash_mode = self.flash_mode @@ -1350,6 +1446,7 @@ class OTAFirmwareImage(BaseFirmwareImage): if irom_segment is not None: # save irom0 segment, make sure it has load addr 0 in the file irom_segment = irom_segment.copy_with_new_addr(0) + irom_segment.pad_to_alignment(16) # irom_segment must end on a 16 byte boundary self.save_segment(f, irom_segment) # second header, matches V1 header and contains loadable segments @@ -1360,6 +1457,29 @@ class OTAFirmwareImage(BaseFirmwareImage): checksum = self.save_segment(f, segment, checksum) self.append_checksum(f, checksum) + # calculate a crc32 of entire file and append + # (algorithm used by recent 8266 SDK bootloaders) + with open(filename, 'rb') as f: + crc = esp8266_crc32(f.read()) + with open(filename, 'ab') as f: + f.write(struct.pack(b' 16 bytes) will be + printed as separately indented lines, with ASCII decoding at the end + of each line. + """ + def __init__(self, binary_string, auto_split=True): + self._s = binary_string + self._auto_split = auto_split + + def __str__(self): + if self._auto_split and len(self._s) > 16: + result = "" + s = self._s + while len(s) > 0: + line = s[:16] + ascii_line = "".join(c if (c == ' ' or (c in string.printable and c not in string.whitespace)) + else '.' for c in line.decode('ascii', 'replace')) + s = s[16:] + result += "\n %-16s %-16s | %s" % (hexify(line[:8], False), hexify(line[8:], False), ascii_line) + return result else: - s += chr(int(hex_string, 16)) - - return s + return hexify(self._s, False) def pad_to(data, alignment, pad_character=b'\xFF'): @@ -1770,6 +1933,11 @@ class NotImplementedInROMError(FatalError): def __init__(self, bootloader, func): FatalError.__init__(self, "%s ROM does not support function %s." % (bootloader.CHIP_NAME, func.__name__)) + +class NotSupportedError(FatalError): + def __init__(self, esp, function_name): + FatalError.__init__(self, "Function %s is not supported for %s." % (function_name, esp.CHIP_NAME)) + # "Operation" commands, executable at command line. One function each # # Each function takes either two args (, ) or a single @@ -1777,18 +1945,19 @@ class NotImplementedInROMError(FatalError): def load_ram(esp, args): - image = LoadFirmwareImage(esp, args.filename) + image = LoadFirmwareImage(esp.CHIP_NAME, args.filename) print('RAM boot...') - for (offset, size, data) in image.segments: - print('Downloading %d bytes at %08x...' % (size, offset), end=' ') + for seg in image.segments: + size = len(seg.data) + print('Downloading %d bytes at %08x...' % (size, seg.addr), end=' ') sys.stdout.flush() - esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, offset) + esp.mem_begin(size, div_roundup(size, esp.ESP_RAM_BLOCK), esp.ESP_RAM_BLOCK, seg.addr) seq = 0 - while len(data) > 0: - esp.mem_block(data[0:esp.ESP_RAM_BLOCK], seq) - data = data[esp.ESP_RAM_BLOCK:] + while len(seg.data) > 0: + esp.mem_block(seg.data[0:esp.ESP_RAM_BLOCK], seq) + seg.data = seg.data[esp.ESP_RAM_BLOCK:] seq += 1 print('done!') @@ -1974,7 +2143,7 @@ def image_info(args): def make_image(args): - image = ESPFirmwareImage() + image = ESP8266ROMFirmwareImage() if len(args.segfile) == 0: raise FatalError('No segments specified') if len(args.segfile) != len(args.segaddr): @@ -1994,10 +2163,11 @@ def elf2image(args): if args.chip == 'esp32': image = ESP32FirmwareImage() + image.secure_pad = args.secure_pad elif args.version == '1': # ESP8266 - image = ESPFirmwareImage() + image = ESP8266ROMFirmwareImage() else: - image = OTAFirmwareImage() + image = ESP8266V2FirmwareImage() image.entrypoint = e.entrypoint image.segments = e.sections # ELFSection is a subclass of ImageSegment image.flash_mode = {'qio':0, 'qout':1, 'dio':2, 'dout': 3}[args.flash_mode] @@ -2018,8 +2188,12 @@ def read_mac(esp, args): def chip_id(esp, args): - chipid = esp.chip_id() - print('Chip ID: 0x%08x' % chipid) + try: + chipid = esp.chip_id() + print('Chip ID: 0x%08x' % chipid) + except NotSupportedError: + print('Warning: %s has no Chip ID. Reading MAC instead.' % esp.CHIP_NAME) + read_mac(esp, args) def erase_flash(esp, args): @@ -2137,7 +2311,7 @@ def main(): parser.add_argument( '--port', '-p', help='Serial port device', - default=os.environ.get('ESPTOOL_PORT', ESPLoader.DEFAULT_PORT)) + default=os.environ.get('ESPTOOL_PORT', None)) parser.add_argument( '--baud', '-b', @@ -2148,7 +2322,7 @@ def main(): parser.add_argument( '--before', help='What to do before connecting to the chip', - choices=['default_reset', 'no_reset'], + choices=['default_reset', 'no_reset', 'no_reset_no_sync'], default=os.environ.get('ESPTOOL_BEFORE', 'default_reset')) parser.add_argument( @@ -2167,6 +2341,12 @@ def main(): help="Enable trace-level output of esptool.py interactions.", action='store_true') + parser.add_argument( + '--override-vddsdio', + help="Override ESP32 VDDSDIO internal voltage regulator (use with care)", + choices=ESP32ROM.OVERRIDE_VDDSDIO_CHOICES, + nargs='?') + subparsers = parser.add_subparsers( dest='operation', help='Run esptool {command} -h for additional help') @@ -2253,6 +2433,7 @@ def main(): parser_elf2image.add_argument('input', help='Input ELF file') parser_elf2image.add_argument('--output', '-o', help='Output filename prefix (for version 1 image), or filename (for version 2 single image)', type=str) parser_elf2image.add_argument('--version', '-e', help='Output image version', choices=['1','2'], default='1') + parser_elf2image.add_argument('--secure-pad', action='store_true', help='Pad image so once signed it will end on a 64KB boundary. For ESP32 images only.') add_spi_flash_subparsers(parser_elf2image, is_elf2image=True) @@ -2344,24 +2525,50 @@ def main(): operation_args = inspect.getfullargspec(operation_func).args if operation_args[0] == 'esp': # operation function takes an ESPLoader connection object - initial_baud = min(ESPLoader.ESP_ROM_BAUD, args.baud) # don't sync faster than the default baud rate - if args.chip == 'auto': - esp = ESPLoader.detect_chip(args.port, initial_baud, args.before, args.trace) + if args.before != "no_reset_no_sync": + initial_baud = min(ESPLoader.ESP_ROM_BAUD, args.baud) # don't sync faster than the default baud rate else: - chip_class = { - 'esp8266': ESP8266ROM, - 'esp32': ESP32ROM, - }[args.chip] - esp = chip_class(args.port, initial_baud, args.trace) - esp.connect(args.before) + initial_baud = args.baud + + if args.port is None: + ser_list = sorted(ports.device for ports in list_ports.comports()) + print("Found %d serial ports" % len(ser_list)) + else: + ser_list = [args.port] + esp = None + for each_port in reversed(ser_list): + print("Serial port %s" % each_port) + try: + if args.chip == 'auto': + esp = ESPLoader.detect_chip(each_port, initial_baud, args.before, args.trace) + else: + chip_class = { + 'esp8266': ESP8266ROM, + 'esp32': ESP32ROM, + }[args.chip] + esp = chip_class(each_port, initial_baud, args.trace) + esp.connect(args.before) + break + except FatalError as err: + if args.port is not None: + raise + print("%s failed to connect: %s" % (each_port, err)) + esp = None + if esp is None: + raise FatalError("All of the %d available serial ports could not connect to a Espressif device." % len(ser_list)) print("Chip is %s" % (esp.get_chip_description())) print("Features: %s" % ", ".join(esp.get_chip_features())) + read_mac(esp, args) + if not args.no_stub: esp = esp.run_stub() + if args.override_vddsdio: + esp.override_vddsdio(args.override_vddsdio) + if args.baud > initial_baud: try: esp.change_baud(args.baud) @@ -2386,8 +2593,11 @@ def main(): operation_func(esp, args) - # finish execution based on args.after - if args.after == 'hard_reset': + # Handle post-operation behaviour (reset or other) + if operation_func == load_ram: + # the ESP is now running the loaded image, so let it run + print('Exiting immediately.') + elif args.after == 'hard_reset': print('Hard resetting via RTS pin...') esp.hard_reset() elif args.after == 'soft_reset': @@ -2399,6 +2609,8 @@ def main(): if esp.IS_STUB: esp.soft_reset(True) # exit stub back to ROM loader + esp._port.close() + else: operation_func(args) @@ -2497,7 +2709,7 @@ class AddrFilenamePairAction(argparse.Action): for i in range(0,len(values),2): try: address = int(values[i],0) - except ValueError as e: + except ValueError: raise argparse.ArgumentError(self,'Address "%s" must be a number' % values[i]) try: argfile = open(values[i + 1], 'rb') @@ -2524,104 +2736,104 @@ class AddrFilenamePairAction(argparse.Action): # Binary stub code (see flasher_stub dir for source & details) ESP8266ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b""" -eNrNPXt/1Da2X2XshJCEASzb40cIy2QShkdhG6BJQ3/TbWzZhlJgkyG7SVn2fvbr85Jkz4RA2e69f4SObFk6Ou9zdKT+6/pZfXF2fWtQXp9dFNnsQgWziyAYt/+o2UXTwN/0Pjzq/mXtX1Pf+/7hzqP2u7j9K6Hr\ -vfat5kZ9j7plzme67alymGVMPenFcW8Ctfy3cvoQaA5AujsTzdCD2n40Xrqc2UWub/A6ikB+tdNedwaOHajNgAxJBxO9hgxXdrDVQdBgw4G1JUZWIVhHDoBAI/N1Do3aaeQG8bHzBj5WpR26CGbzHnIyA8LsTH7u\ -t//UTkOFzhDaAaMMnIZqzCK228c5AxS4oAKxisqBLnCgCzovNc1l5lEjB0WqywNB4LAeNmT2UguNWsJnmdMobOMIvxoPn+B/gjv4n4uHhl0e868yfsS/tL7Fv1Q7QR1yo8py/PXaPGsHqWTGvAWsRq4eP1kTkHhI\ -j0CFReXtl4UipodPVPtbB36x4iMBacFhsds+DYtJO35Y7MB8RTtcExb3SHTqlEbTBkUwRQgP27dlxAgE9ABfJ67AAUjhd34KvTOeNdObHvRvpw1aSpTQWXlC2nYeJcRT8nBzCNMPWAEAZsKJLEHWMqJ5q2IJtEjE\ -hrERKDMYECYM4oF5gEMP4R8eLe6PdtlzgBVxsiM/nrU/EDmn8oOxFJYMCA+mm2WDoa7xSCabZis0MK63/7TDqWQunwliMnpDk5gXG/apisId4JSQOyn/2S4+GfmFDwwD4wKd8G0U2rEywLNSgT9oJrOz9WEHmrD9\ -msmgeU1l2V+TUB/UNzQyGBYpl90nBKG5kDkj352cBlNqAD8GLVYyZsomJV5UKbFAXuGyaOS6ZmDUJcAItEWzSGbdMnJVMd8Qtui/VQi6HFCFSE4AffBJGj5rBOD2Yc56r0k+rDTYefqzPNmdvW9WpOsTnjNh6A0M\ -zS5+dYq/XzjTRRbCPOtqvbwDXJB8JMgAy80HZwgxWgl3Dhr5anphRyud0abv4Pm0/YbVpdI9ROQ013pDWoFWN5bO8KAF5D2N3PTgvGWRAKSVT5QLwESe+87DlwJV6NC1UtBDRcN2wjN5FtAz4HCA9t89XuiSNUuu\ -ue+i7jtSrcHIxZWqQJmD8UIUz1glJcYWNow64gN8d+pqld8XebBulVldgUtBpjNL3hkjO9yBj/7Z/+iQYFMFrog4GFd/i3pl+ukAeDA+fAGGjRVmCPbkLuuohDW59SlA7FC/vl+Y7jnhsw5oLo1z3eYf6V9oDTAH\ -mrHFoWkZzWXLSJYu45AtRA2o/tHSAHyNKhTZXjMIPxJuLxnzQpCyEZIeC03uLLy6R6908leX2mvSZfoUHmdPvA1Hx7uAhMJ4jrxP7/B8MFbM06mwHWXly0aZig7YooEAQ0E83XGR2+pJVbvDhSxugTNuQhbeijG6\ -MNkQfJDnxBpooIBpwI5oqzx5mBwMBbK+mPi6mdqZ6mJ3YskOTmRdj30YLr0F4z9n6EaleBET/oGK6gD0vqjg9PgArc4ePNzfG0AHtBzjaABwaTEqWsmaByi+LZDTGw5eAGWAF4sGBzcqiWZnoFDM2+yQdVoWshZC\ -5OhkYHVVRgqEeGJgyYsOMLLMdGBY73vstSpMRwLb4bsANdCIKNQJZ/hr4ILV7jSW90lLqbTzmeFY35kXRwa3ryGBsgS/IKppnXbZpdF/V6SXGnfO/DU5Gk2aDOHzAQU6Lky5YRRyy3PWpgHCudk2cvats+98agWj\ -zR8H1Esjz4Cqal4SaNghmgoDGQ3Lq48dGasslhYRStpJXGKBGPkjGIACH31gXxibejR3vAzthJgLSqwEnViKL6NkFnBbVNhaqQjFfyIkRzPVLq0pnSewhHgN+XMKLNaAdBG/AOetpGyO2rcXGh7HoZg0nOYR29Io\ -5QAMB/YY2sSOhZIBXmRTW28MlayrUpAFauMAArVCeAwSVQ8idO/AhY4GKyAUrjtd6/54d+HlTYwlFdmK7nufXMM64w5Jv4PlYhvG4fQ0cTSBf+MjsMfZ6B8wCrMLdV/ubkboa0YDYFfgaFQtyLf3f2JiJ/TXjR0/\ -7zn7qMVJk1qNWdxgDq0ddyyWoAWiPEF4GfrMoIqCzqYumZ8iH93JuXejLK5RlMvW+HrKulfELsQOYQFcNXrCDnLojU6Z6WvgJu/GyXdsw4s9iq3Bca+K38piAwcZjo84sCzIfwZ5Vqiu3sKM5xQDkEl5SzCAs1rr\ -+ZA+zIBAarT+FiYs1ubFKg68uf0CtOsnkEnoEL8GjQN8X0ZWKCADFMSK4tqmJpu0Tu8RIyFzK4Dd1D1NDByVk9TAf7MwB2HJKXIr0ns5RsGr7+iT9ucaezhgTVrsgGbWKwFmobx/MdI00w4t+qPyZ0Kbrig50JL2\ -PWGhSEkP1xiGIf94/6AxwDjqJidvFtXUiKNSfMBDWS8qtGmjzqcLwKN3UMPc2xtTJ8bBEee0nmv7Ka7nV7seFb2kdUxvOekRgX9k4a968OehcQBEFAKvcDpp7OT9wo9AHiPIUYWv2SoE10Bq3viTInhexGVxG4gD\ -qoBZV5H2X1AGCPXEC557cenhR15EDE4SV5M+GjTEhFr/c38Qi2RmAwyv9n+AmLg84OHC00PmIUweYUSDIfyr1OI/GI3HkJkRvyMZg8xEQQMco1nnqGQB+d4ujD3czRnR5K0EkatWmJWa5O6YSMjM4b40fMbc6Q/W\ -WT41LS7QkYc6Iy+FSWkYzKdEDl1DIaQvy+M5bG7Ht6lXIif/rsaitCFUr0FcspLZL2EfA0c8vUUobQ3qarucMh14O7CslAStjnbIDsOymuoQqLCC1ngVNUF1BxGx+hlE5AYRG5z21S8OyQA2BbsdcY+js+Urn7r+\ -wh9YetZZOi+Ds29jXjBQSn0C+g3oIxVYL1glT9llBf6sclz8yqWLn8vKMWTAcfQhW/N4+uXr/kaKw7IbSWMFMVszUENN/cbf8oHVJmSVDKk5lKyzHVl5Lzebbu98OfeDVwBKgkNoyuTMNzSNUHJsZBWyR3FuU3EY\ -1dRGxb3xH/uCJYKap7b+a/sR+G1N9SZ6HPm70Mcg22PnB0YG56+pjF6EkQUPgloF8DTJ1PECQ87pKrAjYPnPcr+NUkBVUmqsaR2Mszvh7GzLdTokJVoFPiZAcnZc0EHWCygcfphKxlmSVcBx24j5a1/KcdvRIdlS\ -8Nf0QtDvoDz503RNE1iBq3GL5Az9izWHwyzbOfFqEGzvTmnhQbioVFptkgP0wCfB3IP0e9nM7wuAB9bzI1v0lBpVsAv+wfEKegnXyTGBVBcSoupl8SCmqcslAGQIQGYAYERxnGd03hAcpjOMCT5aP38J4YZgpNrJ\ -ymyJNCGVIOPZ0ndjH4DWGO98hH/OKfEaKEikhdBKpJXcBG0Frr2G1adkwOfoXPVseJWQeFobPvdCsd1ktcGCw4z648FJw9kfIE6TcfYC0d3K9nzaj+t668FtoYgTp8gaazYiyiAiEn7yX4H4DMUTB1aqJvAsFP9y\ -9JlFQfJhYVGSGsk2zxWxEHSxS2xX3K4bMJfK3kY22RW2is7Ju8T4V4cntLEnef08nkhytPQ5HGxSX7YZZBsIaKzP+gHw5KH5lCQsy2QI8PBgB6bOtjguhzxHKuM1mw/ne/ZjdtExU4iJSuVk5gC74Jq22hH2CljY\ -HFt+7WucGkxOi5LR+v9MydRoQrwTIiYJvLO+nff8AoYKcShwtNR4yhQGfNUYbgYDm0Bd4hk8RFY8guEeR4M1+By2kSDuRVtRJgmiqbKQtLEvgv0cN5H7vnPUZ1GhU8uErtc8Zb5xt8CTu9tXkmyJ+wVu3SFZFx3+\ -P7AL3hM0yFt9pmxRHqxurkJZAqDIuqHWThsftUW+h6gE+VZRmpCFVTpC8kQ4J2z9q9MdlzQncyAXCvr45AKs0xy83yOIRNSeRDytuVIu7eYFjXW0qF9m13dQpdC6N2fXnYRWoF70P/CY/i2ZcEgEanNjQiUHuD2k\ -/rrIIi2HqZZB1iFNhCoaqzN4qiwE6VR+cRMhv2UtoRuEZYmbgxfgN3GPKnI1EYpKMFkRLt+baPrZAnGLbCAG8LHMA4ymYLdTPXUNMJt/zOnMEb1tqyAVnGdgJaGVgVIufE720IzRBlE7L/Z4T6se2eWid4kZ2NB5\ -GLDux61A3TpjvsAxIA0Of4C1HLMHn8grBTe3yTkkvcRSRx67jhoiONzFy2RyJGJeZLwPJnhMWHgx2IXqCdzxli3idFKgmO3BLn00L7KTdMBJfqXCIg29ZOKlCEo895KwWB9Hg4mXnZwi4+/Ni2RSZA8orwOGHO0r\ -uDRpGpw8JCzmwZ7N2I/HalKs2/ATgcx4ixDrTTA7h+BP2jWNP8AAE28daBRNfoTWXHbTQVWk5CahD9XIV8EJWMTxOX7LdMZQv/JxBOQOCfnrIN8RfDDusZAkbFd+Ais/2QMRADql4wfIq/AER67i2Vm7HpgjlnQC\ -CFALsP8D6vSJSfrVLQYBa+ct1tqfgdppMQySr405S9mzLOdeCvNlJ4h6zMEHQRawcOYIxBjZ6CSiteXhC6sJ89yVEcyUsbotKykM8W6ubdhMeZHa7eCsstYAVHXFO+zUV7aeIVkPkBeJL682JD8cEvfX6JHGp1xQ\ -ozdXTnxGnNnPYbYAockl96nGj5TIzAOCWbbe3eoG7JCOaWM25Wdm34QXY4qCNLkKtJgNytOgB60/kSfp2FxM44C46ABSOkH8GLBcRITs0Kb5gOfriAPVcnKjdYHA6UUnLub4N5EYE5IV3eKYz8fsGJxFhzDd6L8X\ -s1uqh07smToxhNlSMjSc2PqIrLzZmSOylS7s/6zirCsDmvgGQSUmVgH/AGlc/vndZZ7QZR5UVMFAmAetd5ArGDujUqT31s7kkjHUzA4xU16V4oTElvzgaBry+2gaCACfJ0Lyw9YlqhMOKppUfAsf4sxWCNdMuQNN\ -EXW8OmfTHL1qpTzorNU7+JdyJOglKMkJaNqfRhFe64eaE0rmNQGGZKA8s+g4FPlISeciX2XvxHIUa1dFTUobR2aG3u5bQiJBkGPpD+1rGBfKLzhNd++KNN0Srl/hJF0WL7qIhvnTKxJ1DudrjhAC8hxWF2XA8l+Q\ -GXlI78JU6HFroWROn2vaWM0K3o5ROY51DmMt4gLgOgeCn8MKN8+9CQy5g/uom2uPaYyzDluQTifO4AGVFg3YYLB+ph4ji+xt7YWEI3VVrD2jpVh3rnXgKNj+2PQ8/m5EcApekZ4giRSGeSrcJAInUhnUNK9YMDi/\ -RItfYKUXoBZ9LO5D7QtobfRihh8XEKgHfZhbgKWqgSsi1IQhij6Ch6RKeoUbd4g1Ne4Pshh2e+AGNrD1ianyMsrpF3iFAfpc67QzCiofQCvRk31hRcdYxDqZsJbUZB3Q5kRcfZmMjPhu7OdiQ1dE135vtzQbLmQ0\ -FlYn65g55yxjiclz0JAds1r+SWY1E7OqLzWrm6xQsew0pl3IP2pWEaS0Y1ZHS8wqp4SvfY2C+cB7lewTAaRNtczCJv8dC6v/JAvLGiVcNLKQQe+y0Fhsm2UhjIIGx8xC6EwFgw11fMypy8RUeWNW7RNZv8yhvSpX\ -OlYPddvxK/Rm0dxuQWqnaMbgkQJe80QYYGpqA/qGdSEzMnA0JVVtvBKHdfrIipOp7dEUC2LmMF6ea+pkWEs3tZslNqGDhISN4xQCt9zW1FqekEqClcFlfLFAG44jy8DQBgqKAZJyy++QKXDIFKiWNKydIivIQAlV\ -rn7ibHbPxwkSVxbnlnBogUD9lB9RNhcF9IU4PkKfkdDnnbN5eQmhuMTTFJyt9gMOsHf5ZCk+UbENVr8cn5MFfJ5y9XD52L80IIHHCusS2kjrkeSpcwezqcmdqPLBJ8fDS3HRJ2LHsSjtBCPJjzCbgnKB0iD7o3Eq\ -rWfpY5anQjuCrhzs2TVYce63M4buWZq4g+JxD8VSLFEevLO04m15GUndOJi+EuqRdDey+wEbA4VgmCrxG6mpQOXR0CY9F4GvSo63fFPCo6QEf0kl4KgmIJXVHsMhOwsBSnp2mdpeQRPAm9gFG/Q8mnqOFC51C8Oe\ -xrYZ77CvsY27c5M3xvo+ImtY0t9Bxz8sOj5h1HEHRTE7KV7Xr1vi9kmqyHUaiGix+BhbPY9BJ5voE+wJQTBkMhYVSwkaSURqLgJU6njMah2YMFDHv4pnEL9iz8Cer+i6CCo9xmLRB1aAM6TvMs/ArGMTlvcDwOhG\ -22QVjpFxH8LCgPuC+M0eZtxMliWPRevsiU+gb0TpXdljSvouwQKPuXb1SjbLmM0K3IPT5DsaDsv/AxzW561gmYeAuHPOGFSjz3oIpeshPL3UQ4jHXC5fYMXscpV5ylUSlzLUxGWorqtJZxNalSkZPesn5FiU3zCk\ -RWLCb8FPYvmB3ETmh0vdxF2hdrzES7hEM+5wtVEpUqm29nBzZVKs7lApJLwDLbAV44Ea3DJWyWt7OqGsJl/OYwsFY102Kzl/VCb/cU4rr1Zkr0CL6fmCCks7H1CqwVFkshto7Z3g+cSxQIg4sILgZzVFiSE09IJS\ -rDaSg9J/qAhpimOMhE5wbIwKwmIz2B38KDpw//6AHLPNvQdwWgiLVqXCr8Ihhi8oK47nQLdfQB6ypiAq0Kt5Of1lOWGc3fw6n3ubTqg/xDw9bnorOxq5X8HmihPgq/LcR6M8LzbR2oqgl6VUHLUBhjkvOREXqeRk\ -QTW57z5X2FTSDO9E+CC8cwBik0iGUfReKnEiJ/wxKMHxCagGiDeShwofqjcH7Ksrq7uLwpa50bE5cAQgX4/udMqFISFv7wK32oKsv2AghntJX5zkHBJMFI1Nf+NUy2U5n9GfEo5ps4v7h2uzeHWxFMvcRVSsffl+\ -9pB3hQgPh4t4uCok/dYCNd0rUKMy9yVFWVNr4b9u/3dI7oANvKHsUf+nom51TsKpyuYhT8R2CafH/SL0NFNOaJey1g7U3ilqkpW8tOdZs8u5GQxYjNnQAuuAyHNsF94qgSqfg7iA6xX/Dr9+pRAhw0eYAIIfo098\ -6AI4j3NUEKroESeTUvZ/EGdIwCMgjGJHu9gn0jSoEfT+PoRiVDLb2e2vCD82BfZv9t1kQ1r/TjWznAJc723LO5uKeCatcJ6pn/5GugPEyDyFndniYMmL6LIX8WUvRpe9SC57kfZeYCNDP7SIztGJPlnZAVT7hG88\ -fh4cd6rA3ANBpb9lRtrcEh/5HNbSoMsAe95B3WIeE5e0b99asdtEhefkZ7/pU6FFuHpJD+uKTkLwQeam33Xu0UYvV+ufkAWmQzXe7dNn0L8l4c9MV/36LrFqCed/tRz0kmPIdKoKGBXnLg5ekrjXrMgqTh7ALlMR\ -fiLNjzpAGJP3/UFv4UcZC2jUyx6LJgt6hc9yZA3236oa9uTBQ7ixjlW+jRwk9OUQAp/GUXA6rthYyWbz0xVGEfxFJ9t2J1WNSjlUgUUyFeqD42vsnZZ/2//bYP8XPlyVz+b7PqhCPWfI0pvEQdkoMgfOsVrDu8Hn\ -yoQ4+iElBrJazpXgF+vbYBUmjlmuRYJr8i61ye/KGaJ0A/Lz2sEgVjXVMJY2ShPK5Qv5JGPMGoaFvmxDMNlveubt4NOf2BsK4PA2d4PdjcLjqh54qTb7fAcPby8+1JAC4vE6ID5z+iJk033puHT8AV1rkDlleciS\ -dABxGzjt5gB29GCXLjPnYEmJCi5zdM7Wh9C/VZ0zJx4N+1d4OIeDgP6j3qEve4jAHBxkzs44eCHlgN/7fLap4rNGVBl4m8tA0LfNW6EUrwGe5RrDqBtgIlYGf6WVw3rwxDyu4eGTo9ns9duLTwgJH43CupIeEUhn\ -yCkFPqISWpCRxQr+VlMCq1fwNeeeseUORKJzHYJzvJBPkeAXEfMOOsb5w9ksGz6So2A4V24TUBSb75CwYhoNZfPIOaumM6gfiLm4u8n3QxZXPLyH73h1grBaYA7hDIV714UOPbzNwsPbLDy8zcK7RznNlghzLpzl\ -G1KIRY7Zqwvdy2TCZTfLZILNpnslw2Cwejjhayuw6hwW3BSdjngXg2eddn78qHNhA95KcXjW6eFc7aBCim8HK4FZSuZcKKOW34kDcbW5QCaL3TtjxuYqmydUT4MXnqjOpxl96sCO8q7Yd8nldpGBHI/FJZ3Bs9zz\ -mF86t1XIaTaqKT4DnfkJP2hUpysebUN5Qg91AK5pNvpeClv52GoO12EEkeLkLhT10I+2/3iXVssDHjGj1XizxuNI0hmIhwZT5hWkHprYfFJiwvvxfQvUHs9PX3os7Q0yVUy7Z9veBQCgLhgedNTcmzzwwOwzsrbt\ -gqU6n7M8TbPAOhagl3LwNRQkmsdxl9uUnB3Y8m0qjzvg2Wu+OwePiOA9ObyDiylvSPdWUjGZdSgsdUWZR+TGmjnmCRW4UuZekdRVxmO7TJu4cUXS4TEdFjyjei3J+ALPPg55B5z3ZoP0PrNxw4YYS7tGfL60oZ5Y\ -4AzLw5OUyHNxB+F5RyiRnw8/QI/1J1zUEc2ur9i9XhXuvGC4jBlfHw4GsRy9qXccCEgBDgveaWnGBx0JCjGnGgSrhxFDV2MCEB23wDS7/KAoWHAeT3SHPbD6jzRL9mSAfJA/yYZb/sZQyAvUvIyKT+T6IulQo3cB\ -Vknt0NKr/NlDMNotv5+dIvdbM4XmA/aUseAGousKrt5Ryc8cPWecmyu4hDLASomuAwl3rZAuATLUlAh6T8+rpk/evovE/s910hs1h4ONCQchHNfgOddPzZlkvXgvR6alnF/HrW+FX23ehEBXgzdUsaVC1zXfBtSe\ -AmrhJozsGZ89aTIjLwNBs3sPWBDsXOOiUCsErE/Fz32OWiiYzXZerj4TYwNfxBsxljnEP/lG7DXetaHzHzbgK3V/iT+QqbtcG4lrGwVD9sw+xxUugHJfSomQBmq7P4l0wFx1vhSEL5upncBcLCAH4Ef3mXHkkOxI\ -jATCJN3wLHlwGWRYF3HrqyHrQUdUYrOIVEMh2GLG+FzGCjmcORK2T/DkWuzK59XadlFAK5ewLfZOw8LeQKUWnEPE0U0CThuAejceQG3xIpqE1Xu8TR2OXL/itds4cRtnbuPCbXzq3uGX9e70y/tt96I2rOXOzHVr\ -3+Gv2Dyr7jjX+uW53LVm3DkXrXxpDioGwC8oPNR2oPVaJeheuAa7CnijHZyBkVwjhgHsr6rCR2Mjt2o0HFYoTFw5gQmF58+ZYZrwLd/dsFRNeXScFrN3nRreJ7JDwBtGdb7k06pmD5ZyBpvPYKo98S+SbelayC1Z\ -uMrX9oxFlcglQHTSEk97YQChSDDwhjR2fWCpcq9ZcfC7bO0po4WrheUVtmqmnfiCE+LaXiLzlnOziThpO+IJ3WT2LfZgpvjuDI7vkXeJaOlNHfanfsa3ZDQ2M9FCfcRZjaJ+xjJDz3+F5wUTw4HW48sl8BFtoWMq\ -HQr8CjlF1pzcFhaKMjGfoa3crmq7LVgLUuVgazv5pHbumQuX4LA0C2g4hQP6h26FeUbnAuX+IEXUecj39uF2rDkPhxXyo8FBgJmVmK9jCzBTaPnjceKbI2177sFoSDFFrKDLfG0PQoYCHdC7PDlWWy69zM2z9+sp\ -LUwE2xzkIzn3j+C32cI9b7hBiddSFOZsx7lclmMWuMN5hsYG3C0HTXC34EHqqNcggJtPUAulpUOqmK9uqStzlJdu22xMaPrFngJ+q/pa6YuUUS2mQNSPlpOEzpguhhr1mzltyXu5sk2tOWtvhBsFqO4KULbEg2oQ\ -gwaIuzxE8HTg3O3Q+6bibG4l2bHgEE9weR/5lj5Hn/IoowVeOV9gFBJW0iU3+xlLJCkUnaizP0Yo6x88F+OJXviP7IyUlptyOJtpjjIFEaVdcZw1uc1obZXPQJlai4m4N3AQJ9zEPZcNiQ47J/ekp8aeszOZGXtT\ -5rkDtPSvlvW3np75hqqgsHl9OMBbgX/5cFbM4W5gFaRxmgetV9q+qd+fzX93H8btw6o4K+ASYd+96BZ1yMjZEHQy/FRDwn+ICnbnVTB+a37xBaPU+DsXkIhdV9JH9u6VuAkB3mM8fm9+dT4oZmf8sJU5+Zk3EIcs\ -ju007hCki32QuLWM2ZjGdTm89ZlB+Yaopd0qPpfUNv7FPiPOwHxK+IlYteMtsnwy64oZL2+UJV0DtPgmC0yDNwbaX7mDd5RH+TRLDWKrxFDhf8xDRBCNdvT1UH5zg/Ih2BgZmPBaallA/4axhUx01Gv3jsJ2z0i6\ -RT9UOtZp9e5iVr258QyYay8D96pZ2+jcHlj0kje9MbVacuO26vXv38Id9tpRrx332kmvnfXauttWPXg6J5fVwG10erpXeavjxUu//7Q/dUU7/EoeuoqnruKxfju5op1e0c4+2z77TOv9Z1rdu76XtfVn2/PPyc6V\ -f18rt8lX4ejsK9bdh7y5Qgv0IFc9SFQPi6oz3orbuOE2OsPecRu7buOF2+gQ5ENP0/TgLHpt3WvX0RIpUf9FKf6ztcC3aolv1SLfqmW+VQtd1f7KPxXY9JmRQHQ3+MToiCUtNhsmc8Ya5zGMpKnL/08Tiyv12ct1\ -neIoDdsQM/v3/wLWvxs5\ +eNrNPHt/1Da2X2XshJCE0Fq2x5bTsMxMwvAo3PLYpHQ3bWPLNpTbdpMhv03K0vvZr89Lkj0TAn3d+0dgZFvS0XmfoyP95+Z5c3l+c3dU3Ty+LPXxpYqOL6No0v2jji/bFv7m9+BR/093f21z96sH04ddv7T7q+DT\ +u91bw43mLn2mvW5NN0NbwCwT+pJenAwmUKt/K+8bAs0DyPRnohkGULtOk5XLOb4szC1eRxnJr27am97AqQe1HZAh6WFi0JDhqh62eggabXmwdqjSNYL10gMQaGR7F9BovEZhEZ96b6CzqtzQZXS8GCBHWxCOz+Xn\ +0+6fxmuo2BvCeGBUkddQrV3EXve4YIAiH1QgVll70EUedFHvpaG57Dxq7KFI9XkgijzWw4bMXhmhUUd4rb1G6Rovsddk5zH+F32B/10+sOzyiH9V6UP+Zcxn/Et1EzQxN2pd4K/X9lk3SC0zFiAHyNWTxxsCEg8Z\ +EKiwqKLrWSpieuiiut8mCsu1EAlIC47L/e5pXM668eNyCvOV3XBtXN4l0WlyGs1YFMEUMTzs3lYJIxDQA3yd+QIHIMVfhjl8rXlWbbYD+H7/HvWOVCB07SZRQjklD7d3YO4RDWkALfFM4JeFjGnSulwBKlKwZVRE\ +yg4GVImjdGQf4NA78A+Plg5Hu+o5wIoImcqPZ90PxMyZ/GAUxRUDwoOZdhXIEWMABLLDwJqFURN4Knsr3QQx/AYnSfproqcqDqfAJiF/BECYdXw2nj3bj8twg1gGJlEmyUlcVTeLznz5lgESmS4GCQyBv6Jw1M6g\ +36Yj2iZ8EZbhXBiDidbB82yffxvGRpUNsSFMkwIbhzBRzDTX90g/opWxKw99mGgwpUbwY9QhVsescHNiYZUT8xSgpBTP1TQ0aGmuAEagLctlBjEZCC9znMMzCBeYgCIh2OAzjXooj5+1AnDGkADg2du1Fj+efytP\ +9o9/btfk08c8J/SpfQXW7mOvM/z9wpsucRAWuq8six5wUfaOIAMst2+9IcTWZfwxqD3qNb90o1XeaPOf4HlHe81aVpkBIgqaa7NldYCrm8jH8KAD5GcauR3A+ZlDgs5dF+UDMJPnoffwG4Eq9uhaK/hCJTvdhOfy\ +LKJn3Z8GaH8d8EKfrDq74b9L+u+63yBIYx9XqgYbIGJ2wrossxa0ZczF81Lenfnq6HyZBZvuy6YGR4QkWGc/WdO8M4VOZ8NORyT5qsQFXdaggXHxn9FX2jwZAQumRy/AHLKmjcEKaVZuGet/54mA1KFi/mFpuueE\ +ziaiuQzO9Tn/yP9Ga4A50PgtD03LKK9aRrZyGUdsWhqg49eOBOCh1LGI9oZF+Eth9pYxLwSpWqFoLTT5YunVPr0y2X/5xN6QT+ZPUJ0/DtY94+ADEgvfeeI+v8vzwVgpT6fibpTuv+bjBpqLFvgbjQVIitL51Mcv\ +DFf4w8UscJE3bkaugRNk9H30Dui/58QdaNyAb8giWfXJwxRgQZD5xTdo2rmbqSn3Z47y4H02zSSE4fLPYPznDN24Evdjxj9QVR2C5hclnJ8cojE6gIdPD0bwAfoek2QEcBkxK0bJmkcowB2Q81seXiQGcGjwcKOy\ +5PgcVIp9q49Yq+mY9RAix2Qjp600qRBii3VHYfSckWvmI8t9X+FXm8J3JLM91ouyLWG9QRzEvYELNvvTOPYnPaXyXjfLtBvevDjylEQVZMoR/JKoZkzeZ5fW/EtxAOfPWbwml6XNsx3oPqIIyYepsIxC/nzB+jRC\ +OLe7RsFOuf4ypFY03v56RF8Z5BnQVu03BBp+kMw5HhxbJcur156Y1Q5LywglBSW+tECM/BGNQIePz9mJxqYZv/X8DHEj2oqVktNjnZUxpXXUZIoWXbLOSCUo/jOhN80cpTCQmOoaleYGMuc8xBhceAW4bi1nXy+e\ +E2ajNBaDhrM8ZEsqbqDMpMQpytxwKBgmoVXgauvhigKSLHroPNmAidOMEvTvwPtORmsgE74njiFIb7w78PI2xqDwfjx8H5LbDbyGH6jhB2xWjB/+4fQ0cTKDf9OXx8fgp/0bRpkTu9Hnq/3NBJ3NZBQzOlCzINve\ ++yezTubSIlH0cR51iEqcFKlTmOUtZtCGXQtg2DQgn7htpg7hVRwyfyoORpqKOSoJQd/Ei+BWVd6g6Jjt8c2cVa9IXYwfxCVMM37C7nocjM8kZQAMFdw6/ZKteHlAMTl47nX531W5hYPsTF5yQNoxT9mSOKvxHBy8\ +9KIb0vLwzwQAuKqNWexQLw3UUePNH2G2cmNRruOo23svQLO+B3mED9LXoG1ArVaJx7swdtrBrRFgskeb9B7RETOr5i3zsq+FgZ0Kkhr4X8cFCEtBEV+Z393F0Hn9J+rS/dxgBwcsSYca8AzNWoSpq+DfjDHDBhQN\ ++sPqW8KZqSmjoDMXWJc5aeEGBJXSDcEpjQLrMm3B3mzGfxE/oMHmvg8Vu3RTr+8S/OgcNDD53g6D48c6OPKCVnbjaY4rM25lUfKNXZG46nYZmVvG94NlFLKMZJh/E/mIgn96fQz2Cb7hRwBBAgmv+DVbiugGiNKb\ +cFZGz8u0Kj8HooEkMD8rio6WNASSfRZEz4O0CrBTkBDXkxg2pKRGLTGnMf9+OkpFXPUIg66nf4cIuzqUIPzsKfMWZqIwzsGUwKvcESUaTyaQ5hFfJJuAICVRC5xk5jyUuHKOFMEdGHtnvyC0zylX0UcjE6TN7txF\ +um6xXfNfWv5jrg1Hmyy0hhYXmSSANTZFJcxLw5iS5rNkjoWuoSyP53CJotDlcYmc/LueiCaHAL4BMQLBRZ4E5xMzJ2ebhM7OwK53S6nyUTCFJeUkfE0yJesIS2rro3ANTfM6qoZ6DzFw4wMYKCwGtthZMC+OwJyW\ +3Ckd5A4te/8J657Lolmdwzo4iTfh5QKN1Hug3IgwpSLnE6vsCTk2LXBmXeDq165c/UKWjgEEjmOOyAa1qadP7Jr1n0Jr0Dpo+9qAHU2wYxF6kW/C3RCYbEZGyhKaY8tGT2XlQzLtTT+e78GOgnrgmJoyO4stQyNU\ +HHg5BR0wneopMUpbW133JnwUCpYIap7aebNTCpvb+k3yKAn34RuL7IA4i0ZWMrKRkQUPgloF8LTZvO8oYmpY0ZDgCpwXYRe1gJqkZFnbeRznX8TH57u+FyKJzzoKMSVSsJ3R7BQOkLjzdi6pa0lfAc9dJ3EDnttL\ +jsi+wqr/cnmjzm3kRK7BvZZz9Dk2PB5zjOfFr1G0tz+nXGMUL+uVTqEUAD3QOloEEFpV7eKeAHjoXEGyQ0+oUUf74DOcrKHncJMcLEh+ISFqL6eX0LPGrJhf4/zazj8X7vNU3g44UOcSFr1zfv8Kuu2QBYX5Kn2F\ +VCGtIBPaLIKtpwC6wSjoHfxzQQnZSEGCLb6gVDC1stugtcDjN4CDnEz4At2ugRWvIxJTZ8UXQSzWm+w22HCY0bw7PG05LYQypTmnAdDGnYwv5sNob7Ae3GVKOKGKDLLhYiWdBY6rwlcgRDvsoBeoEmbwLBbPc/yB\ +RYFLvLQoSZjo7QtF4gyfuCV2K+7WDZjLZbdEz/aFuZIL4g+Mik18SvuEEXuiRTqTpGkVcqDY5qFsXMiuEtDZnA/D4tkD25XkTGsZYhzTnk6jdzlah+xHLuO12w8WB64zO++YQsRgQHkpuyx4jyoyDK28faRFX/Jp\ +MGMtesaYvp653rbppaTAb/VnJIEXBW+ImiT33hqnr/kFbp/gcOBrqcmcSQwIazAMjUYutbrCRXiAvAhpuvpRMtqA7rAzBUkdNBpVBupaBd85SLqYGEF/jpvSPR79dcigQqWOBftecyTpFWsV7vwmJww8uyMyMCb+\ +f2Aagjla5XTIlB26o/Xt9ek+Ych5os5YWze1Q3xwG216iIkX3i9QJkHSgHBi3k6dfeFT5XQBTI1CPjm9BPu0AP/3JcQh6kDinc5gKZ9sixIrEtTzZd1yfHOK6oSWvX1800txRerJsAPBjFTCIRGo7a0ZZSJwywjY\ +bcggnRyqjj02IUmK6hkLPXgqHYNwqrC8jZB/5myhz0woemOf6gD8Nu5bJb4WQimJZmvC4AczQz87ID4jM4hhfSrzAJ+pLV6uM8HsAGCaZ4Ho7Vol2fFCg62ElgaFDNm7lpwnVLhbROyiPOB9LshZyXLRw8zW2XJY\ +dCtyHnB70HTuWChwjEh7o4UHccacwnvyTBVsqOFO/xWWOgnYdzRFxdt6hcyMFCxKzakEQWL2kiRHYQkG7pwnkliflShfB7DVnyxKfZqPOOGvVFzmcZDNghzhSBdBFpebk2Q0C/TpGXL8waLMZqW+T3memvMdILo6\ +z9XpA1pKER247P1komblpgs7EULNG4ZYtIKpOoR91i1o8hYGmAWbQJ1k9jW0FrIrDzoCQkVU5DbLDt2iUzCEkwvszCQGX0HjlCEOM5rZ5FwTFVNBicstdsayW/wpLP70APh/QUmvtp3cR2aFpzh+51ufd8uCmVLJ\ +JoAEdXCHf0d97s3VIRKQd9Ehr/sZqWmHaBB9Y81Zzs5luQhyYAx9ihTAtHwU6Yils0AgJshHpwlViRTxC6cJi8IXElW4BLMrMglub2y55HmZuz1i7bmjoKpr3nanb2U/GvL3AHmZhfJqS8pMKmL/Bh3T9Iyzm2Z7\ +7TRkxNktHuYOkJpC9qfV5KESobkP/oHbj7ccLNKdT2i3NudnGDHdcIuxBUaGXAVazBY5X1iqYt6TG+nZW8zigNSYCDI6UfoIsFwmhOzYZf+A9ZtE8pSzW53/Ax4venApB8GZBJp768NCmw8H7hifJRy7F39h7O4I\ +720h1LkXSuRLqb2Zq5vQ1e3eHImrnWH3Zx1nXRvRxLcIKrGyClgINLLPQguff2Kff1BlRSPmH6oMiAoFY2uqbPqZIyTFlSSGuSFlwqtKfJDUUR/8TEv9EE0DTR5yphOpj8z1hGt3Mlb8bmcCos1ODjdsGQS9SHpO\ +nbebjl616lT9MYAJxQWtoWQJugpKkgOGdq7dX2EncWZvRnVXbYSxGehTnZzEIitSJwRd9E9iSQDgKx06ZcSf+SfmdRrCJc3d4cfueFhHKiw5ZXdX+P9jk1bKrB0RS+hk2VG0/J+v5v/5CuY3HCdE5ECsL4uBY8FI\ +W5HI78BUwTNaKxGzoO6Gdlx1yRs1qsCxLmCsZVwAXBdA8wtY4fZFAO6gmX6OjL3xiMY473EGaXZiDh5QGdGDLcbs52ofmeRg9yAmHKlrwu1DWolz6jo3jsLtd63vqM2HUcEZ4bo1MySSwlhPxdtE4kzKhtr2lbcX\ +kMnyl3jpBUfbbaugLsAEVE3TmuVcP66iswpDyDuwA6JBy/USasZAJe/AYVIpvcJ9PUQdFkiYvk87DL8DgrmF4jxMm1dJQb80q7HWbFLtHmqACp3aF1KmyHaxyWZcfmfIRqDlSUSEsp7wbj0txJquicr9yhV+tYVT\ +K569BXcqgqqglLajGwgfi7RnZKs/xcjOr7ewrFyxmjWlTcrfamHbj7awNz5Fw7zlbUx2jdC1rFdZ2ewvtLL6j7eyrFLiZUML2fQ+70zExjnewWhodCIGNqN6dXVywknMzBaOY2btPVlB7dFdVWs9y4fK7eQVOrVo\ +dnchw1O2E3BMAa9FJsSf27KBFQa2nxwZeaqS6jleid86f+gVD8ReDQ/bFgwho2uSrZWf5EW+8/1k2FbOIYYrbAWpxxNSZLA2uoovlmjD8WQVWdpMqc60rXbDHpkij0yR6khDUlMmToKBEqpaf0/CMvR1osyXw4Uj\ +HJogEIvqHcrlsnC+EAdI6DMW+vzkbWFeQSgu/7SlaOvDuAMMXjFbiU/UaKP1j8fnbAmfZ1xsXD0Kr4xL4LHCqoUu4HrImG29+uwytzkUVd1/73l5OS76VAw5lqudYlD5DmbDGtDKIvuddS6dhxlitqdGQ4JeHMQA\ +qOzbsJsx9o/npD0UTwYotqUUhz85WpEkxDKSugWbF9krISAJeMssAxVHVSlIphL/NvhVlEdLW/VcNb4e/AdevKmgnVXgLalsg0ev6gMGQrYWIhRzfZXOXkNnlfexS7bkRQLldW39IacwHqhrl/KOh+raeju3eX9s\ +6CGyeiXlHfW8w7LnESY9Z1C0spfi9b26FU6f5It8l4EolkrkvTvwFUy2jZ7AHaEGxkzWlEI9ZNRKMtJwbaBSJxPW6VSPf/KD+APpK/YH3JGNvmOg8hOsIb3vpFcjfdlf6bkEdh3bsDxIRFZ+xE0m4QS59gEsDPgu\ +St8cYNrNZlqKVFTOAUcvlbmVAP5pkynr+wKkf3o85hvVa9lMM5uVUG7YcD7DcljxB3DYkLeiVe4B4s47fFCPP+geVL578ORK9yCdcB19iYW0q/XlGVecXMlQM5+h+g4mHVro9KUk95yTgOq/ZUDLzIbggp7MsQO5\ +h8wOV7qH+0LsdIWHcIVWnNJxMlobWubdA9xbmZXrU1oWvAMlsJtqLPGDyFhlr92phaqefTyLLZWS9bmsYgcXHY0/ltGq6/XYK1BiZrGkwfJeB8oweHpMdgOdrRM8n3rWBxEHFhDL+ssK4+eICh9NF8HBmQA8llCe\ +YAh0imNjNBCX29H+6GtRgU/vjcgp2z64D6eIsJZVav8MDrHzgpLjeKx070VAFUVQzBGZ9aKaf7+aMN6eflMsgm0vzt9BHwE3vZUbjVyvaHvNi+5VdRGiQV6U22hpRc6r6ogAheDCHr+ciXtUcaagnt3znytsKmnG\ +XyT4IP7iEMQmkxBI1B4zfclVM3joisYnoFqsAZeHCh+qN4fspysXzZWlK3SjU20QkUDmHl3pnMtD0KH4kbjVVWbdwSAM95M+Os+5QzBRJDZ/w3mWqxI+4z8lFDPeRu5vqM+S4xhSLvO3j0HD0p72Dm8NESIO/08Q\ +obN+sRoVwK8o0Jo7I/9p28A75BG4wHsGC/2jom5QPSCgqmof8ERsmnB6DPEzrppBe1rKWntQ41Z+ubNWVK6SV19NSjBiKaZDS6wIIuexW3inCOpiASID3lf6C/z6gUIEjY8w+wM/xu+5Sg5cQ85PQahixpxNytkF\ +QpwhAV8CYRQ42uVTokuLKsE8hVrVMVXN9oplM66AtLmvX9l3k11p8wuVzbp9/00mireviAfVSu+Z+sd3pDdAhOxT2JktD1e8SK56kV71YnzVi+yqF/ngBTY0uqBlcoH+8+naFFAcEp7xJDteR+ACI1+3h7t2oO3d\ +EeBndAELadQ/CKlN9NmoQzmmKmnXvrNfnxP6n5ODbYbo7zCNO/ml1C/dlkPR3w8/XQS008vl+6dke+mQTfD52SP4vqPdt0xQ8/oOMWgVbbnzQY0caaZTVniIDYl5+A0JecNqDDgQNkVgf6mM35POR8kXduRdf1BY\ +2EnPvXDfOOU4PHhjq57lDBvsvtWNukPOwa1NrPRt5XBhKMcSWDcrLhQvt9b08eJMWmT/TXK653ZT1biSwxZYJFOjMji5wd5p9d3T70ZPv+czV8Xx4mkIetAsGL78Njty49SeYceSjeAWHzfTPLN5QFkB3ch5E8TD\ +5h6YhplnlxsRX0PupWF5bFs5WpRvwc6P8YrosbKpgbGM1ZgvoZt00ayZbPUifOvZEPth0Y09f8HeUAQnvfkr2NooA04yQ2ZDrQ25Dx5uLj80cL4RH2oBEMn+pczrneVR9Yr+wizR/D4DBrcK9D8b0Q0KmuW9MLIE\ +GBuPLe4BP94ewY4fMK22B2h5241RjQV85eYOwjoGRNtwNR4yqXemCNhjPDgq5o4Z2OOG7sBra6+0oP4hH4mq+YgSVQ5+zqUimPAtOtEVzwLOPRUGo6xbYD7WRv/lVWnmsoYHj18eH7/+8fI9QsInqlq+ZaV3rrj2\ +LxPgwy2xA7nNBPVcL10slYQtvLop5h5E4tJlBXgokQ+f2GJ/4C0wY23x4PhY7zyUE2Q4V+GSUxS6ywmoQkT3pXfKzWgoMYBEKKQn2uIp7w/SkT98F7ldQ1R5AnMc7Pev1jBxgJdnBHh5RoCXZwR3iU06IixovXIh\ +C7HICXt+sX93TbzqIhutyH/zbnvYxFNyo/WjGV8TQbs6Um3uPoR1YLlP3nv8kNWHdw/G0XnvC+1laGKKf0drkV2K9u6vUauv4IG4295Xo1P/ipqJvTnnMWdEmrv+zTzQVVNXD3bUWIr9GilxktsvakLsOTwrgoD5\ +r3c/hhyCo5rjc1Cp77GDXAHDn4ZrLE/kvY7AbdXjr6TwlU+GFRmwcqL+B5A/xX+7Lyf7tE4e6iWzGJ54bR8lkudADLSYSK8hKdGmtkuFafBH9xw4Bzwz9Qz4LGOL7JTSZtpe8C8AQOG/U2bVdteRGA/YPiNr3C1V\ +qvc5/dO2S0zjAPqGD8qKZvMep30+U3K6YDdcuoYEz2rzJT14iATv1uBtXUyEw+GOWsopdY+2UnSkAyI0VtQxN6jIly//Lqa+Gp64ZbqUji+MHneZuOQZ0XvC6fFYE+rflOI0dBDze8zALVtojAbGfCa6pS+x9LmV\ ++Be5Le0hvOiJI3LyEV7vsvmY7U5yfHONnQiUyOkjhsva982d0SiVwznN1IOAVN9OyWarnRz2ZCfGZGsUrR8lDB0epm3RsbNna9s+PygKIbzHM9NjD6wQJJ2iH4+QD4rHemc33NoR8gI1r6LiY7knST5o0O8Aa67Y\ +MNXFswdgrjt+Pz9D7ncGCg0HbDFjOQ7E3jVc86Oyb9muaufutXxHRGum/QOOcDsLaREgQ0Mpop/ped0OyTv0ndgzukkao+GSwLYS9oM43YBn3Tyxh5jN8lUe2kihv0k7rwt7bd+G8NeAd1azjULPttgD1J4BauHy\ +DP2Mz6a02srLSNDsXziGJ44QHUVPDliZig/8HBVRdHw8/Wb9mVga6JFupVj7kP4jtJJv8IYOU/x9C3qpvRXOgFa4GSvLG0d8hOSDjOEDKJesVAhppJY8DvkA89jRShA+bqZuAnsXgZybH99j3pG7T8ZiIRCm3F2l\ +FOGtMqtBw1KJG58M2gA8IhMbRSQbCsIuM8eH0jh67LgS9lbQKU59Gb1e4y4Lae1TtkPfWVy6G6+WCYVIuk3AGQvQ4JYEYNdlNAm7D/ibPnjpexWv/cap3zj3G5d+433/wkA9uECwGLb9W+Gw2lvbu92+xF+pfVZ/\ +4d0hWBRysZtyJToOrXzXDioHwC8oPdR4oPk6Rejf7ga3MuD1eVARJZlIDALYW1VliAZHrmloOahQmNLywhIK4Z8zw7Txj3zhw0pVFfA5SE3KzhX5Ppb9A95NaooVXeuG/VfKK2w/g6kOxMfI9uTTkpP/La7ytQsm\ +6kzuDiI4IiXhgyLBwBvZ2P2BpW6S4VTl4S+y76esJq6Xlle6qtVu4ktOlxt38cyPZAxwJyFhnUre0G3m+vIAZkrvHMMRP/ItES2DqePh1M8oNEcBFZteHr7kxEfZPGOZoec/wPOS9xc8aCVMwke0uY6Jdqj9gzgG\ +NUl7+rmwUKLFhMautLtu3J5hI0iV46/d5LPGu9cuXoHDyi4AIyG+A41uknlGJwflziFF1HlA66xwr9aelsOzDuPRYYRpl5QvcYswl+j441EW2gNvB35GGtJQCWvoqtg4gIChRCf0Dk+OhZiQIVOrbudLPNcKwYRN\ +EPKTvEtL0N3TS7fD4e4lXmdR2tMfF3LBjl2gVOi0LtzuOGiG+wn3c0+9RhFcl4JaKK88UqV85UtTuwO/BSt6Dkw/2lso5IRhu0LZf1gZNWIKRP0YOWfojeljqMXKUO1Q5fawDefzrXCjADV9AdIrvKiWbj8UIO7I\ +WdEnI+5TLPepOd9bS+osOoIUVR2847v9PH3Ko4yXeOViiVFIWEmXsFZ0TieS1EhFz28glPMPnovxRE/8a/ZGKsdNBZzctIedooRSszjOBp+rGW+s8ykpW4gxE/8GDuzE27gbsyURon+noP3S4JfH5zIzfk3Z6R7Q\ +8n296nvn6tk+VB+FzZs7I7yC+Pu35+UCLiJWUZ7qNM/TtHvT/Hy++MV/qLuHdXleyo3FNkuBOmTs7ZJ5ewBUYMJ/iIovOSjAu1cjr4Ha0b7JuYwIL4qtKejFRt3aN3yrMXXIvIbX4ZL38DGS1V6j4nBzeQav8YLi\ +1OFjvuySLjquSD12jX376+oRKW+y+jO68o0bsB/eKnlT8yE1RFRLEZaSS3QxJfLhSa9uoEyNV70pjG38h3yX7tczjy5YLS5di9ZDLm7UCDWKsX1zy454/umQ/u4G1KkzIE/sr7G3hqW9kmFaenixzuDobP9QpV8g\ +RGVmvdbgHmg1mBvPjEWDG/Tstbmu0buAsBzkcwZjGrXitm81+H54A3g8aCeDdjpoZ4O2HrRNv60G8Kje9yO/0fvSv0ZcnSzvcf1pf+qadvyJPHQdT13HY8N2dk07v6atP9g+/0Dr5w+0+veMr2qbD7YXH5Kda/8+\ +VW6zT8LR+Sesewh5e40WGECuBpCoARZVb7w1v3HLb/SG7R1l2/cbL/xGjyBvB5pmAGc5aJtBu0lWSIn6C6X4z9YCv1dL/F4t8nu1zO/VQte1P/FPRS6bZiUwR8mj46VjlrTU7qEsGGuNy4OtsnlLlOmt9CY7vb6P\ +nORxF3HqX/8XohBRvg==\ """))) ESP32ROM.STUB_CODE = eval(zlib.decompress(base64.b64decode(b""" -eNqNWnt31LgV/yqOIU/I1rI9tsQ5W5JAhxC2XcKWEOic3bFkO4EtKWSnm7BL+9mr+7LkmUnbPybYsnR1dR+/+xC/by+628X2o8Ruz257nfg/5WN4yvCpOpzdZv7RKP/a+l8/u3VZQoNazxb+Lzxl98+O6SvObP6f\ -mQroZTRBfioTDrLoKfpp4aib+M+OKGnY09Jz5seyfNh7F9bEXG2ssJe+J4r8ujNbnF2v8o9kgLjK5ST+vUx2svUnybIDYrULfKrKc9IEnrs2kplb2tMY2jMMIBNnX+6W3vBT4Vln0WpQavuYCMgvo3NE6t4QbvIU\ -PgHfT/zDBE6iw0m6hr42E5H++RGJqBdRFYdAFj698fNg1J6nwNNrULU/m5vAjJyJguoKkHZ6cO5f1aYfLyIVZ/wMx5oAhdMwGHQFcpvQijYffTy6HGn6GOW5YKL66DhlVbvsUQmEjky6JGgRItglspstGSm+mCyS\ -NaxBb3KPI8MR7ZTx+8GBPB0DE7xGjUiXA+mgLJQwCKiGh0N5GA56Di5x8gQsT40+7Pg/VZIsWKE5eKmr7sEnP7nraLJV4XkQc5Nv8QP+FuSRYAtobZ6cY/sA6+5iq7cRWRup1NC/Fn78PGzn2AON16iySzsblioI\ -Aj6CrcOY4bHgQvnfWO6eH+1GxznmL9EGyLmKOGR6poY9/hgv13RWPF8WvLpFD6/J7ZWZEjZl2Vc/DezCf1Egaf9lMfZhJr0CAjBQDnTuxgsTGGrVAI0LPnoxEso5b2vTLSYMAOpV2BrWOjyXghfe5NzYHN7SkjEm\ -vdwH62IU9H8aJHBeZhPH9laAv4Onl+9+eDmb+Tm6ktUdSYhc86lf7b8okbK+T7JD6MnJ9ETsMciCWlQJUioSz6jNE0YSxoUu8mntHqVkU67c/Sty9ej1W/gHWIajgu+N0WAcotB7P6Ef+Rjz+Pg+nh/mpySJJoQu\ -kWzTElzrKAQErr6dXYWg0znyI0RyRZba5AHlwX+UAKAi4bRdFGHyCEqLZXcOEbpJYjTNOTrafINngon3q6gcy7LJ7pGRLUcpNCAJOpnE8kbdRmxyUMTjZXLUE5iZf4BX1NVhCs8FcgYe2UBYMXt7tK2mOSEb0OZk\ -9x3bC1rV/uyK6bsJ82tG/D4krBnCeGAIgBnVlpMR4rSOdAHfWzvOSEaCkTmObb0Y08a1QlMznfq/0Gl5Trk6ZzVDoJM8AtpVQBChJ+/KppxeWQGvnLF1bcYmz+fxiwe4Fsx94u2/1d+wJxgXDUP8hPP6l2pjg3gA\ -qEIFR1nkyEmrgJMQ/CsOJehFL58AoreclYiGVJgWUwJvgh1kvmVHXOGiWF57kh4gfJ45MlZ0CHZdG60GYG8ajgndGh3CuIlSHytrNoOVooWQ3BGd3LIWBh+KrBN2dO3/sojLWF+f4pdF/HIbvwBIXTDWAZ6zi8AW\ -l+wsG6A2E+GDHLHp6XxaPwdzuA6SQi+tHs6uII5oe8Hz7tAcng4B6JkXOAzmUw4bqPQ6nhIv/TPsciroBbq3wtrrD7RIkses2o+StEFRB44ETMcIdQEZz/xS7K9KQCEcbABgVoMNY3mUYaAUJq/g9NVHYsM0p9PZ\ -tXCyKfKY+x1xC7ZZDH9sgQhxvCPxQjK2KvE6bmpmyq4414f0w9Oa0NQ5Thxwt5ft+kPr2n9uCtqii6sJlllbrlee5COK021M+vIdPOIvbGU1ygfqsGo6u4IDT2hik78QmOppa8LHr5RMWs612nprOtsmJ0OR9J/g\ -YzJ2y2YFWrtwFFyarfNPlvgkSJz8+yGEa1R5cZfzvQKmFOwLB2rVG5K47ijJGkqhO6o7XxB8f3z4HJzvARYBJVrA4oDNh8oEfSBl/JJWlgtEMEM9AvODUQW7lgHCyywqT7YjCmVUrAzbMwvCdFRIAQUbyqWvl7xv\ -xzBzLjnhwd/3MIjonGOJcw/x6Tv6p6SaEBeD/VINdpCRPn2MOR/Q6juKtzhVlbQc6hXFya1kkl6iVylEK33EqYiAwQq0bFAowyqsZU/EGIs0j7CeeJHWoN264wwRd3hByO1UshklhRNBhUPmphO2OqqbhmQclO72\ -INN074a07XkIfd1Kpgur8YApmTgMRHVi4Y042UxGDZSCwfEuf7ZrxOHMKMPUXFQ4gh7wJ5cn98B8UniMmwYJwQokchn73V1wAvJ2fMRWveIto0Er/s9Sb6Q14gZf7ddICGuVztNriwcbTK3zyrCo2xM7rqABscct\ -o1tW/2ozikdVZQ/h8JYCVqbS09kCh9TuaU8FtKpT/lrINOw9QVNCzdOkh3aL3gH3i7jJd085958EG9FW7Aw27UgRaAJEnz1ivAXn0XmyEZASklNIcpQapxywoeM5Mt4BKtIgGDdi4lRMcjg4MdjmcAwjaWlFoTHL\ -LvK/4Bm4IB2govo16SsZ72QQ6mLdb8k4Rgo/1iD+9FI1V7/j6xkf1pPR/ZBe3jZ2sBAAjCWuCIwuMD3vfw2MaRdRwDm9LJyS5whNG9GcfhEOJfd2ox1dZWi7HTDlYfCJTIYBzwsXif0St9/wplwQyxI1mqYriacu\ -jRhzzJhBTOXC2AduiF7Vvt9zIWMZjVF1DqIwQ7iQKUsbbsbfimhTqDDVlKxVxAWVL1H/VpL6fXTdQRlbnJKILlnWGE7LOHptEhz4/GmazFOyblXtcYnpp9dRqMTmEpSQWt0sA8QZJQIKHBBRCdPhnDzBuftEDWqD\ -QG0O3JzRWfqu+YndKaoBG/712Lz8x5pNW0TO+VPYaNjxGbdiV0gR85crdN5B7rTK+Zmg3pTSmWxIzKUtEiQ9/TlY+zA3Y6u3kTI6Jzb4bM3XthZVNZFJZGorTMuquXSpMM3AltZzBpAmtjLH5bgy4iY/cudCU/N5\ -m1CqsaGn5dblRmB0JXL6ENY9gx0PonBbLW/YoEjO5KqgjrZMSGKKSwsHLe3G8D0EOCPEJWw5q/dQdrf5A5iJO4AjFPt85uoktCRVTeuIG9TfIhZEdcEOj2J+TrXe9s5bAnnopPbYMurJYM0A4/Nd6IJYAm1wZ8MF\ -hBVEZ7lJ/ig7c9vV0CxrwdrhmFiM1nsUp4cIM2G8g+dS4kDF0Yal1eCVRcJGAyPY5K0SmV9HjCs+TUYPyZwgBHfPdqmzQ8KaluMSBcSIfsqilL7LkjAHk/qDXKZo+a4vgslx1WixlbwD2VT1IOCuJhjUHBNMH/uY\ -gN00JNP9Mc9sCnGijSUnQu1PAt7FFz9CgGNSudaj6aNa78JRXMqk+8rizorYIbj/7aILssjQxIg02xpoowEsMZDpGcM5YCTtVwzUUAR1H8HEWrw7kllwOVB/+yci2UnVMT4ZEOoeDba8Tz06N/S99ijqeHUsXqTI\ -xtULqu3wDCah6zmy4JxeFLbEU7JtmAZdAUxPK24dxEIcBaV2HNFEbqtKW4a1vk/4lgMUbWqu//1IJ6+bZCI9ZDSI5XopuerlqqFSF+BfE0qFpq+RU0yvpngxsiUJi7KhhpHbkNUk4fuVIK8gmwhJhqpChqTKgLuq\ -CS0wbDJ0XK0UnKkP0arhPJYnyDPnu5cMT3A4LcYsho1IMm8nDA50tcSNZUvYjD0avG+qGM8VV2Hdmn5rwZc2EdNhzpSAOq62SSR4dzAEL8r+wH0gPGySd0gmgPVyJ/12yc3TODEHdIVzAd82oWnYxmImydo3/825\ -dm+Eor0r1e8l1e+TVNZbTp/EYg1bQsdXORbJfqYmBrhpl9/HTRqi3GU3oIRreK1uId9z5qYKBgkEwfFb7qw5NVyFaxj9zADAl0CAOGAqVipg7u0avunopbLR1BEHFpyMcS/L1qta9bK/AlsAB9KfJXiR+VgDoxIj\ -Ld88NXDP0GjuAsFcdFgOfA2ghuWbNxzA1sOnQBU7Ew1xh71+kXAb7hXw3qRiLIqamiSwzX/GgvrC6QHUFdUt6NbdUKise4yZNxzjqxtqlLUDUglS1rs/gLa12O0ZWs31DnMBaGWLIdrFV3QDHBMFRvyOTPuMslLL\ -d1t4I9etNsC1Ds5tJqtzcHyN6jQ3bMi4d+qANZZjglxnwEzbBceiPIwp52soi8HxtQyGK1CBnpIe+t6X3Jf1HEvjcDFsS+ZBs/FVdNfK1wLi9fSU85GpCxNnntUQHKcRKOgb8IQLCIRvQM7PGPQorR2irvpt+Twf\ -uTi8mvPVGEbifLge3Y57LItVaUgHA4tmAjc8/QDB7/m7k/QHRFD9himulfz2zSVshHaXb0Al1L0PCYz0+I36Mcpr9eVQYjo93wHmP+Lyd0zU4IWlCdurnKYB1Z9RTWjCrwgfQJSmCGaw/hbFyK3RkBPvMGayA1Lv\ -JA8yxwhexcLCjtlX6nPQLlsc9CdbKT9VoV87uvrLdu/JXkDGpdx+y6qlvLR1GIdN/P+ScO4+jcTHG3Zov7Is5DB2tDQNjITlvGQsru2HCf6/sZ9+WTTX8L/HVFaXRaGqUvsv3dXi+sswWGQ5DLbNouH/ZhY1f7f5\ -S0yomEyqQut//QdAk8Ky\ +eNqNWnt31LgV/yqOYfJaskeyPbZEz0IS6BBg2xIoIdDp2bFlOyFbcoDOQjgL/ezVfVnyzNDtHxNkPa/u43cf4vedZXez3LmbNDvzm94k/k9xH1oKW+XR/Eb5ptX+s/W/fn7jVEKdxsyX/i+01O2zExrFmfX/M1PD\ +foomyE8roUBFrehnhKJu6ocd7WTgzIbayvepbDh7D9bEVG2tkZe+pR35c3e+PPu4Tj9uA5vrTG7iv4tkV22+iVKHRGoX6NSlp6QONHdtxDO3cqa1dGboQCLOvnyfe8NPh7ZRYbUDofb3aQP5KbpHJO4toSZLYQjo\ +fuAbU7iJCTfpahqtp8L982NiUS+syo9gWxh65edBb3OeAk0vQdSeIDeFGRlvCqLLgdvp4bn/1BPfn0ciVtyGa01hh9PQGWQFfJvSijYbDR5fjiR9gvxc8qbm+CRlUTt1t4CNjm26wmhD/6JeIrlqRUnxw6qI18oc\ +cstE4kBKi/j78FBaJ9SNa/Ro32LYN0gK2QvcqaBxJI3hludgD08egNrp0cCu/1MmyZKlmYGJuvIWDPnJXUeTGx3aA4/rbJsb+FtOWLqgZ34vx5oBet3F+t5EezaRMC3928CP28NZjm3PelnqZnQscZqgigZBy6HP\ +cl8wnuwfzHRPj3Gju5zwSHQAUq4jCnk/W8EZ9+Llhu6K91PBnlu07YoMXtsZoZJSX/00v8T4EQ1s9iPLsfXy1mvmDx3FsM/3kcIGglo9gOKSr56PmHLOxzbpNm8M0OlF2FoWObQLQQqvb26sC69pyRiNnh2AajH+\ ++T81bnBeqKljZcvB0sHGizcvns3nfo4pZXVHHCKjfOhX+xEtXDa3iXcIOhm5AWF7DK8gFl0Al/LEE9pkCWMII0IXWbNxd1PSKVfs/R2puvvyNfwDJMNVwfDGODB2Tmi679GIvHe5f3Ib7w/zU+JEHZyWcLZuCahN\ +BP6Bqp/m18HddI7sCD2AJk2ts4DvYD9aoE8Tc9ou8i1ZBKL5qi0H31wnMY5m7BebbItngor363gc87JWt0jJVv0TKpC4GyVevNY3EZnsDvF6Sq76BGZmV/CJsjpKoZ0jZWCRNTgUu79PxxqaE+IAY5/svWF9Qa06\ +mF/z/m7K9NoRvXcIawYHHggC7EWxZaSEOK0jWcB424xjkRFjZI5jXc/He+Na2dPwPtX/2KflOcX6nPXYgG5yF/YuA4LIfvKtm5QDq0bAK2Ns3RirSfs8/vAA14K6T73+t+ZHtgTrom7wnHBf/1FubRENAFUo4Ch+\ +HBlpGXAS3H7JrgSt6NkDQPSW4xGRkA7T4p3AmuAEmd+wIa5Rka+ufZIeInyeOVJWNAg23SZaDcBe1+wTug0yhH4bBT2NrJkELUUNIb4jOrlVKQw2FGknnOjaP9KIy1he7+OPZfxxE38ASF0w1gGes4nAEZdsLFsg\ +Nhvhg1yx7ul+xjwGdfgYOIVWWt6ZX4MfMc0Fz/uO5PB2CECPPMOhM5ux20ChV/GUeOlf4JRTQS+QfSOkvbyiRRI2qvIgitAGQR06YjBdI2QEpDyLS9G/MgGBsLMBgFl3NozlUYSBXJg+h9uX74gMW5/O5h+Fkonw\ +Y+FPxCNYZ9H9sQYixPGJRAvxuNGJl3FdMVHNmnFdpVcPK0JT5zhwwNOetZsvbSo/XOd0RBfnEcyzttgsPIlHNAfaGPRlu+j1f2Mtq5A/kIGVs/k1XHhKE+vsqcBUT0cTPn6lYLLhWKuttmfzHTIyZEn/HgaTsVnW\ +a9DahavgUrXJPpnj08Bxsu874K5R5Pn3jO85EKXhXLhQq18Rx01HQdaQBG1AWoz5u/t/Ozl6TMZHwfP9AmP65SFrEKUJmG4U91cSvA3ZIWiiGeH54Sh93UgDQebw4QW5E+1QRMnKcDyTENEt4Spv0oR06eslH90x\ +2JxLZHj4r310JSZjj+LcHWz9TP8UlBPiYtBiS5dQJFXvac4HzPqZvC5O1QUth6xFc4gr8aRn6nUKPsscc0AikLAGMFvk0DARa9ke0dPinseYVTxNK5Bx1XGciCc8Jfx2OplEoeFUsOGIqemErI6ypyEkB7m7fYg3\ +3ZsheHscHGC3Fu/CarxgSooOHVGqmHtVTibJqICSM0R+z6qbDexwdhRnGk4tHAEQWJXLklugQSk046JBQuAC4Zxi6/seqAC/HV+x1c/5yKizERRgrtdSGnGDxfYbOIQZS+f3a/Mfjng3QO0GZXt1e7jXJec/5afR\ +dW84qHKkBtz7NvTqLD3iy4PbQj1xu9iHUe/pfPn2dDuEg9qVF5QM6H4W7q+GDfKGG1iegrqFXqRJfwyNXTDSKOvP9k5n4yqRdmnqj+zGmmUa0U4gdSJucziS7Wh8KsfgWcKBHUYDFQVIWsfhiiBfHzq7bhI6MVtC\ +M5hJPt3E7ML6zg6VHBSHthYvdZH9Fe/AyWzNENSXn5K+lP5OOpGf/bb0o5fxfTVO6CXjLn/HzzO+bEnQzaEpugbWK5DZClUEYRcoy/5TIMw00Q6IXn1YiBPysG0TbTv7IkRqEeDoUFdaOnEXbGDofCCTocOTwzlm\ +v0Lwj3xoybUFXqJH00z5dNCdiDDHhNmCtROTFY3OrzzwZy6lT1EfJfd42T5SapyycuAkHsujQ2FAz6jCIexCW8Hd70lOcIA2X4qn2OaIRsTJvEb1M2PvB6pYI1AsZskiJR3X5T4nqeV/ooQKfpCBGv1xFVnOKAnS\ +3TEbGkbTGbk/526zpuhgnLVagD89o7t4DHrDFhWlkDX/eqx6Xm04FGtQbvEQDhpOfMQ13LWtiHi3YR8IgnSzTvyZIOaMAhk1hPZSWAnMnl0Fne+zmM29BPU8KB4XDXR1tG1EWotIK5TeDtNU+YvUuTBKwaLYQ4aR\ +OlY0xwm9tmIp/+Tah6HC9U5HJj6UxPINcRUoXYFk3oFFj+C4P0V+ulw9rUZ+vJQ3hio6LyF2ac5MHMf6FLZ6ZNUV+TQsV+u3kLi32Q8wGQ8BW8gP+M7l41DU1BmtE89UZ5RWC2ngZWwtbD4hF7ez+5qgHmqxPRad\ +etJZO4D5Yg/qKJ6xriKLtpyCNALtzLpBszNJ6LFwa2lW04DC15bT2WqffPzgZ6ZcsYB2Id6gZJ/DDKvxuSNhpYEeLBOXicyvIsI130ZRI1kQKuPpao9qQ8SsWT5OcjC9bQMrxVWvMHNQqR/lIcbIuLkIKgdZsB9v\ +kOW7EIkhujD0GkJCMiDOvVQ4mvButj1Y0olMrATKkxUbQuFbBmuSCa2Kh9asmLPKbrTZ6Byu1TJrMQmI1c1IzMoPaZFSicIY1ivgfA24YSEitJbDpYizzym+Q0F070CdWnxjklnwlFD99GfaspMEZXwj2Ki7O+jt\ +AVX03FAl2ycn41m/fJoiGddP2d3DHWxCz3ikrRl9oNuxt5mLjmoIGMZGUcOAebEPstnYgQ0BZDmO15RahbC+T/hNBAIJK9UC39PJ50QCsjPG7WolnOrlYaLUF2BL0xD8nCGxQ0yFjynbJUtfVyHjkReUtcgAhp+t\ +OXcNUUQILnQU+2jFod/w6iMveh0nBKxcwUXVHDB2UbmhG8XqAEhwRcMeSEvhDLFj0U4ZDug5iovRDQEy1nXwjapkEIczpqtEcDSb80NPRHSYM4uK4sws4ge+NwzuikI+cM7gEyZURhX3j0XaTmr0EpOncUAOeAr3\ +ArqbhKZhDK9EA0DnJ9+Y0f007Dho2eZQv5dQv09S2afh2En01zKLW34GajBE+EA8BOTs8FXn7QfgzGeQw5f6BkI5Zz+zHtjoKQAQoOWCnNNS9QJMbPUHCvF6fjsC6MEijuOUmUvClh9IeklqDCUWcC8nfVwCa/J1\ +wXqIugZ1wPfOD+KxSIMaC73iGBt+sKrheaI2XDyCuWi57O1qgI+GH+ywA2sV78OuWMqoiTp8IhDmtuE5Ap9bohxEaqHEsMkyZtQXjgkgnyhvQKzuM/nHqkdH+Zkde0mPnVBig2IglkcH+K32XoAt3RM1OYMIo99l\ +OgC4mmxwcnElZCXAd3bvxQye3YLegaKfUZGgYUdrN5mY1CPY1K1an4P92Xo/KCkm8t1lxe+RwL0uLt2a9o/NGjBjdU7HTlAi3CYyKQnkpNy8Rq9oLj8LoQMEWZoZmWDf+0z+slpgeh0eppuCgZPXO85w+FlCEIRa\ +2QRELfWfOHQtB3c74wAHppnPcOELcK2vQJqPGEBBTpEfBwsc3+cdZ5fXC36aU+W34W12Jy7t/LrOCnm9U1JXgcLFDohrvZRCFXu4f/kbRsevJTR+dQkHoepmW6+g922IcOSBweqXUYxiLocE1ZnFLlD+Dpef8qYW\ +X0ttXMmhabDrUHElU0gheOW0FBZvfr+x8l41xNK7jLhswxiQuCxwG6OBMuYUVum+UomLTtnmAGK6nXKrDGXi0aOj2rslZ8E2LuWSnypX4tnWoTe38f+FwrkHXKOKrjec0H4luB0u04yWpoGQsJyXjNm1cyfB/6v2\ +y7+X9Uf4H2taVUVuc2WMH+mulx+/DJ1FUUJnWy9r/q9tUcF5h0fijfIqL0udffsvV73qkg==\ """))) diff --git a/tools/gen_esp32part.exe b/tools/gen_esp32part.exe index 6f939c74..55b8436a 100644 Binary files a/tools/gen_esp32part.exe and b/tools/gen_esp32part.exe differ diff --git a/tools/gen_esp32part.py b/tools/gen_esp32part.py index 08855923..66f5b30b 100755 --- a/tools/gen_esp32part.py +++ b/tools/gen_esp32part.py @@ -62,6 +62,7 @@ SUBTYPES = { quiet = False md5sum = True +secure = False offset_part_table = 0 def status(msg): @@ -95,19 +96,23 @@ class PartitionTable(list): if line.startswith("#") or len(line) == 0: continue try: - res.append(PartitionDefinition.from_csv(line)) + res.append(PartitionDefinition.from_csv(line, line_no+1)) except InputError as e: raise InputError("Error at line %d: %s" % (line_no+1, e)) except Exception: - critical("Unexpected error parsing line %d: %s" % (line_no+1, line)) + critical("Unexpected error parsing CSV line %d: %s" % (line_no+1, line)) raise # fix up missing offsets & negative sizes last_end = offset_part_table + PARTITION_TABLE_SIZE # first offset after partition table for e in res: - if offset_part_table != 0 and e.offset is not None and e.offset < last_end: - critical("WARNING: 0x%x address in the partition table is below 0x%x" % (e.offset, last_end)) - e.offset = None + if e.offset is not None and e.offset < last_end: + if e == res[0]: + raise InputError("CSV Error: First partition offset 0x%x overlaps end of partition table 0x%x" + % (e.offset, last_end)) + else: + raise InputError("CSV Error: Partitions overlap. Partition at line %d sets offset 0x%x. Previous partition ends 0x%x" + % (e.line_no, e.offset, last_end)) if e.offset is None: pad_to = 0x10000 if e.type == APP_TYPE else 4 if last_end % pad_to != 0: @@ -164,6 +169,19 @@ class PartitionTable(list): # verify each partition individually for p in self: p.verify() + + # check on duplicate name + names = [ p.name for p in self ] + duplicates = set( n for n in names if names.count(n) > 1 ) + + # print sorted duplicate partitions by name + if len(duplicates) != 0: + print("A list of partitions that have the same name:") + for p in sorted(self, key=lambda x:x.name): + if len(duplicates.intersection([p.name])) != 0: + print("%s" % (p.to_csv())) + raise InputError("Partition names must be unique") + # check for overlaps last = None for p in sorted(self, key=lambda x:x.offset): @@ -245,12 +263,13 @@ class PartitionDefinition(object): self.encrypted = False @classmethod - def from_csv(cls, line): + def from_csv(cls, line, line_no): """ Parse a line from the CSV """ line_w_defaults = line + ",,,," # lazy way to support default fields fields = [ f.strip() for f in line_w_defaults.split(",") ] res = PartitionDefinition() + res.line_no = line_no res.name = fields[0] res.type = res.parse_type(fields[1]) res.subtype = res.parse_subtype(fields[2]) @@ -322,6 +341,8 @@ class PartitionDefinition(object): align = self.ALIGNMENT.get(self.type, 4) if self.offset % align: raise ValidationError(self, "Offset 0x%x is not aligned to 0x%x" % (self.offset, align)) + if self.size % align and secure: + raise ValidationError(self, "Size 0x%x is not aligned to 0x%x" % (self.size, align)) if self.size is None: raise ValidationError(self, "Size field is not set") @@ -414,6 +435,7 @@ def main(): global quiet global md5sum global offset_part_table + global secure parser = argparse.ArgumentParser(description='ESP32 partition table utility') parser.add_argument('--flash-size', help='Optional flash size limit, checks partition table fits in flash', @@ -423,7 +445,7 @@ def main(): parser.add_argument('--verify', '-v', help="Verify partition table fields (deprecated, this behaviour is enabled by default and this flag does nothing.", action='store_true') parser.add_argument('--quiet', '-q', help="Don't print non-critical status messages to stderr", action='store_true') parser.add_argument('--offset', '-o', help='Set offset partition table', default='0x8000') - + parser.add_argument('--secure', help="Require app partitions to be suitable for secure boot", action='store_true') parser.add_argument('input', help='Path to CSV or binary file to parse.', type=argparse.FileType('rb')) parser.add_argument('output', help='Path to output converted binary or CSV file. Will use stdout if omitted.', nargs='?', default='-') @@ -432,6 +454,7 @@ def main(): quiet = args.quiet md5sum = not args.disable_md5sum + secure = args.secure offset_part_table = int(args.offset, 0) input = args.input.read() input_is_binary = input[0:2] == PartitionDefinition.MAGIC_BYTES diff --git a/tools/platformio-build.py b/tools/platformio-build.py index 171445bc..a7619c2f 100644 --- a/tools/platformio-build.py +++ b/tools/platformio-build.py @@ -107,11 +107,14 @@ env.Append( join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp32"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp_adc_cal"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp_http_client"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp_https_ota"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp-mqtt"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "esp-tls"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "ethernet"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "fatfs"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "freertos"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "heap"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "http_server"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "jsmn"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "log"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "mdns"), @@ -125,15 +128,16 @@ env.Append( join(FRAMEWORK_DIR, "tools", "sdk", "include", "smartconfig_ack"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "spiffs"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "tcpip_adapter"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "tcp_transport"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "ulp"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "vfs"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "wear_levelling"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "xtensa-debug-module"), + join(FRAMEWORK_DIR, "tools", "sdk", "include", "lwip"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "coap"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "console"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "expat"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "json"), - join(FRAMEWORK_DIR, "tools", "sdk", "include", "lwip"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "newlib"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "nghttp"), join(FRAMEWORK_DIR, "tools", "sdk", "include", "soc"), @@ -147,7 +151,7 @@ env.Append( ], LIBS=[ - "gcc", "openssl", "btdm_app", "fatfs", "wps", "coexist", "wear_levelling", "esp_http_client", "hal", "newlib", "driver", "bootloader_support", "pp", "mesh", "smartconfig", "jsmn", "wpa", "ethernet", "phy", "app_trace", "console", "ulp", "wpa_supplicant", "freertos", "bt", "micro-ecc", "cxx", "xtensa-debug-module", "mdns", "vfs", "soc", "core", "sdmmc", "coap", "tcpip_adapter", "c_nano", "esp-tls", "rtc", "spi_flash", "wpa2", "esp32", "app_update", "nghttp", "spiffs", "espnow", "nvs_flash", "esp_adc_cal", "log", "smartconfig_ack", "expat", "m", "c", "heap", "mbedtls", "lwip", "net80211", "pthread", "json", "stdc++" + "gcc", "openssl", "btdm_app", "fatfs", "wps", "http_server", "coexist", "wear_levelling", "esp_http_client", "hal", "newlib", "driver", "bootloader_support", "pp", "mesh", "smartconfig", "jsmn", "wpa", "ethernet", "phy", "app_trace", "console", "ulp", "wpa_supplicant", "freertos", "bt", "micro-ecc", "cxx", "xtensa-debug-module", "tcp_transport", "mdns", "vfs", "esp_ringbuf", "soc", "core", "sdmmc", "coap", "tcpip_adapter", "c_nano", "esp-tls", "asio", "rtc", "spi_flash", "wpa2", "esp32", "app_update", "nghttp", "spiffs", "espnow", "nvs_flash", "esp_adc_cal", "log", "smartconfig_ack", "expat", "m", "mqtt", "c", "heap", "mbedtls", "lwip", "net80211", "pthread", "json", "esp_https_ota", "stdc++" ], LIBSOURCE_DIRS=[ diff --git a/tools/sdk/bin/bootloader_dio_40m.bin b/tools/sdk/bin/bootloader_dio_40m.bin index ab424c15..b07c320a 100644 Binary files a/tools/sdk/bin/bootloader_dio_40m.bin and b/tools/sdk/bin/bootloader_dio_40m.bin differ diff --git a/tools/sdk/bin/bootloader_dio_80m.bin b/tools/sdk/bin/bootloader_dio_80m.bin index 7bae0dc7..d0d0a8b6 100644 Binary files a/tools/sdk/bin/bootloader_dio_80m.bin and b/tools/sdk/bin/bootloader_dio_80m.bin differ diff --git a/tools/sdk/bin/bootloader_dout_40m.bin b/tools/sdk/bin/bootloader_dout_40m.bin index 1dbe296c..82d8fd2a 100644 Binary files a/tools/sdk/bin/bootloader_dout_40m.bin and b/tools/sdk/bin/bootloader_dout_40m.bin differ diff --git a/tools/sdk/bin/bootloader_dout_80m.bin b/tools/sdk/bin/bootloader_dout_80m.bin index 4a7dd15d..616d1b27 100644 Binary files a/tools/sdk/bin/bootloader_dout_80m.bin and b/tools/sdk/bin/bootloader_dout_80m.bin differ diff --git a/tools/sdk/bin/bootloader_qio_40m.bin b/tools/sdk/bin/bootloader_qio_40m.bin index f7a10baa..c01ad4a5 100644 Binary files a/tools/sdk/bin/bootloader_qio_40m.bin and b/tools/sdk/bin/bootloader_qio_40m.bin differ diff --git a/tools/sdk/bin/bootloader_qio_80m.bin b/tools/sdk/bin/bootloader_qio_80m.bin index 7c073e2c..7525f2a5 100644 Binary files a/tools/sdk/bin/bootloader_qio_80m.bin and b/tools/sdk/bin/bootloader_qio_80m.bin differ diff --git a/tools/sdk/bin/bootloader_qout_40m.bin b/tools/sdk/bin/bootloader_qout_40m.bin index ab424c15..c01ad4a5 100644 Binary files a/tools/sdk/bin/bootloader_qout_40m.bin and b/tools/sdk/bin/bootloader_qout_40m.bin differ diff --git a/tools/sdk/bin/bootloader_qout_80m.bin b/tools/sdk/bin/bootloader_qout_80m.bin index bd07e358..63cc8e3b 100644 Binary files a/tools/sdk/bin/bootloader_qout_80m.bin and b/tools/sdk/bin/bootloader_qout_80m.bin differ diff --git a/tools/sdk/include/app_trace/esp_ota_ops.h b/tools/sdk/include/app_trace/esp_ota_ops.h index a089a92b..ca77b542 100644 --- a/tools/sdk/include/app_trace/esp_ota_ops.h +++ b/tools/sdk/include/app_trace/esp_ota_ops.h @@ -20,7 +20,6 @@ #include #include "esp_err.h" #include "esp_partition.h" -#include "esp_spi_flash.h" #ifdef __cplusplus extern "C" @@ -133,7 +132,7 @@ esp_err_t esp_ota_set_boot_partition(const esp_partition_t* partition); * If the OTA data partition is not present or not valid then the result is the first app partition found in the * partition table. In priority order, this means: the factory app, the first OTA app slot, or the test app partition. * - * Note that there is no guarantee the returned partition is a valid app. Use esp_image_load(ESP_IMAGE_VERIFY, ...) to verify if the + * Note that there is no guarantee the returned partition is a valid app. Use esp_image_verify(ESP_IMAGE_VERIFY, ...) to verify if the * returned partition contains a bootable image. * * @return Pointer to info for partition structure, or NULL if partition table is invalid or a flash read operation failed. Any returned pointer is valid for the lifetime of the application. diff --git a/tools/sdk/include/app_update/esp_ota_ops.h b/tools/sdk/include/app_update/esp_ota_ops.h index a089a92b..ca77b542 100644 --- a/tools/sdk/include/app_update/esp_ota_ops.h +++ b/tools/sdk/include/app_update/esp_ota_ops.h @@ -20,7 +20,6 @@ #include #include "esp_err.h" #include "esp_partition.h" -#include "esp_spi_flash.h" #ifdef __cplusplus extern "C" @@ -133,7 +132,7 @@ esp_err_t esp_ota_set_boot_partition(const esp_partition_t* partition); * If the OTA data partition is not present or not valid then the result is the first app partition found in the * partition table. In priority order, this means: the factory app, the first OTA app slot, or the test app partition. * - * Note that there is no guarantee the returned partition is a valid app. Use esp_image_load(ESP_IMAGE_VERIFY, ...) to verify if the + * Note that there is no guarantee the returned partition is a valid app. Use esp_image_verify(ESP_IMAGE_VERIFY, ...) to verify if the * returned partition contains a bootable image. * * @return Pointer to info for partition structure, or NULL if partition table is invalid or a flash read operation failed. Any returned pointer is valid for the lifetime of the application. diff --git a/tools/sdk/include/bluedroid/api/esp_a2dp_api.h b/tools/sdk/include/bluedroid/api/esp_a2dp_api.h index 8117d4c5..3b002a40 100644 --- a/tools/sdk/include/bluedroid/api/esp_a2dp_api.h +++ b/tools/sdk/include/bluedroid/api/esp_a2dp_api.h @@ -116,7 +116,7 @@ typedef union { struct a2d_audio_cfg_param { esp_bd_addr_t remote_bda; /*!< remote bluetooth device address */ esp_a2d_mcc_t mcc; /*!< A2DP media codec capability information */ - } audio_cfg; /*!< media codec configuration infomation */ + } audio_cfg; /*!< media codec configuration information */ /** * @brief ESP_A2D_MEDIA_CTRL_ACK_EVT @@ -147,12 +147,12 @@ typedef void (* esp_a2d_sink_data_cb_t)(const uint8_t *buf, uint32_t len); /** * @brief A2DP source data read callback function * - * @param[in] buf : buffer to be filled with PCM data stream from higer layer + * @param[in] buf : buffer to be filled with PCM data stream from higher layer * * @param[in] len : size(in bytes) of data block to be copied to buf. -1 is an indication to user * that data buffer shall be flushed * - * @return size of bytes read successfully, if the argumetn len is -1, this value is ignored. + * @return size of bytes read successfully, if the argument len is -1, this value is ignored. * */ typedef int32_t (* esp_a2d_source_data_cb_t)(uint8_t *buf, int32_t len); diff --git a/tools/sdk/include/bluedroid/api/esp_avrc_api.h b/tools/sdk/include/bluedroid/api/esp_avrc_api.h index 228beb8a..e1f68392 100644 --- a/tools/sdk/include/bluedroid/api/esp_avrc_api.h +++ b/tools/sdk/include/bluedroid/api/esp_avrc_api.h @@ -111,7 +111,7 @@ typedef enum { /// AVRC shuffle modes typedef enum { ESP_AVRC_PS_SHUFFLE_OFF = 0x1, /* #include @@ -44,3 +47,5 @@ extern esp_err_t esp_ble_gatt_set_local_mtu (uint16_t mtu); #ifdef __cplusplus } #endif + +#endif /* __ESP_GATT_COMMON_API_H__ */ diff --git a/tools/sdk/include/bluedroid/api/esp_gatt_defs.h b/tools/sdk/include/bluedroid/api/esp_gatt_defs.h index 77cdcd65..de4bc897 100644 --- a/tools/sdk/include/bluedroid/api/esp_gatt_defs.h +++ b/tools/sdk/include/bluedroid/api/esp_gatt_defs.h @@ -224,7 +224,7 @@ typedef enum { ESP_GATT_CONN_L2C_FAILURE = 1, /*!< General L2cap failure */ /* relate to BTA_GATT_CONN_L2C_FAILURE in bta/bta_gatt_api.h */ ESP_GATT_CONN_TIMEOUT = 0x08, /*!< Connection timeout */ /* relate to BTA_GATT_CONN_TIMEOUT in bta/bta_gatt_api.h */ ESP_GATT_CONN_TERMINATE_PEER_USER = 0x13, /*!< Connection terminate by peer user */ /* relate to BTA_GATT_CONN_TERMINATE_PEER_USER in bta/bta_gatt_api.h */ - ESP_GATT_CONN_TERMINATE_LOCAL_HOST = 0x16, /*!< Connectionterminated by local host */ /* relate to BTA_GATT_CONN_TERMINATE_LOCAL_HOST in bta/bta_gatt_api.h */ + ESP_GATT_CONN_TERMINATE_LOCAL_HOST = 0x16, /*!< Connection terminated by local host */ /* relate to BTA_GATT_CONN_TERMINATE_LOCAL_HOST in bta/bta_gatt_api.h */ ESP_GATT_CONN_FAIL_ESTABLISH = 0x3e, /*!< Connection fail to establish */ /* relate to BTA_GATT_CONN_FAIL_ESTABLISH in bta/bta_gatt_api.h */ ESP_GATT_CONN_LMP_TIMEOUT = 0x22, /*!< Connection fail for LMP response tout */ /* relate to BTA_GATT_CONN_LMP_TIMEOUT in bta/bta_gatt_api.h */ ESP_GATT_CONN_CONN_CANCEL = 0x0100, /*!< L2CAP connection cancelled */ /* relate to BTA_GATT_CONN_CONN_CANCEL in bta/bta_gatt_api.h */ @@ -422,7 +422,7 @@ typedef struct { * @brief service element */ typedef struct { - bool is_primary; /*!< The service flag, ture if the service is primary service, else is secondly service */ + bool is_primary; /*!< The service flag, true if the service is primary service, else is secondly service */ uint16_t start_handle; /*!< The start handle of the service */ uint16_t end_handle; /*!< The end handle of the service */ esp_bt_uuid_t uuid; /*!< The uuid of the service */ @@ -453,7 +453,7 @@ typedef struct { uint16_t incl_srvc_s_handle; /*!< The start handle of the service which has been included */ uint16_t incl_srvc_e_handle; /*!< The end handle of the service which has been included */ esp_bt_uuid_t uuid; /*!< The include service uuid */ -} esp_gattc_incl_svc_elem_t; /*!< The gattc inclue service element */ +} esp_gattc_incl_svc_elem_t; /*!< The gattc include service element */ #ifdef __cplusplus diff --git a/tools/sdk/include/bluedroid/api/esp_gattc_api.h b/tools/sdk/include/bluedroid/api/esp_gattc_api.h index 44c013d5..b0fabb7a 100644 --- a/tools/sdk/include/bluedroid/api/esp_gattc_api.h +++ b/tools/sdk/include/bluedroid/api/esp_gattc_api.h @@ -312,7 +312,7 @@ esp_err_t esp_ble_gattc_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda, e /** - * @brief Close a virtual connection to a GATT server. gattc maybe have multiple virtual GATT server connections when multiple app_id registed, + * @brief Close the virtual connection to the GATT server. gattc may have multiple virtual GATT server connections when multiple app_id registered, * this API only close one virtual GATT server connection. if there exist other virtual GATT server connections, * it does not disconnect the physical connection. * if you want to disconnect the physical connection directly, you can use esp_ble_gap_disconnect(esp_bd_addr_t remote_device). @@ -371,7 +371,7 @@ esp_err_t esp_ble_gattc_search_service(esp_gatt_if_t gattc_if, uint16_t conn_id, * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id: connection ID which identify the server. * @param[in] svc_uuid: the pointer to the service uuid. - * @param[out] result: The pointer to the service whith has been found in the gattc cache. + * @param[out] result: The pointer to the service which has been found in the gattc cache. * @param[inout] count: input the number of service want to find, * it will output the number of service has been found in the gattc cache with the given service uuid. * @param[in] offset: Offset of the service position to get. @@ -392,7 +392,7 @@ esp_gatt_status_t esp_ble_gattc_get_service(esp_gatt_if_t gattc_if, uint16_t con * @param[in] conn_id: connection ID which identify the server. * @param[in] start_handle: the attribute start handle. * @param[in] end_handle: the attribute end handle - * @param[out] result: The pointer to the charateristic in the service. + * @param[out] result: The pointer to the characteristic in the service. * @param[inout] count: input the number of characteristic want to find, * it will output the number of characteristic has been found in the gattc cache with the given service. * @param[in] offset: Offset of the characteristic position to get. @@ -695,7 +695,7 @@ esp_err_t esp_ble_gattc_write_char_descr (esp_gatt_if_t gattc_if, * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID. - * @param[in] handle : charateristic handle to prepare write. + * @param[in] handle : characteristic handle to prepare write. * @param[in] offset : offset of the write value. * @param[in] value_len: length of the value to be written. * @param[in] value : the value to be written. @@ -720,7 +720,7 @@ esp_err_t esp_ble_gattc_prepare_write(esp_gatt_if_t gattc_if, * * @param[in] gattc_if: Gatt client access interface. * @param[in] conn_id : connection ID. - * @param[in] handle : characteristic descriptor hanlde to prepare write. + * @param[in] handle : characteristic descriptor handle to prepare write. * @param[in] offset : offset of the write value. * @param[in] value_len: length of the value to be written. * @param[in] value : the value to be written. diff --git a/tools/sdk/include/bluedroid/api/esp_gatts_api.h b/tools/sdk/include/bluedroid/api/esp_gatts_api.h index bc97b76e..d25d2978 100644 --- a/tools/sdk/include/bluedroid/api/esp_gatts_api.h +++ b/tools/sdk/include/bluedroid/api/esp_gatts_api.h @@ -350,7 +350,8 @@ esp_err_t esp_ble_gatts_create_attr_tab(const esp_gatts_attr_db_t *gatts_attr_db uint8_t max_nb_attr, uint8_t srvc_inst_id); /** - * @brief This function is called to add an included service. After included + * @brief This function is called to add an included service. This function have to be called between + * 'esp_ble_gatts_create_service' and 'esp_ble_gatts_add_char'. After included * service is included, a callback event BTA_GATTS_ADD_INCL_SRVC_EVT * is reported the included service ID. * diff --git a/tools/sdk/include/bluedroid/api/esp_hf_client_api.h b/tools/sdk/include/bluedroid/api/esp_hf_client_api.h index 65598e08..67ec894e 100644 --- a/tools/sdk/include/bluedroid/api/esp_hf_client_api.h +++ b/tools/sdk/include/bluedroid/api/esp_hf_client_api.h @@ -40,7 +40,7 @@ typedef enum { ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED = 0, /*!< audio connection released */ ESP_HF_CLIENT_AUDIO_STATE_CONNECTING, /*!< audio connection has been initiated */ ESP_HF_CLIENT_AUDIO_STATE_CONNECTED, /*!< audio connection is established */ - ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC, /*!< mSBC audio connection is estalibshed */ + ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC, /*!< mSBC audio connection is established */ } esp_hf_client_audio_state_t; /// in-band ring tone state @@ -66,9 +66,9 @@ typedef enum { #define ESP_HF_CLIENT_CHLD_FEAT_REL_ACC 0x02 /* 1 Release active calls and accept other waiting or held call */ #define ESP_HF_CLIENT_CHLD_FEAT_REL_X 0x04 /* 1x Release specified active call only */ #define ESP_HF_CLIENT_CHLD_FEAT_HOLD_ACC 0x08 /* 2 Active calls on hold and accept other waiting or held call */ -#define ESP_HF_CLIENT_CHLD_FEAT_PRIV_X 0x10 /* 2x Request private mode with specified call(put the rest on hold */ +#define ESP_HF_CLIENT_CHLD_FEAT_PRIV_X 0x10 /* 2x Request private mode with specified call(put the rest on hold) */ #define ESP_HF_CLIENT_CHLD_FEAT_MERGE 0x20 /* 3 Add held call to multiparty */ -#define ESP_HF_CLIENT_CHLD_FEAT_MERGE_DETACH 0x40 /* 4 Connect two calls and leave(disconnct from multiparty */ +#define ESP_HF_CLIENT_CHLD_FEAT_MERGE_DETACH 0x40 /* 4 Connect two calls and leave(disconnect from multiparty) */ /// HF CLIENT callback events typedef enum { @@ -140,7 +140,7 @@ typedef union { * @brief ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT */ struct hf_client_signal_strength_ind_param { - int value; /*!< singal strength value, ranges from 0 to 5 */ + int value; /*!< signal strength value, ranges from 0 to 5 */ } signal_strength; /*!< HF callback param of ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT */ /** @@ -175,7 +175,7 @@ typedef union { * @brief ESP_HF_CLIENT_CIND_CALL_HELD_EVT */ struct hf_client_call_held_ind_param { - esp_hf_call_held_status_t status; /*!< bluetooth proprietary call hold status indocator */ + esp_hf_call_held_status_t status; /*!< bluetooth proprietary call hold status indicator */ } call_held; /*!< HF callback param of ESP_HF_CLIENT_CIND_CALL_HELD_EVT */ /** @@ -619,7 +619,7 @@ void esp_hf_client_pcm_resample_init(uint32_t src_sps, uint32_t bits, uint32_t c * @brief Down sampling utility to convert high sampling rate into 8K/16bits 1-channel mode PCM * samples. This can only be used in the case that Voice Over HCI is enabled. * - * @param[in] src: pointer to the buffer where the original smapling PCM are stored + * @param[in] src: pointer to the buffer where the original sampling PCM are stored * @param[in] in_bytes: length of the input PCM sample buffer in byte * @param[in] dst: pointer to the buffer which is to be used to store the converted PCM samples * diff --git a/tools/sdk/include/bluedroid/api/esp_hf_defs.h b/tools/sdk/include/bluedroid/api/esp_hf_defs.h index b7127793..1ff9f14f 100644 --- a/tools/sdk/include/bluedroid/api/esp_hf_defs.h +++ b/tools/sdk/include/bluedroid/api/esp_hf_defs.h @@ -120,7 +120,7 @@ typedef enum { /// response indication codes for AT commands typedef enum { - ESP_HF_AT_RESPONSE_CODE_OK = 0, /*!< acknoweledges execution of a command line */ + ESP_HF_AT_RESPONSE_CODE_OK = 0, /*!< acknowledges execution of a command line */ ESP_HF_AT_RESPONSE_CODE_ERR, /*!< command not accepted */ ESP_HF_AT_RESPONSE_CODE_NO_CARRIER, /*!< connection terminated */ ESP_HF_AT_RESPONSE_CODE_BUSY, /*!< busy signal detected */ diff --git a/tools/sdk/include/bluedroid/api/esp_spp_api.h b/tools/sdk/include/bluedroid/api/esp_spp_api.h index e819158c..d7f35774 100644 --- a/tools/sdk/include/bluedroid/api/esp_spp_api.h +++ b/tools/sdk/include/bluedroid/api/esp_spp_api.h @@ -62,9 +62,9 @@ typedef enum { ESP_SPP_CLOSE_EVT = 27, /*!< When SPP connection closed, the event comes */ ESP_SPP_START_EVT = 28, /*!< When SPP server started, the event comes */ ESP_SPP_CL_INIT_EVT = 29, /*!< When SPP client initiated a connection, the event comes */ - ESP_SPP_DATA_IND_EVT = 30, /*!< When SPP connection received data, the event comes, olny for ESP_SPP_MODE_CB */ - ESP_SPP_CONG_EVT = 31, /*!< When SPP connection congestion status changed, the event comes, olny for ESP_SPP_MODE_CB */ - ESP_SPP_WRITE_EVT = 33, /*!< When SPP write operation completes, the event comes, olny for ESP_SPP_MODE_CB */ + ESP_SPP_DATA_IND_EVT = 30, /*!< When SPP connection received data, the event comes, only for ESP_SPP_MODE_CB */ + ESP_SPP_CONG_EVT = 31, /*!< When SPP connection congestion status changed, the event comes, only for ESP_SPP_MODE_CB */ + ESP_SPP_WRITE_EVT = 33, /*!< When SPP write operation completes, the event comes, only for ESP_SPP_MODE_CB */ ESP_SPP_SRV_OPEN_EVT = 34, /*!< When SPP Server connection open, the event comes */ } esp_spp_cb_event_t; @@ -95,7 +95,7 @@ typedef union { struct spp_open_evt_param { esp_spp_status_t status; /*!< status */ uint32_t handle; /*!< The connection handle */ - int fd; /*!< The file descriptor olny for ESP_SPP_MODE_VFS*/ + int fd; /*!< The file descriptor only for ESP_SPP_MODE_VFS */ esp_bd_addr_t rem_bda; /*!< The peer address */ } open; /*!< SPP callback param of ESP_SPP_OPEN_EVT */ @@ -106,7 +106,7 @@ typedef union { esp_spp_status_t status; /*!< status */ uint32_t handle; /*!< The connection handle */ uint32_t new_listen_handle; /*!< The new listen handle */ - int fd; /*!< The file descriptor olny for ESP_SPP_MODE_VFS*/ + int fd; /*!< The file descriptor only for ESP_SPP_MODE_VFS */ esp_bd_addr_t rem_bda; /*!< The peer address */ } srv_open; /*!< SPP callback param of ESP_SPP_SRV_OPEN_EVT */ /** @@ -155,7 +155,7 @@ typedef union { esp_spp_status_t status; /*!< status */ uint32_t handle; /*!< The connection handle */ uint16_t len; /*!< The length of data */ - uint8_t *data; /*!< The data recived */ + uint8_t *data; /*!< The data received */ } data_ind; /*!< SPP callback param of ESP_SPP_DATA_IND_EVT */ /** @@ -224,14 +224,14 @@ esp_err_t esp_spp_deinit(); esp_err_t esp_spp_start_discovery(esp_bd_addr_t bd_addr); /** - * @brief This function makes an SPP conection to a remote BD Address. + * @brief This function makes an SPP connection to a remote BD Address. * When the connection is initiated or failed to initiate, * the callback is called with ESP_SPP_CL_INIT_EVT. * When the connection is established or failed, * the callback is called with ESP_SPP_OPEN_EVT. * * @param[in] sec_mask: Security Setting Mask . - * @param[in] role: Msater or slave. + * @param[in] role: Master or slave. * @param[in] remote_scn: Remote device bluetooth device SCN. * @param[in] peer_bd_addr: Remote device bluetooth device address. * @@ -262,7 +262,7 @@ esp_err_t esp_spp_disconnect(uint32_t handle); * with ESP_SPP_SRV_OPEN_EVT. * * @param[in] sec_mask: Security Setting Mask . - * @param[in] role: Msater or slave. + * @param[in] role: Master or slave. * @param[in] local_scn: The specific channel you want to get. * If channel is 0, means get any channel. * @param[in] name: Server's name. @@ -276,7 +276,7 @@ esp_err_t esp_spp_start_srv(esp_spp_sec_t sec_mask, /** - * @brief This function is used to write data, olny for ESP_SPP_MODE_CB. + * @brief This function is used to write data, only for ESP_SPP_MODE_CB. * * @param[in] handle: The connection handle. * @param[in] len: The length of the data written. @@ -302,4 +302,4 @@ esp_err_t esp_spp_vfs_register(void); } #endif -#endif ///__ESP_SPP_API_H__ \ No newline at end of file +#endif ///__ESP_SPP_API_H__ diff --git a/tools/sdk/include/bluedroid/bta/bta_api.h b/tools/sdk/include/bluedroid/bta/bta_api.h index c8903bfd..15c22ba6 100644 --- a/tools/sdk/include/bluedroid/bta/bta_api.h +++ b/tools/sdk/include/bluedroid/bta/bta_api.h @@ -631,10 +631,13 @@ typedef UINT8 tBTA_SIG_STRENGTH_MASK; #define BTA_DM_SP_RMT_OOB_EXT_EVT 23 /* Simple Pairing Remote OOB Extended Data request. */ #define BTA_DM_BLE_AUTH_CMPL_EVT 24 /* BLE Auth complete */ // btla-specific -- -#define BTA_DM_DEV_UNPAIRED_EVT 25 +#define BTA_DM_DEV_UNPAIRED_EVT 25 /* BT unpair event */ #define BTA_DM_HW_ERROR_EVT 26 /* BT Chip H/W error */ #define BTA_DM_LE_FEATURES_READ 27 /* Cotroller specific LE features are read */ #define BTA_DM_ENER_INFO_READ 28 /* Energy info read */ +#define BTA_DM_BLE_DEV_UNPAIRED_EVT 29 /* BLE unpair event */ +#define BTA_DM_SP_KEY_REQ_EVT 30 /* Simple Pairing Passkey request */ + typedef UINT8 tBTA_DM_SEC_EVT; /* Structure associated with BTA_DM_ENABLE_EVT */ @@ -867,6 +870,13 @@ typedef struct { tBTA_AUTH_REQ rmt_io_caps; /* IO Capabilities of remote device */ } tBTA_DM_SP_CFM_REQ; +/* Structure associated with tBTA_DM_SP_KEY_REQ */ +typedef struct { + BD_ADDR bd_addr; /* peer address */ + DEV_CLASS dev_class; /* peer CoD */ + BD_NAME bd_name; /* peer device name */ +} tBTA_DM_SP_KEY_REQ; + enum { BTA_SP_KEY_STARTED, /* passkey entry started */ BTA_SP_KEY_ENTERED, /* passkey digit entered */ @@ -906,23 +916,24 @@ typedef struct { /* Union of all security callback structures */ typedef union { - tBTA_DM_ENABLE enable; /* BTA enabled */ - tBTA_DM_PIN_REQ pin_req; /* PIN request. */ - tBTA_DM_AUTH_CMPL auth_cmpl; /* Authentication complete indication. */ - tBTA_DM_AUTHORIZE authorize; /* Authorization request. */ - tBTA_DM_LINK_UP link_up; /* ACL connection down event */ - tBTA_DM_LINK_DOWN link_down; /* ACL connection down event */ - tBTA_DM_BUSY_LEVEL busy_level; /* System busy level */ - tBTA_DM_SP_CFM_REQ cfm_req; /* user confirm request */ - tBTA_DM_SP_KEY_NOTIF key_notif; /* passkey notification */ - tBTA_DM_SP_RMT_OOB rmt_oob; /* remote oob */ - tBTA_DM_BOND_CANCEL_CMPL bond_cancel_cmpl; /* Bond Cancel Complete indication */ - tBTA_DM_SP_KEY_PRESS key_press; /* key press notification event */ - tBTA_DM_ROLE_CHG role_chg; /* role change event */ - tBTA_DM_BLE_SEC_REQ ble_req; /* BLE SMP related request */ - tBTA_DM_BLE_KEY ble_key; /* BLE SMP keys used when pairing */ - tBTA_BLE_LOCAL_ID_KEYS ble_id_keys; /* IR event */ - BT_OCTET16 ble_er; /* ER event data */ + tBTA_DM_ENABLE enable; /* BTA enabled */ + tBTA_DM_PIN_REQ pin_req; /* PIN request. */ + tBTA_DM_AUTH_CMPL auth_cmpl; /* Authentication complete indication. */ + tBTA_DM_AUTHORIZE authorize; /* Authorization request. */ + tBTA_DM_LINK_UP link_up; /* ACL connection down event */ + tBTA_DM_LINK_DOWN link_down; /* ACL connection down event */ + tBTA_DM_BUSY_LEVEL busy_level; /* System busy level */ + tBTA_DM_SP_CFM_REQ cfm_req; /* user confirm request */ + tBTA_DM_SP_KEY_REQ key_req; /* user passkey request */ + tBTA_DM_SP_KEY_NOTIF key_notif; /* passkey notification */ + tBTA_DM_SP_RMT_OOB rmt_oob; /* remote oob */ + tBTA_DM_BOND_CANCEL_CMPL bond_cancel_cmpl; /* Bond Cancel Complete indication */ + tBTA_DM_SP_KEY_PRESS key_press; /* key press notification event */ + tBTA_DM_ROLE_CHG role_chg; /* role change event */ + tBTA_DM_BLE_SEC_REQ ble_req; /* BLE SMP related request */ + tBTA_DM_BLE_KEY ble_key; /* BLE SMP keys used when pairing */ + tBTA_BLE_LOCAL_ID_KEYS ble_id_keys; /* IR event */ + BT_OCTET16 ble_er; /* ER event data */ } tBTA_DM_SEC; /* Security callback */ @@ -1559,6 +1570,18 @@ extern void BTA_DmBondByTransport(BD_ADDR bd_addr, tBTA_TRANSPORT transport); *******************************************************************************/ extern void BTA_DmBondCancel(BD_ADDR bd_addr); +/******************************************************************************* +** +** Function BTA_DMSetPinType +** +** Description This function sets pin type as BTM_PIN_TYPE_FIXED or BTM_PIN_TYPE_VARIABLE +** +** +** Returns void +** +*******************************************************************************/ +extern void BTA_DMSetPinType (UINT8 pin_type, UINT8 *pin_code, UINT8 pin_code_len); + /******************************************************************************* ** ** Function BTA_DmPinReply @@ -1601,6 +1624,18 @@ extern void BTA_DmLocalOob(void); *******************************************************************************/ extern void BTA_DmConfirm(BD_ADDR bd_addr, BOOLEAN accept); +/******************************************************************************* +** +** Function BTA_DmPasskeyReqReply +** +** Description This function is called to provide the passkey for +** Simple Pairing in response to BTA_DM_SP_KEY_REQ_EVT +** +** Returns void +** +*******************************************************************************/ +extern void BTA_DmPasskeyReqReply(BOOLEAN accept, BD_ADDR bd_addr, UINT32 passkey); + /******************************************************************************* ** ** Function BTA_DmAddDevice @@ -1632,7 +1667,7 @@ extern void BTA_DmAddDevice(BD_ADDR bd_addr, DEV_CLASS dev_class, ** BTA_FAIL if operation failed. ** *******************************************************************************/ -extern tBTA_STATUS BTA_DmRemoveDevice(BD_ADDR bd_addr); +extern tBTA_STATUS BTA_DmRemoveDevice(BD_ADDR bd_addr, tBT_TRANSPORT transport); /******************************************************************************* ** @@ -1789,6 +1824,22 @@ extern void BTA_DmBleSetBgConnType(tBTA_DM_BLE_CONN_TYPE bg_conn_type, tBTA_DM_B *******************************************************************************/ extern void BTA_DmBlePasskeyReply(BD_ADDR bd_addr, BOOLEAN accept, UINT32 passkey); +/******************************************************************************* +** +** Function BTA_DmBleSetStaticPasskey +** +** Description Set BLE SMP static passkey. +** +** Parameters: add - add static passkey when add is true +** clear static passkey when add is false +** passkey - static passkey value +** +** +** Returns void +** +*******************************************************************************/ +extern void BTA_DmBleSetStaticPasskey(bool add, uint32_t passkey); + /******************************************************************************* ** ** Function BTA_DmBleConfirmReply diff --git a/tools/sdk/include/bluedroid/bta/bta_av_api.h b/tools/sdk/include/bluedroid/bta/bta_av_api.h index 6e70acf9..87c2d374 100644 --- a/tools/sdk/include/bluedroid/bta/bta_av_api.h +++ b/tools/sdk/include/bluedroid/bta/bta_av_api.h @@ -98,7 +98,7 @@ typedef UINT8 tBTA_AV_HNDL; #endif #ifndef BTA_AV_MAX_SEPS -#define BTA_AV_MAX_SEPS 2 +#define BTA_AV_MAX_SEPS 1 #endif #ifndef BTA_AV_MAX_A2DP_MTU @@ -259,7 +259,7 @@ typedef UINT8 tBTA_AV_ERR; /* function types for call-out functions */ typedef BOOLEAN (*tBTA_AV_CO_INIT) (UINT8 *p_codec_type, UINT8 *p_codec_info, - UINT8 *p_num_protect, UINT8 *p_protect_info, UINT8 index); + UINT8 *p_num_protect, UINT8 *p_protect_info, UINT8 tsep); typedef void (*tBTA_AV_CO_DISC_RES) (tBTA_AV_HNDL hndl, UINT8 num_seps, UINT8 num_snk, UINT8 num_src, BD_ADDR addr, UINT16 uuid_local); typedef UINT8 (*tBTA_AV_CO_GETCFG) (tBTA_AV_HNDL hndl, tBTA_AV_CODEC codec_type, @@ -580,7 +580,7 @@ void BTA_AvDisable(void); ** *******************************************************************************/ void BTA_AvRegister(tBTA_AV_CHNL chnl, const char *p_service_name, - UINT8 app_id, tBTA_AV_DATA_CBACK *p_data_cback, tBTA_AV_CO_FUNCTS *bta_av_cos); + UINT8 app_id, tBTA_AV_DATA_CBACK *p_data_cback, tBTA_AV_CO_FUNCTS *bta_av_cos, UINT8 tsep); /******************************************************************************* ** diff --git a/tools/sdk/include/bluedroid/bta/bta_av_co.h b/tools/sdk/include/bluedroid/bta/bta_av_co.h index 403b7a92..03c07c33 100644 --- a/tools/sdk/include/bluedroid/bta/bta_av_co.h +++ b/tools/sdk/include/bluedroid/bta/bta_av_co.h @@ -85,7 +85,7 @@ typedef struct { ** *******************************************************************************/ extern BOOLEAN bta_av_co_audio_init(UINT8 *p_codec_type, UINT8 *p_codec_info, - UINT8 *p_num_protect, UINT8 *p_protect_info, UINT8 index); + UINT8 *p_num_protect, UINT8 *p_protect_info, UINT8 tsep); /******************************************************************************* ** diff --git a/tools/sdk/include/bluedroid/bta/bta_dm_co.h b/tools/sdk/include/bluedroid/bta/bta_dm_co.h index 1f1f648a..3d49a698 100644 --- a/tools/sdk/include/bluedroid/bta/bta_dm_co.h +++ b/tools/sdk/include/bluedroid/bta/bta_dm_co.h @@ -30,6 +30,20 @@ ** Function Declarations *****************************************************************************/ +/******************************************************************************* +** +** Function bta_dm_co_bt_set_io_cap +** +** Description This function is used to set IO capabilities +** +** Parameters bt_io_cap - IO capabilities +** +** @return - ESP_BT_STATUS_SUCCESS : success +** - other : failed +** +*******************************************************************************/ +extern esp_err_t bta_dm_co_bt_set_io_cap(UINT8 bt_io_cap); + /******************************************************************************* ** ** Function bta_dm_co_io_req diff --git a/tools/sdk/include/bluedroid/bta/bta_gatts_co.h b/tools/sdk/include/bluedroid/bta/bta_gatts_co.h index 79c70c8b..9d81d646 100644 --- a/tools/sdk/include/bluedroid/bta/bta_gatts_co.h +++ b/tools/sdk/include/bluedroid/bta/bta_gatts_co.h @@ -55,7 +55,7 @@ extern void bta_gatts_co_update_handle_range(BOOLEAN is_add, tBTA_GATTS_HNDL_RAN ** ** Returns TRUE - if the request is processed successfully and ** the response is returned in p_rsp. -** FASLE - if the request can not be processed +** FALSE - if the request can not be processed ** *******************************************************************************/ extern BOOLEAN bta_gatts_co_srv_chg(tBTA_GATTS_SRV_CHG_CMD cmd, diff --git a/tools/sdk/include/bluedroid/btc/btc_task.h b/tools/sdk/include/bluedroid/btc/btc_task.h index f644e865..5813c521 100644 --- a/tools/sdk/include/bluedroid/btc/btc_task.h +++ b/tools/sdk/include/bluedroid/btc/btc_task.h @@ -28,6 +28,11 @@ typedef struct btc_msg { void *arg; //param for btc function or function param } btc_msg_t; +typedef struct btc_adv_packet { + uint8_t addr[6]; + uint8_t addr_type; +} btc_adv_packet_t; + typedef enum { BTC_SIG_API_CALL = 0, // APP TO STACK BTC_SIG_API_CB, // STACK TO APP @@ -72,5 +77,6 @@ bt_status_t btc_transfer_context(btc_msg_t *msg, void *arg, int arg_len, btc_arg int btc_init(void); void btc_deinit(void); +bool btc_check_queue_is_congest(void); #endif /* __BTC_TASK_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_gap_ble.h b/tools/sdk/include/bluedroid/btc_gap_ble.h index 9ee03d41..c9e0f564 100644 --- a/tools/sdk/include/bluedroid/btc_gap_ble.h +++ b/tools/sdk/include/bluedroid/btc_gap_ble.h @@ -166,5 +166,7 @@ void btc_gap_ble_cb_deep_free(btc_msg_t *msg); void btc_gap_ble_cb_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src); void btc_gap_callback_init(void); void btc_gap_ble_deinit(void); +void btc_adv_list_init(void); +void btc_adv_list_deinit(void); #endif /* __BTC_GAP_BLE_H__ */ diff --git a/tools/sdk/include/bluedroid/btc_gap_bt.h b/tools/sdk/include/bluedroid/btc_gap_bt.h index 41674956..67e03cb3 100644 --- a/tools/sdk/include/bluedroid/btc_gap_bt.h +++ b/tools/sdk/include/bluedroid/btc_gap_bt.h @@ -26,8 +26,12 @@ typedef enum { BTC_GAP_BT_SEARCH_DEVICES_EVT = 0, BTC_GAP_BT_SEARCH_SERVICES_EVT, BTC_GAP_BT_SEARCH_SERVICE_RECORD_EVT, - BTC_GAP_BT_READ_RSSI_DELTA_EVT, BTC_GAP_BT_AUTH_CMPL_EVT, + BTC_GAP_BT_PIN_REQ_EVT, + BTC_GAP_BT_CFM_REQ_EVT, + BTC_GAP_BT_KEY_NOTIF_EVT, + BTC_GAP_BT_KEY_REQ_EVT, + BTC_GAP_BT_READ_RSSI_DELTA_EVT, }btc_gap_bt_evt_t; typedef enum { @@ -39,6 +43,11 @@ typedef enum { BTC_GAP_BT_ACT_SET_COD, BTC_GAP_BT_ACT_READ_RSSI_DELTA, BTC_GAP_BT_ACT_REMOVE_BOND_DEVICE, + BTC_GAP_BT_ACT_SET_PIN_TYPE, + BTC_GAP_BT_ACT_PIN_REPLY, + BTC_GAP_BT_ACT_SET_SECURITY_PARAM, + BTC_GAP_BT_ACT_PASSKEY_REPLY, + BTC_GAP_BT_ACT_CONFIRM_REPLY, } btc_gap_bt_act_t; /* btc_bt_gap_args_t */ @@ -79,11 +88,46 @@ typedef union { struct rm_bond_device_args { bt_bdaddr_t bda; } rm_bond_device; + + // BTC_GAP_BT_ACT_SET_PIN_TYPE + struct set_pin_type_args { + esp_bt_pin_type_t pin_type; + uint8_t pin_code_len; + esp_bt_pin_code_t pin_code; + } set_pin_type; + + // BTC_GAP_BT_ACT_PIN_REPLY + struct pin_reply_args { + bt_bdaddr_t bda; + bool accept; + uint8_t pin_code_len; + esp_bt_pin_code_t pin_code; + } pin_reply; + + // BTC_GAP_BT_ACT_SET_SECURITY_PARAM + struct set_sec_param_args { + esp_bt_sp_param_t param_type; + uint8_t len; + uint8_t *value; + } set_security_param; + + // BTC_GAP_BT_ACT_PASSKEY_REPLY + struct passkey_reply_args { + bt_bdaddr_t bda; + bool accept; + uint32_t passkey; + } passkey_reply; + + // BTC_GAP_BT_ACT_CONFIRM_REPLY + struct confirm_reply_args { + bt_bdaddr_t bda; + bool accept; + } confirm_reply; } btc_gap_bt_args_t; void btc_gap_bt_call_handler(btc_msg_t *msg); void btc_gap_bt_cb_handler(btc_msg_t *msg); - +void btc_gap_bt_arg_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src); void btc_gap_bt_busy_level_updated(uint8_t bl_flags); esp_err_t btc_gap_bt_get_cod(esp_bt_cod_t *cod); diff --git a/tools/sdk/include/bluedroid/common/bt_defs.h b/tools/sdk/include/bluedroid/common/bt_defs.h index 51ba9a9d..77719bc8 100644 --- a/tools/sdk/include/bluedroid/common/bt_defs.h +++ b/tools/sdk/include/bluedroid/common/bt_defs.h @@ -26,9 +26,6 @@ #define UNUSED(x) (void)(x) -#ifndef SIZE_MAX -#define SIZE_MAX 254 -#endif /*Timer Related Defination*/ //by Snake.T diff --git a/tools/sdk/include/bluedroid/common/bt_target.h b/tools/sdk/include/bluedroid/common/bt_target.h index a5bb49b6..331ff20e 100644 --- a/tools/sdk/include/bluedroid/common/bt_target.h +++ b/tools/sdk/include/bluedroid/common/bt_target.h @@ -52,6 +52,7 @@ #define BTA_SDP_INCLUDED TRUE #define BTA_DM_PM_INCLUDED TRUE #define SDP_INCLUDED TRUE +#define BT_SSP_INCLUDED TRUE #if CONFIG_A2DP_ENABLE #define BTA_AR_INCLUDED TRUE @@ -127,7 +128,7 @@ #else #define SMP_INCLUDED FALSE #define BLE_PRIVACY_SPT FALSE -#endif /* CONFIG_GATTC_ENABLE */ +#endif /* CONFIG_SMP_ENABLE */ #if (CONFIG_BT_ACL_CONNECTIONS) #define MAX_ACL_CONNECTIONS CONFIG_BT_ACL_CONNECTIONS @@ -307,6 +308,16 @@ #define BTA_AV_CO_CP_SCMS_T FALSE//FALSE #endif +#ifndef QUEUE_CONGEST_SIZE +#define QUEUE_CONGEST_SIZE 40 +#endif + +#ifndef CONFIG_BLE_HOST_QUEUE_CONGESTION_CHECK +#define SCAN_QUEUE_CONGEST_CHECK FALSE +#else +#define SCAN_QUEUE_CONGEST_CHECK CONFIG_BLE_HOST_QUEUE_CONGESTION_CHECK +#endif + /* This feature is used to eanble interleaved scan*/ #ifndef BTA_HOST_INTERLEAVE_SEARCH #define BTA_HOST_INTERLEAVE_SEARCH FALSE//FALSE @@ -981,7 +992,7 @@ #endif #ifndef BTM_BLE_ADV_TX_POWER -#define BTM_BLE_ADV_TX_POWER {-21, -15, -7, 1, 9} +#define BTM_BLE_ADV_TX_POWER {-12, -9, -6, -3, 0, 3, 6, 9} #endif @@ -1145,6 +1156,20 @@ #define SMP_LINK_TOUT_MIN 2 #endif #endif + +/****************************************************************************** +** +** BT_SSP +** +******************************************************************************/ +#ifndef BT_SSP_INCLUDED +#define BT_SSP_INCLUDED FALSE +#endif + +#if BT_SSP_INCLUDED == TRUE && CLASSIC_BT_INCLUDED == FALSE +#error "Can't have SSP without CLASSIC BT" +#endif + /****************************************************************************** ** ** SDP diff --git a/tools/sdk/include/bluedroid/common/bte_appl.h b/tools/sdk/include/bluedroid/common/bte_appl.h index 4850250b..47a0184b 100644 --- a/tools/sdk/include/bluedroid/common/bte_appl.h +++ b/tools/sdk/include/bluedroid/common/bte_appl.h @@ -32,6 +32,18 @@ typedef struct { UINT8 ble_resp_key; UINT8 ble_max_key_size; #endif + } tBTE_APPL_CFG; extern tBTE_APPL_CFG bte_appl_cfg; + + +typedef struct { +#if ((CLASSIC_BT_INCLUDED == TRUE) && (BT_SSP_INCLUDED == TRUE)) + UINT8 bt_auth_req; + UINT8 bt_io_cap; + UINT8 *bt_oob_auth_data; +#endif +} tBTE_BT_APPL_CFG; + +extern tBTE_BT_APPL_CFG bte_bt_appl_cfg; \ No newline at end of file diff --git a/tools/sdk/include/bluedroid/esp_bt.h b/tools/sdk/include/bluedroid/esp_bt.h index fe594b03..3115cacd 100644 --- a/tools/sdk/include/bluedroid/esp_bt.h +++ b/tools/sdk/include/bluedroid/esp_bt.h @@ -25,83 +25,7 @@ extern "C" { #endif -/** - * @brief Controller config options, depend on config mask. - * Config mask indicate which functions enabled, this means - * some options or parameters of some functions enabled by config mask. - */ -typedef struct { - uint16_t controller_task_stack_size; /*!< Bluetooth controller task stack size */ - uint8_t controller_task_prio; /*!< Bluetooth controller task priority */ - uint8_t hci_uart_no; /*!< If use UART1/2 as HCI IO interface, indicate UART number */ - uint32_t hci_uart_baudrate; /*!< If use UART1/2 as HCI IO interface, indicate UART baudrate */ - uint8_t scan_duplicate_mode; /*!< If use UART1/2 as HCI IO interface, indicate UART baudrate */ - uint16_t normal_adv_size; /*!< Normal adv size for scan duplicate */ - uint16_t mesh_adv_size; /*!< Mesh adv size for scan duplicate */ - uint16_t send_adv_reserved_size; /*!< Controller minimum memory value */ - uint32_t controller_debug_flag; /*!< Controller debug log flag */ -} esp_bt_controller_config_t; - -#ifdef CONFIG_BT_ENABLED -/* While scanning, if the free memory value in controller is less than SCAN_SEND_ADV_RESERVED_SIZE, -the adv packet will be discarded until the memory is restored. */ -#define SCAN_SEND_ADV_RESERVED_SIZE 1000 -/* enable controller log debug when adv lost */ -#define CONTROLLER_ADV_LOST_DEBUG_BIT (0<<0) - -#ifdef CONFIG_BT_HCI_UART_NO -#define BT_HCI_UART_NO_DEFAULT CONFIG_BT_HCI_UART_NO -#else -#define BT_HCI_UART_NO_DEFAULT 1 -#endif /* BT_HCI_UART_NO_DEFAULT */ - -#ifdef CONFIG_BT_HCI_UART_BAUDRATE -#define BT_HCI_UART_BAUDRATE_DEFAULT CONFIG_BT_HCI_UART_BAUDRATE -#else -#define BT_HCI_UART_BAUDRATE_DEFAULT 921600 -#endif /* BT_HCI_UART_BAUDRATE_DEFAULT */ - -/* normal adv cache size */ -#ifdef CONFIG_DUPLICATE_SCAN_CACHE_SIZE -#define NORMAL_SCAN_DUPLICATE_CACHE_SIZE CONFIG_DUPLICATE_SCAN_CACHE_SIZE -#else -#define NORMAL_SCAN_DUPLICATE_CACHE_SIZE 20 -#endif - -#ifndef CONFIG_BLE_MESH_SCAN_DUPLICATE_EN -#define CONFIG_BLE_MESH_SCAN_DUPLICATE_EN FALSE -#endif - -#define SCAN_DUPLICATE_MODE_NORMAL_ADV_ONLY 0 -#define SCAN_DUPLICATE_MODE_NORMAL_ADV_MESH_ADV 1 - -#if CONFIG_BLE_MESH_SCAN_DUPLICATE_EN - #define SCAN_DUPLICATE_MODE SCAN_DUPLICATE_MODE_NORMAL_ADV_MESH_ADV - #ifdef CONFIG_MESH_DUPLICATE_SCAN_CACHE_SIZE - #define MESH_DUPLICATE_SCAN_CACHE_SIZE CONFIG_MESH_DUPLICATE_SCAN_CACHE_SIZE - #else - #define MESH_DUPLICATE_SCAN_CACHE_SIZE 50 - #endif -#else - #define SCAN_DUPLICATE_MODE SCAN_DUPLICATE_MODE_NORMAL_ADV_ONLY - #define MESH_DUPLICATE_SCAN_CACHE_SIZE 0 -#endif - -#define BT_CONTROLLER_INIT_CONFIG_DEFAULT() { \ - .controller_task_stack_size = ESP_TASK_BT_CONTROLLER_STACK, \ - .controller_task_prio = ESP_TASK_BT_CONTROLLER_PRIO, \ - .hci_uart_no = BT_HCI_UART_NO_DEFAULT, \ - .hci_uart_baudrate = BT_HCI_UART_BAUDRATE_DEFAULT, \ - .scan_duplicate_mode = SCAN_DUPLICATE_MODE, \ - .normal_adv_size = NORMAL_SCAN_DUPLICATE_CACHE_SIZE, \ - .mesh_adv_size = MESH_DUPLICATE_SCAN_CACHE_SIZE, \ - .send_adv_reserved_size = SCAN_SEND_ADV_RESERVED_SIZE, \ - .controller_debug_flag = CONTROLLER_ADV_LOST_DEBUG_BIT, \ -}; - -#else -#define BT_CONTROLLER_INIT_CONFIG_DEFAULT() {0}; _Static_assert(0, "please enable bluetooth in menuconfig to use bt.h"); -#endif +#define ESP_BT_CONTROLLER_CONFIG_MAGIC_VAL 0x5A5AA5A5 /** * @brief Bluetooth mode for controller enable/disable @@ -113,6 +37,122 @@ typedef enum { ESP_BT_MODE_BTDM = 0x03, /*!< Run dual mode */ } esp_bt_mode_t; +#ifdef CONFIG_BT_ENABLED +/* While scanning, if the free memory value in controller is less than SCAN_SEND_ADV_RESERVED_SIZE, +the adv packet will be discarded until the memory is restored. */ +#define SCAN_SEND_ADV_RESERVED_SIZE 1000 +/* enable controller log debug when adv lost */ +#define CONTROLLER_ADV_LOST_DEBUG_BIT (0<<0) + +#ifdef CONFIG_BT_HCI_UART_NO +#define BT_HCI_UART_NO_DEFAULT CONFIG_BT_HCI_UART_NO +#else +#define BT_HCI_UART_NO_DEFAULT 1 +#endif /* BT_HCI_UART_NO_DEFAULT */ + +#ifdef CONFIG_BT_HCI_UART_BAUDRATE +#define BT_HCI_UART_BAUDRATE_DEFAULT CONFIG_BT_HCI_UART_BAUDRATE +#else +#define BT_HCI_UART_BAUDRATE_DEFAULT 921600 +#endif /* BT_HCI_UART_BAUDRATE_DEFAULT */ + +#ifdef CONFIG_SCAN_DUPLICATE_TYPE +#define SCAN_DUPLICATE_TYPE_VALUE CONFIG_SCAN_DUPLICATE_TYPE +#else +#define SCAN_DUPLICATE_TYPE_VALUE 0 +#endif + +/* normal adv cache size */ +#ifdef CONFIG_DUPLICATE_SCAN_CACHE_SIZE +#define NORMAL_SCAN_DUPLICATE_CACHE_SIZE CONFIG_DUPLICATE_SCAN_CACHE_SIZE +#else +#define NORMAL_SCAN_DUPLICATE_CACHE_SIZE 20 +#endif + +#ifndef CONFIG_BLE_MESH_SCAN_DUPLICATE_EN +#define CONFIG_BLE_MESH_SCAN_DUPLICATE_EN FALSE +#endif + +#define SCAN_DUPLICATE_MODE_NORMAL_ADV_ONLY 0 +#define SCAN_DUPLICATE_MODE_NORMAL_ADV_MESH_ADV 1 + +#if CONFIG_BLE_MESH_SCAN_DUPLICATE_EN + #define SCAN_DUPLICATE_MODE SCAN_DUPLICATE_MODE_NORMAL_ADV_MESH_ADV + #ifdef CONFIG_MESH_DUPLICATE_SCAN_CACHE_SIZE + #define MESH_DUPLICATE_SCAN_CACHE_SIZE CONFIG_MESH_DUPLICATE_SCAN_CACHE_SIZE + #else + #define MESH_DUPLICATE_SCAN_CACHE_SIZE 50 + #endif +#else + #define SCAN_DUPLICATE_MODE SCAN_DUPLICATE_MODE_NORMAL_ADV_ONLY + #define MESH_DUPLICATE_SCAN_CACHE_SIZE 0 +#endif + +#if defined(CONFIG_BTDM_CONTROLLER_MODE_BLE_ONLY) +#define BTDM_CONTROLLER_MODE_EFF ESP_BT_MODE_BLE +#elif defined(CONFIG_BTDM_CONTROLLER_MODE_BR_EDR_ONLY) +#define BTDM_CONTROLLER_MODE_EFF ESP_BT_MODE_CLASSIC_BT +#else +#define BTDM_CONTROLLER_MODE_EFF ESP_BT_MODE_BTDM +#endif + +#define BTDM_CONTROLLER_BLE_MAX_CONN_LIMIT 9 //Maximum BLE connection limitation +#define BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN_LIMIT 7 //Maximum ACL connection limitation +#define BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_LIMIT 3 //Maximum SCO/eSCO connection limitation + +#define BT_CONTROLLER_INIT_CONFIG_DEFAULT() { \ + .controller_task_stack_size = ESP_TASK_BT_CONTROLLER_STACK, \ + .controller_task_prio = ESP_TASK_BT_CONTROLLER_PRIO, \ + .hci_uart_no = BT_HCI_UART_NO_DEFAULT, \ + .hci_uart_baudrate = BT_HCI_UART_BAUDRATE_DEFAULT, \ + .scan_duplicate_mode = SCAN_DUPLICATE_MODE, \ + .scan_duplicate_type = SCAN_DUPLICATE_TYPE_VALUE, \ + .normal_adv_size = NORMAL_SCAN_DUPLICATE_CACHE_SIZE, \ + .mesh_adv_size = MESH_DUPLICATE_SCAN_CACHE_SIZE, \ + .send_adv_reserved_size = SCAN_SEND_ADV_RESERVED_SIZE, \ + .controller_debug_flag = CONTROLLER_ADV_LOST_DEBUG_BIT, \ + .mode = BTDM_CONTROLLER_MODE_EFF, \ + .ble_max_conn = CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN_EFF, \ + .bt_max_acl_conn = CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN_EFF, \ + .bt_max_sync_conn = CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_EFF, \ + .magic = ESP_BT_CONTROLLER_CONFIG_MAGIC_VAL, \ +}; + +#else +#define BT_CONTROLLER_INIT_CONFIG_DEFAULT() {0}; _Static_assert(0, "please enable bluetooth in menuconfig to use bt.h"); +#endif + +/** + * @brief Controller config options, depend on config mask. + * Config mask indicate which functions enabled, this means + * some options or parameters of some functions enabled by config mask. + */ +typedef struct { + /* + * Following parameters can be configured runtime, when call esp_bt_controller_init() + */ + uint16_t controller_task_stack_size; /*!< Bluetooth controller task stack size */ + uint8_t controller_task_prio; /*!< Bluetooth controller task priority */ + uint8_t hci_uart_no; /*!< If use UART1/2 as HCI IO interface, indicate UART number */ + uint32_t hci_uart_baudrate; /*!< If use UART1/2 as HCI IO interface, indicate UART baudrate */ + uint8_t scan_duplicate_mode; /*!< scan duplicate mode */ + uint8_t scan_duplicate_type; /*!< scan duplicate type */ + uint16_t normal_adv_size; /*!< Normal adv size for scan duplicate */ + uint16_t mesh_adv_size; /*!< Mesh adv size for scan duplicate */ + uint16_t send_adv_reserved_size; /*!< Controller minimum memory value */ + uint32_t controller_debug_flag; /*!< Controller debug log flag */ + uint8_t mode; /*!< Controller mode: BR/EDR, BLE or Dual Mode */ + uint8_t ble_max_conn; /*!< BLE maximum connection numbers */ + uint8_t bt_max_acl_conn; /*!< BR/EDR maximum ACL connection numbers */ + /* + * Following parameters can not be configured runtime when call esp_bt_controller_init() + * It will be overwrite with a constant value which in menuconfig or from a macro. + * So, do not modify the value when esp_bt_controller_init() + */ + uint8_t bt_max_sync_conn; /*!< BR/EDR maximum ACL connection numbers. Effective in menuconfig */ + uint32_t magic; /*!< Magic number */ +} esp_bt_controller_config_t; + /** * @brief Bluetooth controller enable/disable/initialised/de-initialised status */ @@ -123,7 +163,6 @@ typedef enum { ESP_BT_CONTROLLER_STATUS_NUM, } esp_bt_controller_status_t; - /** * @brief BLE tx power type * ESP_BLE_PWR_TYPE_CONN_HDL0-8: for each connection, and only be set after connection completed. @@ -202,7 +241,7 @@ esp_power_level_t esp_ble_tx_power_get(esp_ble_power_type_t power_type); * BR/EDR power control will use the power in range of minimum value and maximum value. * The power level will effect the global BR/EDR TX power, such inquire, page, connection and so on. * Please call the function after esp_bt_controller_enable and before any function which cause RF do TX. - * So you can call the function can before do discover, beofre profile init and so on. + * So you can call the function before doing discovery, profile init and so on. * For example, if you want BR/EDR use the new TX power to do inquire, you should call * this function before inquire. Another word, If call this function when BR/EDR is in inquire(ING), * please do inquire again after call this function. @@ -231,10 +270,11 @@ esp_err_t esp_bredr_tx_power_get(esp_power_level_t *min_power_level, esp_power_l esp_err_t esp_bredr_sco_datapath_set(esp_sco_data_path_t data_path); /** - * @brief Initialize BT controller to allocate task and other resource. - * @param cfg: Initial configuration of BT controller. - * This function should be called only once, before any other BT functions are called. - * @return ESP_OK - success, other - failed + * @brief Initialize BT controller to allocate task and other resource. + * This function should be called only once, before any other BT functions are called. + * @param cfg: Initial configuration of BT controller. Different from previous version, there's a mode and some + * connection configuration in "cfg" to configure controller work mode and allocate the resource which is needed. + * @return ESP_OK - success, other - failed */ esp_err_t esp_bt_controller_init(esp_bt_controller_config_t *cfg); @@ -252,7 +292,8 @@ esp_err_t esp_bt_controller_deinit(void); * Due to a known issue, you cannot call esp_bt_controller_enable() a second time * to change the controller mode dynamically. To change controller mode, call * esp_bt_controller_disable() and then call esp_bt_controller_enable() with the new mode. - * @param mode : the mode(BLE/BT/BTDM) to enable. + * @param mode : the mode(BLE/BT/BTDM) to enable. For compatible of API, retain this argument. This mode must be + * equal as the mode in "cfg" of esp_bt_controller_init(). * @return ESP_OK - success, other - failed */ esp_err_t esp_bt_controller_enable(esp_bt_mode_t mode); @@ -291,40 +332,70 @@ bool esp_vhci_host_check_send_available(void); void esp_vhci_host_send_packet(uint8_t *data, uint16_t len); /** @brief esp_vhci_host_register_callback - * register the vhci referece callback, the call back + * register the vhci reference callback * struct defined by vhci_host_callback structure. * @param callback esp_vhci_host_callback type variable + * @return ESP_OK - success, ESP_FAIL - failed */ -void esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback); +esp_err_t esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback); /** @brief esp_bt_controller_mem_release - * release the memory by mode, if never use the bluetooth mode - * it can release the .bss, .data and other section to heap. - * The total size is about 70k bytes. + * release the controller memory as per the mode + * + * This function releases the BSS, data and other sections of the controller to heap. The total size is about 70k bytes. * * esp_bt_controller_mem_release(mode) should be called only before esp_bt_controller_init() * or after esp_bt_controller_deinit(). * - * Note that once BT controller memory is released, the process cannot be reversed. It means you can not use the bluetooth + * Note that once BT controller memory is released, the process cannot be reversed. It means you cannot use the bluetooth * mode which you have released by this function. * * If your firmware will later upgrade the Bluetooth controller mode (BLE -> BT Classic or disabled -> enabled) * then do not call this function. * * If the app calls esp_bt_controller_enable(ESP_BT_MODE_BLE) to use BLE only then it is safe to call - * esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT) at initialisation time to free unused BT Classic memory. + * esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT) at initialization time to free unused BT Classic memory. * - * If user never use bluetooth controller, could call esp_bt_controller_mem_release(ESP_BT_MODE_BTDM) - * before esp_bt_controller_init or after esp_bt_controller_deinit. - * - * For example, user only use bluetooth to config SSID and PASSWORD of WIFI, after config, will never use bluetooth. - * Then, could call esp_bt_controller_mem_release(ESP_BT_MODE_BTDM) after esp_bt_controller_deinit. + * If the mode is ESP_BT_MODE_BTDM, then it may be useful to call API esp_bt_mem_release(ESP_BT_MODE_BTDM) instead, + * which internally calls esp_bt_controller_mem_release(ESP_BT_MODE_BTDM) and additionally releases the BSS and data + * consumed by the BT/BLE host stack to heap. For more details about usage please refer to the documentation of + * esp_bt_mem_release() function * * @param mode : the mode want to release memory * @return ESP_OK - success, other - failed */ esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode); +/** @brief esp_bt_mem_release + * release controller memory and BSS and data section of the BT/BLE host stack as per the mode + * + * This function first releases controller memory by internally calling esp_bt_controller_mem_release(). + * Additionally, if the mode is set to ESP_BT_MODE_BTDM, it also releases the BSS and data consumed by the BT/BLE host stack to heap + * + * Note that once BT memory is released, the process cannot be reversed. It means you cannot use the bluetooth + * mode which you have released by this function. + * + * If your firmware will later upgrade the Bluetooth controller mode (BLE -> BT Classic or disabled -> enabled) + * then do not call this function. + * + * If you never intend to use bluetooth in a current boot-up cycle, you can call esp_bt_mem_release(ESP_BT_MODE_BTDM) + * before esp_bt_controller_init or after esp_bt_controller_deinit. + * + * For example, if a user only uses bluetooth for setting the WiFi configuration, and does not use bluetooth in the rest of the product operation". + * In such cases, after receiving the WiFi configuration, you can disable/deinit bluetooth and release its memory. + * Below is the sequence of APIs to be called for such scenarios: + * + * esp_bluedroid_disable(); + * esp_bluedroid_deinit(); + * esp_bt_controller_disable(); + * esp_bt_controller_deinit(); + * esp_bt_mem_release(ESP_BT_MODE_BTDM); + * + * @param mode : the mode whose memory is to be released + * @return ESP_OK - success, other - failed + */ +esp_err_t esp_bt_mem_release(esp_bt_mode_t mode); + /** * @brief enable bluetooth to enter modem sleep * @@ -377,10 +448,23 @@ bool esp_bt_controller_is_sleeping(void); * Note that after this request, bluetooth controller may again enter sleep as long as the modem sleep is enabled * * Profiling shows that it takes several milliseconds to wakeup from modem sleep after this request. - * Generally it takes longer if 32kHz XTAL is used than the main XTAL, due to the lower frequncy of the former as the bluetooth low power clock source. + * Generally it takes longer if 32kHz XTAL is used than the main XTAL, due to the lower frequency of the former as the bluetooth low power clock source. */ void esp_bt_controller_wakeup_request(void); +/** + * @brief Manually clear scan duplicate list + * + * Note that scan duplicate list will be automatically cleared when the maximum amount of device in the filter is reached + * the amount of device in the filter can be configured in menuconfig. + * + * + * @return + * - ESP_OK : success + * - other : failed + */ +esp_err_t esp_ble_scan_dupilcate_list_flush(void); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/bluedroid/hci/buffer_allocator.h b/tools/sdk/include/bluedroid/hci/buffer_allocator.h deleted file mode 100644 index da44bf6c..00000000 --- a/tools/sdk/include/bluedroid/hci/buffer_allocator.h +++ /dev/null @@ -1,25 +0,0 @@ -/****************************************************************************** - * - * Copyright (C) 2014 Google, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -#ifndef _BUFFER_ALLOCATOR_H_ - -#include "osi/allocator.h" - -const allocator_t *buffer_allocator_get_interface(); - -#endif /*_BUFFER_ALLOCATOR_H_*/ diff --git a/tools/sdk/include/bluedroid/hci/hci_packet_factory.h b/tools/sdk/include/bluedroid/hci/hci_packet_factory.h index e48c4be4..21bd2c9a 100644 --- a/tools/sdk/include/bluedroid/hci/hci_packet_factory.h +++ b/tools/sdk/include/bluedroid/hci/hci_packet_factory.h @@ -44,6 +44,7 @@ typedef struct { BT_HDR *(*make_ble_write_suggested_default_data_length)(uint16_t SuggestedMaxTxOctets, uint16_t SuggestedMaxTxTime); BT_HDR *(*make_ble_set_event_mask)(const bt_event_mask_t *event_mask); BT_HDR *(*make_write_sync_flow_control_enable)(uint8_t enable); + BT_HDR *(*make_write_default_erroneous_data_report)(uint8_t enable); } hci_packet_factory_t; const hci_packet_factory_t *hci_packet_factory_get_interface(); diff --git a/tools/sdk/include/bluedroid/hid_le_prf.h b/tools/sdk/include/bluedroid/hid_le_prf.h deleted file mode 100644 index 3b567d0c..00000000 --- a/tools/sdk/include/bluedroid/hid_le_prf.h +++ /dev/null @@ -1,265 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "prf_defs.h" - -#if (HIDD_LE_PROFILE_CFG) -#include "bta_gatts_int.h" -#include "stack/bt_types.h" -#include "bta/bta_api.h" -#include "stack/gatt_api.h" -#include "bt_app_api.h" - -/// Maximal number of HIDS that can be added in the DB -#ifndef USE_ONE_HIDS_INSTANCE -#define HIDD_LE_NB_HIDS_INST_MAX (2) -#else -#define HIDD_LE_NB_HIDS_INST_MAX (1) -#endif - -// Number of HID reports defined in the service -#define HID_NUM_REPORTS 9 - - -#define ATT_SVC_HID 0x1812 - -/// Maximal number of Report Char. that can be added in the DB for one HIDS - Up to 11 -#define HIDD_LE_NB_REPORT_INST_MAX (5) - -/// Maximal length of Report Char. Value -#define HIDD_LE_REPORT_MAX_LEN (45) -/// Maximal length of Report Map Char. Value -#define HIDD_LE_REPORT_MAP_MAX_LEN (512) - -/// Length of Boot Report Char. Value Maximal Length -#define HIDD_LE_BOOT_REPORT_MAX_LEN (8) - -/// Boot KB Input Report Notification Configuration Bit Mask -#define HIDD_LE_BOOT_KB_IN_NTF_CFG_MASK (0x40) -/// Boot KB Input Report Notification Configuration Bit Mask -#define HIDD_LE_BOOT_MOUSE_IN_NTF_CFG_MASK (0x80) -/// Boot Report Notification Configuration Bit Mask -#define HIDD_LE_REPORT_NTF_CFG_MASK (0x20) - - -/* HID information flags */ -#define HID_FLAGS_REMOTE_WAKE 0x01 // RemoteWake -#define HID_FLAGS_NORMALLY_CONNECTABLE 0x02 // NormallyConnectable - -/* Control point commands */ -#define HID_CMD_SUSPEND 0x00 // Suspend -#define HID_CMD_EXIT_SUSPEND 0x01 // Exit Suspend - -/* HID protocol mode values */ -#define HID_PROTOCOL_MODE_BOOT 0x00 // Boot Protocol Mode -#define HID_PROTOCOL_MODE_REPORT 0x01 // Report Protocol Mode - -/* Attribute value lengths */ -#define HID_PROTOCOL_MODE_LEN 1 // HID Protocol Mode -#define HID_INFORMATION_LEN 4 // HID Information -#define HID_REPORT_REF_LEN 2 // HID Report Reference Descriptor -#define HID_EXT_REPORT_REF_LEN 2 // External Report Reference Descriptor - -// HID feature flags -#define HID_KBD_FLAGS HID_FLAGS_REMOTE_WAKE - - -/// HID Service Attributes Indexes -enum { - HIDD_LE_IDX_SVC, - - // Included Service - HIDD_LE_IDX_INCL_SVC, - - // HID Information - HIDD_LE_IDX_HID_INFO_CHAR, - HIDD_LE_IDX_HID_INFO_VAL, - - // HID Control Point - HIDD_LE_IDX_HID_CTNL_PT_CHAR, - HIDD_LE_IDX_HID_CTNL_PT_VAL, - - // Report Map - HIDD_LE_IDX_REPORT_MAP_CHAR, - HIDD_LE_IDX_REPORT_MAP_VAL, - HIDD_LE_IDX_REPORT_MAP_EXT_REP_REF, - - // Protocol Mode - HIDD_LE_IDX_PROTO_MODE_CHAR, - HIDD_LE_IDX_PROTO_MODE_VAL, - - // Boot Keyboard Input Report - HIDD_LE_IDX_BOOT_KB_IN_REPORT_CHAR, - HIDD_LE_IDX_BOOT_KB_IN_REPORT_VAL, - HIDD_LE_IDX_BOOT_KB_IN_REPORT_NTF_CFG, - - // Boot Keyboard Output Report - HIDD_LE_IDX_BOOT_KB_OUT_REPORT_CHAR, - HIDD_LE_IDX_BOOT_KB_OUT_REPORT_VAL, - - // Boot Mouse Input Report - HIDD_LE_IDX_BOOT_MOUSE_IN_REPORT_CHAR, - HIDD_LE_IDX_BOOT_MOUSE_IN_REPORT_VAL, - HIDD_LE_IDX_BOOT_MOUSE_IN_REPORT_NTF_CFG, - - // Report - HIDD_LE_IDX_REPORT_CHAR, - HIDD_LE_IDX_REPORT_VAL, - HIDD_LE_IDX_REPORT_REP_REF, - HIDD_LE_IDX_REPORT_NTF_CFG, - - HIDD_LE_IDX_NB, -}; - - -/// Attribute Table Indexes -enum { - HIDD_LE_INFO_CHAR, - HIDD_LE_CTNL_PT_CHAR, - HIDD_LE_REPORT_MAP_CHAR, - HIDD_LE_REPORT_CHAR, - HIDD_LE_PROTO_MODE_CHAR, - HIDD_LE_BOOT_KB_IN_REPORT_CHAR, - HIDD_LE_BOOT_KB_OUT_REPORT_CHAR, - HIDD_LE_BOOT_MOUSE_IN_REPORT_CHAR, - HIDD_LE_CHAR_MAX //= HIDD_LE_REPORT_CHAR + HIDD_LE_NB_REPORT_INST_MAX, -}; - -///att read event table Indexs -enum { - HIDD_LE_READ_INFO_EVT, - HIDD_LE_READ_CTNL_PT_EVT, - HIDD_LE_READ_REPORT_MAP_EVT, - HIDD_LE_READ_REPORT_EVT, - HIDD_LE_READ_PROTO_MODE_EVT, - HIDD_LE_BOOT_KB_IN_REPORT_EVT, - HIDD_LE_BOOT_KB_OUT_REPORT_EVT, - HIDD_LE_BOOT_MOUSE_IN_REPORT_EVT, - - HID_LE_EVT_MAX -}; - -/// Client Characteristic Configuration Codes -enum { - HIDD_LE_DESC_MASK = 0x10, - - HIDD_LE_BOOT_KB_IN_REPORT_CFG = HIDD_LE_BOOT_KB_IN_REPORT_CHAR | HIDD_LE_DESC_MASK, - HIDD_LE_BOOT_MOUSE_IN_REPORT_CFG = HIDD_LE_BOOT_MOUSE_IN_REPORT_CHAR | HIDD_LE_DESC_MASK, - HIDD_LE_REPORT_CFG = HIDD_LE_REPORT_CHAR | HIDD_LE_DESC_MASK, -}; - -/// Features Flag Values -enum { - HIDD_LE_CFG_KEYBOARD = 0x01, - HIDD_LE_CFG_MOUSE = 0x02, - HIDD_LE_CFG_PROTO_MODE = 0x04, - HIDD_LE_CFG_MAP_EXT_REF = 0x08, - HIDD_LE_CFG_BOOT_KB_WR = 0x10, - HIDD_LE_CFG_BOOT_MOUSE_WR = 0x20, -}; - -/// Report Char. Configuration Flag Values -enum { - HIDD_LE_CFG_REPORT_IN = 0x01, - HIDD_LE_CFG_REPORT_OUT = 0x02, - //HOGPD_CFG_REPORT_FEAT can be used as a mask to check Report type - HIDD_LE_CFG_REPORT_FEAT = 0x03, - HIDD_LE_CFG_REPORT_WR = 0x10, -}; - -/// Pointer to the connection clean-up function -#define HIDD_LE_CLEANUP_FNCT (NULL) - -/* - * TYPE DEFINITIONS - **************************************************************************************** - */ - -/// HIDD Features structure -typedef struct { - /// Service Features - uint8_t svc_features; - /// Number of Report Char. instances to add in the database - uint8_t report_nb; - /// Report Char. Configuration - uint8_t report_char_cfg[HIDD_LE_NB_REPORT_INST_MAX]; -} hidd_feature_t; - - -typedef struct { - BOOLEAN in_use; - BOOLEAN congest; - uint16_t conn_id; - BOOLEAN connected; - BD_ADDR remote_bda; - uint32_t trans_id; - uint8_t cur_srvc_id; - -} hidd_clcb_t; - -// HID report mapping table -typedef struct { - uint16_t handle; // Handle of report characteristic - uint16_t cccdHandle; // Handle of CCCD for report characteristic - uint8_t id; // Report ID - uint8_t type; // Report type - uint8_t mode; // Protocol mode (report or boot) -} hidRptMap_t; - - -typedef struct { - /// hidd profile id - uint8_t app_id; - /// Notified handle - uint16_t ntf_handle; - ///Attribute handle Table - uint16_t att_tbl[HIDD_LE_CHAR_MAX]; - /// Supported Features - hidd_feature_t hidd_feature[HIDD_LE_NB_HIDS_INST_MAX]; - /// Current Protocol Mode - uint8_t proto_mode[HIDD_LE_NB_HIDS_INST_MAX]; - /// Number of HIDS added in the database - uint8_t hids_nb; - uint8_t pending_evt; - uint16_t pending_hal; -} hidd_inst_t; - - -/* service engine control block */ -typedef struct { - hidd_clcb_t hidd_clcb; /* connection link*/ - esp_gatt_if_t gatt_if; - BOOLEAN enabled; - BOOLEAN is_primery; - hidd_inst_t hidd_inst; - uint8_t inst_id; -} hidd_le_env_t; - -extern hidd_le_env_t hidd_le_env; - - -void hidd_le_create_service(BOOLEAN is_primary); - -void hidd_rsp (uint32_t trans_id, uint16_t conn_id, uint8_t app_id, - esp_gatt_status_t status, uint8_t event, tGATTS_DATA *p_rsp); - -void hidd_read_attr_value(tGATTS_DATA *p_data, uint32_t trans_id); - - -tGATT_STATUS hidd_le_init (void); - - -#endif ///HIDD_LE_PROFILE_CFG - - diff --git a/tools/sdk/include/bluedroid/osi/allocator.h b/tools/sdk/include/bluedroid/osi/allocator.h index 707901f4..888d8134 100644 --- a/tools/sdk/include/bluedroid/osi/allocator.h +++ b/tools/sdk/include/bluedroid/osi/allocator.h @@ -24,18 +24,6 @@ #include "esp_heap_caps.h" #include "sdkconfig.h" -typedef void *(*alloc_fn)(size_t size); -typedef void (*free_fn)(void *ptr); - -typedef struct { - alloc_fn alloc; - free_fn free; -} allocator_t; - -// allocator_t abstractions for the osi_*alloc and osi_free functions -extern const allocator_t allocator_malloc; -extern const allocator_t allocator_calloc; - char *osi_strdup(const char *str); void *osi_malloc_func(size_t size); diff --git a/tools/sdk/include/bluedroid/osi/fixed_queue.h b/tools/sdk/include/bluedroid/osi/fixed_queue.h index e3bf2f67..5ec0c074 100644 --- a/tools/sdk/include/bluedroid/osi/fixed_queue.h +++ b/tools/sdk/include/bluedroid/osi/fixed_queue.h @@ -22,6 +22,10 @@ #include #include "osi/list.h" +#ifndef QUEUE_SIZE_MAX +#define QUEUE_SIZE_MAX 254 +#endif + struct fixed_queue_t; typedef struct fixed_queue_t fixed_queue_t; diff --git a/tools/sdk/include/bluedroid/osi/thread.h b/tools/sdk/include/bluedroid/osi/thread.h index 8bb2fdc7..1aa773c0 100644 --- a/tools/sdk/include/bluedroid/osi/thread.h +++ b/tools/sdk/include/bluedroid/osi/thread.h @@ -69,7 +69,7 @@ typedef enum { #define HCI_H4_TASK_STACK_SIZE (2048 + BT_TASK_EXTRA_STACK_SIZE) #define HCI_H4_TASK_PRIO (configMAX_PRIORITIES - 4) #define HCI_H4_TASK_NAME "hciH4T" -#define HCI_H4_QUEUE_LEN 60 +#define HCI_H4_QUEUE_LEN 1 #define BTU_TASK_PINNED_TO_CORE (TASK_PINNED_TO_CORE) #define BTU_TASK_STACK_SIZE (4096 + BT_TASK_EXTRA_STACK_SIZE) diff --git a/tools/sdk/include/bluedroid/p_256_ecc_pp.h b/tools/sdk/include/bluedroid/p_256_ecc_pp.h index 029a79ff..f91d6056 100644 --- a/tools/sdk/include/bluedroid/p_256_ecc_pp.h +++ b/tools/sdk/include/bluedroid/p_256_ecc_pp.h @@ -58,6 +58,8 @@ extern elliptic_curve_t curve_p256; void ECC_PointMult_Bin_NAF(Point *q, Point *p, DWORD *n, uint32_t keyLength); +bool ECC_CheckPointIsInElliCur_P256(Point *p); + #define ECC_PointMult(q, p, n, keyLength) ECC_PointMult_Bin_NAF(q, p, n, keyLength) void p_256_init_curve(UINT32 keyLength); diff --git a/tools/sdk/include/bluedroid/smp_int.h b/tools/sdk/include/bluedroid/smp_int.h index 10d6f4bc..029869ef 100644 --- a/tools/sdk/include/bluedroid/smp_int.h +++ b/tools/sdk/include/bluedroid/smp_int.h @@ -132,6 +132,8 @@ typedef UINT8 tSMP_EVENT; /* Assumption it's only using the low 8 bits, if bigger than that, need to expand it to 16 bits */ #define SMP_SEC_KEY_MASK 0x00ff +#define SMP_PASSKEY_MASK 0xfff00000 + /* SMP pairing state */ enum { SMP_STATE_IDLE, @@ -331,6 +333,8 @@ typedef struct { UINT8 rcvd_cmd_len; UINT16 total_tx_unacked; BOOLEAN wait_for_authorization_complete; + BOOLEAN use_static_passkey; + UINT32 static_passkey; } tSMP_CB; /* Server Action functions are of this type */ diff --git a/tools/sdk/include/bluedroid/stack/avrc_defs.h b/tools/sdk/include/bluedroid/stack/avrc_defs.h index 1933d8a9..8c56cf53 100644 --- a/tools/sdk/include/bluedroid/stack/avrc_defs.h +++ b/tools/sdk/include/bluedroid/stack/avrc_defs.h @@ -47,21 +47,21 @@ /* command type codes */ #define AVRC_CMD_CTRL 0 /* Instruct a target to perform an operation */ -#define AVRC_CMD_STATUS 1 /* Check a device’s current status */ +#define AVRC_CMD_STATUS 1 /* Check a deviceÂ’s current status */ #define AVRC_CMD_SPEC_INQ 2 /* Check whether a target supports a particular control command; all operands are included */ -#define AVRC_CMD_NOTIF 3 /* Used for receiving notification of a change in a device’s state */ +#define AVRC_CMD_NOTIF 3 /* Used for receiving notification of a change in a deviceÂ’s state */ #define AVRC_CMD_GEN_INQ 4 /* Check whether a target supports a particular control command; operands are not included */ /* response type codes */ #define AVRC_RSP_NOT_IMPL 8 /* The target does not implement the command specified by the opcode and operand, - or doesn’t implement the specified subunit */ + or doesnÂ’t implement the specified subunit */ #define AVRC_RSP_ACCEPT 9 /* The target executed or is executing the command */ #define AVRC_RSP_REJ 10 /* The target implements the command specified by the opcode but cannot respond because the current state - of the target doesn’t allow it */ + of the target doesnÂ’t allow it */ #define AVRC_RSP_IN_TRANS 11 /* The target implements the status command but it is in a state of transition; the status command may be retried at a future time */ @@ -70,7 +70,7 @@ commands, the target returns stable and includes the status results */ #define AVRC_RSP_CHANGED 13 /* The response frame contains a notification that the - target device’s state has changed */ + target deviceÂ’s state has changed */ #define AVRC_RSP_INTERIM 15 /* For control commands, the target has accepted the request but cannot return information within 100 milliseconds; for notify commands, the target accepted diff --git a/tools/sdk/include/bluedroid/stack/btm_api.h b/tools/sdk/include/bluedroid/stack/btm_api.h index 067878a8..c483268a 100644 --- a/tools/sdk/include/bluedroid/stack/btm_api.h +++ b/tools/sdk/include/bluedroid/stack/btm_api.h @@ -3417,8 +3417,7 @@ BOOLEAN BTM_SecAddDevice (BD_ADDR bd_addr, DEV_CLASS dev_class, ** *******************************************************************************/ //extern -BOOLEAN BTM_SecDeleteDevice (BD_ADDR bd_addr); - +BOOLEAN BTM_SecDeleteDevice (BD_ADDR bd_addr, tBT_TRANSPORT transport); /******************************************************************************* ** diff --git a/tools/sdk/include/bluedroid/stack/btm_ble_api.h b/tools/sdk/include/bluedroid/stack/btm_ble_api.h index b3d254df..0a07c643 100644 --- a/tools/sdk/include/bluedroid/stack/btm_ble_api.h +++ b/tools/sdk/include/bluedroid/stack/btm_ble_api.h @@ -375,10 +375,7 @@ typedef UINT8 tBTM_BLE_AD_TYPE; /* adv tx power level */ #define BTM_BLE_ADV_TX_POWER_MIN 0 /* minimum tx power */ -#define BTM_BLE_ADV_TX_POWER_LOW 1 /* low tx power */ -#define BTM_BLE_ADV_TX_POWER_MID 2 /* middle tx power */ -#define BTM_BLE_ADV_TX_POWER_UPPER 3 /* upper tx power */ -#define BTM_BLE_ADV_TX_POWER_MAX 4 /* maximum tx power */ +#define BTM_BLE_ADV_TX_POWER_MAX 7 /* maximum tx power */ typedef UINT8 tBTM_BLE_ADV_TX_POWER; /* adv tx power in dBm */ @@ -582,6 +579,12 @@ typedef struct { tBTM_BLE_REF_VALUE ref_value; } tBTM_BLE_BATCH_SCAN_CB; +/// Ble scan duplicate type +enum { + BTM_BLE_SCAN_DUPLICATE_DISABLE = 0x0, /*!< the Link Layer should generate advertising reports to the host for each packet received */ + BTM_BLE_SCAN_DUPLICATE_ENABLE = 0x1, /*!< the Link Layer should filter out duplicate advertising reports to the Host */ + BTM_BLE_SCAN_DUPLICATE_MAX = 0x2, /*!< 0x02 – 0xFF, Reserved for future use */ +}; /* filter selection bit index */ #define BTM_BLE_PF_ADDR_FILTER 0 #define BTM_BLE_PF_SRVC_DATA 1 @@ -1312,6 +1315,21 @@ void BTM_SecurityGrant(BD_ADDR bd_addr, UINT8 res); //extern void BTM_BlePasskeyReply (BD_ADDR bd_addr, UINT8 res, UINT32 passkey); +/******************************************************************************* +** +** Function BTM_BleSetStaticPasskey +** +** Description This function is called to set static passkey +** +** +** Parameters: add - set static passkey when add is TRUE +** clear static passkey when add is FALSE +** passkey - static passkey +** +** +*******************************************************************************/ +void BTM_BleSetStaticPasskey(BOOLEAN add, UINT32 passkey); + /******************************************************************************* ** ** Function BTM_BleConfirmReply diff --git a/tools/sdk/include/bluedroid/stack/gatt_api.h b/tools/sdk/include/bluedroid/stack/gatt_api.h index 98cdcc7f..24a186ae 100644 --- a/tools/sdk/include/bluedroid/stack/gatt_api.h +++ b/tools/sdk/include/bluedroid/stack/gatt_api.h @@ -64,7 +64,7 @@ #define GATT_NOT_ENCRYPTED 0x8e #define GATT_CONGESTED 0x8f -#define GATT_DUP_REG 0x90 +#define GATT_DUP_REG 0x90 #define GATT_ALREADY_OPEN 0x91 #define GATT_CANCEL 0x92 @@ -111,6 +111,7 @@ typedef UINT8 tGATT_STATUS; #define GATT_SIGN_CMD_WRITE 0xD2 /* changed in V4.0 1101-0010 (signed write) see write cmd above*/ #define GATT_OP_CODE_MAX GATT_HANDLE_VALUE_CONF + 1 /* 0x1E = 30 + 1 = 31*/ +#define GATT_COMMAND_FLAG 0x40 /* Command Flag: set to one means commond */ #define GATT_HANDLE_IS_VALID(x) ((x) != 0) @@ -766,7 +767,7 @@ extern UINT16 GATTS_AddIncludeService (UINT16 service_handle, ** *******************************************************************************/ extern UINT16 GATTS_AddCharacteristic (UINT16 service_handle, tBT_UUID *p_char_uuid, - tGATT_PERM perm, tGATT_CHAR_PROP property, + tGATT_PERM perm, tGATT_CHAR_PROP property, tGATT_ATTR_VAL *attr_val, tGATTS_ATTR_CONTROL *control); /******************************************************************************* diff --git a/tools/sdk/include/bluedroid/stack/smp_api.h b/tools/sdk/include/bluedroid/stack/smp_api.h index 722850c3..6a3ca5af 100644 --- a/tools/sdk/include/bluedroid/stack/smp_api.h +++ b/tools/sdk/include/bluedroid/stack/smp_api.h @@ -401,6 +401,21 @@ extern void SMP_SecurityGrant(BD_ADDR bd_addr, UINT8 res); *******************************************************************************/ extern void SMP_PasskeyReply (BD_ADDR bd_addr, UINT8 res, UINT32 passkey); +/******************************************************************************* +** +** Function SMP_SetStaticPasskey +** +** Description This function is called to set static passkey +** +** +** Parameters: add - set static passkey when add is TRUE +** clear static passkey when add is FALSE +** passkey - static passkey +** +** +*******************************************************************************/ +extern void SMP_SetStaticPasskey (BOOLEAN add, UINT32 passkey); + /******************************************************************************* ** ** Function SMP_ConfirmReply diff --git a/tools/sdk/include/bootloader_support/bootloader_common.h b/tools/sdk/include/bootloader_support/bootloader_common.h index 07fc9341..d5a92cc7 100644 --- a/tools/sdk/include/bootloader_support/bootloader_common.h +++ b/tools/sdk/include/bootloader_support/bootloader_common.h @@ -68,3 +68,26 @@ bool bootloader_common_erase_part_type_data(const char *list_erase, bool ota_dat * @return Returns true if the list contains the label, false otherwise. */ bool bootloader_common_label_search(const char *list, char *label); + +/** + * @brief Calculates a sha-256 for a given partition or returns a appended digest. + * + * This function can be used to return the SHA-256 digest of application, bootloader and data partitions. + * For apps with SHA-256 appended to the app image, the result is the appended SHA-256 value for the app image content. + * The hash is verified before returning, if app content is invalid then the function returns ESP_ERR_IMAGE_INVALID. + * For apps without SHA-256 appended to the image, the result is the SHA-256 of all bytes in the app image. + * For other partition types, the result is the SHA-256 of the entire partition. + * + * @param[in] address Address of partition. + * @param[in] size Size of partition. + * @param[in] type Type of partition. For applications the type is 0, otherwise type is data. + * @param[out] out_sha_256 Returned SHA-256 digest for a given partition. + * + * @return + * - ESP_OK: In case of successful operation. + * - ESP_ERR_INVALID_ARG: The size was 0 or the sha_256 was NULL. + * - ESP_ERR_NO_MEM: Cannot allocate memory for sha256 operation. + * - ESP_ERR_IMAGE_INVALID: App partition doesn't contain a valid app image. + * - ESP_FAIL: An allocation error occurred. + */ +esp_err_t bootloader_common_get_sha256_of_partition(uint32_t address, uint32_t size, int type, uint8_t *out_sha_256); diff --git a/tools/sdk/include/bootloader_support/bootloader_random.h b/tools/sdk/include/bootloader_support/bootloader_random.h new file mode 100644 index 00000000..bb3b2a81 --- /dev/null +++ b/tools/sdk/include/bootloader_support/bootloader_random.h @@ -0,0 +1,49 @@ +// Copyright 2010-2016 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#pragma once + +#include + +/** + * @brief Enable early entropy source for RNG + * + * Uses the SAR ADC to feed entropy into the HWRNG. The ADC is put + * into a test mode that reads the 1.1V internal reference source and + * feeds the LSB of data into the HWRNG. + * + * Can also be used from app code early during operation, if entropy + * is required before WiFi stack is initialised. Call this function + * from app code only if WiFi/BT are not yet enabled and I2S and SAR + * ADC are not in use. + * + * Call bootloader_random_disable() when done. + */ +void bootloader_random_enable(void); + +/** + * @brief Disable early entropy source for RNG + * + * Disables SAR ADC source and resets the I2S hardware. + * + */ +void bootloader_random_disable(void); + +/** + * @brief Fill buffer with 'length' random bytes + * + * @param buffer Pointer to buffer + * @param length This many bytes of random data will be copied to buffer + */ +void bootloader_fill_random(void *buffer, size_t length); diff --git a/tools/sdk/include/bootloader_support/esp_flash_encrypt.h b/tools/sdk/include/bootloader_support/esp_flash_encrypt.h index ba370644..59eca33b 100644 --- a/tools/sdk/include/bootloader_support/esp_flash_encrypt.h +++ b/tools/sdk/include/bootloader_support/esp_flash_encrypt.h @@ -17,7 +17,9 @@ #include #include "esp_attr.h" #include "esp_err.h" +#ifndef BOOTLOADER_BUILD #include "esp_spi_flash.h" +#endif #include "soc/efuse_reg.h" /** @@ -83,6 +85,8 @@ static inline /** @cond */ IRAM_ATTR /** @endcond */ bool esp_flash_encryption_e * @note Take care not to power off the device while this function * is running, or the partition currently being encrypted will be lost. * + * @note RTC_WDT will reset while encryption operations will be performed (if RTC_WDT is configured). + * * @return ESP_OK if all operations succeeded, ESP_ERR_INVALID_STATE * if a fatal error occured during encryption of all partitions. */ @@ -91,6 +95,7 @@ esp_err_t esp_flash_encrypt_check_and_update(void); /** @brief Encrypt-in-place a block of flash sectors * + * @note This function resets RTC_WDT between operations with sectors. * @param src_addr Source offset in flash. Should be multiple of 4096 bytes. * @param data_length Length of data to encrypt in bytes. Will be rounded up to next multiple of 4096 bytes. * @@ -99,4 +104,14 @@ esp_err_t esp_flash_encrypt_check_and_update(void); */ esp_err_t esp_flash_encrypt_region(uint32_t src_addr, size_t data_length); +/** @brief Write protect FLASH_CRYPT_CNT + * + * Intended to be called as a part of boot process if flash encryption + * is enabled but secure boot is not used. This should protect against + * serial re-flashing of an unauthorised code in absence of secure boot. + * + * @return + */ +void esp_flash_write_protect_crypt_cnt(); + #endif diff --git a/tools/sdk/include/bootloader_support/esp_flash_partitions.h b/tools/sdk/include/bootloader_support/esp_flash_partitions.h index 24b6f25d..b5f37aa5 100644 --- a/tools/sdk/include/bootloader_support/esp_flash_partitions.h +++ b/tools/sdk/include/bootloader_support/esp_flash_partitions.h @@ -27,7 +27,7 @@ #define ESP_PARTITION_TABLE_MAX_LEN 0xC00 /* Maximum length of partition table data */ #define ESP_PARTITION_TABLE_MAX_ENTRIES (ESP_PARTITION_TABLE_MAX_LEN / sizeof(esp_partition_info_t)) /* Maximum length of partition table data, including terminating entry */ -/* @brief Verify the partition table (does not include verifying secure boot cryptographic signature) +/* @brief Verify the partition table * * @param partition_table Pointer to at least ESP_PARTITION_TABLE_MAX_ENTRIES of potential partition table data. (ESP_PARTITION_TABLE_MAX_LEN bytes.) * @param log_errors Log errors if the partition table is invalid. @@ -35,6 +35,13 @@ * * @return ESP_OK on success, ESP_ERR_INVALID_STATE if partition table is not valid. */ -esp_err_t esp_partition_table_basic_verify(const esp_partition_info_t *partition_table, bool log_errors, int *num_partitions); +esp_err_t esp_partition_table_verify(const esp_partition_info_t *partition_table, bool log_errors, int *num_partitions); + + +/* This function is included for compatibility with the ESP-IDF v3.x API */ +inline static __attribute__((deprecated)) esp_err_t esp_partition_table_basic_verify(const esp_partition_info_t *partition_table, bool log_errors, int *num_partitions) +{ + return esp_partition_table_verify(partition_table, log_errors, num_partitions); +} #endif diff --git a/tools/sdk/include/bootloader_support/esp_image_format.h b/tools/sdk/include/bootloader_support/esp_image_format.h index d2dcfd31..6d92a35b 100644 --- a/tools/sdk/include/bootloader_support/esp_image_format.h +++ b/tools/sdk/include/bootloader_support/esp_image_format.h @@ -36,7 +36,7 @@ typedef enum { } esp_image_spi_mode_t; /* SPI flash clock frequency */ -enum { +typedef enum { ESP_IMAGE_SPI_SPEED_40M, ESP_IMAGE_SPI_SPEED_26M, ESP_IMAGE_SPI_SPEED_20M, @@ -96,11 +96,12 @@ typedef struct { esp_image_segment_header_t segments[ESP_IMAGE_MAX_SEGMENTS]; /* Per-segment header data */ uint32_t segment_data[ESP_IMAGE_MAX_SEGMENTS]; /* Data offsets for each segment */ uint32_t image_len; /* Length of image on flash, in bytes */ + uint8_t image_digest[32]; /* appended SHA-256 digest */ } esp_image_metadata_t; /* Mode selection for esp_image_load() */ typedef enum { - ESP_IMAGE_VERIFY, /* Verify image contents, load metadata. Print errorsors. */ + ESP_IMAGE_VERIFY, /* Verify image contents, load metadata. Print errors. */ ESP_IMAGE_VERIFY_SILENT, /* Verify image contents, load metadata. Don't print errors. */ #ifdef BOOTLOADER_BUILD ESP_IMAGE_LOAD, /* Verify image contents, load to memory. Print errors. */ @@ -110,6 +111,11 @@ typedef enum { /** * @brief Verify and (optionally, in bootloader mode) load an app image. * + * This name is deprecated and is included for compatibility with the ESP-IDF v3.x API. + * It will be removed in V4.0 version. + * Function has been renamed to esp_image_verify(). + * Use function esp_image_verify() to verify a image. And use function bootloader_load_image() to load image from a bootloader space. + * * If encryption is enabled, data will be transparently decrypted. * * @param mode Mode of operation (verify, silent verify, or load). @@ -130,7 +136,60 @@ typedef enum { * - ESP_ERR_IMAGE_INVALID if the image appears invalid. * - ESP_ERR_INVALID_ARG if the partition or data pointers are invalid. */ -esp_err_t esp_image_load(esp_image_load_mode_t mode, const esp_partition_pos_t *part, esp_image_metadata_t *data); +esp_err_t esp_image_load(esp_image_load_mode_t mode, const esp_partition_pos_t *part, esp_image_metadata_t *data) __attribute__((deprecated)); + +/** + * @brief Verify an app image. + * + * If encryption is enabled, data will be transparently decrypted. + * + * @param mode Mode of operation (verify, silent verify, or load). + * @param part Partition to load the app from. + * @param[inout] data Pointer to the image metadata structure which is be filled in by this function. + * 'start_addr' member should be set (to the start address of the image.) + * Other fields will all be initialised by this function. + * + * Image validation checks: + * - Magic byte. + * - Partition smaller than 16MB. + * - All segments & image fit in partition. + * - 8 bit image checksum is valid. + * - SHA-256 of image is valid (if image has this appended). + * - (Signature) if signature verification is enabled. + * + * @return + * - ESP_OK if verify or load was successful + * - ESP_ERR_IMAGE_FLASH_FAIL if a SPI flash error occurs + * - ESP_ERR_IMAGE_INVALID if the image appears invalid. + * - ESP_ERR_INVALID_ARG if the partition or data pointers are invalid. + */ +esp_err_t esp_image_verify(esp_image_load_mode_t mode, const esp_partition_pos_t *part, esp_image_metadata_t *data); + +/** + * @brief Verify and load an app image (available only in space of bootloader). + * + * If encryption is enabled, data will be transparently decrypted. + * + * @param part Partition to load the app from. + * @param[inout] data Pointer to the image metadata structure which is be filled in by this function. + * 'start_addr' member should be set (to the start address of the image.) + * Other fields will all be initialised by this function. + * + * Image validation checks: + * - Magic byte. + * - Partition smaller than 16MB. + * - All segments & image fit in partition. + * - 8 bit image checksum is valid. + * - SHA-256 of image is valid (if image has this appended). + * - (Signature) if signature verification is enabled. + * + * @return + * - ESP_OK if verify or load was successful + * - ESP_ERR_IMAGE_FLASH_FAIL if a SPI flash error occurs + * - ESP_ERR_IMAGE_INVALID if the image appears invalid. + * - ESP_ERR_INVALID_ARG if the partition or data pointers are invalid. + */ +esp_err_t bootloader_load_image(const esp_partition_pos_t *part, esp_image_metadata_t *data); /** * @brief Verify the bootloader image. diff --git a/tools/sdk/include/bootloader_support/esp_secure_boot.h b/tools/sdk/include/bootloader_support/esp_secure_boot.h index 6aa4b628..370bdd36 100644 --- a/tools/sdk/include/bootloader_support/esp_secure_boot.h +++ b/tools/sdk/include/bootloader_support/esp_secure_boot.h @@ -17,6 +17,14 @@ #include #include "soc/efuse_reg.h" +#include "sdkconfig.h" + +#ifdef CONFIG_SECURE_BOOT_ENABLED +#if !defined(CONFIG_SECURE_SIGNED_ON_BOOT) || !defined(CONFIG_SECURE_SIGNED_ON_UPDATE) || !defined(CONFIG_SECURE_SIGNED_APPS) +#error "internal sdkconfig error, secure boot should always enable all signature options" +#endif +#endif + #ifdef __cplusplus extern "C" { #endif diff --git a/tools/sdk/include/bt/esp_bt.h b/tools/sdk/include/bt/esp_bt.h index fe594b03..3115cacd 100644 --- a/tools/sdk/include/bt/esp_bt.h +++ b/tools/sdk/include/bt/esp_bt.h @@ -25,83 +25,7 @@ extern "C" { #endif -/** - * @brief Controller config options, depend on config mask. - * Config mask indicate which functions enabled, this means - * some options or parameters of some functions enabled by config mask. - */ -typedef struct { - uint16_t controller_task_stack_size; /*!< Bluetooth controller task stack size */ - uint8_t controller_task_prio; /*!< Bluetooth controller task priority */ - uint8_t hci_uart_no; /*!< If use UART1/2 as HCI IO interface, indicate UART number */ - uint32_t hci_uart_baudrate; /*!< If use UART1/2 as HCI IO interface, indicate UART baudrate */ - uint8_t scan_duplicate_mode; /*!< If use UART1/2 as HCI IO interface, indicate UART baudrate */ - uint16_t normal_adv_size; /*!< Normal adv size for scan duplicate */ - uint16_t mesh_adv_size; /*!< Mesh adv size for scan duplicate */ - uint16_t send_adv_reserved_size; /*!< Controller minimum memory value */ - uint32_t controller_debug_flag; /*!< Controller debug log flag */ -} esp_bt_controller_config_t; - -#ifdef CONFIG_BT_ENABLED -/* While scanning, if the free memory value in controller is less than SCAN_SEND_ADV_RESERVED_SIZE, -the adv packet will be discarded until the memory is restored. */ -#define SCAN_SEND_ADV_RESERVED_SIZE 1000 -/* enable controller log debug when adv lost */ -#define CONTROLLER_ADV_LOST_DEBUG_BIT (0<<0) - -#ifdef CONFIG_BT_HCI_UART_NO -#define BT_HCI_UART_NO_DEFAULT CONFIG_BT_HCI_UART_NO -#else -#define BT_HCI_UART_NO_DEFAULT 1 -#endif /* BT_HCI_UART_NO_DEFAULT */ - -#ifdef CONFIG_BT_HCI_UART_BAUDRATE -#define BT_HCI_UART_BAUDRATE_DEFAULT CONFIG_BT_HCI_UART_BAUDRATE -#else -#define BT_HCI_UART_BAUDRATE_DEFAULT 921600 -#endif /* BT_HCI_UART_BAUDRATE_DEFAULT */ - -/* normal adv cache size */ -#ifdef CONFIG_DUPLICATE_SCAN_CACHE_SIZE -#define NORMAL_SCAN_DUPLICATE_CACHE_SIZE CONFIG_DUPLICATE_SCAN_CACHE_SIZE -#else -#define NORMAL_SCAN_DUPLICATE_CACHE_SIZE 20 -#endif - -#ifndef CONFIG_BLE_MESH_SCAN_DUPLICATE_EN -#define CONFIG_BLE_MESH_SCAN_DUPLICATE_EN FALSE -#endif - -#define SCAN_DUPLICATE_MODE_NORMAL_ADV_ONLY 0 -#define SCAN_DUPLICATE_MODE_NORMAL_ADV_MESH_ADV 1 - -#if CONFIG_BLE_MESH_SCAN_DUPLICATE_EN - #define SCAN_DUPLICATE_MODE SCAN_DUPLICATE_MODE_NORMAL_ADV_MESH_ADV - #ifdef CONFIG_MESH_DUPLICATE_SCAN_CACHE_SIZE - #define MESH_DUPLICATE_SCAN_CACHE_SIZE CONFIG_MESH_DUPLICATE_SCAN_CACHE_SIZE - #else - #define MESH_DUPLICATE_SCAN_CACHE_SIZE 50 - #endif -#else - #define SCAN_DUPLICATE_MODE SCAN_DUPLICATE_MODE_NORMAL_ADV_ONLY - #define MESH_DUPLICATE_SCAN_CACHE_SIZE 0 -#endif - -#define BT_CONTROLLER_INIT_CONFIG_DEFAULT() { \ - .controller_task_stack_size = ESP_TASK_BT_CONTROLLER_STACK, \ - .controller_task_prio = ESP_TASK_BT_CONTROLLER_PRIO, \ - .hci_uart_no = BT_HCI_UART_NO_DEFAULT, \ - .hci_uart_baudrate = BT_HCI_UART_BAUDRATE_DEFAULT, \ - .scan_duplicate_mode = SCAN_DUPLICATE_MODE, \ - .normal_adv_size = NORMAL_SCAN_DUPLICATE_CACHE_SIZE, \ - .mesh_adv_size = MESH_DUPLICATE_SCAN_CACHE_SIZE, \ - .send_adv_reserved_size = SCAN_SEND_ADV_RESERVED_SIZE, \ - .controller_debug_flag = CONTROLLER_ADV_LOST_DEBUG_BIT, \ -}; - -#else -#define BT_CONTROLLER_INIT_CONFIG_DEFAULT() {0}; _Static_assert(0, "please enable bluetooth in menuconfig to use bt.h"); -#endif +#define ESP_BT_CONTROLLER_CONFIG_MAGIC_VAL 0x5A5AA5A5 /** * @brief Bluetooth mode for controller enable/disable @@ -113,6 +37,122 @@ typedef enum { ESP_BT_MODE_BTDM = 0x03, /*!< Run dual mode */ } esp_bt_mode_t; +#ifdef CONFIG_BT_ENABLED +/* While scanning, if the free memory value in controller is less than SCAN_SEND_ADV_RESERVED_SIZE, +the adv packet will be discarded until the memory is restored. */ +#define SCAN_SEND_ADV_RESERVED_SIZE 1000 +/* enable controller log debug when adv lost */ +#define CONTROLLER_ADV_LOST_DEBUG_BIT (0<<0) + +#ifdef CONFIG_BT_HCI_UART_NO +#define BT_HCI_UART_NO_DEFAULT CONFIG_BT_HCI_UART_NO +#else +#define BT_HCI_UART_NO_DEFAULT 1 +#endif /* BT_HCI_UART_NO_DEFAULT */ + +#ifdef CONFIG_BT_HCI_UART_BAUDRATE +#define BT_HCI_UART_BAUDRATE_DEFAULT CONFIG_BT_HCI_UART_BAUDRATE +#else +#define BT_HCI_UART_BAUDRATE_DEFAULT 921600 +#endif /* BT_HCI_UART_BAUDRATE_DEFAULT */ + +#ifdef CONFIG_SCAN_DUPLICATE_TYPE +#define SCAN_DUPLICATE_TYPE_VALUE CONFIG_SCAN_DUPLICATE_TYPE +#else +#define SCAN_DUPLICATE_TYPE_VALUE 0 +#endif + +/* normal adv cache size */ +#ifdef CONFIG_DUPLICATE_SCAN_CACHE_SIZE +#define NORMAL_SCAN_DUPLICATE_CACHE_SIZE CONFIG_DUPLICATE_SCAN_CACHE_SIZE +#else +#define NORMAL_SCAN_DUPLICATE_CACHE_SIZE 20 +#endif + +#ifndef CONFIG_BLE_MESH_SCAN_DUPLICATE_EN +#define CONFIG_BLE_MESH_SCAN_DUPLICATE_EN FALSE +#endif + +#define SCAN_DUPLICATE_MODE_NORMAL_ADV_ONLY 0 +#define SCAN_DUPLICATE_MODE_NORMAL_ADV_MESH_ADV 1 + +#if CONFIG_BLE_MESH_SCAN_DUPLICATE_EN + #define SCAN_DUPLICATE_MODE SCAN_DUPLICATE_MODE_NORMAL_ADV_MESH_ADV + #ifdef CONFIG_MESH_DUPLICATE_SCAN_CACHE_SIZE + #define MESH_DUPLICATE_SCAN_CACHE_SIZE CONFIG_MESH_DUPLICATE_SCAN_CACHE_SIZE + #else + #define MESH_DUPLICATE_SCAN_CACHE_SIZE 50 + #endif +#else + #define SCAN_DUPLICATE_MODE SCAN_DUPLICATE_MODE_NORMAL_ADV_ONLY + #define MESH_DUPLICATE_SCAN_CACHE_SIZE 0 +#endif + +#if defined(CONFIG_BTDM_CONTROLLER_MODE_BLE_ONLY) +#define BTDM_CONTROLLER_MODE_EFF ESP_BT_MODE_BLE +#elif defined(CONFIG_BTDM_CONTROLLER_MODE_BR_EDR_ONLY) +#define BTDM_CONTROLLER_MODE_EFF ESP_BT_MODE_CLASSIC_BT +#else +#define BTDM_CONTROLLER_MODE_EFF ESP_BT_MODE_BTDM +#endif + +#define BTDM_CONTROLLER_BLE_MAX_CONN_LIMIT 9 //Maximum BLE connection limitation +#define BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN_LIMIT 7 //Maximum ACL connection limitation +#define BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_LIMIT 3 //Maximum SCO/eSCO connection limitation + +#define BT_CONTROLLER_INIT_CONFIG_DEFAULT() { \ + .controller_task_stack_size = ESP_TASK_BT_CONTROLLER_STACK, \ + .controller_task_prio = ESP_TASK_BT_CONTROLLER_PRIO, \ + .hci_uart_no = BT_HCI_UART_NO_DEFAULT, \ + .hci_uart_baudrate = BT_HCI_UART_BAUDRATE_DEFAULT, \ + .scan_duplicate_mode = SCAN_DUPLICATE_MODE, \ + .scan_duplicate_type = SCAN_DUPLICATE_TYPE_VALUE, \ + .normal_adv_size = NORMAL_SCAN_DUPLICATE_CACHE_SIZE, \ + .mesh_adv_size = MESH_DUPLICATE_SCAN_CACHE_SIZE, \ + .send_adv_reserved_size = SCAN_SEND_ADV_RESERVED_SIZE, \ + .controller_debug_flag = CONTROLLER_ADV_LOST_DEBUG_BIT, \ + .mode = BTDM_CONTROLLER_MODE_EFF, \ + .ble_max_conn = CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN_EFF, \ + .bt_max_acl_conn = CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN_EFF, \ + .bt_max_sync_conn = CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_EFF, \ + .magic = ESP_BT_CONTROLLER_CONFIG_MAGIC_VAL, \ +}; + +#else +#define BT_CONTROLLER_INIT_CONFIG_DEFAULT() {0}; _Static_assert(0, "please enable bluetooth in menuconfig to use bt.h"); +#endif + +/** + * @brief Controller config options, depend on config mask. + * Config mask indicate which functions enabled, this means + * some options or parameters of some functions enabled by config mask. + */ +typedef struct { + /* + * Following parameters can be configured runtime, when call esp_bt_controller_init() + */ + uint16_t controller_task_stack_size; /*!< Bluetooth controller task stack size */ + uint8_t controller_task_prio; /*!< Bluetooth controller task priority */ + uint8_t hci_uart_no; /*!< If use UART1/2 as HCI IO interface, indicate UART number */ + uint32_t hci_uart_baudrate; /*!< If use UART1/2 as HCI IO interface, indicate UART baudrate */ + uint8_t scan_duplicate_mode; /*!< scan duplicate mode */ + uint8_t scan_duplicate_type; /*!< scan duplicate type */ + uint16_t normal_adv_size; /*!< Normal adv size for scan duplicate */ + uint16_t mesh_adv_size; /*!< Mesh adv size for scan duplicate */ + uint16_t send_adv_reserved_size; /*!< Controller minimum memory value */ + uint32_t controller_debug_flag; /*!< Controller debug log flag */ + uint8_t mode; /*!< Controller mode: BR/EDR, BLE or Dual Mode */ + uint8_t ble_max_conn; /*!< BLE maximum connection numbers */ + uint8_t bt_max_acl_conn; /*!< BR/EDR maximum ACL connection numbers */ + /* + * Following parameters can not be configured runtime when call esp_bt_controller_init() + * It will be overwrite with a constant value which in menuconfig or from a macro. + * So, do not modify the value when esp_bt_controller_init() + */ + uint8_t bt_max_sync_conn; /*!< BR/EDR maximum ACL connection numbers. Effective in menuconfig */ + uint32_t magic; /*!< Magic number */ +} esp_bt_controller_config_t; + /** * @brief Bluetooth controller enable/disable/initialised/de-initialised status */ @@ -123,7 +163,6 @@ typedef enum { ESP_BT_CONTROLLER_STATUS_NUM, } esp_bt_controller_status_t; - /** * @brief BLE tx power type * ESP_BLE_PWR_TYPE_CONN_HDL0-8: for each connection, and only be set after connection completed. @@ -202,7 +241,7 @@ esp_power_level_t esp_ble_tx_power_get(esp_ble_power_type_t power_type); * BR/EDR power control will use the power in range of minimum value and maximum value. * The power level will effect the global BR/EDR TX power, such inquire, page, connection and so on. * Please call the function after esp_bt_controller_enable and before any function which cause RF do TX. - * So you can call the function can before do discover, beofre profile init and so on. + * So you can call the function before doing discovery, profile init and so on. * For example, if you want BR/EDR use the new TX power to do inquire, you should call * this function before inquire. Another word, If call this function when BR/EDR is in inquire(ING), * please do inquire again after call this function. @@ -231,10 +270,11 @@ esp_err_t esp_bredr_tx_power_get(esp_power_level_t *min_power_level, esp_power_l esp_err_t esp_bredr_sco_datapath_set(esp_sco_data_path_t data_path); /** - * @brief Initialize BT controller to allocate task and other resource. - * @param cfg: Initial configuration of BT controller. - * This function should be called only once, before any other BT functions are called. - * @return ESP_OK - success, other - failed + * @brief Initialize BT controller to allocate task and other resource. + * This function should be called only once, before any other BT functions are called. + * @param cfg: Initial configuration of BT controller. Different from previous version, there's a mode and some + * connection configuration in "cfg" to configure controller work mode and allocate the resource which is needed. + * @return ESP_OK - success, other - failed */ esp_err_t esp_bt_controller_init(esp_bt_controller_config_t *cfg); @@ -252,7 +292,8 @@ esp_err_t esp_bt_controller_deinit(void); * Due to a known issue, you cannot call esp_bt_controller_enable() a second time * to change the controller mode dynamically. To change controller mode, call * esp_bt_controller_disable() and then call esp_bt_controller_enable() with the new mode. - * @param mode : the mode(BLE/BT/BTDM) to enable. + * @param mode : the mode(BLE/BT/BTDM) to enable. For compatible of API, retain this argument. This mode must be + * equal as the mode in "cfg" of esp_bt_controller_init(). * @return ESP_OK - success, other - failed */ esp_err_t esp_bt_controller_enable(esp_bt_mode_t mode); @@ -291,40 +332,70 @@ bool esp_vhci_host_check_send_available(void); void esp_vhci_host_send_packet(uint8_t *data, uint16_t len); /** @brief esp_vhci_host_register_callback - * register the vhci referece callback, the call back + * register the vhci reference callback * struct defined by vhci_host_callback structure. * @param callback esp_vhci_host_callback type variable + * @return ESP_OK - success, ESP_FAIL - failed */ -void esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback); +esp_err_t esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback); /** @brief esp_bt_controller_mem_release - * release the memory by mode, if never use the bluetooth mode - * it can release the .bss, .data and other section to heap. - * The total size is about 70k bytes. + * release the controller memory as per the mode + * + * This function releases the BSS, data and other sections of the controller to heap. The total size is about 70k bytes. * * esp_bt_controller_mem_release(mode) should be called only before esp_bt_controller_init() * or after esp_bt_controller_deinit(). * - * Note that once BT controller memory is released, the process cannot be reversed. It means you can not use the bluetooth + * Note that once BT controller memory is released, the process cannot be reversed. It means you cannot use the bluetooth * mode which you have released by this function. * * If your firmware will later upgrade the Bluetooth controller mode (BLE -> BT Classic or disabled -> enabled) * then do not call this function. * * If the app calls esp_bt_controller_enable(ESP_BT_MODE_BLE) to use BLE only then it is safe to call - * esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT) at initialisation time to free unused BT Classic memory. + * esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT) at initialization time to free unused BT Classic memory. * - * If user never use bluetooth controller, could call esp_bt_controller_mem_release(ESP_BT_MODE_BTDM) - * before esp_bt_controller_init or after esp_bt_controller_deinit. - * - * For example, user only use bluetooth to config SSID and PASSWORD of WIFI, after config, will never use bluetooth. - * Then, could call esp_bt_controller_mem_release(ESP_BT_MODE_BTDM) after esp_bt_controller_deinit. + * If the mode is ESP_BT_MODE_BTDM, then it may be useful to call API esp_bt_mem_release(ESP_BT_MODE_BTDM) instead, + * which internally calls esp_bt_controller_mem_release(ESP_BT_MODE_BTDM) and additionally releases the BSS and data + * consumed by the BT/BLE host stack to heap. For more details about usage please refer to the documentation of + * esp_bt_mem_release() function * * @param mode : the mode want to release memory * @return ESP_OK - success, other - failed */ esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode); +/** @brief esp_bt_mem_release + * release controller memory and BSS and data section of the BT/BLE host stack as per the mode + * + * This function first releases controller memory by internally calling esp_bt_controller_mem_release(). + * Additionally, if the mode is set to ESP_BT_MODE_BTDM, it also releases the BSS and data consumed by the BT/BLE host stack to heap + * + * Note that once BT memory is released, the process cannot be reversed. It means you cannot use the bluetooth + * mode which you have released by this function. + * + * If your firmware will later upgrade the Bluetooth controller mode (BLE -> BT Classic or disabled -> enabled) + * then do not call this function. + * + * If you never intend to use bluetooth in a current boot-up cycle, you can call esp_bt_mem_release(ESP_BT_MODE_BTDM) + * before esp_bt_controller_init or after esp_bt_controller_deinit. + * + * For example, if a user only uses bluetooth for setting the WiFi configuration, and does not use bluetooth in the rest of the product operation". + * In such cases, after receiving the WiFi configuration, you can disable/deinit bluetooth and release its memory. + * Below is the sequence of APIs to be called for such scenarios: + * + * esp_bluedroid_disable(); + * esp_bluedroid_deinit(); + * esp_bt_controller_disable(); + * esp_bt_controller_deinit(); + * esp_bt_mem_release(ESP_BT_MODE_BTDM); + * + * @param mode : the mode whose memory is to be released + * @return ESP_OK - success, other - failed + */ +esp_err_t esp_bt_mem_release(esp_bt_mode_t mode); + /** * @brief enable bluetooth to enter modem sleep * @@ -377,10 +448,23 @@ bool esp_bt_controller_is_sleeping(void); * Note that after this request, bluetooth controller may again enter sleep as long as the modem sleep is enabled * * Profiling shows that it takes several milliseconds to wakeup from modem sleep after this request. - * Generally it takes longer if 32kHz XTAL is used than the main XTAL, due to the lower frequncy of the former as the bluetooth low power clock source. + * Generally it takes longer if 32kHz XTAL is used than the main XTAL, due to the lower frequency of the former as the bluetooth low power clock source. */ void esp_bt_controller_wakeup_request(void); +/** + * @brief Manually clear scan duplicate list + * + * Note that scan duplicate list will be automatically cleared when the maximum amount of device in the filter is reached + * the amount of device in the filter can be configured in menuconfig. + * + * + * @return + * - ESP_OK : success + * - other : failed + */ +esp_err_t esp_ble_scan_dupilcate_list_flush(void); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/config/sdkconfig.h b/tools/sdk/include/config/sdkconfig.h index be1114e1..95967a29 100644 --- a/tools/sdk/include/config/sdkconfig.h +++ b/tools/sdk/include/config/sdkconfig.h @@ -8,8 +8,10 @@ #define CONFIG_ESP32_PHY_MAX_TX_POWER 20 #define CONFIG_TRACEMEM_RESERVE_DRAM 0x0 #define CONFIG_FREERTOS_MAX_TASK_NAME_LEN 16 +#define CONFIG_MQTT_TRANSPORT_SSL 1 #define CONFIG_BLE_SMP_ENABLE 1 #define CONFIG_STACK_CHECK 1 +#define CONFIG_MQTT_PROTOCOL_311 1 #define CONFIG_TCP_RECVMBOX_SIZE 6 #define CONFIG_LWIP_ETHARP_TRUST_IP_MAC 1 #define CONFIG_BLE_SCAN_DUPLICATE 1 @@ -41,10 +43,13 @@ #define CONFIG_SPIFFS_CACHE 1 #define CONFIG_INT_WDT 1 #define CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL 1 +#define CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN 3 #define CONFIG_MBEDTLS_SSL_PROTO_TLS1 1 #define CONFIG_BT_STACK_NO_LOG 1 +#define CONFIG_ESP_GRATUITOUS_ARP 1 #define CONFIG_MBEDTLS_ECDSA_C 1 #define CONFIG_ESPTOOLPY_FLASHFREQ_40M 1 +#define CONFIG_HTTPD_MAX_REQ_HDR_LEN 512 #define CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE 0 #define CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS 1 #define CONFIG_MBEDTLS_ECDH_C 1 @@ -54,7 +59,7 @@ #define CONFIG_MBEDTLS_SSL_ALPN 1 #define CONFIG_MBEDTLS_PEM_WRITE_C 1 #define CONFIG_BT_SPP_ENABLED 1 -#define CONFIG_BT_RESERVE_DRAM 0x10000 +#define CONFIG_BT_RESERVE_DRAM 0xdb5c #define CONFIG_CXX_EXCEPTIONS 1 #define CONFIG_FATFS_FS_LOCK 0 #define CONFIG_IP_LOST_TIMER_INTERVAL 120 @@ -71,6 +76,8 @@ #define CONFIG_TIMER_TASK_STACK_DEPTH 2048 #define CONFIG_TCP_MSS 1436 #define CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED 1 +#define CONFIG_BTDM_CONTROLLER_MODE_BTDM 1 +#define CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN_EFF 3 #define CONFIG_FATFS_CODEPAGE 850 #define CONFIG_ULP_COPROC_RESERVE_MEM 512 #define CONFIG_LWIP_MAX_UDP_PCBS 16 @@ -102,6 +109,7 @@ #define CONFIG_TIMER_TASK_STACK_SIZE 4096 #define CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE 1 #define CONFIG_MBEDTLS_X509_CRL_PARSE_C 1 +#define CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR 1 #define CONFIG_LWIP_DHCPS_LEASE_UNIT 60 #define CONFIG_SPIFFS_USE_MAGIC 1 #define CONFIG_TCPIP_TASK_STACK_SIZE 2560 @@ -139,6 +147,7 @@ #define CONFIG_MDNS_MAX_SERVICES 10 #define CONFIG_ULP_COPROC_ENABLED 1 #define CONFIG_HFP_AUDIO_DATA_PATH_PCM 1 +#define CONFIG_EMAC_CHECK_LINK_PERIOD_MS 2000 #define CONFIG_BTDM_LPCLK_SEL_MAIN_XTAL 1 #define CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED 1 #define CONFIG_LIBSODIUM_USE_MBEDTLS_SHA 1 @@ -146,6 +155,7 @@ #define CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED 1 #define CONFIG_TCP_SYNMAXRTX 6 #define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA 1 +#define CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_EFF 0 #define CONFIG_HEAP_POISONING_LIGHT 1 #define CONFIG_PYTHON "python" #define CONFIG_MBEDTLS_ECP_NIST_OPTIM 1 @@ -153,6 +163,7 @@ #define CONFIG_ESPTOOLPY_COMPRESSED 1 #define CONFIG_PARTITION_TABLE_FILENAME "partitions_singleapp.csv" #define CONFIG_TCP_SND_BUF_DEFAULT 5744 +#define CONFIG_GARP_TMR_INTERVAL 60 #define CONFIG_LWIP_DHCP_MAX_NTP_SERVERS 1 #define CONFIG_TCP_MSL 60000 #define CONFIG_MBEDTLS_SSL_PROTO_TLS1_1 1 @@ -161,8 +172,13 @@ #define CONFIG_ESP32_WIFI_RX_BA_WIN 6 #define CONFIG_MBEDTLS_X509_CSR_PARSE_C 1 #define CONFIG_SPIFFS_USE_MTIME 1 +#define CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN 0 +#define CONFIG_LWIP_DHCP_RESTORE_LAST_IP 1 +#define CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN 2 +#define CONFIG_EMAC_TASK_STACK_SIZE 3072 #define CONFIG_SW_COEXIST_PREFERENCE_VALUE 2 #define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA 1 +#define CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER 1 #define CONFIG_PPP_SUPPORT 1 #define CONFIG_SPIRAM_SPEED_40M 1 #define CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE 2048 @@ -175,6 +191,7 @@ #define CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 1 #define CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_RSA 1 #define CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM 32 +#define CONFIG_HTTPD_MAX_URI_LEN 512 #define CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED 1 #define CONFIG_ARDUHAL_ESP_LOG 1 #define CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED 1 @@ -204,6 +221,7 @@ #define CONFIG_WARN_WRITE_STRINGS 1 #define CONFIG_SPIFFS_OBJ_NAME_LEN 32 #define CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT 5 +#define CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN_EFF 2 #define CONFIG_LOG_BOOTLOADER_LEVEL_NONE 1 #define CONFIG_PARTITION_TABLE_MD5 1 #define CONFIG_TCPIP_RECVMBOX_SIZE 32 @@ -218,6 +236,7 @@ #define CONFIG_FREERTOS_INTERRUPT_BACKTRACE 1 #define CONFIG_WL_SECTOR_SIZE 4096 #define CONFIG_ESP32_DEBUG_OCDAWARE 1 +#define CONFIG_MQTT_TRANSPORT_WEBSOCKET 1 #define CONFIG_TIMER_TASK_PRIORITY 1 #define CONFIG_PPP_PAP_SUPPORT 1 #define CONFIG_MBEDTLS_TLS_CLIENT 1 @@ -227,7 +246,10 @@ #define CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED 1 #define CONFIG_MONITOR_BAUD 115200 #define CONFIG_ESP32_DEBUG_STUBS_ENABLE 1 +#define CONFIG_TCPIP_LWIP 1 #define CONFIG_WIFI_LWIP_ALLOCATION_FROM_SPIRAM_FIRST 1 +#define CONFIG_REDUCE_PHY_TX_POWER 1 +#define CONFIG_BOOTLOADER_WDT_TIME_MS 9000 #define CONFIG_FREERTOS_CORETIMER_0 1 #define CONFIG_PARTITION_TABLE_CUSTOM_FILENAME "partitions.csv" #define CONFIG_MBEDTLS_HAVE_TIME 1 @@ -239,25 +261,30 @@ #define CONFIG_MBEDTLS_TLS_SERVER 1 #define CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT 1 #define CONFIG_FREERTOS_ISR_STACKSIZE 1536 +#define CONFIG_SUPPORT_TERMIOS 1 #define CONFIG_CLASSIC_BT_ENABLED 1 #define CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK 1 #define CONFIG_OPENSSL_ASSERT_DO_NOTHING 1 #define CONFIG_WL_SECTOR_SIZE_4096 1 #define CONFIG_OPTIMIZATION_LEVEL_DEBUG 1 #define CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED 1 +#define CONFIG_SCAN_DUPLICATE_TYPE 0 #define CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED 1 #define CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED 1 #define CONFIG_HFP_CLIENT_ENABLE 1 #define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA 1 +#define CONFIG_SPI_SLAVE_ISR_IN_IRAM 1 #define CONFIG_SYSTEM_EVENT_QUEUE_SIZE 32 #define CONFIG_BT_ACL_CONNECTIONS 4 #define CONFIG_FATFS_MAX_LFN 255 #define CONFIG_ESP32_WIFI_TX_BUFFER_TYPE 1 #define CONFIG_ESPTOOLPY_BAUD_921600B 1 +#define CONFIG_BOOTLOADER_WDT_ENABLE 1 #define CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED 1 #define CONFIG_LWIP_LOOPBACK_MAX_PBUFS 8 #define CONFIG_A2DP_ENABLE 1 #define CONFIG_SPI_FLASH_ROM_DRIVER_PATCH 1 +#define CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE 1 #define CONFIG_SPIFFS_PAGE_SIZE 256 #define CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED 1 #define CONFIG_PPP_MSCHAP_SUPPORT 1 diff --git a/tools/sdk/include/driver/driver/can.h b/tools/sdk/include/driver/driver/can.h new file mode 100644 index 00000000..af7b66e0 --- /dev/null +++ b/tools/sdk/include/driver/driver/can.h @@ -0,0 +1,400 @@ +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _DRIVER_CAN_H_ +#define _DRIVER_CAN_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "esp_types.h" +#include "esp_intr.h" +#include "esp_err.h" +#include "gpio.h" + +/* -------------------- Default initializers and flags ---------------------- */ +/** @cond */ //Doxy command to hide preprocessor definitions from docs +/** + * @brief Initializer macro for general configuration structure. + * + * This initializer macros allows the TX GPIO, RX GPIO, and operating mode to be + * configured. The other members of the general configuration structure are + * assigned default values. + */ +#define CAN_GENERAL_CONFIG_DEFAULT(tx_io_num, rx_io_num, op_mode) {.mode = op_mode, .tx_io = tx_io_num, .rx_io = rx_io_num, \ + .clkout_io = CAN_IO_UNUSED, .bus_off_io = CAN_IO_UNUSED, \ + .tx_queue_len = 5, .rx_queue_len = 5, \ + .alerts_enabled = CAN_ALERT_NONE, .clkout_divider = 0, } + +/** + * @brief Initializer macros for timing configuration structure + * + * The following initializer macros offer commonly found bit rates. + * + * @note These timing values are based on the assumption APB clock is at 80MHz + */ +#define CAN_TIMING_CONFIG_25KBITS() {.brp = 128, .tseg_1 = 16, .tseg_2 = 8, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_50KBITS() {.brp = 80, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_100KBITS() {.brp = 40, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_125KBITS() {.brp = 32, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_250KBITS() {.brp = 16, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_500KBITS() {.brp = 8, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_800KBITS() {.brp = 4, .tseg_1 = 16, .tseg_2 = 8, .sjw = 3, .triple_sampling = false} +#define CAN_TIMING_CONFIG_1MBITS() {.brp = 4, .tseg_1 = 15, .tseg_2 = 4, .sjw = 3, .triple_sampling = false} + +/** + * @brief Initializer macro for filter configuration to accept all IDs + */ +#define CAN_FILTER_CONFIG_ACCEPT_ALL() {.acceptance_code = 0, .acceptance_mask = 0xFFFFFFFF, .single_filter = true} + +/** + * @brief Alert flags + * + * The following flags represents the various kind of alerts available in + * the CAN driver. These flags can be used when configuring/reconfiguring + * alerts, or when calling can_read_alerts(). + * + * @note The CAN_ALERT_AND_LOG flag is not an actual alert, but will configure + * the CAN driver to log to UART when an enabled alert occurs. + */ +#define CAN_ALERT_TX_IDLE 0x0001 /**< Alert(1): No more messages to transmit */ +#define CAN_ALERT_TX_SUCCESS 0x0002 /**< Alert(2): The previous transmission was successful */ +#define CAN_ALERT_BELOW_ERR_WARN 0x0004 /**< Alert(4): Both error counters have dropped below error warning limit */ +#define CAN_ALERT_ERR_ACTIVE 0x0008 /**< Alert(8): CAN controller has become error active */ +#define CAN_ALERT_RECOVERY_IN_PROGRESS 0x0010 /**< Alert(16): CAN controller is undergoing bus recovery */ +#define CAN_ALERT_BUS_RECOVERED 0x0020 /**< Alert(32): CAN controller has successfully completed bus recovery */ +#define CAN_ALERT_ARB_LOST 0x0040 /**< Alert(64): The previous transmission lost arbitration */ +#define CAN_ALERT_ABOVE_ERR_WARN 0x0080 /**< Alert(128): One of the error counters have exceeded the error warning limit */ +#define CAN_ALERT_BUS_ERROR 0x0100 /**< Alert(256): A (Bit, Stuff, CRC, Form, ACK) error has occurred on the bus */ +#define CAN_ALERT_TX_FAILED 0x0200 /**< Alert(512): The previous transmission has failed (for single shot transmission) */ +#define CAN_ALERT_RX_QUEUE_FULL 0x0400 /**< Alert(1024): The RX queue is full causing a frame to be lost */ +#define CAN_ALERT_ERR_PASS 0x0800 /**< Alert(2048): CAN controller has become error passive */ +#define CAN_ALERT_BUS_OFF 0x1000 /**< Alert(4096): Bus-off condition occurred. CAN controller can no longer influence bus */ +#define CAN_ALERT_ALL 0x1FFF /**< Bit mask to enable all alerts during configuration */ +#define CAN_ALERT_NONE 0x0000 /**< Bit mask to disable all alerts during configuration */ +#define CAN_ALERT_AND_LOG 0x2000 /**< Bit mask to enable alerts to also be logged when they occur */ + +/** + * @brief Message flags + * + * The message flags are used to indicate the type of message transmitted/received. + * Some flags also specify the type of transmission. + */ +#define CAN_MSG_FLAG_NONE 0x00 /**< No message flags (Standard Frame Format) */ +#define CAN_MSG_FLAG_EXTD 0x01 /**< Extended Frame Format (29bit ID) */ +#define CAN_MSG_FLAG_RTR 0x02 /**< Message is a Remote Transmit Request */ +#define CAN_MSG_FLAG_SS 0x04 /**< Transmit as a Single Shot Transmission */ +#define CAN_MSG_FLAG_SELF 0x08 /**< Transmit as a Self Reception Request */ +#define CAN_MSG_FLAG_DLC_NON_COMP 0x10 /**< Message's Data length code is larger than 8. This will break compliance with CAN2.0B */ + +/** + * @brief Miscellaneous macros + */ +#define CAN_EXTD_ID_MASK 0x1FFFFFFF /**< Bit mask for 29 bit Extended Frame Format ID */ +#define CAN_STD_ID_MASK 0x7FF /**< Bit mask for 11 bit Standard Frame Format ID */ +#define CAN_MAX_DATA_LEN 8 /**< Maximum number of data bytes in a CAN2.0B frame */ +#define CAN_IO_UNUSED (-1) /**< Marks GPIO as unused in CAN configuration */ +/** @endcond */ + +/* ----------------------- Enum and Struct Definitions ---------------------- */ + +/** + * @brief CAN driver operating modes + */ +typedef enum { + CAN_MODE_NORMAL, /**< Normal operating mode where CAN controller can send/receive/acknowledge messages */ + CAN_MODE_NO_ACK, /**< Transmission does not require acknowledgment. Use this mode for self testing */ + CAN_MODE_LISTEN_ONLY, /**< The CAN controller will not influence the bus (No transmissions or acknowledgments) but can receive messages */ +} can_mode_t; + +/** + * @brief CAN driver states + */ +typedef enum { + CAN_STATE_STOPPED, /**< Stopped state. The CAN controller will not participate in any CAN bus activities */ + CAN_STATE_RUNNING, /**< Running state. The CAN controller can transmit and receive messages */ + CAN_STATE_BUS_OFF, /**< Bus-off state. The CAN controller cannot participate in bus activities until it has recovered */ + CAN_STATE_RECOVERING, /**< Recovering state. The CAN controller is undergoing bus recovery */ +} can_state_t; + +/** + * @brief Structure for general configuration of the CAN driver + * + * @note Macro initializers are available for this structure + */ +typedef struct { + can_mode_t mode; /**< Mode of CAN controller */ + gpio_num_t tx_io; /**< Transmit GPIO number */ + gpio_num_t rx_io; /**< Receive GPIO number */ + gpio_num_t clkout_io; /**< CLKOUT GPIO number (optional, set to -1 if unused) */ + gpio_num_t bus_off_io; /**< Bus off indicator GPIO number (optional, set to -1 if unused) */ + uint32_t tx_queue_len; /**< Number of messages TX queue can hold (set to 0 to disable TX Queue) */ + uint32_t rx_queue_len; /**< Number of messages RX queue can hold */ + uint32_t alerts_enabled; /**< Bit field of alerts to enable (see documentation) */ + uint32_t clkout_divider; /**< CLKOUT divider. Can be 1 or any even number from 2 to 14 (optional, set to 0 if unused) */ +} can_general_config_t; + +/** + * @brief Structure for bit timing configuration of the CAN driver + * + * @note Macro initializers are available for this structure + */ +typedef struct { + uint8_t brp; /**< Baudrate prescaler (APB clock divider, even number from 2 to 128) */ + uint8_t tseg_1; /**< Timing segment 1 (Number of time quanta, between 1 to 16) */ + uint8_t tseg_2; /**< Timing segment 2 (Number of time quanta, 1 to 8) */ + uint8_t sjw; /**< Synchronization Jump Width (Max time quanta jump for synchronize from 1 to 4) */ + bool triple_sampling; /**< Enables triple sampling when the CAN controller samples a bit */ +} can_timing_config_t; + +/** + * @brief Structure for acceptance filter configuration of the CAN driver (see documentation) + * + * @note Macro initializers are available for this structure + */ +typedef struct { + uint32_t acceptance_code; /**< 32-bit acceptance code */ + uint32_t acceptance_mask; /**< 32-bit acceptance mask */ + bool single_filter; /**< Use Single Filter Mode (see documentation) */ +} can_filter_config_t; + +/** + * @brief Structure to store status information of CAN driver + */ +typedef struct { + can_state_t state; /**< Current state of CAN controller (Stopped/Running/Bus-Off/Recovery) */ + uint32_t msgs_to_tx; /**< Number of messages queued for transmission or awaiting transmission completion */ + uint32_t msgs_to_rx; /**< Number of messages in RX queue waiting to be read */ + uint32_t tx_error_counter; /**< Current value of Transmit Error Counter */ + uint32_t rx_error_counter; /**< Current value of Receive Error Counter */ + uint32_t tx_failed_count; /**< Number of messages that failed transmissions */ + uint32_t rx_missed_count; /**< Number of messages that were lost due to a full RX queue */ + uint32_t arb_lost_count; /**< Number of instances arbitration was lost */ + uint32_t bus_error_count; /**< Number of instances a bus error has occurred */ +} can_status_info_t; + +/** + * @brief Structure to store a CAN message + * + * @note The flags member is used to control the message type, and transmission + * type (see documentation for message flags) + */ +typedef struct { + uint32_t flags; /**< Bit field of message flags indicates frame/transmission type (see documentation) */ + uint32_t identifier; /**< 11 or 29 bit identifier */ + uint8_t data_length_code; /**< Data length code */ + uint8_t data[CAN_MAX_DATA_LEN]; /**< Data bytes (not relevant in RTR frame) */ +} can_message_t; + +/* ----------------------------- Public API -------------------------------- */ + +/** + * @brief Install CAN driver + * + * This function installs the CAN driver using three configuration structures. + * The required memory is allocated and the CAN driver is placed in the stopped + * state after running this function. + * + * @param[in] g_config General configuration structure + * @param[in] t_config Timing configuration structure + * @param[in] f_config Filter configuration structure + * + * @note Macro initializers are available for the configuration structures (see documentation) + * + * @note To reinstall the CAN driver, call can_driver_uninstall() first + * + * @return + * - ESP_OK: Successfully installed CAN driver + * - ESP_ERR_INVALID_ARG: Arguments are invalid + * - ESP_ERR_NO_MEM: Insufficient memory + * - ESP_ERR_INVALID_STATE: Driver is already installed + */ +esp_err_t can_driver_install(const can_general_config_t *g_config, const can_timing_config_t *t_config, const can_filter_config_t *f_config); + +/** + * @brief Uninstall the CAN driver + * + * This function uninstalls the CAN driver, freeing the memory utilized by the + * driver. This function can only be called when the driver is in the stopped + * state or the bus-off state. + * + * @warning The application must ensure that no tasks are blocked on TX/RX + * queues or alerts when this function is called. + * + * @return + * - ESP_OK: Successfully uninstalled CAN driver + * - ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed + */ +esp_err_t can_driver_uninstall(); + +/** + * @brief Start the CAN driver + * + * This function starts the CAN driver, putting the CAN driver into the running + * state. This allows the CAN driver to participate in CAN bus activities such + * as transmitting/receiving messages. The RX queue is reset in this function, + * clearing any unread messages. This function can only be called when the CAN + * driver is in the stopped state. + * + * @return + * - ESP_OK: CAN driver is now running + * - ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed + */ +esp_err_t can_start(); + +/** + * @brief Stop the CAN driver + * + * This function stops the CAN driver, preventing any further message from being + * transmitted or received until can_start() is called. Any messages in the TX + * queue are cleared. Any messages in the RX queue should be read by the + * application after this function is called. This function can only be called + * when the CAN driver is in the running state. + * + * @warning A message currently being transmitted/received on the CAN bus will + * be ceased immediately. This may lead to other CAN nodes interpreting + * the unfinished message as an error. + * + * @return + * - ESP_OK: CAN driver is now Stopped + * - ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed + */ +esp_err_t can_stop(); + +/** + * @brief Transmit a CAN message + * + * This function queues a CAN message for transmission. Transmission will start + * immediately if no other messages are queued for transmission. If the TX queue + * is full, this function will block until more space becomes available or until + * it timesout. If the TX queue is disabled (TX queue length = 0 in configuration), + * this function will return immediately if another message is undergoing + * transmission. This function can only be called when the CAN driver is in the + * running state and cannot be called under Listen Only Mode. + * + * @param[in] message Message to transmit + * @param[in] ticks_to_wait Number of FreeRTOS ticks to block on the TX queue + * + * @note This function does not guarantee that the transmission is successful. + * The TX_SUCCESS/TX_FAILED alert can be enabled to alert the application + * upon the success/failure of a transmission. + * + * @note The TX_IDLE alert can be used to alert the application when no other + * messages are awaiting transmission. + * + * @return + * - ESP_OK: Transmission successfully queued/initiated + * - ESP_ERR_INVALID_ARG: Arguments are invalid + * - ESP_ERR_TIMEOUT: Timed out waiting for space on TX queue + * - ESP_FAIL: TX queue is disabled and another message is currently transmitting + * - ESP_ERR_INVALID_STATE: CAN driver is not in running state, or is not installed + * - ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions + */ +esp_err_t can_transmit(const can_message_t *message, TickType_t ticks_to_wait); + +/** + * @brief Receive a CAN message + * + * This function receives a message from the RX queue. The flags field of the + * message structure will indicate the type of message received. This function + * will block if there are no messages in the RX queue + * + * @param[out] message Received message + * @param[in] ticks_to_wait Number of FreeRTOS ticks to block on RX queue + * + * @warning The flags field of the received message should be checked to determine + * if the received message contains any data bytes. + * + * @return + * - ESP_OK: Message successfully received from RX queue + * - ESP_ERR_TIMEOUT: Timed out waiting for message + * - ESP_ERR_INVALID_ARG: Arguments are invalid + * - ESP_ERR_INVALID_STATE: CAN driver is not installed + */ +esp_err_t can_receive(can_message_t *message, TickType_t ticks_to_wait); + +/** + * @brief Read CAN driver alerts + * + * This function will read the alerts raised by the CAN driver. If no alert has + * been when this function is called, this function will block until an alert + * occurs or until it timeouts. + * + * @param[out] alerts Bit field of raised alerts (see documentation for alert flags) + * @param[in] ticks_to_wait Number of FreeRTOS ticks to block for alert + * + * @note Multiple alerts can be raised simultaneously. The application should + * check for all alerts that have been enabled. + * + * @return + * - ESP_OK: Alerts read + * - ESP_ERR_TIMEOUT: Timed out waiting for alerts + * - ESP_ERR_INVALID_ARG: Arguments are invalid + * - ESP_ERR_INVALID_STATE: CAN driver is not installed + */ +esp_err_t can_read_alerts(uint32_t *alerts, TickType_t ticks_to_wait); + +/** + * @brief Reconfigure which alerts are enabled + * + * This function reconfigures which alerts are enabled. If there are alerts + * which have not been read whilst reconfiguring, this function can read those + * alerts. + * + * @param[in] alerts_enabled Bit field of alerts to enable (see documentation for alert flags) + * @param[out] current_alerts Bit field of currently raised alerts. Set to NULL if unused + * + * @return + * - ESP_OK: Alerts reconfigured + * - ESP_ERR_INVALID_STATE: CAN driver is not installed + */ +esp_err_t can_reconfigure_alerts(uint32_t alerts_enabled, uint32_t *current_alerts); + +/** + * @brief Start the bus recovery process + * + * This function initiates the bus recovery process when the CAN driver is in + * the bus-off state. Once initiated, the CAN driver will enter the recovering + * state and wait for 128 occurrences of the bus-free signal on the CAN bus + * before returning to the stopped state. This function will reset the TX queue, + * clearing any messages pending transmission. + * + * @note The BUS_RECOVERED alert can be enabled to alert the application when + * the bus recovery process completes. + * + * @return + * - ESP_OK: Bus recovery started + * - ESP_ERR_INVALID_STATE: CAN driver is not in the bus-off state, or is not installed + */ +esp_err_t can_initiate_recovery(); + +/** + * @brief Get current status information of the CAN driver + * + * @param[out] status_info Status information + * + * @return + * - ESP_OK: Status information retrieved + * - ESP_ERR_INVALID_ARG: Arguments are invalid + * - ESP_ERR_INVALID_STATE: CAN driver is not installed + */ +esp_err_t can_get_status_info(can_status_info_t *status_info); + +#ifdef __cplusplus +} +#endif + +#endif /*_DRIVER_CAN_H_*/ + diff --git a/tools/sdk/include/driver/driver/gpio.h b/tools/sdk/include/driver/driver/gpio.h index 5c47b577..2e878dc1 100644 --- a/tools/sdk/include/driver/driver/gpio.h +++ b/tools/sdk/include/driver/driver/gpio.h @@ -249,13 +249,13 @@ esp_err_t gpio_config(const gpio_config_t *pGPIOConfig); /** * @brief Reset an gpio to default state (select gpio function, enable pullup and disable input and output). - * + * * @param gpio_num GPIO number. - * + * * @note This function also configures the IOMUX for this pin to the GPIO * function, and disconnects any other peripheral output configured via GPIO * Matrix. - * + * * @return Always return ESP_OK. */ esp_err_t gpio_reset_pin(gpio_num_t gpio_num); @@ -359,27 +359,27 @@ esp_err_t gpio_set_direction(gpio_num_t gpio_num, gpio_mode_t mode); esp_err_t gpio_set_pull_mode(gpio_num_t gpio_num, gpio_pull_mode_t pull); /** - * @brief Enable GPIO wake-up function. - * - * @param gpio_num GPIO number. - * - * @param intr_type GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ + * @brief Enable GPIO wake-up function. + * + * @param gpio_num GPIO number. + * + * @param intr_type GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ esp_err_t gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type); /** - * @brief Disable GPIO wake-up function. - * - * @param gpio_num GPIO number - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ + * @brief Disable GPIO wake-up function. + * + * @param gpio_num GPIO number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ esp_err_t gpio_wakeup_disable(gpio_num_t gpio_num); /** diff --git a/tools/sdk/include/driver/driver/i2c.h b/tools/sdk/include/driver/driver/i2c.h index 0f892db5..8f8cb9a1 100644 --- a/tools/sdk/include/driver/driver/i2c.h +++ b/tools/sdk/include/driver/driver/i2c.h @@ -1,550 +1,550 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _DRIVER_I2C_H_ -#define _DRIVER_I2C_H_ - - -#ifdef __cplusplus -extern "C" { -#endif -#include -#include "esp_err.h" -#include "esp_intr_alloc.h" -#include "freertos/FreeRTOS.h" -#include "freertos/semphr.h" -#include "freertos/xtensa_api.h" -#include "freertos/task.h" -#include "freertos/queue.h" -#include "freertos/ringbuf.h" -#include "driver/gpio.h" - -#define I2C_APB_CLK_FREQ APB_CLK_FREQ /*!< I2C source clock is APB clock, 80MHz */ -#define I2C_FIFO_LEN (32) /*!< I2C hardware fifo length */ -typedef enum{ - I2C_MODE_SLAVE = 0, /*!< I2C slave mode */ - I2C_MODE_MASTER, /*!< I2C master mode */ - I2C_MODE_MAX, -}i2c_mode_t; - -typedef enum { - I2C_MASTER_WRITE = 0, /*!< I2C write data */ - I2C_MASTER_READ, /*!< I2C read data */ -} i2c_rw_t; - -typedef enum { - I2C_DATA_MODE_MSB_FIRST = 0, /*!< I2C data msb first */ - I2C_DATA_MODE_LSB_FIRST = 1, /*!< I2C data lsb first */ - I2C_DATA_MODE_MAX -} i2c_trans_mode_t; - -typedef enum{ - I2C_CMD_RESTART = 0, /*!=0) The number of data bytes that pushed to the I2C slave buffer. - */ -int i2c_slave_write_buffer(i2c_port_t i2c_num, uint8_t* data, int size, TickType_t ticks_to_wait); - -/** - * @brief I2C slave read data from internal buffer. When I2C slave receive data, isr will copy received data - * from hardware rx fifo to internal ringbuffer. Then users can read from internal ringbuffer. - * @note - * Only call this function in I2C slave mode - * - * @param i2c_num I2C port number - * @param data data pointer to write into internal buffer - * @param max_size Maximum data size to read - * @param ticks_to_wait Maximum waiting ticks - * - * @return - * - ESP_FAIL(-1) Parameter error - * - Others(>=0) The number of data bytes that read from I2C slave buffer. - */ -int i2c_slave_read_buffer(i2c_port_t i2c_num, uint8_t* data, size_t max_size, TickType_t ticks_to_wait); - -/** - * @brief set I2C master clock period - * - * @param i2c_num I2C port number - * @param high_period clock cycle number during SCL is high level, high_period is a 14 bit value - * @param low_period clock cycle number during SCL is low level, low_period is a 14 bit value - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_set_period(i2c_port_t i2c_num, int high_period, int low_period); - -/** - * @brief get I2C master clock period - * - * @param i2c_num I2C port number - * @param high_period pointer to get clock cycle number during SCL is high level, will get a 14 bit value - * @param low_period pointer to get clock cycle number during SCL is low level, will get a 14 bit value - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_get_period(i2c_port_t i2c_num, int* high_period, int* low_period); - -/** - * @brief set I2C master start signal timing - * - * @param i2c_num I2C port number - * @param setup_time clock number between the falling-edge of SDA and rising-edge of SCL for start mark, it's a 10-bit value. - * @param hold_time clock num between the falling-edge of SDA and falling-edge of SCL for start mark, it's a 10-bit value. - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_set_start_timing(i2c_port_t i2c_num, int setup_time, int hold_time); - -/** - * @brief get I2C master start signal timing - * - * @param i2c_num I2C port number - * @param setup_time pointer to get setup time - * @param hold_time pointer to get hold time - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_get_start_timing(i2c_port_t i2c_num, int* setup_time, int* hold_time); - -/** - * @brief set I2C master stop signal timing - * - * @param i2c_num I2C port number - * @param setup_time clock num between the rising-edge of SCL and the rising-edge of SDA, it's a 10-bit value. - * @param hold_time clock number after the STOP bit's rising-edge, it's a 14-bit value. - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_set_stop_timing(i2c_port_t i2c_num, int setup_time, int hold_time); - -/** - * @brief get I2C master stop signal timing - * - * @param i2c_num I2C port number - * @param setup_time pointer to get setup time. - * @param hold_time pointer to get hold time. - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_get_stop_timing(i2c_port_t i2c_num, int* setup_time, int* hold_time); - -/** - * @brief set I2C data signal timing - * - * @param i2c_num I2C port number - * @param sample_time clock number I2C used to sample data on SDA after the rising-edge of SCL, it's a 10-bit value - * @param hold_time clock number I2C used to hold the data after the falling-edge of SCL, it's a 10-bit value - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_set_data_timing(i2c_port_t i2c_num, int sample_time, int hold_time); - -/** - * @brief get I2C data signal timing - * - * @param i2c_num I2C port number - * @param sample_time pointer to get sample time - * @param hold_time pointer to get hold time - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_get_data_timing(i2c_port_t i2c_num, int* sample_time, int* hold_time); - -/** - * @brief set I2C timeout value - * @param i2c_num I2C port number - * @param timeout timeout value for I2C bus (unit: APB 80Mhz clock cycle) - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_set_timeout(i2c_port_t i2c_num, int timeout); - -/** - * @brief get I2C timeout value - * @param i2c_num I2C port number - * @param timeout pointer to get timeout value - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_get_timeout(i2c_port_t i2c_num, int* timeout); -/** - * @brief set I2C data transfer mode - * - * @param i2c_num I2C port number - * @param tx_trans_mode I2C sending data mode - * @param rx_trans_mode I2C receving data mode - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_set_data_mode(i2c_port_t i2c_num, i2c_trans_mode_t tx_trans_mode, i2c_trans_mode_t rx_trans_mode); - -/** - * @brief get I2C data transfer mode - * - * @param i2c_num I2C port number - * @param tx_trans_mode pointer to get I2C sending data mode - * @param rx_trans_mode pointer to get I2C receiving data mode - * - * @return - * - ESP_OK Success - * - ESP_ERR_INVALID_ARG Parameter error - */ -esp_err_t i2c_get_data_mode(i2c_port_t i2c_num, i2c_trans_mode_t *tx_trans_mode, i2c_trans_mode_t *rx_trans_mode); - -#ifdef __cplusplus -} -#endif - -#endif /*_DRIVER_I2C_H_*/ +// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _DRIVER_I2C_H_ +#define _DRIVER_I2C_H_ + + +#ifdef __cplusplus +extern "C" { +#endif +#include +#include "esp_err.h" +#include "esp_intr_alloc.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "freertos/xtensa_api.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/ringbuf.h" +#include "driver/gpio.h" + +#define I2C_APB_CLK_FREQ APB_CLK_FREQ /*!< I2C source clock is APB clock, 80MHz */ +#define I2C_FIFO_LEN (32) /*!< I2C hardware fifo length */ +typedef enum{ + I2C_MODE_SLAVE = 0, /*!< I2C slave mode */ + I2C_MODE_MASTER, /*!< I2C master mode */ + I2C_MODE_MAX, +}i2c_mode_t; + +typedef enum { + I2C_MASTER_WRITE = 0, /*!< I2C write data */ + I2C_MASTER_READ, /*!< I2C read data */ +} i2c_rw_t; + +typedef enum { + I2C_DATA_MODE_MSB_FIRST = 0, /*!< I2C data msb first */ + I2C_DATA_MODE_LSB_FIRST = 1, /*!< I2C data lsb first */ + I2C_DATA_MODE_MAX +} i2c_trans_mode_t; + +typedef enum{ + I2C_CMD_RESTART = 0, /*!=0) The number of data bytes that pushed to the I2C slave buffer. + */ +int i2c_slave_write_buffer(i2c_port_t i2c_num, uint8_t* data, int size, TickType_t ticks_to_wait); + +/** + * @brief I2C slave read data from internal buffer. When I2C slave receive data, isr will copy received data + * from hardware rx fifo to internal ringbuffer. Then users can read from internal ringbuffer. + * @note + * Only call this function in I2C slave mode + * + * @param i2c_num I2C port number + * @param data data pointer to write into internal buffer + * @param max_size Maximum data size to read + * @param ticks_to_wait Maximum waiting ticks + * + * @return + * - ESP_FAIL(-1) Parameter error + * - Others(>=0) The number of data bytes that read from I2C slave buffer. + */ +int i2c_slave_read_buffer(i2c_port_t i2c_num, uint8_t* data, size_t max_size, TickType_t ticks_to_wait); + +/** + * @brief set I2C master clock period + * + * @param i2c_num I2C port number + * @param high_period clock cycle number during SCL is high level, high_period is a 14 bit value + * @param low_period clock cycle number during SCL is low level, low_period is a 14 bit value + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_period(i2c_port_t i2c_num, int high_period, int low_period); + +/** + * @brief get I2C master clock period + * + * @param i2c_num I2C port number + * @param high_period pointer to get clock cycle number during SCL is high level, will get a 14 bit value + * @param low_period pointer to get clock cycle number during SCL is low level, will get a 14 bit value + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_period(i2c_port_t i2c_num, int* high_period, int* low_period); + +/** + * @brief set I2C master start signal timing + * + * @param i2c_num I2C port number + * @param setup_time clock number between the falling-edge of SDA and rising-edge of SCL for start mark, it's a 10-bit value. + * @param hold_time clock num between the falling-edge of SDA and falling-edge of SCL for start mark, it's a 10-bit value. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_start_timing(i2c_port_t i2c_num, int setup_time, int hold_time); + +/** + * @brief get I2C master start signal timing + * + * @param i2c_num I2C port number + * @param setup_time pointer to get setup time + * @param hold_time pointer to get hold time + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_start_timing(i2c_port_t i2c_num, int* setup_time, int* hold_time); + +/** + * @brief set I2C master stop signal timing + * + * @param i2c_num I2C port number + * @param setup_time clock num between the rising-edge of SCL and the rising-edge of SDA, it's a 10-bit value. + * @param hold_time clock number after the STOP bit's rising-edge, it's a 14-bit value. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_stop_timing(i2c_port_t i2c_num, int setup_time, int hold_time); + +/** + * @brief get I2C master stop signal timing + * + * @param i2c_num I2C port number + * @param setup_time pointer to get setup time. + * @param hold_time pointer to get hold time. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_stop_timing(i2c_port_t i2c_num, int* setup_time, int* hold_time); + +/** + * @brief set I2C data signal timing + * + * @param i2c_num I2C port number + * @param sample_time clock number I2C used to sample data on SDA after the rising-edge of SCL, it's a 10-bit value + * @param hold_time clock number I2C used to hold the data after the falling-edge of SCL, it's a 10-bit value + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_data_timing(i2c_port_t i2c_num, int sample_time, int hold_time); + +/** + * @brief get I2C data signal timing + * + * @param i2c_num I2C port number + * @param sample_time pointer to get sample time + * @param hold_time pointer to get hold time + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_data_timing(i2c_port_t i2c_num, int* sample_time, int* hold_time); + +/** + * @brief set I2C timeout value + * @param i2c_num I2C port number + * @param timeout timeout value for I2C bus (unit: APB 80Mhz clock cycle) + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_timeout(i2c_port_t i2c_num, int timeout); + +/** + * @brief get I2C timeout value + * @param i2c_num I2C port number + * @param timeout pointer to get timeout value + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_timeout(i2c_port_t i2c_num, int* timeout); +/** + * @brief set I2C data transfer mode + * + * @param i2c_num I2C port number + * @param tx_trans_mode I2C sending data mode + * @param rx_trans_mode I2C receving data mode + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_data_mode(i2c_port_t i2c_num, i2c_trans_mode_t tx_trans_mode, i2c_trans_mode_t rx_trans_mode); + +/** + * @brief get I2C data transfer mode + * + * @param i2c_num I2C port number + * @param tx_trans_mode pointer to get I2C sending data mode + * @param rx_trans_mode pointer to get I2C receiving data mode + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_data_mode(i2c_port_t i2c_num, i2c_trans_mode_t *tx_trans_mode, i2c_trans_mode_t *rx_trans_mode); + +#ifdef __cplusplus +} +#endif + +#endif /*_DRIVER_I2C_H_*/ diff --git a/tools/sdk/include/driver/driver/ledc.h b/tools/sdk/include/driver/driver/ledc.h index 8f70b1c0..6a82c19a 100644 --- a/tools/sdk/include/driver/driver/ledc.h +++ b/tools/sdk/include/driver/driver/ledc.h @@ -455,7 +455,7 @@ void ledc_fade_func_uninstall(); esp_err_t ledc_fade_start(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_fade_mode_t fade_mode); /** - * @brief A thread-safe API to set duty for LEDC channel and update the settings immediately + * @brief A thread-safe API to set duty for LEDC channel and return when duty updated. * @note If a fade operation is running in progress on that channel, the driver would not allow it to be stopped. * Other duty operations will have to wait until the fade operation has finished. * diff --git a/tools/sdk/include/driver/driver/mcpwm.h b/tools/sdk/include/driver/driver/mcpwm.h index 2a4433fc..d1c10e86 100644 --- a/tools/sdk/include/driver/driver/mcpwm.h +++ b/tools/sdk/include/driver/driver/mcpwm.h @@ -1,709 +1,709 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _DRIVER_MCPWM_H_ -#define _DRIVER_MCPWM_H_ - -#include "esp_err.h" -#include "soc/soc.h" -#include "driver/gpio.h" -#include "driver/periph_ctrl.h" -#include "esp_intr.h" -#include "esp_intr_alloc.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief IO signals for MCPWM - * 6 MCPWM output pins that generate PWM signals - * 3 MCPWM fault input pins to detect faults like overcurrent, overvoltage, etc - * 3 MCPWM sync input pins to synchronize MCPWM outputs signals - * 3 MCPWM capture input pin to capture hall sell signal to measure time - */ -typedef enum { - MCPWM0A = 0, /*!rx_data, 15); + * + * @param data Data to be rearranged, can be uint8_t, uint16_t or uint32_t. + * @param len Length of data received, since the SPI peripheral writes from + * the MSB, this helps to shift the data to the LSB. + */ +#define SPI_SWAP_DATA_RX(data, len) (__builtin_bswap32(data)>>(32-len)) /** * @brief Enum with the three SPI peripherals that are software-accessible in it @@ -45,7 +74,7 @@ typedef enum { * @brief This is a configuration structure for a SPI bus. * * You can use this structure to specify the GPIO pins of the bus. Normally, the driver will use the - * GPIO matrix to route the signals. An exception is made when all signals either can be routed through + * GPIO matrix to route the signals. An exception is made when all signals either can be routed through * the IO_MUX or are -1. In that case, the IO_MUX is used, allowing for >40MHz speeds. * * @note Be advised that the slave driver does not use the quadwp/quadhd lines and fields in spi_bus_config_t refering to these lines will be ignored and can thus safely be left uninitialized. @@ -81,20 +110,20 @@ bool spicommon_periph_free(spi_host_device_t host); /** * @brief Try to claim a SPI DMA channel - * + * * Call this if your driver wants to use SPI with a DMA channnel. - * + * * @param dma_chan channel to claim - * + * * @return True if success; false otherwise. */ bool spicommon_dma_chan_claim(int dma_chan); /** * @brief Return the SPI DMA channel so other driver can claim it, or just to power down DMA. - * + * * @param dma_chan channel to return - * + * * @return True if success; false otherwise. */ bool spicommon_dma_chan_free(int dma_chan); @@ -113,7 +142,7 @@ bool spicommon_dma_chan_free(int dma_chan); * @brief Connect a SPI peripheral to GPIO pins * * This routine is used to connect a SPI peripheral to the IO-pads and DMA channel given in - * the arguments. Depending on the IO-pads requested, the routing is done either using the + * the arguments. Depending on the IO-pads requested, the routing is done either using the * IO_mux or using the GPIO matrix. * * @param host SPI peripheral to be routed @@ -123,7 +152,7 @@ bool spicommon_dma_chan_free(int dma_chan); * - ``SPICOMMON_BUSFLAG_MASTER``: Initialize I/O in master mode * - ``SPICOMMON_BUSFLAG_SLAVE``: Initialize I/O in slave mode * - ``SPICOMMON_BUSFLAG_NATIVE_PINS``: Pins set should match the iomux pins of the controller. - * - ``SPICOMMON_BUSFLAG_SCLK``, ``SPICOMMON_BUSFLAG_MISO``, ``SPICOMMON_BUSFLAG_MOSI``: + * - ``SPICOMMON_BUSFLAG_SCLK``, ``SPICOMMON_BUSFLAG_MISO``, ``SPICOMMON_BUSFLAG_MOSI``: * Make sure SCLK/MISO/MOSI is/are set to a valid GPIO. Also check output capability according to the mode. * - ``SPICOMMON_BUSFLAG_DUAL``: Make sure both MISO and MOSI are output capable so that DIO mode is capable. * - ``SPICOMMON_BUSFLAG_WPHD`` Make sure WP and HD are set to valid output GPIOs. @@ -136,7 +165,7 @@ bool spicommon_dma_chan_free(int dma_chan); * - ``SPICOMMON_BUSFLAG_DUAL``: The bus is capable with DIO mode. * - ``SPICOMMON_BUSFLAG_WPHD`` The bus has WP and HD connected. * - ``SPICOMMON_BUSFLAG_QUAD``: Combination of ``SPICOMMON_BUSFLAG_DUAL`` and ``SPICOMMON_BUSFLAG_WPHD``. - * @return + * @return * - ESP_ERR_INVALID_ARG if parameter is invalid * - ESP_OK on success */ @@ -145,10 +174,10 @@ esp_err_t spicommon_bus_initialize_io(spi_host_device_t host, const spi_bus_conf /** * @brief Free the IO used by a SPI peripheral * @deprecated Use spicommon_bus_free_io_cfg instead. - * + * * @param host SPI peripheral to be freed - * - * @return + * + * @return * - ESP_ERR_INVALID_ARG if parameter is invalid * - ESP_OK on success */ @@ -158,8 +187,8 @@ esp_err_t spicommon_bus_free_io(spi_host_device_t host) __attribute__((deprecate * @brief Free the IO used by a SPI peripheral * * @param bus_cfg Bus config struct which defines which pins to be used. - * - * @return + * + * @return * - ESP_ERR_INVALID_ARG if parameter is invalid * - ESP_OK on success */ @@ -240,10 +269,10 @@ typedef void(*dmaworkaround_cb_t)(void *arg); * @note In some (well-defined) cases in the ESP32 (at least rev v.0 and v.1), a SPI DMA channel will get confused. This can be remedied * by resetting the SPI DMA hardware in case this happens. Unfortunately, the reset knob used for thsi will reset _both_ DMA channels, and * as such can only done safely when both DMA channels are idle. These functions coordinate this. - * + * * Essentially, when a reset is needed, a driver can request this using spicommon_dmaworkaround_req_reset. This is supposed to be called - * with an user-supplied function as an argument. If both DMA channels are idle, this call will reset the DMA subsystem and return true. - * If the other DMA channel is still busy, it will return false; as soon as the other DMA channel is done, however, it will reset the + * with an user-supplied function as an argument. If both DMA channels are idle, this call will reset the DMA subsystem and return true. + * If the other DMA channel is still busy, it will return false; as soon as the other DMA channel is done, however, it will reset the * DMA subsystem and call the callback. The callback is then supposed to be used to continue the SPI drivers activity. * * @param dmachan DMA channel associated with the SPI host that needs a reset diff --git a/tools/sdk/include/driver/driver/touch_pad.h b/tools/sdk/include/driver/driver/touch_pad.h index 643b07be..21e2e2ec 100644 --- a/tools/sdk/include/driver/driver/touch_pad.h +++ b/tools/sdk/include/driver/driver/touch_pad.h @@ -122,6 +122,7 @@ esp_err_t touch_pad_init(); /** * @brief Un-install touch pad driver. + * @note After this function is called, other touch functions are prohibited from being called. * @return * - ESP_OK Success * - ESP_FAIL Touch pad driver not initialized @@ -550,6 +551,15 @@ esp_err_t touch_pad_filter_stop(); */ esp_err_t touch_pad_filter_delete(); +/** + * @brief Get the touch pad which caused wakeup from sleep + * @param pad_num pointer to touch pad which caused wakeup + * @return + * - ESP_OK Success + * - ESP_FAIL get status err + */ +esp_err_t touch_pad_get_wakeup_status(touch_pad_t *pad_num); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/driver/driver/uart.h b/tools/sdk/include/driver/driver/uart.h index 08c398f6..93c65c66 100644 --- a/tools/sdk/include/driver/driver/uart.h +++ b/tools/sdk/include/driver/driver/uart.h @@ -46,6 +46,17 @@ extern "C" { #define UART_INVERSE_TXD (UART_TXD_INV_M) /*!< UART TXD output inverse*/ #define UART_INVERSE_RTS (UART_RTS_INV_M) /*!< UART RTS output inverse*/ +/** + * @brief UART mode selection + */ +typedef enum { + UART_MODE_UART = 0x00, /*!< mode: regular UART mode*/ + UART_MODE_RS485_HALF_DUPLEX = 0x01, /*!< mode: half duplex RS485 UART mode control by RTS pin */ + UART_MODE_IRDA = 0x02, /*!< mode: IRDA UART mode*/ + UART_MODE_RS485_COLLISION_DETECT = 0x03, /*!< mode: RS485 collision detection UART mode (used for test purposes)*/ + UART_MODE_RS485_APP_CTRL = 0x04, /*!< mode: application control RS485 UART mode (used for test purposes)*/ +} uart_mode_t; + /** * @brief UART word length constants */ @@ -54,7 +65,7 @@ typedef enum { UART_DATA_6_BITS = 0x1, /*!< word length: 6bits*/ UART_DATA_7_BITS = 0x2, /*!< word length: 7bits*/ UART_DATA_8_BITS = 0x3, /*!< word length: 8bits*/ - UART_DATA_BITS_MAX = 0X4, + UART_DATA_BITS_MAX = 0x4, } uart_word_length_t; /** @@ -249,8 +260,8 @@ esp_err_t uart_get_baudrate(uart_port_t uart_num, uint32_t* baudrate); * @param uart_num UART_NUM_0, UART_NUM_1 or UART_NUM_2 * @param inverse_mask Choose the wires that need to be inverted. * Inverse_mask should be chosen from - UART_INVERSE_RXD / UART_INVERSE_TXD / UART_INVERSE_RTS / UART_INVERSE_CTS, - combined with OR operation. + * UART_INVERSE_RXD / UART_INVERSE_TXD / UART_INVERSE_RTS / UART_INVERSE_CTS, + * combined with OR operation. * * @return * - ESP_OK Success @@ -474,7 +485,7 @@ esp_err_t uart_set_dtr(uart_port_t uart_num, int level); esp_err_t uart_set_tx_idle_num(uart_port_t uart_num, uint16_t idle_num); /** -* @brief Set UART configuration parameters. + * @brief Set UART configuration parameters. * * @param uart_num UART_NUM_0, UART_NUM_1 or UART_NUM_2 * @param uart_config UART parameter settings @@ -486,7 +497,7 @@ esp_err_t uart_set_tx_idle_num(uart_port_t uart_num, uint16_t idle_num); esp_err_t uart_param_config(uart_port_t uart_num, const uart_config_t *uart_config); /** -* @brief Configure UART interrupts. + * @brief Configure UART interrupts. * * @param uart_num UART_NUM_0, UART_NUM_1 or UART_NUM_2 * @param intr_conf UART interrupt settings @@ -552,8 +563,8 @@ esp_err_t uart_wait_tx_done(uart_port_t uart_num, TickType_t ticks_to_wait); * @note This function should only be used when UART TX buffer is not enabled. * * @param uart_num UART_NUM_0, UART_NUM_1 or UART_NUM_2 - * @param buffer data buffer address - * @param len data length to send + * @param buffer data buffer address + * @param len data length to send * * @return * - (-1) Parameter error @@ -571,8 +582,8 @@ int uart_tx_chars(uart_port_t uart_num, const char* buffer, uint32_t len); * UART ISR will then move data from the ring buffer to TX FIFO gradually. * * @param uart_num UART_NUM_0, UART_NUM_1 or UART_NUM_2 - * @param src data buffer address - * @param size data length to send + * @param src data buffer address + * @param size data length to send * * @return * - (-1) Parameter error @@ -581,7 +592,7 @@ int uart_tx_chars(uart_port_t uart_num, const char* buffer, uint32_t len); int uart_write_bytes(uart_port_t uart_num, const char* src, size_t size); /** - * @brief Send data to the UART port from a given buffer and length. + * @brief Send data to the UART port from a given buffer and length, * * If the UART driver's parameter 'tx_buffer_size' is set to zero: * This function will not return until all the data and the break signal have been sent out. @@ -641,9 +652,10 @@ esp_err_t uart_flush(uart_port_t uart_num); esp_err_t uart_flush_input(uart_port_t uart_num); /** - * @brief UART get RX ring buffer cached data length - * @param uart_num UART port number. - * @param size Pointer of size_t to accept cached data length + * @brief UART get RX ring buffer cached data length + * + * @param uart_num UART port number. + * @param size Pointer of size_t to accept cached data length * * @return * - ESP_OK Success @@ -652,9 +664,9 @@ esp_err_t uart_flush_input(uart_port_t uart_num); esp_err_t uart_get_buffered_data_len(uart_port_t uart_num, size_t* size); /** - * @brief UART disable pattern detect function. - * Designed for applications like 'AT commands'. - * When the hardware detects a series of one same character, the interrupt will be triggered. + * @brief UART disable pattern detect function. + * Designed for applications like 'AT commands'. + * When the hardware detects a series of one same character, the interrupt will be triggered. * * @param uart_num UART port number. * @@ -737,6 +749,96 @@ int uart_pattern_get_pos(uart_port_t uart_num); */ esp_err_t uart_pattern_queue_reset(uart_port_t uart_num, int queue_length); +/** + * @brief UART set communication mode + * @note This function must be executed after uart_driver_install(), when the driver object is initialized. + * @param uart_num Uart number to configure + * @param mode UART UART mode to set + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t uart_set_mode(uart_port_t uart_num, uart_mode_t mode); + +/** + * @brief UART set threshold timeout for TOUT feature + * + * @param uart_num Uart number to configure + * @param tout_thresh This parameter defines timeout threshold in uart symbol periods. The maximum value of threshold is 126. + * tout_thresh = 1, defines TOUT interrupt timeout equal to transmission time of one symbol (~11 bit) on current baudrate. + * If the time is expired the UART_RXFIFO_TOUT_INT interrupt is triggered. If tout_thresh == 0, + * the TOUT feature is disabled. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_INVALID_STATE Driver is not installed + */ +esp_err_t uart_set_rx_timeout(uart_port_t uart_num, const uint8_t tout_thresh); + +/** + * @brief Returns collision detection flag for RS485 mode + * Function returns the collision detection flag into variable pointed by collision_flag. + * *collision_flag = true, if collision detected else it is equal to false. + * This function should be executed when actual transmission is completed (after uart_write_bytes()). + * + * @param uart_num Uart number to configure + * @param collision_flag Pointer to variable of type bool to return collision flag. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t uart_get_collision_flag(uart_port_t uart_num, bool* collision_flag); + +/** + * @brief Set the number of RX pin signal edges for light sleep wakeup + * + * UART can be used to wake up the system from light sleep. This feature works + * by counting the number of positive edges on RX pin and comparing the count to + * the threshold. When the count exceeds the threshold, system is woken up from + * light sleep. This function allows setting the threshold value. + * + * Stop bit and parity bits (if enabled) also contribute to the number of edges. + * For example, letter 'a' with ASCII code 97 is encoded as 010001101 on the wire + * (with 8n1 configuration), start and stop bits included. This sequence has 3 + * positive edges (transitions from 0 to 1). Therefore, to wake up the system + * when 'a' is sent, set wakeup_threshold=3. + * + * The character that triggers wakeup is not received by UART (i.e. it can not + * be obtained from UART FIFO). Depending on the baud rate, a few characters + * after that will also not be received. Note that when the chip enters and exits + * light sleep mode, APB frequency will be changing. To make sure that UART has + * correct baud rate all the time, select REF_TICK as UART clock source, + * by setting use_ref_tick field in uart_config_t to true. + * + * @note in ESP32, UART2 does not support light sleep wakeup feature. + * + * @param uart_num UART number + * @param wakeup_threshold number of RX edges for light sleep wakeup, value is 3 .. 0x3ff. + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if uart_num is incorrect or wakeup_threshold is + * outside of [3, 0x3ff] range. + */ +esp_err_t uart_set_wakeup_threshold(uart_port_t uart_num, int wakeup_threshold); + +/** + * @brief Get the number of RX pin signal edges for light sleep wakeup. + * + * See description of uart_set_wakeup_threshold for the explanation of UART + * wakeup feature. + * + * @param uart_num UART number + * @param[out] out_wakeup_threshold output, set to the current value of wakeup + * threshold for the given UART. + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if out_wakeup_threshold is NULL + */ +esp_err_t uart_get_wakeup_threshold(uart_port_t uart_num, int* out_wakeup_threshold); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/esp-mqtt/mqtt_client.h b/tools/sdk/include/esp-mqtt/mqtt_client.h new file mode 100755 index 00000000..45fcbe7d --- /dev/null +++ b/tools/sdk/include/esp-mqtt/mqtt_client.h @@ -0,0 +1,101 @@ +/* + * This file is subject to the terms and conditions defined in + * file 'LICENSE', which is part of this source code package. + * Tuan PM + */ + +#ifndef _MQTT_CLIENT_H_ +#define _MQTT_CLIENT_H_ + +#include +#include +#include +#include "esp_err.h" + +#include "mqtt_config.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct esp_mqtt_client* esp_mqtt_client_handle_t; + +typedef enum { + MQTT_EVENT_ERROR = 0, + MQTT_EVENT_CONNECTED, + MQTT_EVENT_DISCONNECTED, + MQTT_EVENT_SUBSCRIBED, + MQTT_EVENT_UNSUBSCRIBED, + MQTT_EVENT_PUBLISHED, + MQTT_EVENT_DATA, +} esp_mqtt_event_id_t; + +typedef enum { + MQTT_TRANSPORT_UNKNOWN = 0x0, + MQTT_TRANSPORT_OVER_TCP, /*!< MQTT over TCP, using scheme: ``mqtt`` */ + MQTT_TRANSPORT_OVER_SSL, /*!< MQTT over SSL, using scheme: ``mqtts`` */ + MQTT_TRANSPORT_OVER_WS, /*!< MQTT over Websocket, using scheme:: ``ws`` */ + MQTT_TRANSPORT_OVER_WSS /*!< MQTT over Websocket Secure, using scheme: ``wss`` */ +} esp_mqtt_transport_t; + +/** + * MQTT event configuration structure + */ +typedef struct { + esp_mqtt_event_id_t event_id; /*!< MQTT event type */ + esp_mqtt_client_handle_t client; /*!< MQTT client handle for this event */ + void *user_context; /*!< User context passed from MQTT client config */ + char *data; /*!< Data asociated with this event */ + int data_len; /*!< Lenght of the data for this event */ + int total_data_len; /*!< Total length of the data (longer data are supplied with multiple events) */ + int current_data_offset; /*!< Actual offset for the data asociated with this event */ + char *topic; /*!< Topic asociated with this event */ + int topic_len; /*!< Length of the topic for this event asociated with this event */ + int msg_id; /*!< MQTT messaged id of message */ +} esp_mqtt_event_t; + +typedef esp_mqtt_event_t* esp_mqtt_event_handle_t; + +typedef esp_err_t (* mqtt_event_callback_t)(esp_mqtt_event_handle_t event); + +/** + * MQTT client configuration structure + */ +typedef struct { + mqtt_event_callback_t event_handle; /*!< handle for MQTT events */ + const char *host; /*!< MQTT server domain (ipv4 as string) */ + const char *uri; /*!< Complete MQTT broker URI */ + uint32_t port; /*!< MQTT server port */ + const char *client_id; /*!< default client id is ``ESP32_%CHIPID%`` where %CHIPID% are last 3 bytes of MAC address in hex format */ + const char *username; /*!< MQTT username */ + const char *password; /*!< MQTT password */ + const char *lwt_topic; /*!< LWT (Last Will and Testament) message topic (NULL by default) */ + const char *lwt_msg; /*!< LWT message (NULL by default) */ + int lwt_qos; /*!< LWT message qos */ + int lwt_retain; /*!< LWT retained message flag */ + int lwt_msg_len; /*!< LWT message length */ + int disable_clean_session; /*!< mqtt clean session, default clean_session is true */ + int keepalive; /*!< mqtt keepalive, default is 120 seconds */ + bool disable_auto_reconnect; /*!< this mqtt client will reconnect to server (when errors/disconnect). Set disable_auto_reconnect=true to disable */ + void *user_context; /*!< pass user context to this option, then can receive that context in ``event->user_context`` */ + int task_prio; /*!< MQTT task priority, default is 5, can be changed in ``make menuconfig`` */ + int task_stack; /*!< MQTT task stack size, default is 6144 bytes, can be changed in ``make menuconfig`` */ + int buffer_size; /*!< size of MQTT send/receive buffer, default is 1024 */ + const char *cert_pem; /*!< pointer to CERT file for server verify (with SSL), default is NULL, not required to verify the server */ + esp_mqtt_transport_t transport; /*!< overrides URI transport */ +} esp_mqtt_client_config_t; + +esp_mqtt_client_handle_t esp_mqtt_client_init(const esp_mqtt_client_config_t *config); +esp_err_t esp_mqtt_client_set_uri(esp_mqtt_client_handle_t client, const char *uri); +esp_err_t esp_mqtt_client_start(esp_mqtt_client_handle_t client); +esp_err_t esp_mqtt_client_stop(esp_mqtt_client_handle_t client); +esp_err_t esp_mqtt_client_subscribe(esp_mqtt_client_handle_t client, const char *topic, int qos); +esp_err_t esp_mqtt_client_unsubscribe(esp_mqtt_client_handle_t client, const char *topic); +int esp_mqtt_client_publish(esp_mqtt_client_handle_t client, const char *topic, const char *data, int len, int qos, int retain); +esp_err_t esp_mqtt_client_destroy(esp_mqtt_client_handle_t client); + +#ifdef __cplusplus +} +#endif //__cplusplus + +#endif diff --git a/tools/sdk/include/esp-mqtt/mqtt_config.h b/tools/sdk/include/esp-mqtt/mqtt_config.h new file mode 100644 index 00000000..c0b4ab75 --- /dev/null +++ b/tools/sdk/include/esp-mqtt/mqtt_config.h @@ -0,0 +1,81 @@ +/* + * This file is subject to the terms and conditions defined in + * file 'LICENSE', which is part of this source code package. + * Tuan PM + */ +#ifndef _MQTT_CONFIG_H_ +#define _MQTT_CONFIG_H_ + +#include "sdkconfig.h" + +#define MQTT_PROTOCOL_311 CONFIG_MQTT_PROTOCOL_311 +#define MQTT_RECONNECT_TIMEOUT_MS (10*1000) + +#if CONFIG_MQTT_BUFFER_SIZE +#define MQTT_BUFFER_SIZE_BYTE CONFIG_MQTT_BUFFER_SIZE +#else +#define MQTT_BUFFER_SIZE_BYTE 1024 +#endif + +#define MQTT_MAX_HOST_LEN 64 +#define MQTT_MAX_CLIENT_LEN 32 +#define MQTT_MAX_USERNAME_LEN 32 +#define MQTT_MAX_PASSWORD_LEN 65 +#define MQTT_MAX_LWT_TOPIC 32 +#define MQTT_MAX_LWT_MSG 128 +#define MQTT_TASK_PRIORITY 5 + +#if CONFIG_MQTT_TASK_STACK_SIZE +#define MQTT_TASK_STACK CONFIG_MQTT_TASK_STACK_SIZE +#else +#define MQTT_TASK_STACK (6*1024) +#endif + +#define MQTT_KEEPALIVE_TICK (120) +#define MQTT_CMD_QUEUE_SIZE (10) +#define MQTT_NETWORK_TIMEOUT_MS (10000) + +#ifdef CONFIG_MQTT_TCP_DEFAULT_PORT +#define MQTT_TCP_DEFAULT_PORT CONFIG_MQTT_TCP_DEFAULT_PORT +#else +#define MQTT_TCP_DEFAULT_PORT 1883 +#endif + +#ifdef CONFIG_MQTT_SSL_DEFAULT_PORT +#define MQTT_SSL_DEFAULT_PORT CONFIG_MQTT_SSL_DEFAULT_PORT +#else +#define MQTT_SSL_DEFAULT_PORT 8883 +#endif + +#ifdef CONFIG_MQTT_WS_DEFAULT_PORT +#define MQTT_WS_DEFAULT_PORT CONFIG_MQTT_WS_DEFAULT_PORT +#else +#define MQTT_WS_DEFAULT_PORT 80 +#endif + +#ifdef MQTT_WSS_DEFAULT_PORT +#define MQTT_WSS_DEFAULT_PORT CONFIG_MQTT_WSS_DEFAULT_PORT +#else +#define MQTT_WSS_DEFAULT_PORT 443 +#endif + +#define MQTT_CORE_SELECTION_ENABLED CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED + +#ifdef CONFIG_MQTT_USE_CORE_0 + #define MQTT_TASK_CORE 0 +#else + #ifdef CONFIG_MQTT_USE_CORE_1 + #define MQTT_TASK_CORE 1 + #else + #define MQTT_TASK_CORE 0 + #endif +#endif + + +#define MQTT_ENABLE_SSL CONFIG_MQTT_TRANSPORT_SSL +#define MQTT_ENABLE_WS CONFIG_MQTT_TRANSPORT_WEBSOCKET +#define MQTT_ENABLE_WSS CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE + +#define OUTBOX_EXPIRED_TIMEOUT_MS (30*1000) +#define OUTBOX_MAX_SIZE (4*1024) +#endif diff --git a/tools/sdk/include/esp-tls/esp_tls.h b/tools/sdk/include/esp-tls/esp_tls.h index 92b0734e..d5975dc1 100644 --- a/tools/sdk/include/esp-tls/esp_tls.h +++ b/tools/sdk/include/esp-tls/esp_tls.h @@ -18,7 +18,6 @@ #include #include - #include "mbedtls/platform.h" #include "mbedtls/net_sockets.h" #include "mbedtls/esp_debug.h" @@ -48,12 +47,14 @@ typedef struct esp_tls_cfg { const unsigned char *cacert_pem_buf; /*!< Certificate Authority's certificate in a buffer */ - const unsigned int cacert_pem_bytes; /*!< Size of Certificate Authority certificate + unsigned int cacert_pem_bytes; /*!< Size of Certificate Authority certificate pointed to by cacert_pem_buf */ bool non_block; /*!< Configure non-blocking mode. If set to true the underneath socket will be configured in non blocking mode after tls session is established */ + + int timeout_ms; /*!< Network timeout in milliseconds */ } esp_tls_cfg_t; /** @@ -165,6 +166,21 @@ static inline ssize_t esp_tls_conn_read(esp_tls_t *tls, void *data, size_t data */ void esp_tls_conn_delete(esp_tls_t *tls); +/** + * @brief Return the number of application data bytes remaining to be + * read from the current record + * + * This API is a wrapper over mbedtls's mbedtls_ssl_get_bytes_avail() API. + * + * @param[in] tls pointer to esp-tls as esp-tls handle. + * + * @return + * - -1 in case of invalid arg + * - bytes available in the application data + * record read buffer + */ +size_t esp_tls_get_bytes_avail(esp_tls_t *tls); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/esp32/esp32/pm.h b/tools/sdk/include/esp32/esp32/pm.h index a7cbf0ea..f64045fb 100644 --- a/tools/sdk/include/esp32/esp32/pm.h +++ b/tools/sdk/include/esp32/esp32/pm.h @@ -31,8 +31,10 @@ extern "C" { * Pass a pointer to this structure as an argument to esp_pm_configure function. */ typedef struct { - rtc_cpu_freq_t max_cpu_freq; /*!< Maximum CPU frequency to use */ - rtc_cpu_freq_t min_cpu_freq; /*!< Minimum CPU frequency to use when no frequency locks are taken */ + rtc_cpu_freq_t max_cpu_freq __attribute__((deprecated)); /*!< Maximum CPU frequency to use. Deprecated, use max_freq_mhz instead. */ + int max_freq_mhz; /*!< Maximum CPU frequency, in MHz */ + rtc_cpu_freq_t min_cpu_freq __attribute__((deprecated)); /*!< Minimum CPU frequency to use when no frequency locks are taken. Deprecated, use min_freq_mhz instead. */ + int min_freq_mhz; /*!< Minimum CPU frequency to use when no locks are taken, in MHz */ bool light_sleep_enable; /*!< Enter light sleep when no locks are taken */ } esp_pm_config_esp32_t; diff --git a/tools/sdk/include/esp32/esp_clk.h b/tools/sdk/include/esp32/esp_clk.h index 6526aa92..1a91d26f 100644 --- a/tools/sdk/include/esp32/esp_clk.h +++ b/tools/sdk/include/esp32/esp_clk.h @@ -62,6 +62,17 @@ int esp_clk_cpu_freq(void); */ int esp_clk_apb_freq(void); +/** + * @brief Return frequency of the main XTAL + * + * Frequency of the main XTAL can be either auto-detected or set at compile + * time (see CONFIG_ESP32_XTAL_FREQ_SEL sdkconfig option). In both cases, this + * function returns the actual value at run time. + * + * @return XTAL frequency, in Hz + */ +int esp_clk_xtal_freq(void); + /** * @brief Read value of RTC counter, converting it to microseconds diff --git a/tools/sdk/include/esp32/esp_err.h b/tools/sdk/include/esp32/esp_err.h index d8820e5a..9dcb25af 100644 --- a/tools/sdk/include/esp32/esp_err.h +++ b/tools/sdk/include/esp32/esp_err.h @@ -27,20 +27,20 @@ typedef int32_t esp_err_t; #define ESP_OK 0 /*!< esp_err_t value indicating success (no error) */ #define ESP_FAIL -1 /*!< Generic esp_err_t code indicating failure */ -#define ESP_ERR_NO_MEM 0x101 /*!< Out of memory */ -#define ESP_ERR_INVALID_ARG 0x102 /*!< Invalid argument */ -#define ESP_ERR_INVALID_STATE 0x103 /*!< Invalid state */ -#define ESP_ERR_INVALID_SIZE 0x104 /*!< Invalid size */ -#define ESP_ERR_NOT_FOUND 0x105 /*!< Requested resource not found */ -#define ESP_ERR_NOT_SUPPORTED 0x106 /*!< Operation or feature not supported */ -#define ESP_ERR_TIMEOUT 0x107 /*!< Operation timed out */ +#define ESP_ERR_NO_MEM 0x101 /*!< Out of memory */ +#define ESP_ERR_INVALID_ARG 0x102 /*!< Invalid argument */ +#define ESP_ERR_INVALID_STATE 0x103 /*!< Invalid state */ +#define ESP_ERR_INVALID_SIZE 0x104 /*!< Invalid size */ +#define ESP_ERR_NOT_FOUND 0x105 /*!< Requested resource not found */ +#define ESP_ERR_NOT_SUPPORTED 0x106 /*!< Operation or feature not supported */ +#define ESP_ERR_TIMEOUT 0x107 /*!< Operation timed out */ #define ESP_ERR_INVALID_RESPONSE 0x108 /*!< Received response was invalid */ -#define ESP_ERR_INVALID_CRC 0x109 /*!< CRC or checksum was invalid */ +#define ESP_ERR_INVALID_CRC 0x109 /*!< CRC or checksum was invalid */ #define ESP_ERR_INVALID_VERSION 0x10A /*!< Version was invalid */ -#define ESP_ERR_INVALID_MAC 0x10B /*!< MAC address was invalid */ +#define ESP_ERR_INVALID_MAC 0x10B /*!< MAC address was invalid */ -#define ESP_ERR_WIFI_BASE 0x3000 /*!< Starting number of WiFi error codes */ -#define ESP_ERR_MESH_BASE 0x4000 /*!< Starting number of MESH error codes */ +#define ESP_ERR_WIFI_BASE 0x3000 /*!< Starting number of WiFi error codes */ +#define ESP_ERR_MESH_BASE 0x4000 /*!< Starting number of MESH error codes */ /** * @brief Returns string for esp_err_t error codes diff --git a/tools/sdk/include/esp32/esp_mesh.h b/tools/sdk/include/esp32/esp_mesh.h index db9cb1d1..6322dc60 100644 --- a/tools/sdk/include/esp32/esp_mesh.h +++ b/tools/sdk/include/esp32/esp_mesh.h @@ -26,7 +26,7 @@ * | | ...) | (LwIP) | | | | * | |-----------------------------------| |---------------| | * | | | | - * | | WiFi Driver | | + * | | Wi-Fi Driver | | * | |--------------------------------------------------| | * | | | * | | Platform HAL | @@ -36,7 +36,7 @@ * * |---------------| * | | default handler - * | WiFi stack | events |---------------------| + * | Wi-Fi stack | events |---------------------| * | | -------------> | | * |---------------| | | * | event task | @@ -58,27 +58,27 @@ * Mesh Stack * * Mesh event defines almost all system events applications tasks need. - * Mesh event contains WiFi connection states on station interface, children connection states on softAP interface and etc.. + * Mesh event contains Wi-Fi connection states on station interface, children connection states on softAP interface and etc.. * Applications need to register a mesh event callback handler by API esp_mesh_set_config() firstly. * This handler is to receive events posted from mesh stack and LwIP stack. * Applications could add relative handler for each event. * Examples: - * (1)Applications could use WiFi station connect states to decide when to send data to its parent, to root or to external IP network; - * (2)Applications could use WiFi softAP states to decide when to send data to its children. + * (1) Applications could use Wi-Fi station connect states to decide when to send data to its parent, to the root or to external IP network; + * (2) Applications could use Wi-Fi softAP states to decide when to send data to its children. * * In present implementation, applications are able to access mesh stack directly without having to go through LwIP stack. * Applications use esp_mesh_send() and esp_mesh_recv() to send and receive messages over the mesh network. * In mesh stack design, normal devices don't require LwIP stack. But since IDF hasn't supported system without initializing LwIP stack yet, * applications still need to do LwIP initialization and two more things are required to be done - * (1)stop DHCP server on softAP interface by default - * (2)stop DHCP client on station interface by default. + * (1) stop DHCP server on softAP interface by default + * (2) stop DHCP client on station interface by default. * Examples: * tcpip_adapter_init(); * tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP)ï¼› * tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA)ï¼› * - * Over the mesh network, only root is able to access external IP network. - * In application mesh event handler, once a device becomes a root, start DHCP client immediately if DHCP is chosen. + * Over the mesh network, only the root is able to access external IP network. + * In application mesh event handler, once a device becomes a root, start DHCP client immediately whether DHCP is chosen. */ #ifndef __ESP_MESH_H__ @@ -100,9 +100,9 @@ extern "C" { #define MESH_MTU (1500) /**< max transmit unit(in bytes) */ #define MESH_MPS (1472) /**< max payload size(in bytes) */ /** - * @brief mesh error code definition + * @brief Mesh error code definition */ -#define ESP_ERR_MESH_WIFI_NOT_START (ESP_ERR_MESH_BASE + 1) /**< WiFi isn't started */ +#define ESP_ERR_MESH_WIFI_NOT_START (ESP_ERR_MESH_BASE + 1) /**< Wi-Fi isn't started */ #define ESP_ERR_MESH_NOT_INIT (ESP_ERR_MESH_BASE + 2) /**< mesh isn't initialized */ #define ESP_ERR_MESH_NOT_CONFIG (ESP_ERR_MESH_BASE + 3) /**< mesh isn't configured */ #define ESP_ERR_MESH_NOT_START (ESP_ERR_MESH_BASE + 4) /**< mesh isn't started */ @@ -120,41 +120,41 @@ extern "C" { #define ESP_ERR_MESH_OPTION_NULL (ESP_ERR_MESH_BASE + 16) /**< no option found */ #define ESP_ERR_MESH_OPTION_UNKNOWN (ESP_ERR_MESH_BASE + 17) /**< unknown option */ #define ESP_ERR_MESH_XON_NO_WINDOW (ESP_ERR_MESH_BASE + 18) /**< no window for software flow control on upstream */ -#define ESP_ERR_MESH_INTERFACE (ESP_ERR_MESH_BASE + 19) /**< low-level WiFi interface error */ +#define ESP_ERR_MESH_INTERFACE (ESP_ERR_MESH_BASE + 19) /**< low-level Wi-Fi interface error */ #define ESP_ERR_MESH_DISCARD_DUPLICATE (ESP_ERR_MESH_BASE + 20) /**< discard the packet due to the duplicate sequence number */ #define ESP_ERR_MESH_DISCARD (ESP_ERR_MESH_BASE + 21) /**< discard the packet */ #define ESP_ERR_MESH_VOTING (ESP_ERR_MESH_BASE + 22) /**< vote in progress */ /** - * @brief flags used with esp_mesh_send() and esp_mesh_recv() + * @brief Flags bitmap for esp_mesh_send() and esp_mesh_recv() */ -#define MESH_DATA_ENC (0x01) /**< data encrypted(Unimplemented) */ +#define MESH_DATA_ENC (0x01) /**< data encrypted (Unimplemented) */ #define MESH_DATA_P2P (0x02) /**< point-to-point delivery over the mesh network */ #define MESH_DATA_FROMDS (0x04) /**< receive from external IP network */ #define MESH_DATA_TODS (0x08) /**< identify this packet is target to external IP network */ #define MESH_DATA_NONBLOCK (0x10) /**< esp_mesh_send() non-block */ -#define MESH_DATA_DROP (0x20) /**< in the situation of root having been changed, identify this packet can be dropped by new root */ +#define MESH_DATA_DROP (0x20) /**< in the situation of the root having been changed, identify this packet can be dropped by new root */ #define MESH_DATA_GROUP (0x40) /**< identify this packet is target to a group address */ /** - * @brief option definitions for esp_mesh_send() and esp_mesh_recv() + * @brief Option definitions for esp_mesh_send() and esp_mesh_recv() */ #define MESH_OPT_SEND_GROUP (7) /**< data transmission by group; used with esp_mesh_send() and shall have payload */ #define MESH_OPT_RECV_DS_ADDR (8) /**< return a remote IP address; used with esp_mesh_send() and esp_mesh_recv() */ /** - * @brief flag of mesh networking IE + * @brief Flag of mesh networking IE */ #define MESH_ASSOC_FLAG_VOTE_IN_PROGRESS (0x02) /**< vote in progress */ #define MESH_ASSOC_FLAG_NETWORK_FREE (0x08) /**< no root in current network */ #define MESH_ASSOC_FLAG_ROOTS_FOUND (0x20) /**< root conflict is found */ -#define MESH_ASSOC_FLAG_ROOT_FIXED (0x40) /**< root is fixed */ +#define MESH_ASSOC_FLAG_ROOT_FIXED (0x40) /**< fixed root */ /******************************************************* * Enumerations *******************************************************/ /** - * @brief enumerated list of mesh event id + * @brief Enumerated list of mesh event id */ typedef enum { MESH_EVENT_STARTED, /**< mesh is started */ @@ -166,30 +166,30 @@ typedef enum { MESH_EVENT_ROUTING_TABLE_REMOVE, /**< routing table is changed by removing leave children */ MESH_EVENT_PARENT_CONNECTED, /**< parent is connected on station interface */ MESH_EVENT_PARENT_DISCONNECTED, /**< parent is disconnected on station interface */ - MESH_EVENT_NO_PARNET_FOUND, /**< no parent found */ + MESH_EVENT_NO_PARENT_FOUND, /**< no parent found */ MESH_EVENT_LAYER_CHANGE, /**< layer changes over the mesh network */ - MESH_EVENT_TODS_STATE, /**< state represents if root is able to access external IP network */ - MESH_EVENT_VOTE_STARTED, /**< the process of voting a new root is started either by children or by root */ + MESH_EVENT_TODS_STATE, /**< state represents whether the root is able to access external IP network */ + MESH_EVENT_VOTE_STARTED, /**< the process of voting a new root is started either by children or by the root */ MESH_EVENT_VOTE_STOPPED, /**< the process of voting a new root is stopped */ MESH_EVENT_ROOT_ADDRESS, /**< the root address is obtained. It is posted by mesh stack automatically. */ MESH_EVENT_ROOT_SWITCH_REQ, /**< root switch request sent from a new voted root candidate */ MESH_EVENT_ROOT_SWITCH_ACK, /**< root switch acknowledgment responds the above request sent from current root */ - MESH_EVENT_ROOT_GOT_IP, /**< root obtains the IP address. It is posted by LwIP stack automatically */ - MESH_EVENT_ROOT_LOST_IP, /**< root loses the IP address. It is posted by LwIP stack automatically */ - MESH_EVENT_ROOT_ASKED_YIELD, /**< root is asked yield by a more powerful existing root. If self organized is disabled + MESH_EVENT_ROOT_GOT_IP, /**< the root obtains the IP address. It is posted by LwIP stack automatically */ + MESH_EVENT_ROOT_LOST_IP, /**< the root loses the IP address. It is posted by LwIP stack automatically */ + MESH_EVENT_ROOT_ASKED_YIELD, /**< the root is asked yield by a more powerful existing root. If self organized is disabled and this device is specified to be a root by users, users should set a new parent for this device. if self organized is enabled, this device will find a new parent by itself, users could ignore this event. */ MESH_EVENT_ROOT_FIXED, /**< when devices join a network, if the setting of Fixed Root for one device is different from that of its parent, the device will update the setting the same as its parent's. - Fixed Root setting of each device is variable as that setting changes of root. */ + Fixed Root Setting of each device is variable as that setting changes of the root. */ MESH_EVENT_SCAN_DONE, /**< if self-organized networking is disabled, user can call esp_wifi_scan_start() to trigger this event, and add the corresponding scan done handler in this event. */ MESH_EVENT_MAX, } mesh_event_id_t; /** - * @brief device type + * @brief Device type */ typedef enum { MESH_IDLE, /**< hasn't joined the mesh network yet */ @@ -199,7 +199,7 @@ typedef enum { } mesh_type_t; /** - * @brief protocol of transmitted application data + * @brief Protocol of transmitted application data */ typedef enum { MESH_PROTO_BIN, /**< binary */ @@ -209,24 +209,24 @@ typedef enum { } mesh_proto_t; /** - * @brief for reliable transmission, mesh stack provides three type of services + * @brief For reliable transmission, mesh stack provides three type of services */ typedef enum { - MESH_TOS_P2P, /**< provide P2P(point-to-point) retransmission on mesh stack by default */ - MESH_TOS_E2E, /**< provide E2E(end-to-end) retransmission on mesh stack (Unimplemented) */ + MESH_TOS_P2P, /**< provide P2P (point-to-point) retransmission on mesh stack by default */ + MESH_TOS_E2E, /**< provide E2E (end-to-end) retransmission on mesh stack (Unimplemented) */ MESH_TOS_DEF, /**< no retransmission on mesh stack */ } mesh_tos_t; /** - * @brief vote reason + * @brief Vote reason */ typedef enum { - MESH_VOTE_REASON_ROOT_INITIATED = 1, /**< vote is initiated by root */ + MESH_VOTE_REASON_ROOT_INITIATED = 1, /**< vote is initiated by the root */ MESH_VOTE_REASON_CHILD_INITIATED, /**< vote is initiated by children */ } mesh_vote_reason_t; /** - * @brief mesh disconnect reason code + * @brief Mesh disconnect reason code */ typedef enum { MESH_REASON_CYCLIC = 100, /**< cyclic is detected */ @@ -250,7 +250,7 @@ typedef struct { } __attribute__((packed)) mip_t; /** - * @brief mesh address + * @brief Mesh address */ typedef union { uint8_t addr[6]; /**< mac address */ @@ -258,47 +258,47 @@ typedef union { } mesh_addr_t; /** - * @brief channel switch information + * @brief Channel switch information */ typedef struct { uint8_t channel; /**< new channel */ } mesh_event_channel_switch_t; /** - * @brief parent connected information + * @brief Parent connected information */ typedef struct { - system_event_sta_connected_t connected; /**< parent information, same as WiFi event SYSTEM_EVENT_STA_CONNECTED does */ + system_event_sta_connected_t connected; /**< parent information, same as Wi-Fi event SYSTEM_EVENT_STA_CONNECTED does */ uint8_t self_layer; /**< layer */ } mesh_event_connected_t; /** - * @brief no parent found information + * @brief No parent found information */ typedef struct { int scan_times; /**< scan times being through */ } mesh_event_no_parent_found_t; /** - * @brief layer change information + * @brief Layer change information */ typedef struct { uint8_t new_layer; /**< new layer */ } mesh_event_layer_change_t; /** - * @brief the reachability of root to a DS(distribute system) + * @brief The reachability of the root to a DS (distribute system) */ typedef enum { - MESH_TODS_UNREACHABLE, /**< root isn't able to access external IP network */ - MESH_TODS_REACHABLE, /**< root is able to access external IP network */ + MESH_TODS_UNREACHABLE, /**< the root isn't able to access external IP network */ + MESH_TODS_REACHABLE, /**< the root is able to access external IP network */ } mesh_event_toDS_state_t; /** * @brief vote started information */ typedef struct { - int reason; /**< vote reason, vote could be initiated by children or by root itself */ + int reason; /**< vote reason, vote could be initiated by children or by the root itself */ int attempts; /**< max vote attempts before stopped */ mesh_addr_t rc_addr; /**< root address specified by users via API esp_mesh_waive_root() */ } mesh_event_vote_started_t; @@ -309,27 +309,27 @@ typedef struct { typedef system_event_sta_got_ip_t mesh_event_root_got_ip_t; /** - * @brief root address + * @brief Root address */ typedef mesh_addr_t mesh_event_root_address_t; /** - * @brief parent disconnected information + * @brief Parent disconnected information */ typedef system_event_sta_disconnected_t mesh_event_disconnected_t; /** - * @brief child connected information + * @brief Child connected information */ typedef system_event_ap_staconnected_t mesh_event_child_connected_t; /** - * @brief child disconnected information + * @brief Child disconnected information */ typedef system_event_ap_stadisconnected_t mesh_event_child_disconnected_t; /** - * @brief root switch request information + * @brief Root switch request information */ typedef struct { int reason; /**< root switch reason, generally root switch is initialized by users via API esp_mesh_waive_root() */ @@ -337,7 +337,7 @@ typedef struct { } mesh_event_root_switch_req_t; /** - * @brief other powerful root address + * @brief Other powerful root address */ typedef struct { int8_t rssi; /**< rssi with router */ @@ -346,7 +346,7 @@ typedef struct { } mesh_event_root_conflict_t; /** - * @brief routing table change + * @brief Routing table change */ typedef struct { uint16_t rt_size_new; /**< the new value */ @@ -354,21 +354,21 @@ typedef struct { } mesh_event_routing_table_change_t; /** - * @brief root fixed + * @brief Root fixed */ typedef struct { bool is_fixed; /**< status */ } mesh_event_root_fixed_t; /** - * @brief scan done event information + * @brief Scan done event information */ typedef struct { - uint8_t number; /**< the number of scanned APs */ + uint8_t number; /**< the number of APs scanned */ } mesh_event_scan_done_t; /** - * @brief mesh event information + * @brief Mesh event information */ typedef union { mesh_event_channel_switch_t channel_switch; /**< channel switch */ @@ -380,7 +380,7 @@ typedef union { mesh_event_no_parent_found_t no_parent; /**< no parent found */ mesh_event_layer_change_t layer_change; /**< layer change */ mesh_event_toDS_state_t toDS_state; /**< toDS state, devices shall check this state firstly before trying to send packets to - external IP network. This state indicates right now if root is capable of sending + external IP network. This state indicates right now whether the root is capable of sending packets out. If not, devices had better to wait until this state changes to be MESH_TODS_REACHABLE. */ mesh_event_vote_started_t vote_started; /**< vote started */ @@ -388,12 +388,12 @@ typedef union { mesh_event_root_address_t root_addr; /**< root address */ mesh_event_root_switch_req_t switch_req; /**< root switch request */ mesh_event_root_conflict_t root_conflict; /**< other powerful root */ - mesh_event_root_fixed_t root_fixed; /**< root fixed */ + mesh_event_root_fixed_t root_fixed; /**< fixed root */ mesh_event_scan_done_t scan_done; /**< scan done */ } mesh_event_info_t; /** - * @brief mesh event + * @brief Mesh event */ typedef struct { mesh_event_id_t id; /**< mesh event id */ @@ -401,14 +401,14 @@ typedef struct { } mesh_event_t; /** - * @brief mesh event callback handler prototype definition + * @brief Mesh event callback handler prototype definition * * @param event mesh_event_t */ typedef void (*mesh_event_cb_t)(mesh_event_t event); /** - * @brief mesh option + * @brief Mesh option */ typedef struct { uint8_t type; /**< option type */ @@ -417,7 +417,7 @@ typedef struct { } __attribute__((packed)) mesh_opt_t; /** - * @brief mesh data for esp_mesh_send() and esp_mesh_recv() + * @brief Mesh data for esp_mesh_send() and esp_mesh_recv() */ typedef struct { uint8_t *data; /**< data */ @@ -427,7 +427,7 @@ typedef struct { } mesh_data_t; /** - * @brief router configuration + * @brief Router configuration */ typedef struct { uint8_t ssid[32]; /**< SSID */ @@ -437,7 +437,7 @@ typedef struct { } mesh_router_t; /** - * @brief mesh softAP configuration + * @brief Mesh softAP configuration */ typedef struct { uint8_t password[64]; /**< mesh softAP password */ @@ -445,7 +445,7 @@ typedef struct { } mesh_ap_cfg_t; /** - * @brief mesh initialization configuration + * @brief Mesh initialization configuration */ typedef struct { uint8_t channel; /**< channel, the mesh network on */ @@ -457,7 +457,7 @@ typedef struct { } mesh_cfg_t; /** - * @brief vote address configuration + * @brief Vote address configuration */ typedef union { int attempts; /**< max vote attempts before a new root is elected automatically by mesh network. (min:15, 15 by default) */ @@ -465,29 +465,29 @@ typedef union { } mesh_rc_config_t; /** - * @brief vote + * @brief Vote */ typedef struct { float percentage; /**< vote percentage threshold for approval of being a root */ - bool is_rc_specified; /**< if true, rc_addr shall be specified(Unimplemented). + bool is_rc_specified; /**< if true, rc_addr shall be specified (Unimplemented). if false, attempts value shall be specified to make network start root election. */ mesh_rc_config_t config; /**< vote address configuration */ } mesh_vote_t; /** - * @brief the number of packets pending in the queue waiting to be sent by the mesh stack + * @brief The number of packets pending in the queue waiting to be sent by the mesh stack */ typedef struct { int to_parent; /**< to parent queue */ - int to_parent_p2p; /**< to parent(P2P) queue */ + int to_parent_p2p; /**< to parent (P2P) queue */ int to_child; /**< to child queue */ - int to_child_p2p; /**< to child(P2P) queue */ + int to_child_p2p; /**< to child (P2P) queue */ int mgmt; /**< management queue */ int broadcast; /**< broadcast and multicast queue */ } mesh_tx_pending_t; /** - * @brief the number of packets available in the queue waiting to be received by applications + * @brief The number of packets available in the queue waiting to be received by applications */ typedef struct { int toDS; /**< to external DS */ @@ -497,7 +497,7 @@ typedef struct { /******************************************************* * Variable Declaration *******************************************************/ -/* mesh vendor IE crypto callback function */ +/* mesh IE crypto callback function */ extern const mesh_crypto_funcs_t g_wifi_default_mesh_crypto_funcs; /* mesh event callback handler */ @@ -511,11 +511,11 @@ extern mesh_event_cb_t g_mesh_event_cb; * Function Definitions *******************************************************/ /** - * @brief mesh initialization - * Check if WiFi is started. - * Initialize mesh global variables with default values. + * @brief Mesh initialization + * - Check whether Wi-Fi is started. + * - Initialize mesh global variables with default values. * - * @attention This API shall be called after WiFi is started. + * @attention This API shall be called after Wi-Fi is started. * * @return * - ESP_OK @@ -524,8 +524,9 @@ extern mesh_event_cb_t g_mesh_event_cb; esp_err_t esp_mesh_init(void); /** - * @brief mesh de-initialization - * Release resources and stop the mesh + * @brief Mesh de-initialization + * + * - Release resources and stop the mesh * * @return * - ESP_OK @@ -534,13 +535,13 @@ esp_err_t esp_mesh_init(void); esp_err_t esp_mesh_deinit(void); /** - * @brief start mesh - * Initialize mesh vendor IE - * Start mesh network management service - * Create TX and RX queues according to the configuration - * Register mesh packets receive callback + * @brief Start mesh + * - Initialize mesh IE. + * - Start mesh network management service. + * - Create TX and RX queues according to the configuration. + * - Register mesh packets receive callback. * - * @attention This API shall be called after esp_mesh_init() and esp_mesh_set_config(). + * @attention This API shall be called after esp_mesh_init() and esp_mesh_set_config(). * * @return * - ESP_OK @@ -552,15 +553,15 @@ esp_err_t esp_mesh_deinit(void); esp_err_t esp_mesh_start(void); /** - * @brief stop mesh - * Deinitialize mesh vendor IE - * Disconnect with current parent - * Disassociate all currently associated children - * Stop mesh network management service - * Unregister mesh packets receive callback - * Delete TX and RX queues - * Release resources - * Restore WiFi softAP to default settings if WiFi dual mode is enabled + * @brief Stop mesh + * - Deinitialize mesh IE. + * - Disconnect with current parent. + * - Disassociate all currently associated children. + * - Stop mesh network management service. + * - Unregister mesh packets receive callback. + * - Delete TX and RX queues. + * - Release resources. + * - Restore Wi-Fi softAP to default settings if Wi-Fi dual mode is enabled. * * @return * - ESP_OK @@ -569,40 +570,42 @@ esp_err_t esp_mesh_start(void); esp_err_t esp_mesh_stop(void); /** - * @brief send a packet over the mesh network - * Send a packet to any device in the mesh network. - * Send a packet to external IP network. + * @brief Send a packet over the mesh network + * - Send a packet to any device in the mesh network. + * - Send a packet to external IP network. * - * @attention This API is not reentrant. + * @attention This API is not reentrant. * - * @param to the address of the final destination of the packet - * (1)if the packet is to root, just set "to" to NULL and set flag to zero. - * (2)if the packet is outgoing to external IP network such as an IP server address, translate IPv4:PORT known as "to". - * This packet will be delivered to root firstly, then root will forward this packet to the final IP server address. - * @param data pointer to a sending mesh packet - * Should specify the data protocol applications used, binary by default. - * Should specify the transmission tos(type of service), P2P reliable by default. - * @param flag - * (1)used to speed up the route selection - * if the packet is target to an internal device, MESH_DATA_P2P should be set. - * if the packet is outgoing to root or to external IP network, MESH_DATA_TODS should be set. - * if the packet is from root to an internal device, MESH_DATA_FROMDS should be set. - * (2)specify if this API is block or non-block, block by default - * if needs non-block, MESH_DATA_NONBLOCK should be set. - * (3)in the situation of root having been changed, MESH_DATA_DROP identifies this packet can be dropped by new root - * for upstream data to external IP network, we try our best to avoid data loss caused by root having been changed, but - * there is a risk that new root is running out of memory because most of memory is occupied by the pending data which - * isn't read out in time by esp_mesh_recv_toDS(). - * Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP network is created. Thus data outgoing - * to external IP network via socket is just from reading esp_mesh_recv_toDS() which avoids unnecessary memory copy. + * @param[in] to the address of the final destination of the packet + * - If the packet is to the root, set this parameter to NULL. + * - If the packet is to an external IP network, set this parameter to the IPv4:PORT combination. + * This packet will be delivered to the root firstly, then the root will forward this packet to the final IP server address. + * @param[in] data pointer to a sending mesh packet + * - Field proto should be set to data protocol in use (default is MESH_PROTO_BIN for binary). + * - Field tos should be set to transmission tos (type of service) in use (default is MESH_TOS_P2P for point-to-point reliable). + * @param[in] flag bitmap for data sent + * - Speed up the route search + * - If the packet is to the root and "to" parameter is NULL, set this parameter to 0. + * - If the packet is to an internal device, MESH_DATA_P2P should be set. + * - If the packet is to the root ("to" parameter isn't NULL) or to external IP network, MESH_DATA_TODS should be set. + * - If the packet is from the root to an internal device, MESH_DATA_FROMDS should be set. + * - Specify whether this API is block or non-block, block by default + * - If needs non-block, MESH_DATA_NONBLOCK should be set. + * - In the situation of the root change, MESH_DATA_DROP identifies this packet can be dropped by the new root + * for upstream data to external IP network, we try our best to avoid data loss caused by the root change, but + * there is a risk that the new root is running out of memory because most of memory is occupied by the pending data which + * isn't read out in time by esp_mesh_recv_toDS(). * - * @param opt options - * (1)in case of sending a packet to a specified group, MESH_OPT_SEND_GROUP is a good choice. - * In this option, the value field should specify the target receiver addresses in this group. - * (2)root sends a packet to an internal device, this packet is from external IP network in case the receiver device responds - * this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. - * @param opt_count option count - * Currently, this API only takes one option, so opt_count is only supported to be 1. + * Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP network is created. Thus data outgoing + * to external IP network via socket is just from reading esp_mesh_recv_toDS() which avoids unnecessary memory copy. + * + * @param[in] opt options + * - In case of sending a packet to a certain group, MESH_OPT_SEND_GROUP is a good choice. + * In this option, the value field should be set to the target receiver addresses in this group. + * - Root sends a packet to an internal device, this packet is from external IP network in case the receiver device responds + * this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. + * @param[in] opt_count option count + * - Currently, this API only takes one option, so opt_count is only supported to be 1. * * @return * - ESP_OK @@ -622,21 +625,26 @@ esp_err_t esp_mesh_send(const mesh_addr_t *to, const mesh_data_t *data, int flag, const mesh_opt_t opt[], int opt_count); /** - * @brief receive a packet targeted to self over the mesh network - * Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting - * to be received by applications in case of running out of memory. + * @brief Receive a packet targeted to self over the mesh network * - * @param from the address of the original source of the packet - * @param data pointer to the received mesh packet - * Contain the protocol and applications should follow it to parse the data. - * @param timeout_ms wait time if a packet isn't immediately available(0:no wait, portMAX_DELAY:wait forever) - * @param flag - * MESH_DATA_FROMDS represents data from external IP network - * MESH_DATA_TODS represents data directed upward within the mesh network - * @param opt options desired to receive - * MESH_OPT_RECV_DS_ADDR attaches the DS address - * @param opt_count option count desired to receive - * Currently, this API only takes one option, so opt_count is only supported to be 1. + * @attention Mesh RX queue should be checked regularly to avoid running out of memory. + * - Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting + * to be received by applications. + * + * @param[out] from the address of the original source of the packet + * @param[out] data pointer to the received mesh packet + * - Field proto is the data protocol in use. Should follow it to parse the received data. + * - Field tos is the transmission tos (type of service) in use. + * @param[in] timeout_ms wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) + * @param[out] flag bitmap for data received + * - MESH_DATA_FROMDS represents data from external IP network + * - MESH_DATA_TODS represents data directed upward within the mesh network + * + * flag could be MESH_DATA_FROMDS or MESH_DATA_TODS. + * @param[out] opt options desired to receive + * - MESH_OPT_RECV_DS_ADDR attaches the DS address + * @param[in] opt_count option count desired to receive + * - Currently, this API only takes one option, so opt_count is only supported to be 1. * * @return * - ESP_OK @@ -649,29 +657,33 @@ esp_err_t esp_mesh_recv(mesh_addr_t *from, mesh_data_t *data, int timeout_ms, int *flag, mesh_opt_t opt[], int opt_count); /** - * @brief receive a packet targeted to external IP network - * root uses this API to receive packets destined to external IP network - * root forwards the received packets to the final destination via socket. - * if no socket connection is ready to send out the received packets and this esp_mesh_recv_toDS() - * hasn't been called by applications, packets from the whole mesh network will be pending in toDS queue. - * Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting - * to be received by applications in case of running out of memory in root. - * Use esp_mesh_set_xon_qsize() could configure the RX queue size, default:72. If this size is too large, - * and esp_mesh_recv_toDS() isn't called in time, there is a risk that a great deal of memory is occupied - * by the pending packets. If this size is too small, it will impact the efficiency on upstream. How to - * decide this value depends on the specific application scenarios. + * @brief Receive a packet targeted to external IP network + * - Root uses this API to receive packets destined to external IP network + * - Root forwards the received packets to the final destination via socket. + * - If no socket connection is ready to send out the received packets and this esp_mesh_recv_toDS() + * hasn't been called by applications, packets from the whole mesh network will be pending in toDS queue. * - * @attention This API is only called by root. + * Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting + * to be received by applications in case of running out of memory in the root. * - * @param from the address of the original source of the packet - * @param to the address contains remote IP address and port(IPv4:PORT) - * @param data pointer to the received packet - * Contain the protocol and applications should follow it to parse the data. - * @param timeout_ms wait time if a packet isn't immediately available(0:no wait, portMAX_DELAY:wait forever) - * @param flag - * MESH_DATA_TODS represents data to external IP network - * @param opt options desired to receive - * @param opt_count option count desired to receive + * Using esp_mesh_set_xon_qsize() users may configure the RX queue size, default:32. If this size is too large, + * and esp_mesh_recv_toDS() isn't called in time, there is a risk that a great deal of memory is occupied + * by the pending packets. If this size is too small, it will impact the efficiency on upstream. How to + * decide this value depends on the specific application scenarios. + * + * @attention This API is only called by the root. + * + * @param[out] from the address of the original source of the packet + * @param[out] to the address contains remote IP address and port (IPv4:PORT) + * @param[out] data pointer to the received packet + * - Contain the protocol and applications should follow it to parse the data. + * @param[in] timeout_ms wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) + * @param[out] flag bitmap for data received + * - MESH_DATA_TODS represents the received data target to external IP network. Root shall forward this data to external IP network via the association with router. + * + * flag could be MESH_DATA_TODS. + * @param[out] opt options desired to receive + * @param[in] opt_count option count desired to receive * * @return * - ESP_OK @@ -685,24 +697,26 @@ esp_err_t esp_mesh_recv_toDS(mesh_addr_t *from, mesh_addr_t *to, int opt_count); /** - * @brief set mesh stack configuration - * Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh vendor IE is encrypted by default. - * mesh network is established on a fixed channel(1-14). - * mesh event callback is mandatory. - * mesh ID is an identifier of an MBSS. Nodes with the same mesh ID can communicate with each other. - * Regarding to the router configuration, if the router is hidden, BSSID field is mandatory. - * If BSSID field isn't set and there exists more than one router with same SSID, there is a risk that more - * roots than one connected with different BSSID will appear. It means more than one mesh network is established - * with the same mesh ID. - * Root conflict function could eliminate redundant roots connected with the same BSSID, but couldn't handle roots - * connected with different BSSID. Because users might have such requirements of setting up routers with same SSID - * for the future replacement. But in that case, if the above situations happen, please make sure applications - * implement forward functions on root to guarantee devices in different mesh network can communicate with each other. - * max_connection of mesh softAP is limited by the max number of WiFi softAP supported(max:10). + * @brief Set mesh stack configuration + * - Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh IE is encrypted by default. + * - Mesh network is established on a fixed channel (1-14). + * - Mesh event callback is mandatory. + * - Mesh ID is an identifier of an MBSS. Nodes with the same mesh ID can communicate with each other. + * - Regarding to the router configuration, if the router is hidden, BSSID field is mandatory. * - * @attention This API shall be called between esp_mesh_init() and esp_mesh_start(). + * If BSSID field isn't set and there exists more than one router with same SSID, there is a risk that more + * roots than one connected with different BSSID will appear. It means more than one mesh network is established + * with the same mesh ID. * - * @param config pointer to mesh stack configuration + * Root conflict function could eliminate redundant roots connected with the same BSSID, but couldn't handle roots + * connected with different BSSID. Because users might have such requirements of setting up routers with same SSID + * for the future replacement. But in that case, if the above situations happen, please make sure applications + * implement forward functions on the root to guarantee devices in different mesh network can communicate with each other. + * max_connection of mesh softAP is limited by the max number of Wi-Fi softAP supported (max:10). + * + * @attention This API shall be called between esp_mesh_init() and esp_mesh_start(). + * + * @param[in] config pointer to mesh stack configuration * * @return * - ESP_OK @@ -712,9 +726,9 @@ esp_err_t esp_mesh_recv_toDS(mesh_addr_t *from, mesh_addr_t *to, esp_err_t esp_mesh_set_config(const mesh_cfg_t *config); /** - * @brief get mesh stack configuration + * @brief Get mesh stack configuration * - * @param config pointer to mesh stack configuration + * @param[out] config pointer to mesh stack configuration * * @return * - ESP_OK @@ -723,11 +737,11 @@ esp_err_t esp_mesh_set_config(const mesh_cfg_t *config); esp_err_t esp_mesh_get_config(mesh_cfg_t *config); /** - * @brief set router configuration + * @brief Get router configuration * - * @attention This API shall be called between esp_mesh_init() and esp_mesh_start(). + * @attention This API shall be called between esp_mesh_init() and esp_mesh_start(). * - * @param router pointer to router configuration + * @param[in] router pointer to router configuration * * @return * - ESP_OK @@ -736,9 +750,9 @@ esp_err_t esp_mesh_get_config(mesh_cfg_t *config); esp_err_t esp_mesh_set_router(const mesh_router_t *router); /** - * @brief get router configuration + * @brief Get router configuration * - * @param router pointer to router configuration + * @param[out] router pointer to router configuration * * @return * - ESP_OK @@ -747,11 +761,11 @@ esp_err_t esp_mesh_set_router(const mesh_router_t *router); esp_err_t esp_mesh_get_router(mesh_router_t *router); /** - * @brief set mesh network ID + * @brief Set mesh network ID * - * @attention This API could be called either before esp_mesh_start() or after esp_mesh_start(). + * @attention This API could be called either before esp_mesh_start() or after esp_mesh_start(). * - * @param id pointer to mesh network ID + * @param[in] id pointer to mesh network ID * * @return * - ESP_OK @@ -760,9 +774,9 @@ esp_err_t esp_mesh_get_router(mesh_router_t *router); esp_err_t esp_mesh_set_id(const mesh_addr_t *id); /** - * @brief get mesh network ID + * @brief Get mesh network ID * - * @param id pointer to mesh network ID + * @param[out] id pointer to mesh network ID * * @return * - ESP_OK @@ -771,9 +785,9 @@ esp_err_t esp_mesh_set_id(const mesh_addr_t *id); esp_err_t esp_mesh_get_id(mesh_addr_t *id); /** - * @brief set device type over the mesh network(Unimplemented) + * @brief Designate device type over the mesh network * - * @param type device type + * @param[in] type device type * * @return * - ESP_OK @@ -782,21 +796,22 @@ esp_err_t esp_mesh_get_id(mesh_addr_t *id); esp_err_t esp_mesh_set_type(mesh_type_t type); /** - * @brief get device type over mesh network + * @brief Get device type over mesh network * - * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. * - * @return mesh type + * @return mesh type * */ mesh_type_t esp_mesh_get_type(void); /** - * @brief set max layer configuration(max:15, default:15) + * @brief Set network max layer value (max:25, default:15) + * - Network max layer limits the max hop count. * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param max_layer max layer value + * @param[in] max_layer max layer value * * @return * - ESP_OK @@ -806,19 +821,19 @@ mesh_type_t esp_mesh_get_type(void); esp_err_t esp_mesh_set_max_layer(int max_layer); /** - * @brief get max layer configuration + * @brief Get max layer value * - * @return max layer value + * @return max layer value */ int esp_mesh_get_max_layer(void); /** - * @brief set mesh softAP password + * @brief Set mesh softAP password * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param pwd pointer to the password - * @param len password length + * @param[in] pwd pointer to the password + * @param[in] len password length * * @return * - ESP_OK @@ -828,11 +843,11 @@ int esp_mesh_get_max_layer(void); esp_err_t esp_mesh_set_ap_password(const uint8_t *pwd, int len); /** - * @brief set mesh softAP authentication mode value + * @brief Set mesh softAP authentication mode * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param authmode authentication mode + * @param[in] authmode authentication mode * * @return * - ESP_OK @@ -842,19 +857,18 @@ esp_err_t esp_mesh_set_ap_password(const uint8_t *pwd, int len); esp_err_t esp_mesh_set_ap_authmode(wifi_auth_mode_t authmode); /** - * @brief get mesh softAP authentication mode - * - * @return authentication mode + * @brief Get mesh softAP authentication mode * + * @return authentication mode */ wifi_auth_mode_t esp_mesh_get_ap_authmode(void); /** - * @brief set mesh softAP max connection value + * @brief Set mesh softAP max connection value * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param connections the number of max connections + * @param[in] connections the number of max connections * * @return * - ESP_OK @@ -863,29 +877,28 @@ wifi_auth_mode_t esp_mesh_get_ap_authmode(void); esp_err_t esp_mesh_set_ap_connections(int connections); /** - * @brief get mesh softAP max connection configuration - * - * @return the number of max connections + * @brief Get mesh softAP max connection configuration * + * @return the number of max connections */ int esp_mesh_get_ap_connections(void); /** - * @brief get current layer value over the mesh network + * @brief Get current layer value over the mesh network * - * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. * - * @return layer value + * @return layer value * */ int esp_mesh_get_layer(void); /** - * @brief get parent BSSID + * @brief Get the parent BSSID * - * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. * - * @param bssid pointer to parent BSSID + * @param[out] bssid pointer to parent BSSID * * @return * - ESP_OK @@ -894,22 +907,22 @@ int esp_mesh_get_layer(void); esp_err_t esp_mesh_get_parent_bssid(mesh_addr_t *bssid); /** - * @brief return if the device is root - * - * @return true/false + * @brief Return whether the device is the root node of the network * + * @return true/false */ bool esp_mesh_is_root(void); /** - * @brief enable/disable mesh networking self-organized, self-organized by default - * if self-organized is disabled, users should set a parent for this device via - * esp_mesh_set_parent(); + * @brief Enable/disable mesh networking self-organized, self-organized by default + * - If self-organized is disabled, users shall set a parent for the device via + * esp_mesh_set_parent(); * - * @attention This API could be called either before esp_mesh_start() or after esp_mesh_start(). + * @attention This API could be called either before esp_mesh_start() or after esp_mesh_start(). * - * @param enable enable or disable self-organized networking - * @param select_parent if enable self-organized networking, let the device select a new parent or + * @param[in] enable enable or disable self-organized networking + * @param[in] select_parent + * - If self-organized networking is enabled, let the device search for a new parent or * keep connecting to the previous parent. * * @return @@ -919,35 +932,36 @@ bool esp_mesh_is_root(void); esp_err_t esp_mesh_set_self_organized(bool enable, bool select_parent); /** - * @brief return if mesh networking is self-organized or not - * - * @return true/false + * @brief Return whether enable self-organized networking or not * + * @return true/false */ bool esp_mesh_get_self_organized(void); /** - * @brief root waive itself - * A device is elected to be a root during the networking mostly because it has a strong RSSI with router. - * If such superior conditions change, users could call this API to perform a root switch. + * @brief Cause the root device to give up (waive) its mesh root status + * - A device is elected root primarily based on RSSI from the external router. + * - If external router conditions change, users can call this API to perform a root switch. + * - In this API, users could specify a desired root address to replace itself or specify an attempts value + * to ask current root to initiate a new round of voting. During the voting, a better root candidate would + * be expected to find to replace the current one. + * - If no desired root candidate, the vote will try a specified number of attempts (at least 15). If no better + * root candidate is found, keep the current one. If a better candidate is found, the new better one will + * send a root switch request to the current root, current root will respond with a root switch acknowledgment. + * - After that, the new candidate will connect to the router to be a new root, the previous root will disconnect + * with the router and choose another parent instead. * - * In this API, users could specify a desired root address to replace itself or specify an attempts value - * to ask current root to initiate a new round of voting. During the voting, a better root candidate would - * be expected to find to replace the current one. - * If no desired root candidate, the vote will try a specified attempts(at least 10 times), if no better - * root candidate is found, keep the current one. If a better candidate is found, the new better one will - * send a root switch request to the current root, current root will respond with a root switch acknowledgment. - * After that, the new candidate will connect to the router to be a new root, the previous root will disconnect - * with the router and choose another parent instead. - * So far, root switch is completed with minimal disruption to the whole mesh network. + * Root switch is completed with minimal disruption to the whole mesh network. * - * @attention This API is only called by root. + * @attention This API is only called by the root. * - * @param vote vote configuration - * Specify a desired root address(Unimplemented) - * Attempts should be at least 10 times. - * if "vote" is set NULL, the vote will perform the default 10 times. - * @param reason only accept MESH_VOTE_REASON_ROOT_INITIATED for now + * @param[in] vote vote configuration + * - If this parameter is set NULL, the vote will perform the default 15 times. + * + * - Field percentage threshold is 0.9 by default. + * - Field is_rc_specified shall be false. + * - Field attempts shall be at least 15 times. + * @param[in] reason only accept MESH_VOTE_REASON_ROOT_INITIATED for now * * @return * - ESP_OK @@ -958,13 +972,13 @@ bool esp_mesh_get_self_organized(void); esp_err_t esp_mesh_waive_root(const mesh_vote_t *vote, int reason); /** - * @brief set vote percentage threshold for approval of being a root - * During the networking, only obtaining vote percentage reaches this threshold, - * the device could be a root. + * @brief Set vote percentage threshold for approval of being a root + * - During the networking, only obtaining vote percentage reaches this threshold, + * the device could be a root. * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param percentage vote percentage threshold + * @param[in] percentage vote percentage threshold * * @return * - ESP_OK @@ -973,18 +987,18 @@ esp_err_t esp_mesh_waive_root(const mesh_vote_t *vote, int reason); esp_err_t esp_mesh_set_vote_percentage(float percentage); /** - * @brief get vote percentage threshold for approval of being a root + * @brief Get vote percentage threshold for approval of being a root * - * @return percentage threshold + * @return percentage threshold */ float esp_mesh_get_vote_percentage(void); /** - * @brief set mesh softAP associate expired time - * If mesh softAP hasn't received any data from an associated child within this time, - * mesh softAP will take this child inactive and disassociate it. + * @brief Set mesh softAP associate expired time + * - If mesh softAP hasn't received any data from an associated child within this time, + * mesh softAP will take this child inactive and disassociate it. * - * @param seconds + * @param[in] seconds the expired time * * @return * - ESP_OK @@ -993,34 +1007,34 @@ float esp_mesh_get_vote_percentage(void); esp_err_t esp_mesh_set_ap_assoc_expire(int seconds); /** - * @brief get mesh softAP associate expired time + * @brief Get mesh softAP associate expired time * - * @return seconds + * @return seconds */ int esp_mesh_get_ap_assoc_expire(void); /** - * @brief get total number of devices in current network(including root) + * @brief Get total number of devices in current network (including the root) * - * @attention The returned value might be incorrect when the network is changing. + * @attention The returned value might be incorrect when the network is changing. ** - * @return total number of devices(including root) + * @return total number of devices (including the root) */ int esp_mesh_get_total_node_num(void); /** - * @brief get the number of devices in this device's sub-network(including self) + * @brief Get the number of devices in this device's sub-network (including self) * - * @return the number of devices over this device's sub-network(including self) + * @return the number of devices over this device's sub-network (including self) */ int esp_mesh_get_routing_table_size(void); /** - * @brief get routing table of this device's sub-network(including itself) + * @brief Get routing table of this device's sub-network (including itself) * - * @param mac pointer to routing table - * @param len routing table size(in bytes) - * @param size pointer to the number of devices in routing table(including itself) + * @param[out] mac pointer to routing table + * @param[in] len routing table size(in bytes) + * @param[out] size pointer to the number of devices in routing table (including itself) * * @return * - ESP_OK @@ -1029,11 +1043,11 @@ int esp_mesh_get_routing_table_size(void); esp_err_t esp_mesh_get_routing_table(mesh_addr_t *mac, int len, int *size); /** - * @brief post the toDS state to the mesh stack + * @brief Post the toDS state to the mesh stack * - * @attention This API is only for root. + * @attention This API is only for the root. * - * @param reachable this state represents if root is able to access external IP network + * @param[in] reachable this state represents whether the root is able to access external IP network * * @return * - ESP_OK @@ -1042,9 +1056,9 @@ esp_err_t esp_mesh_get_routing_table(mesh_addr_t *mac, int len, int *size); esp_err_t esp_mesh_post_toDS_state(bool reachable); /** - * @brief return the number of packets pending in the queue waiting to be sent by the mesh stack + * @brief Return the number of packets pending in the queue waiting to be sent by the mesh stack * - * @param pending pointer to the TX pending + * @param[out] pending pointer to the TX pending * * @return * - ESP_OK @@ -1053,9 +1067,9 @@ esp_err_t esp_mesh_post_toDS_state(bool reachable); esp_err_t esp_mesh_get_tx_pending(mesh_tx_pending_t *pending); /** - * @brief return the number of packets available in the queue waiting to be received by applications + * @brief Return the number of packets available in the queue waiting to be received by applications * - * @param pending pointer to the RX pending + * @param[out] pending pointer to the RX pending * * @return * - ESP_OK @@ -1064,21 +1078,21 @@ esp_err_t esp_mesh_get_tx_pending(mesh_tx_pending_t *pending); esp_err_t esp_mesh_get_rx_pending(mesh_rx_pending_t *pending); /** - * @brief return the number of packets could be accepted from the specified address + * @brief Return the number of packets could be accepted from the specified address * - * @param addr self address or an associate children address - * @param xseqno_in sequence number of the last received packet from the specified address + * @param[in] addr self address or an associate children address + * @param[out] xseqno_in sequence number of the last received packet from the specified address * - * @return the number of upQ for a specified address + * @return the number of upQ for a certain address */ int esp_mesh_available_txupQ_num(const mesh_addr_t *addr, uint32_t *xseqno_in); /** - * @brief set queue size + * @brief Set the number of queue * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param qsize default:32(min:16) + * @param[in] qsize default:32 (min:16) * * @return * - ESP_OK @@ -1087,16 +1101,16 @@ int esp_mesh_available_txupQ_num(const mesh_addr_t *addr, uint32_t *xseqno_in); esp_err_t esp_mesh_set_xon_qsize(int qsize); /** - * @brief get queue size + * @brief Get queue size * - * @return qsize + * @return the number of queue */ int esp_mesh_get_xon_qsize(void); /** - * @brief set if allow more than one root existing in one network + * @brief Set whether allow more than one root existing in one network * - * @param allowed allow or not + * @param[in] allowed allow or not * * @return * - ESP_OK @@ -1106,17 +1120,17 @@ int esp_mesh_get_xon_qsize(void); esp_err_t esp_mesh_allow_root_conflicts(bool allowed); /** - * @brief check if allow more than one root to exist in one network + * @brief Check whether allow more than one root to exist in one network * - * @return true/false + * @return true/false */ bool esp_mesh_is_root_conflicts_allowed(void); /** - * @brief set group ID addresses + * @brief Set group ID addresses * - * @param addr pointer to new group ID addresses - * @param num the number of group ID addresses + * @param[in] addr pointer to new group ID addresses + * @param[in] num the number of group ID addresses * * @return * - ESP_OK @@ -1125,10 +1139,10 @@ bool esp_mesh_is_root_conflicts_allowed(void); esp_err_t esp_mesh_set_group_id(const mesh_addr_t *addr, int num); /** - * @brief delete group ID addresses + * @brief Delete group ID addresses * - * @param addr pointer to deleted group ID address - * @param num the number of group ID addresses + * @param[in] addr pointer to deleted group ID address + * @param[in] num the number of group ID addresses * * @return * - ESP_OK @@ -1137,17 +1151,17 @@ esp_err_t esp_mesh_set_group_id(const mesh_addr_t *addr, int num); esp_err_t esp_mesh_delete_group_id(const mesh_addr_t *addr, int num); /** - * @brief get the number of group ID addresses + * @brief Get the number of group ID addresses * - * @return the number of group ID addresses + * @return the number of group ID addresses */ int esp_mesh_get_group_num(void); /** - * @brief get group ID addresses + * @brief Get group ID addresses * - * @param addr pointer to group ID addresses - * @param num the number of group ID addresses + * @param[out] addr pointer to group ID addresses + * @param[in] num the number of group ID addresses * * @return * - ESP_OK @@ -1156,18 +1170,18 @@ int esp_mesh_get_group_num(void); esp_err_t esp_mesh_get_group_list(mesh_addr_t *addr, int num); /** - * @brief check if the specified group address is my group + * @brief Check whether the specified group address is my group * - * @return true/false + * @return true/false */ bool esp_mesh_is_my_group(const mesh_addr_t *addr); /** - * @brief set mesh network capacity + * @brief Set mesh network capacity * - * @attention This API shall be called before esp_mesh_start(). + * @attention This API shall be called before esp_mesh_start(). * - * @param num mesh network capacity + * @param[in] num mesh network capacity * * @return * - ESP_OK @@ -1177,16 +1191,16 @@ bool esp_mesh_is_my_group(const mesh_addr_t *addr); esp_err_t esp_mesh_set_capacity_num(int num); /** - * @brief get mesh network capacity + * @brief Get mesh network capacity * - * @return mesh network capacity + * @return mesh network capacity */ int esp_mesh_get_capacity_num(void); /** - * @brief set mesh ie crypto functions + * @brief Set mesh IE crypto functions * - * @param crypto_funcs crypto functions for mesh ie + * @param[in] crypto_funcs crypto functions for mesh IE * * @return * - ESP_OK @@ -1194,12 +1208,12 @@ int esp_mesh_get_capacity_num(void); esp_err_t esp_mesh_set_ie_crypto_funcs(const mesh_crypto_funcs_t *crypto_funcs); /** - * @brief set mesh ie crypto key + * @brief Set mesh IE crypto key * - * @attention This API shall be called after esp_mesh_set_config() and before esp_mesh_start(). + * @attention This API shall be called after esp_mesh_set_config() and before esp_mesh_start(). * - * @param key ASCII crypto key - * @param len length in bytes, range:8~64 + * @param[in] key ASCII crypto key + * @param[in] len length in bytes, range:8~64 * * @return * - ESP_OK @@ -1210,10 +1224,10 @@ esp_err_t esp_mesh_set_ie_crypto_funcs(const mesh_crypto_funcs_t *crypto_funcs); esp_err_t esp_mesh_set_ie_crypto_key(const char *key, int len); /** - * @brief get mesh ie crypto key + * @brief Get mesh IE crypto key * - * @param key ASCII crypto key - * @param len length in bytes, range:8~64 + * @param[out] key ASCII crypto key + * @param[in] len length in bytes, range:8~64 * * @return * - ESP_OK @@ -1222,9 +1236,9 @@ esp_err_t esp_mesh_set_ie_crypto_key(const char *key, int len); esp_err_t esp_mesh_get_ie_crypto_key(char *key, int len); /** - * @brief set delay time before starting root healing + * @brief Set delay time before network starts root healing * - * @param delay_ms delay time in milliseconds + * @param[in] delay_ms delay time in milliseconds * * @return * - ESP_OK @@ -1232,16 +1246,16 @@ esp_err_t esp_mesh_get_ie_crypto_key(char *key, int len); esp_err_t esp_mesh_set_root_healing_delay(int delay_ms); /** - * @brief get delay time before starting root healing + * @brief Get delay time before network starts root healing * - * @return delay time in milliseconds + * @return delay time in milliseconds */ int esp_mesh_get_root_healing_delay(void); /** - * @brief set mesh event callback + * @brief Set mesh event callback * - * @param event_cb mesh event call back + * @param[in] event_cb mesh event call back * * @return * - ESP_OK @@ -1249,11 +1263,12 @@ int esp_mesh_get_root_healing_delay(void); esp_err_t esp_mesh_set_event_cb(const mesh_event_cb_t event_cb); /** - * @brief set Fixed Root setting for the device - * If Fixed Root setting of the device is enabled, it won't compete to be a root. - * If a scenario needs a fixed root, all devices in this network shall enable this setting. + * @brief Enable network Fixed Root Setting + * - Enabling fixed root disables automatic election of the root node via voting. + * - All devices in the network shall use the same Fixed Root Setting (enabled or disabled). + * - If Fixed Root is enabled, users should make sure a root node is designated for the network. * - * @param enable enable or not + * @param[in] enable enable or not * * @return * - ESP_OK @@ -1261,21 +1276,21 @@ esp_err_t esp_mesh_set_event_cb(const mesh_event_cb_t event_cb); esp_err_t esp_mesh_fix_root(bool enable); /** - * @brief check if Fixed Root setting is enabled - * Fixed Root setting can be changed by API esp_mesh_fix_root(). - * Fixed Root setting can also be changed by event MESH_EVENT_ROOT_FIXED. + * @brief Check whether network Fixed Root Setting is enabled + * - Enable/disable network Fixed Root Setting by API esp_mesh_fix_root(). + * - Network Fixed Root Setting also changes with the "flag" value in parent networking IE. * - * @return true/false + * @return true/false */ bool esp_mesh_is_root_fixed(void); /** - * @brief set a specified parent + * @brief Specify a parent for the device * - * @param parent parent configuration, the ssid and the channel of the parent are mandatory. - * @param parent_mesh_id parent mesh ID, if not set, use the device default one. - * @param my_type my mesh type - * @param my_layer my mesh layer + * @param[in] parent parent configuration, the SSID and the channel of the parent are mandatory. + * @param[in] parent_mesh_id parent mesh ID, if not set, use the device default one. + * @param[in] my_type my mesh type + * @param[in] my_layer my mesh layer * * @return * - ESP_OK @@ -1285,9 +1300,9 @@ bool esp_mesh_is_root_fixed(void); esp_err_t esp_mesh_set_parent(const wifi_config_t *parent, const mesh_addr_t *parent_mesh_id, mesh_type_t my_type, int my_layer); /** - * @brief get mesh networking IE length of one AP + * @brief Get mesh networking IE length of one AP * - * @param len mesh networking IE length + * @param[out] len mesh networking IE length * * @return * - ESP_OK @@ -1298,11 +1313,13 @@ esp_err_t esp_mesh_set_parent(const wifi_config_t *parent, const mesh_addr_t *pa esp_err_t esp_mesh_scan_get_ap_ie_len(int *len); /** - * @brief get AP record - * Different from esp_wifi_scan_get_ap_records(), this API only gets one of scanned APs each time. + * @brief Get AP record * - * @param ap_record pointer to the AP record - * @param buffer pointer to the mesh networking IE of this AP + * @attention Different from esp_wifi_scan_get_ap_records(), this API only gets one of APs scanned each time. + * See "manual_networking" example. + * + * @param[out] ap_record pointer to one AP record + * @param[out] buffer pointer to the mesh networking IE of this AP * * @return * - ESP_OK @@ -1312,6 +1329,41 @@ esp_err_t esp_mesh_scan_get_ap_ie_len(int *len); */ esp_err_t esp_mesh_scan_get_ap_record(wifi_ap_record_t *ap_record, void *buffer); +/** + * @brief flush upstream packets pending in to_parent queue and to_parent_p2p queue + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_flush_upstream_packets(void); + +/** + * @brief get the number of nodes in the subnet of a specific child + * + * @param child_mac an associated child address of this device + * @param nodes_num pointer to the number of nodes in the subnet of a specific child + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_NOT_START + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_subnet_nodes_num(const mesh_addr_t *child_mac, int *nodes_num); + +/** + * @brief get nodes in the subnet of a specific child + * + * @param child_mac an associated child address of this device + * @param nodes pointer to nodes in the subnet of a specific child + * @param nodes_num the number of nodes in the subnet of a specific child + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_NOT_START + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_subnet_nodes_list(const mesh_addr_t *child_mac, mesh_addr_t *nodes, int nodes_num); + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/esp32/esp_mesh_internal.h b/tools/sdk/include/esp32/esp_mesh_internal.h index da349297..e1dbf7f7 100644 --- a/tools/sdk/include/esp32/esp_mesh_internal.h +++ b/tools/sdk/include/esp32/esp_mesh_internal.h @@ -34,23 +34,30 @@ extern "C" { *******************************************************/ typedef struct { int scan; /**< minimum scan times before being a root, default:10 */ - int vote; /**< max vote times in self-healing, default:10000 */ + int vote; /**< max vote times in self-healing, default:1000 */ int fail; /**< parent selection fail times, if the scan times reach this value, - will disconnect with associated children and join self-healing. default:60 */ - int monitor_ie; /**< acceptable times of parent ie change before update self ie, default:3 */ + device will disconnect with associated children and join self-healing. default:60 */ + int monitor_ie; /**< acceptable times of parent networking IE change before update its own networking IE. default:3 */ } mesh_attempts_t; typedef struct { int duration_ms; /* parent weak RSSI monitor duration, if the RSSI continues to be weak during this duration_ms, - will switch to a better parent */ - int cnx_rssi; /* RSSI threshold for keeping a good connection with parent */ - int select_rssi; /* RSSI threshold for parent selection, should be a value greater than switch_rssi */ - int switch_rssi; /* RSSI threshold for action to reselect a better parent */ + device will search for a new parent. */ + int cnx_rssi; /* RSSI threshold for keeping a good connection with parent. + If set a value greater than -120 dBm, a timer will be armed to monitor parent RSSI at a period time of duration_ms. */ + int select_rssi; /* RSSI threshold for parent selection. It should be a value greater than switch_rssi. */ + int switch_rssi; /* Disassociate with current parent and switch to a new parent when the RSSI is greater than this set threshold. */ int backoff_rssi; /* RSSI threshold for connecting to the root */ } mesh_switch_parent_t; +typedef struct { + int high; + int medium; + int low; +} mesh_rssi_threshold_t; + /** - * @brief mesh networking IE + * @brief Mesh networking IE */ typedef struct { /**< mesh networking IE head */ @@ -58,8 +65,8 @@ typedef struct { uint8_t len; /**< element length */ uint8_t oui[3]; /**< organization identifier */ /**< mesh networking IE content */ - uint8_t type; /** mesh networking IE type */ - uint8_t encryped : 1; /**< if mesh networking IE is encrypted */ + uint8_t type; /** ESP defined IE type */ + uint8_t encryped : 1; /**< whether mesh networking IE is encrypted */ uint8_t version : 7; /**< mesh networking IE version */ /**< content */ uint8_t mesh_type; /**< mesh device type */ @@ -73,14 +80,14 @@ typedef struct { uint16_t root_cap; /**< root capacity */ uint16_t self_cap; /**< self capacity */ uint16_t layer2_cap; /**< layer2 capacity */ - uint16_t scan_ap_num; /**< the number of scanned APs */ - int8_t rssi; /**< rssi of the parent */ - int8_t router_rssi; /**< rssi of the router */ + uint16_t scan_ap_num; /**< the number of scanning APs */ + int8_t rssi; /**< RSSI of the parent */ + int8_t router_rssi; /**< RSSI of the router */ uint8_t flag; /**< flag of networking */ uint8_t rc_addr[6]; /**< root address */ - int8_t rc_rssi; /**< root rssi */ + int8_t rc_rssi; /**< root RSSI */ uint8_t vote_addr[6]; /**< voter address */ - int8_t vote_rssi; /**< vote rssi of the router */ + int8_t vote_rssi; /**< vote RSSI of the router */ uint8_t vote_ttl; /**< vote ttl */ uint16_t votes; /**< votes */ uint16_t my_votes; /**< my votes */ @@ -93,9 +100,9 @@ typedef struct { * Function Definitions *******************************************************/ /** - * @brief set mesh softAP beacon interval + * @brief Set mesh softAP beacon interval * - * @param interval beacon interval(ms) (100ms ~ 60000ms) + * @param[in] interval beacon interval (msecs) (100 msecs ~ 60000 msecs) * * @return * - ESP_OK @@ -105,9 +112,9 @@ typedef struct { esp_err_t esp_mesh_set_beacon_interval(int interval_ms); /** - * @brief get mesh softAP beacon interval + * @brief Get mesh softAP beacon interval * - * @param interval beacon interval(ms) + * @param[out] interval beacon interval (msecs) * * @return * - ESP_OK @@ -115,9 +122,9 @@ esp_err_t esp_mesh_set_beacon_interval(int interval_ms); esp_err_t esp_mesh_get_beacon_interval(int *interval_ms); /** - * @brief set attempts for mesh self-organized networking + * @brief Set attempts for mesh self-organized networking * - * @param attempts + * @param[in] attempts * * @return * - ESP_OK @@ -126,40 +133,77 @@ esp_err_t esp_mesh_get_beacon_interval(int *interval_ms); esp_err_t esp_mesh_set_attempts(mesh_attempts_t *attempts); /** - * @brief get attempts for mesh self-organized networking + * @brief Get attempts for mesh self-organized networking * - * @param attempts + * @param[out] attempts * * @return * - ESP_OK - * - ESP_FAIL + * - ESP_ERR_MESH_ARGUMENT */ esp_err_t esp_mesh_get_attempts(mesh_attempts_t *attempts); /** - * @brief set parameters for parent switch + * @brief Set parameters for parent switch * - * @param paras parameters for parent switch + * @param[in] paras parameters for parent switch * * @return * - ESP_OK - * - ESP_FAIL + * - ESP_ERR_MESH_ARGUMENT */ esp_err_t esp_mesh_set_switch_parent_paras(mesh_switch_parent_t *paras); /** - * @brief get parameters for parent switch + * @brief Get parameters for parent switch * - * @param paras parameters for parent switch + * @param[out] paras parameters for parent switch * * @return * - ESP_OK - * - ESP_FAIL + * - ESP_ERR_MESH_ARGUMENT */ esp_err_t esp_mesh_get_switch_parent_paras(mesh_switch_parent_t *paras); /** - * @brief print the number of txQ waiting + * @brief Set RSSI threshold + * - The default high RSSI threshold value is -78 dBm. + * - The default medium RSSI threshold value is -82 dBm. + * - The default low RSSI threshold value is -85 dBm. + * + * @param[in] threshold RSSI threshold + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_set_rssi_threshold(const mesh_rssi_threshold_t *threshold); + +/** + * @brief Get RSSI threshold + * + * @param[out] threshold RSSI threshold + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_rssi_threshold(mesh_rssi_threshold_t *threshold); + +/** + * @brief Enable the minimum rate to 6 Mbps + * + * @attention This API shall be called before Wi-Fi is started. + * + * @param[in] is_6m enable or not + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_set_6m_rate(bool is_6m); + +/** + * @brief Print the number of txQ waiting * * @return * - ESP_OK @@ -168,7 +212,7 @@ esp_err_t esp_mesh_get_switch_parent_paras(mesh_switch_parent_t *paras); esp_err_t esp_mesh_print_txQ_waiting(void); /** - * @brief print the number of rxQ waiting + * @brief Print the number of rxQ waiting * * @return * - ESP_OK @@ -177,9 +221,9 @@ esp_err_t esp_mesh_print_txQ_waiting(void); esp_err_t esp_mesh_print_rxQ_waiting(void); /** - * @brief set passive scan time + * @brief Set passive scan time * - * @param interval_ms passive scan time(ms) + * @param[in] interval_ms passive scan time (msecs) * * @return * - ESP_OK @@ -189,12 +233,35 @@ esp_err_t esp_mesh_print_rxQ_waiting(void); esp_err_t esp_mesh_set_passive_scan_time(int time_ms); /** - * @brief get passive scan time + * @brief Get passive scan time * - * @return interval_ms passive scan time(ms) + * @return interval_ms passive scan time (msecs) */ int esp_mesh_get_passive_scan_time(void); +/** + * @brief Set announce interval + * - The default short interval is 500 milliseconds. + * - The default long interval is 3000 milliseconds. + * + * @param[in] short_ms shall be greater than the default value + * @param[in] long_ms shall be greater than the default value + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_set_announce_interval(int short_ms, int long_ms); + +/** + * @brief Get announce interval + * + * @param[out] short_ms short interval + * @param[out] long_ms long interval + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_get_announce_interval(int *short_ms, int *long_ms); #ifdef __cplusplus } diff --git a/tools/sdk/include/esp32/esp_panic.h b/tools/sdk/include/esp32/esp_panic.h index 4e0630a2..b9e192f0 100644 --- a/tools/sdk/include/esp32/esp_panic.h +++ b/tools/sdk/include/esp32/esp_panic.h @@ -61,12 +61,6 @@ esp_err_t esp_set_watchpoint(int no, void *adr, int size, int flags); */ void esp_clear_watchpoint(int no); - -/** - * @brief Stops panic WDT - */ -void esp_panic_wdt_stop(void); - /** * @brief Checks stack pointer */ diff --git a/tools/sdk/include/esp32/esp_phy_init.h b/tools/sdk/include/esp32/esp_phy_init.h index 7a453bfc..f06375d1 100644 --- a/tools/sdk/include/esp32/esp_phy_init.h +++ b/tools/sdk/include/esp32/esp_phy_init.h @@ -202,6 +202,10 @@ esp_err_t esp_modem_sleep_exit(modem_sleep_module_t module); /** * @brief Register module to make it be able to require to enter/exit modem sleep + * Although the module has no sleep function, as long as the module use RF, + * it must call esp_modem_sleep_regsiter. Otherwise, other modules with sleep + * function will disable RF without checking the module which doesn't call + * esp_modem_sleep_regsiter. */ esp_err_t esp_modem_sleep_register(modem_sleep_module_t module); diff --git a/tools/sdk/include/esp32/esp_sleep.h b/tools/sdk/include/esp32/esp_sleep.h index 8e50c7e2..6ebe79ce 100644 --- a/tools/sdk/include/esp32/esp_sleep.h +++ b/tools/sdk/include/esp32/esp_sleep.h @@ -56,11 +56,14 @@ typedef enum { */ typedef enum { ESP_SLEEP_WAKEUP_UNDEFINED, //!< In case of deep sleep, reset was not caused by exit from deep sleep + ESP_SLEEP_WAKEUP_ALL, //!< Not a wakeup cause, used to disable all wakeup sources with esp_sleep_disable_wakeup_source ESP_SLEEP_WAKEUP_EXT0, //!< Wakeup caused by external signal using RTC_IO ESP_SLEEP_WAKEUP_EXT1, //!< Wakeup caused by external signal using RTC_CNTL ESP_SLEEP_WAKEUP_TIMER, //!< Wakeup caused by timer ESP_SLEEP_WAKEUP_TOUCHPAD, //!< Wakeup caused by touchpad ESP_SLEEP_WAKEUP_ULP, //!< Wakeup caused by ULP program + ESP_SLEEP_WAKEUP_GPIO, //!< Wakeup caused by GPIO (light sleep only) + ESP_SLEEP_WAKEUP_UART, //!< Wakeup caused by UART (light sleep only) } esp_sleep_source_t; /* Leave this type define for compatibility */ @@ -189,6 +192,43 @@ esp_err_t esp_sleep_enable_ext0_wakeup(gpio_num_t gpio_num, int level); */ esp_err_t esp_sleep_enable_ext1_wakeup(uint64_t mask, esp_sleep_ext1_wakeup_mode_t mode); +/** + * @brief Enable wakeup from light sleep using GPIOs + * + * Each GPIO supports wakeup function, which can be triggered on either low level + * or high level. Unlike EXT0 and EXT1 wakeup sources, this method can be used + * both for all IOs: RTC IOs and digital IOs. It can only be used to wakeup from + * light sleep though. + * + * To enable wakeup, first call gpio_wakeup_enable, specifying gpio number and + * wakeup level, for each GPIO which is used for wakeup. + * Then call this function to enable wakeup feature. + * + * @note In revisions 0 and 1 of the ESP32, GPIO wakeup source + * can not be used together with touch or ULP wakeup sources. + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if wakeup triggers conflict + */ +esp_err_t esp_sleep_enable_gpio_wakeup(); + +/** + * @brief Enable wakeup from light sleep using UART + * + * Use uart_set_wakeup_threshold function to configure UART wakeup threshold. + * + * Wakeup from light sleep takes some time, so not every character sent + * to the UART can be received by the application. + * + * @note ESP32 does not support wakeup from UART2. + * + * @param uart_num UART port to wake up from + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if wakeup from given UART is not supported + */ +esp_err_t esp_sleep_enable_uart_wakeup(int uart_num); /** * @brief Get the bit mask of GPIOs which caused wakeup (ext1) @@ -265,9 +305,9 @@ void system_deep_sleep(uint64_t time_in_us) __attribute__((noreturn, deprecated) /** - * @brief Get the source which caused wakeup from sleep + * @brief Get the wakeup source which caused wakeup from sleep * - * @return wakeup cause, or ESP_DEEP_SLEEP_WAKEUP_UNDEFINED if reset happened for reason other than deep sleep wakeup + * @return cause of wake up from last sleep (deep sleep or light sleep) */ esp_sleep_wakeup_cause_t esp_sleep_get_wakeup_cause(); @@ -319,6 +359,12 @@ esp_deep_sleep_wake_stub_fn_t esp_get_deep_sleep_wake_stub(void); */ void esp_default_wake_deep_sleep(void); +/** + * @brief Disable logging from the ROM code after deep sleep. + * + * Using LSB of RTC_STORE4. + */ +void esp_deep_sleep_disable_rom_logging(void); #ifdef __cplusplus } diff --git a/tools/sdk/include/esp32/esp_smartconfig.h b/tools/sdk/include/esp32/esp_smartconfig.h index 916c4c17..34cf8667 100644 --- a/tools/sdk/include/esp32/esp_smartconfig.h +++ b/tools/sdk/include/esp32/esp_smartconfig.h @@ -42,7 +42,7 @@ typedef enum { * * @param status Status of SmartConfig: * - SC_STATUS_GETTING_SSID_PSWD : pdata is a pointer of smartconfig_type_t, means config type. - * - SC_STATUS_LINK : pdata is a pointer of struct station_config. + * - SC_STATUS_LINK : pdata is a pointer to wifi_config_t. * - SC_STATUS_LINK_OVER : pdata is a pointer of phone's IP address(4 bytes) if pdata unequal NULL. * - otherwise : parameter void *pdata is NULL. * @param pdata According to the different status have different values. diff --git a/tools/sdk/include/esp32/esp_spiram.h b/tools/sdk/include/esp32/esp_spiram.h index 9663dcdd..aafd85ce 100644 --- a/tools/sdk/include/esp32/esp_spiram.h +++ b/tools/sdk/include/esp32/esp_spiram.h @@ -18,8 +18,37 @@ #include #include +#include #include "esp_err.h" +typedef enum { + ESP_SPIRAM_VOLT_3V3 = 0, /*!< SPI RAM voltage is 3.3v */ + ESP_SPIRAM_VOLT_1V8 = 1, /*!< SPI RAM voltage is 1.8v */ + ESP_SPIRAM_VOLT_INVALID, /*!< SPI RAM voltage is invalid*/ +} esp_spiram_volt_t; + +typedef enum { + ESP_SPIRAM_SIZE_32MBITS = 0, /*!< SPI RAM size is 32 MBits */ + ESP_SPIRAM_SIZE_64MBITS = 1, /*!< SPI RAM size is 64 MBits */ + ESP_SPIRAM_SIZE_INVALID, /*!< SPI RAM size is invalid */ +} esp_spiram_size_t; + +/** + * @brief get SPI RAM voltage + * @return + * - ESP_SPIRAM_VOLT_INVALID if SPI RAM not enabled or not valid. + * - SPI RAM voltage + */ +esp_spiram_volt_t esp_spiram_get_chip_volt(); + +/** + * @brief get SPI RAM size + * @return + * - ESP_SPIRAM_SIZE_INVALID if SPI RAM not enabled or not valid + * - SPI RAM size + */ +esp_spiram_size_t esp_spiram_get_chip_size(); + /** * @brief Initialize spiram interface/hardware. Normally called from cpu_start.c. * diff --git a/tools/sdk/include/esp32/esp_system.h b/tools/sdk/include/esp32/esp_system.h index 0d57d84d..05214c8f 100644 --- a/tools/sdk/include/esp32/esp_system.h +++ b/tools/sdk/include/esp32/esp_system.h @@ -31,12 +31,32 @@ typedef enum { ESP_MAC_ETH, } esp_mac_type_t; +/** @cond */ #define TWO_UNIVERSAL_MAC_ADDR 2 #define FOUR_UNIVERSAL_MAC_ADDR 4 #define UNIVERSAL_MAC_ADDR_NUM CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS +/** @endcond */ /** - * @attention application don't need to call this function anymore. It do nothing and will + * @brief Reset reasons + */ +typedef enum { + ESP_RST_UNKNOWN, //!< Reset reason can not be determined + ESP_RST_POWERON, //!< Reset due to power-on event + ESP_RST_EXT, //!< Reset by external pin (not applicable for ESP32) + ESP_RST_SW, //!< Software reset via esp_restart + ESP_RST_PANIC, //!< Software reset due to exception/panic + ESP_RST_INT_WDT, //!< Reset (software or hardware) due to interrupt watchdog + ESP_RST_TASK_WDT, //!< Reset due to task watchdog + ESP_RST_WDT, //!< Reset due to other watchdogs + ESP_RST_DEEPSLEEP, //!< Reset after exiting deep sleep mode + ESP_RST_BROWNOUT, //!< Brownout reset (software or hardware) + ESP_RST_SDIO, //!< Reset over SDIO +} esp_reset_reason_t; + +/** @cond */ +/** + * @attention Applications don't need to call this function anymore. It does nothing and will * be removed in future version. */ void system_init(void) __attribute__ ((deprecated)); @@ -48,13 +68,18 @@ void system_init(void) __attribute__ ((deprecated)); * This name will be removed in a future release. */ void system_restore(void) __attribute__ ((deprecated)); +/** @endcond */ +/** + * Shutdown handler type + */ typedef void (*shutdown_handler_t)(void); + /** * @brief Register shutdown handler * - * This function allows you to register a handler that gets invoked before a - * systematic shutdown of the chip. + * This function allows you to register a handler that gets invoked before + * the application is restarted using esp_restart function. */ esp_err_t esp_register_shutdown_handler(shutdown_handler_t handle); @@ -68,17 +93,7 @@ esp_err_t esp_register_shutdown_handler(shutdown_handler_t handle); */ void esp_restart(void) __attribute__ ((noreturn)); -/** - * @brief Internal function to restart PRO and APP CPUs. - * - * @note This function should not be called from FreeRTOS applications. - * Use esp_restart instead. - * - * This is an internal function called by esp_restart. It is called directly - * by the panic handler and brownout detector interrupt. - */ -void esp_restart_noos() __attribute__ ((noreturn)); - +/** @cond */ /** * @brief Restart system. * @@ -86,7 +101,15 @@ void esp_restart_noos() __attribute__ ((noreturn)); * This name will be removed in a future release. */ void system_restart(void) __attribute__ ((deprecated, noreturn)); +/** @endcond */ +/** + * @brief Get reason of last reset + * @return See description of esp_reset_reason_t for explanation of each value. + */ +esp_reset_reason_t esp_reset_reason(void); + +/** @cond */ /** * @brief Get system time, unit: microsecond. * @@ -94,6 +117,7 @@ void system_restart(void) __attribute__ ((deprecated, noreturn)); * This definition will be removed in a future release. */ uint32_t system_get_time(void) __attribute__ ((deprecated)); +/** @endcond */ /** * @brief Get the size of available heap. @@ -105,6 +129,7 @@ uint32_t system_get_time(void) __attribute__ ((deprecated)); */ uint32_t esp_get_free_heap_size(void); +/** @cond */ /** * @brief Get the size of available heap. * @@ -114,6 +139,7 @@ uint32_t esp_get_free_heap_size(void); * @return Available heap size, in bytes. */ uint32_t system_get_free_heap_size(void) __attribute__ ((deprecated)); +/** @endcond */ /** * @brief Get the minimum heap that has ever been available @@ -125,18 +151,31 @@ uint32_t esp_get_minimum_free_heap_size( void ); /** * @brief Get one random 32-bit word from hardware RNG * - * The hardware RNG is fully functional whenever an RF subsystem is running (ie Bluetooth or WiFi is enabled). For secure + * The hardware RNG is fully functional whenever an RF subsystem is running (ie Bluetooth or WiFi is enabled). For * random values, call this function after WiFi or Bluetooth are started. * - * When the app is running without an RF subsystem enabled, it should be considered a PRNG. To help improve this - * situation, the RNG is pre-seeded with entropy while the IDF bootloader is running. However no new entropy is - * available during the window of time between when the bootloader exits and an RF subsystem starts. It may be possible - * to discern a non-random pattern in a very large amount of output captured during this window of time. + * If the RF subsystem is not used by the program, the function bootloader_random_enable() can be called to enable an + * entropy source. bootloader_random_disable() must be called before RF subsystem or I2S peripheral are used. See these functions' + * documentation for more details. + * + * Any time the app is running without an RF subsystem (or bootloader_random) enabled, RNG hardware should be + * considered a PRNG. A very small amount of entropy is available due to pre-seeding while the IDF + * bootloader is running, but this should not be relied upon for any use. * * @return Random value between 0 and UINT32_MAX */ uint32_t esp_random(void); +/** + * @brief Fill a buffer with random bytes from hardware RNG + * + * @note This function has the same restrictions regarding available entropy as esp_random() + * + * @param buf Pointer to buffer to fill with random numbers. + * @param len Length of buffer in bytes + */ +void esp_fill_random(void *buf, size_t len); + /** * @brief Set base MAC address with the MAC address which is stored in BLK3 of EFUSE or * external storage e.g. flash and EEPROM. @@ -187,6 +226,7 @@ esp_err_t esp_efuse_mac_get_custom(uint8_t *mac); */ esp_err_t esp_efuse_mac_get_default(uint8_t *mac); +/** @cond */ /** * @brief Read hardware MAC address from efuse. * @@ -209,6 +249,7 @@ esp_err_t esp_efuse_read_mac(uint8_t *mac) __attribute__ ((deprecated)); * @return ESP_OK on success */ esp_err_t system_efuse_read_mac(uint8_t *mac) __attribute__ ((deprecated)); +/** @endcond */ /** * @brief Read base MAC address and set MAC address of the interface. @@ -240,6 +281,7 @@ esp_err_t esp_read_mac(uint8_t* mac, esp_mac_type_t type); */ esp_err_t esp_derive_local_mac(uint8_t* local_mac, const uint8_t* universal_mac); +/** @cond */ /** * Get SDK version * @@ -248,6 +290,7 @@ esp_err_t esp_derive_local_mac(uint8_t* local_mac, const uint8_t* universal_mac) * @return constant string "master" */ const char* system_get_sdk_version(void) __attribute__ ((deprecated)); +/** @endcond */ /** * Get IDF version @@ -264,13 +307,11 @@ typedef enum { CHIP_ESP32 = 1, //!< ESP32 } esp_chip_model_t; -/** - * Chip feature flags, used in esp_chip_info_t - */ -#define CHIP_FEATURE_EMB_FLASH BIT(0) -#define CHIP_FEATURE_WIFI_BGN BIT(1) -#define CHIP_FEATURE_BLE BIT(4) -#define CHIP_FEATURE_BT BIT(5) +/* Chip feature flags, used in esp_chip_info_t */ +#define CHIP_FEATURE_EMB_FLASH BIT(0) //!< Chip has embedded flash memory +#define CHIP_FEATURE_WIFI_BGN BIT(1) //!< Chip has 2.4GHz WiFi +#define CHIP_FEATURE_BLE BIT(4) //!< Chip has Bluetooth LE +#define CHIP_FEATURE_BT BIT(5) //!< Chip has Bluetooth Classic /** * @brief The structure represents information about the chip diff --git a/tools/sdk/include/esp32/esp_wifi.h b/tools/sdk/include/esp32/esp_wifi.h index d4c11c38..66ccdcdd 100644 --- a/tools/sdk/include/esp32/esp_wifi.h +++ b/tools/sdk/include/esp32/esp_wifi.h @@ -223,7 +223,9 @@ esp_err_t esp_wifi_init(const wifi_init_config_t *config); * * @attention 1. This API should be called if you want to remove WiFi driver from the system * - * @return ESP_OK: succeed + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init */ esp_err_t esp_wifi_deinit(void); @@ -303,7 +305,13 @@ esp_err_t esp_wifi_restore(void); * * @attention 1. This API only impact WIFI_MODE_STA or WIFI_MODE_APSTA mode * @attention 2. If the ESP32 is connected to an AP, call esp_wifi_disconnect to disconnect. - * + * @attention 3. The scanning triggered by esp_wifi_start_scan() will not be effective until connection between ESP32 and the AP is established. + * If ESP32 is scanning and connecting at the same time, ESP32 will abort scanning and return a warning message and error + * number ESP_ERR_WIFI_STATE. + * If you want to do reconnection after ESP32 received disconnect event, remember to add the maximum retry time, otherwise the called + * scan will not work. This is especially true when the AP doesn't exist, and you still try reconnection after ESP32 received disconnect + * event with the reason code WIFI_REASON_NO_AP_FOUND. + * * @return * - ESP_OK: succeed * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init @@ -366,6 +374,7 @@ esp_err_t esp_wifi_deauth_sta(uint16_t aid); * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start * - ESP_ERR_WIFI_TIMEOUT: blocking scan is timeout + * - ESP_ERR_WIFI_STATE: wifi still connecting when invoke esp_wifi_scan_start * - others: refer to error code in esp_err.h */ esp_err_t esp_wifi_scan_start(const wifi_scan_config_t *config, bool block); diff --git a/tools/sdk/include/esp32/esp_wifi_crypto_types.h b/tools/sdk/include/esp32/esp_wifi_crypto_types.h index 0848f06a..e1e2a51a 100644 --- a/tools/sdk/include/esp32/esp_wifi_crypto_types.h +++ b/tools/sdk/include/esp32/esp_wifi_crypto_types.h @@ -607,7 +607,7 @@ typedef void (*esp_uuid_gen_mac_addr_t)(const unsigned char *mac_addr, unsigned * @brief free the message after finish DH * */ -typedef void * (*esp_dh5_free_t)(void *ctx); +typedef void (*esp_dh5_free_t)(void *ctx); /** * @brief Build WPS IE for (Re)Association Request diff --git a/tools/sdk/include/esp32/esp_wifi_internal.h b/tools/sdk/include/esp32/esp_wifi_internal.h index 7ddfd694..f486b7aa 100644 --- a/tools/sdk/include/esp32/esp_wifi_internal.h +++ b/tools/sdk/include/esp32/esp_wifi_internal.h @@ -127,6 +127,26 @@ esp_err_t esp_wifi_internal_reg_rxcb(wifi_interface_t ifx, wifi_rxcb_t fn); */ esp_err_t esp_wifi_internal_set_sta_ip(void); +/** + * @brief enable or disable transmitting WiFi MAC frame with fixed rate + * + * @attention 1. If fixed rate is enabled, both management and data frame are transmitted with fixed rate + * @attention 2. Make sure that the receiver is able to receive the frame with the fixed rate if you want the frame to be received + * + * @param ifx : wifi interface + * @param en : false - disable, true - enable + * @param rate : PHY rate + * + * @return + * - ERR_OK : succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start + * - ESP_ERR_WIFI_IF : invalid WiFi interface + * - ESP_ERR_INVALID_ARG : invalid rate + * - ESP_ERR_NOT_SUPPORTED : do not support to set fixed rate if TX AMPDU is enabled + */ +esp_err_t esp_wifi_internal_set_fix_rate(wifi_interface_t ifx, bool en, wifi_phy_rate_t rate); + /** * @brief Check the MD5 values of the OS adapter header files in IDF and WiFi library * @@ -149,6 +169,17 @@ esp_err_t esp_wifi_internal_osi_funcs_md5_check(const char *md5); */ esp_err_t esp_wifi_internal_crypto_funcs_md5_check(const char *md5); +/** + * @brief Check the git commit id of WiFi library + * + * @attention 1. It is used for internal CI WiFi library check + * + * @return + * - ESP_OK : succeed + * - ESP_FAIL : fail + */ +esp_err_t esp_wifi_internal_git_commit_id_check(void); + /** * @brief Allocate a chunk of memory for WiFi driver * diff --git a/tools/sdk/include/esp32/esp_wifi_types.h b/tools/sdk/include/esp32/esp_wifi_types.h index a453c427..2a4d2beb 100644 --- a/tools/sdk/include/esp32/esp_wifi_types.h +++ b/tools/sdk/include/esp32/esp_wifi_types.h @@ -186,6 +186,8 @@ typedef struct { wifi_auth_mode_t authmode; /**< The weakest authmode to accept in the fast scan mode */ }wifi_fast_scan_threshold_t; +typedef wifi_fast_scan_threshold_t wifi_scan_threshold_t; /**< wifi_fast_scan_threshold_t only used in fast scan mode once, now it enabled in all channel scan, the wifi_fast_scan_threshold_t will be remove in version 4.0 */ + typedef enum { WIFI_PS_NONE, /**< No power save */ WIFI_PS_MIN_MODEM, /**< Minimum modem power saving. In this mode, station wakes up to receive beacon every DTIM period */ @@ -226,7 +228,7 @@ typedef struct { uint8_t channel; /**< channel of target AP. Set to 1~13 to scan starting from the specified channel before connecting to AP. If the channel of AP is unknown, set it to 0.*/ uint16_t listen_interval; /**< Listen interval for ESP32 station to receive beacon when WIFI_PS_MAX_MODEM is set. Units: AP beacon intervals. Defaults to 3 if set to 0. */ wifi_sort_method_t sort_method; /**< sort the connect AP in the list by rssi or security mode */ - wifi_fast_scan_threshold_t threshold; /**< When scan_method is set to WIFI_FAST_SCAN, only APs which have an auth mode that is more secure than the selected auth mode and a signal stronger than the minimum RSSI will be used. */ + wifi_scan_threshold_t threshold; /**< When scan_method is set, only APs which have an auth mode that is more secure than the selected auth mode and a signal stronger than the minimum RSSI will be used. */ } wifi_sta_config_t; /** @brief Configuration data for ESP32 AP or STA. @@ -310,7 +312,7 @@ typedef struct { unsigned sig_mode:2; /**< 0: non HT(11bg) packet; 1: HT(11n) packet; 3: VHT(11ac) packet */ unsigned :16; /**< reserve */ unsigned mcs:7; /**< Modulation Coding Scheme. If is HT(11n) packet, shows the modulation, range from 0 to 76(MSC0 ~ MCS76) */ - unsigned cwb:1; /**< if is HT(11n) packet, shows if is HT40 packet or HT20 packet. 1: HT40 packet; 0: HT20 packet */ + unsigned cwb:1; /**< Channel Bandwidth of the packet. 0: 20MHz; 1: 40MHz */ unsigned :16; /**< reserve */ unsigned smoothing:1; /**< reserve */ unsigned not_sounding:1; /**< reserve */ @@ -390,6 +392,8 @@ typedef struct { bool lltf_en; /**< enable to receive legacy long training field(lltf) data. Default enabled */ bool htltf_en; /**< enable to receive HT long training field(htltf) data. Default enabled */ bool stbc_htltf2_en; /**< enable to receive space time block code HT long training field(stbc-htltf2) data. Default enabled */ + bool ltf_merge_en; /**< enable to generate htlft data by averaging lltf and ht_ltf data when receiving HT packet. Otherwise, use ht_ltf data directly. Default enabled */ + bool channel_filter_en; /**< enable to turn on channel filter to smooth adjacent sub-carrier. Disable it to keep independence of adjacent sub-carrier. Default enabled */ bool manu_scale; /**< manually scale the CSI data by left shifting or automatically scale the CSI data. If set true, please set the shift bits. false: automatically. true: manually. Default false */ uint8_t shift; /**< manually left shift bits of the scale of the CSI data. The range of the left shift bits is 0~15 */ } wifi_csi_config_t; @@ -402,7 +406,7 @@ typedef struct { wifi_pkt_rx_ctrl_t rx_ctrl;/**< received packet radio metadata header of the CSI data */ uint8_t mac[6]; /**< source MAC address of the CSI data */ bool last_word_invalid; /**< last four bytes of the CSI data is invalid or not */ - uint8_t *buf; /**< buffer of CSI data */ + int8_t *buf; /**< buffer of CSI data */ uint16_t len; /**< length of CSI data */ } wifi_csi_info_t; @@ -446,6 +450,47 @@ typedef struct { enabled_ant1: 4; /**< Index (in antenna GPIO configuration) of enabled WIFI_ANT_MODE_ANT1 */ } wifi_ant_config_t; +/** + * @brief WiFi PHY rate encodings + * + */ +typedef enum { + WIFI_PHY_RATE_1M_L = 0x00, /**< 1 Mbps with long preamble */ + WIFI_PHY_RATE_2M_L = 0x01, /**< 2 Mbps with long preamble */ + WIFI_PHY_RATE_5M_L = 0x02, /**< 5.5 Mbps with long preamble */ + WIFI_PHY_RATE_11M_L = 0x03, /**< 11 Mbps with long preamble */ + WIFI_PHY_RATE_2M_S = 0x05, /**< 2 Mbps with short preamble */ + WIFI_PHY_RATE_5M_S = 0x06, /**< 5.5 Mbps with short preamble */ + WIFI_PHY_RATE_11M_S = 0x07, /**< 11 Mbps with short preamble */ + WIFI_PHY_RATE_48M = 0x08, /**< 48 Mbps */ + WIFI_PHY_RATE_24M = 0x09, /**< 24 Mbps */ + WIFI_PHY_RATE_12M = 0x0A, /**< 12 Mbps */ + WIFI_PHY_RATE_6M = 0x0B, /**< 6 Mbps */ + WIFI_PHY_RATE_54M = 0x0C, /**< 54 Mbps */ + WIFI_PHY_RATE_36M = 0x0D, /**< 36 Mbps */ + WIFI_PHY_RATE_18M = 0x0E, /**< 18 Mbps */ + WIFI_PHY_RATE_9M = 0x0F, /**< 9 Mbps */ + WIFI_PHY_RATE_MCS0_LGI = 0x10, /**< MCS0 with long GI, 6.5 Mbps for 20MHz, 13.5 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS1_LGI = 0x11, /**< MCS1 with long GI, 13 Mbps for 20MHz, 27 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS2_LGI = 0x12, /**< MCS2 with long GI, 19.5 Mbps for 20MHz, 40.5 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS3_LGI = 0x13, /**< MCS3 with long GI, 26 Mbps for 20MHz, 54 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS4_LGI = 0x14, /**< MCS4 with long GI, 39 Mbps for 20MHz, 81 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS5_LGI = 0x15, /**< MCS5 with long GI, 52 Mbps for 20MHz, 108 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS6_LGI = 0x16, /**< MCS6 with long GI, 58.5 Mbps for 20MHz, 121.5 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS7_LGI = 0x17, /**< MCS7 with long GI, 65 Mbps for 20MHz, 135 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS0_SGI = 0x18, /**< MCS0 with short GI, 7.2 Mbps for 20MHz, 15 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS1_SGI = 0x19, /**< MCS1 with short GI, 14.4 Mbps for 20MHz, 30 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS2_SGI = 0x1A, /**< MCS2 with short GI, 21.7 Mbps for 20MHz, 45 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS3_SGI = 0x1B, /**< MCS3 with short GI, 28.9 Mbps for 20MHz, 60 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS4_SGI = 0x1C, /**< MCS4 with short GI, 43.3 Mbps for 20MHz, 90 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS5_SGI = 0x1D, /**< MCS5 with short GI, 57.8 Mbps for 20MHz, 120 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS6_SGI = 0x1E, /**< MCS6 with short GI, 65 Mbps for 20MHz, 135 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS7_SGI = 0x1F, /**< MCS7 with short GI, 72.2 Mbps for 20MHz, 150 Mbps for 40MHz */ + WIFI_PHY_RATE_LORA_250K = 0x29, /**< 250 Kbps */ + WIFI_PHY_RATE_LORA_500K = 0x2A, /**< 500 Kbps */ + WIFI_PHY_RATE_MAX, +} wifi_phy_rate_t; + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/esp32/rom/libc_stubs.h b/tools/sdk/include/esp32/rom/libc_stubs.h index 0c1876e5..90c0b446 100644 --- a/tools/sdk/include/esp32/rom/libc_stubs.h +++ b/tools/sdk/include/esp32/rom/libc_stubs.h @@ -51,7 +51,7 @@ struct syscall_stub_table int (*_rename_r)(struct _reent *r, const char*, const char*); clock_t (*_times_r)(struct _reent *r, struct tms *); int (*_gettimeofday_r) (struct _reent *r, struct timeval *, void *); - void (*_raise_r)(struct _reent *r); + void (*_raise_r)(struct _reent *r); /* function signature is incorrect in ROM */ int (*_unlink_r)(struct _reent *r, const char*); int (*_link_r)(struct _reent *r, const char*, const char*); int (*_stat_r)(struct _reent *r, const char*, struct stat *); diff --git a/tools/sdk/include/esp32/rom/rtc.h b/tools/sdk/include/esp32/rom/rtc.h index 3161fb27..6d9d2977 100644 --- a/tools/sdk/include/esp32/rom/rtc.h +++ b/tools/sdk/include/esp32/rom/rtc.h @@ -55,7 +55,7 @@ extern "C" { * RTC_CNTL_STORE1_REG RTC_SLOW_CLK calibration value * RTC_CNTL_STORE2_REG Boot time, low word * RTC_CNTL_STORE3_REG Boot time, high word - * RTC_CNTL_STORE4_REG External XTAL frequency + * RTC_CNTL_STORE4_REG External XTAL frequency. The frequency must necessarily be even, otherwise there will be a conflict with the low bit, which is used to disable logs in the ROM code. * RTC_CNTL_STORE5_REG APB bus frequency * RTC_CNTL_STORE6_REG FAST_RTC_MEMORY_ENTRY * RTC_CNTL_STORE7_REG FAST_RTC_MEMORY_CRC @@ -68,8 +68,10 @@ extern "C" { #define RTC_XTAL_FREQ_REG RTC_CNTL_STORE4_REG #define RTC_APB_FREQ_REG RTC_CNTL_STORE5_REG #define RTC_ENTRY_ADDR_REG RTC_CNTL_STORE6_REG +#define RTC_RESET_CAUSE_REG RTC_CNTL_STORE6_REG #define RTC_MEMORY_CRC_REG RTC_CNTL_STORE7_REG +#define RTC_DISABLE_ROM_LOG ((1 << 0) | (1 << 16)) //!< Disable logging from the ROM code. typedef enum { AWAKE = 0, // + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief HTTPS OTA Firmware upgrade. + * + * This function performs HTTPS OTA Firmware upgrade + * + * @param[in] config pointer to esp_http_client_config_t structure. + * + * @note For secure HTTPS updates, the `cert_pem` member of `config` + * structure must be set to the server certificate. + * + * @return + * - ESP_OK: OTA data updated, next reboot will use specified partition. + * - ESP_FAIL: For generic failure. + * - ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image + * - ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. + * - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. + * - For other return codes, refer OTA documentation in esp-idf's app_update component. + */ +esp_err_t esp_https_ota(const esp_http_client_config_t *config); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/ethernet/esp_eth.h b/tools/sdk/include/ethernet/esp_eth.h index f4622d0e..0d39b8ef 100644 --- a/tools/sdk/include/ethernet/esp_eth.h +++ b/tools/sdk/include/ethernet/esp_eth.h @@ -29,10 +29,9 @@ typedef enum { } eth_mode_t; typedef enum { - ETH_CLOCK_GPIO0_IN = 0, - ETH_CLOCK_GPIO0_OUT = 1, + ETH_CLOCK_GPIO0_IN = 0, ETH_CLOCK_GPIO16_OUT = 2, - ETH_CLOCK_GPIO17_OUT = 3 + ETH_CLOCK_GPIO17_OUT = 3, } eth_clock_mode_t; typedef enum { @@ -125,6 +124,16 @@ typedef struct { */ esp_err_t esp_eth_init(eth_config_t *config); +/** + * @brief Deinit ethernet mac + * + * @return + * - ESP_OK + * - ESP_FAIL + * - ESP_ERR_INVALID_STATE + */ +esp_err_t esp_eth_deinit(void); + /** * @brief Init Ethernet mac driver only * @@ -236,7 +245,8 @@ esp_err_t esp_eth_smi_wait_value(uint32_t reg_num, uint16_t value, uint16_t valu * * @return ESP_OK if desired value matches, ESP_ERR_TIMEOUT if timed out. */ -static inline esp_err_t esp_eth_smi_wait_set(uint32_t reg_num, uint16_t value_mask, int timeout_ms) { +static inline esp_err_t esp_eth_smi_wait_set(uint32_t reg_num, uint16_t value_mask, int timeout_ms) +{ return esp_eth_smi_wait_value(reg_num, value_mask, value_mask, timeout_ms); } @@ -250,14 +260,6 @@ static inline esp_err_t esp_eth_smi_wait_set(uint32_t reg_num, uint16_t value_ma */ void esp_eth_free_rx_buf(void *buf); -/** - * @brief Get mac of ethernet interface. - * - * @param[out] mac: store mac of the interface. - * - */ -void esp_eth_get_mac(uint8_t mac[6]); - /** * @brief Set mac of ethernet interface. * @@ -265,7 +267,7 @@ void esp_eth_get_mac(uint8_t mac[6]); * * @param[in] mac: the Mac address. * - * @return + * @return * - ESP_OK: succeed * - ESP_ERR_INVALID_MAC: invalid mac address */ diff --git a/tools/sdk/include/expat/.gitignore b/tools/sdk/include/expat/.gitignore new file mode 100644 index 00000000..9c9cf881 --- /dev/null +++ b/tools/sdk/include/expat/.gitignore @@ -0,0 +1,18 @@ +Makefile +.libs +*.lo +expat.h +Debug +Debug-w +Release +Release-w +expat.ncb +expat.opt +expat.plg +Debug_static +Debug-w_static +Release_static +Release-w_static +expat_static.plg +expatw.plg +expatw_static.plg diff --git a/tools/sdk/include/expat/Makefile.am b/tools/sdk/include/expat/Makefile.am new file mode 100644 index 00000000..d655a29f --- /dev/null +++ b/tools/sdk/include/expat/Makefile.am @@ -0,0 +1,77 @@ +# +# __ __ _ +# ___\ \/ /_ __ __ _| |_ +# / _ \\ /| '_ \ / _` | __| +# | __// \| |_) | (_| | |_ +# \___/_/\_\ .__/ \__,_|\__| +# |_| XML parser +# +# Copyright (c) 2017 Expat development team +# Licensed under the MIT license: +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to permit +# persons to whom the Software is furnished to do so, subject to the +# following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +# USE OR OTHER DEALINGS IN THE SOFTWARE. + +include_HEADERS = \ + ../expat_config.h \ + expat.h \ + expat_external.h + +lib_LTLIBRARIES = libexpat.la + +libexpat_la_LDFLAGS = \ + -no-undefined \ + -version-info @LIBCURRENT@:@LIBREVISION@:@LIBAGE@ \ + -rpath $(libdir) + +libexpat_la_SOURCES = \ + loadlibrary.c \ + xmlparse.c \ + xmltok.c \ + xmlrole.c + +doc_DATA = \ + ../AUTHORS \ + ../Changes + +install-data-hook: + cd "$(DESTDIR)$(docdir)" && $(am__mv) Changes changelog + +uninstall-local: + $(RM) "$(DESTDIR)$(docdir)/changelog" + +EXTRA_DIST = \ + ascii.h \ + asciitab.h \ + expat_external.h \ + expat.h \ + iasciitab.h \ + internal.h \ + latin1tab.h \ + libexpat.def \ + libexpatw.def \ + nametab.h \ + siphash.h \ + utf8tab.h \ + winconfig.h \ + xmlrole.h \ + xmltok.h \ + xmltok_impl.c \ + xmltok_impl.h \ + xmltok_ns.c diff --git a/tools/sdk/include/expat/ascii.h b/tools/sdk/include/expat/ascii.h index d10530b0..c3587e57 100644 --- a/tools/sdk/include/expat/ascii.h +++ b/tools/sdk/include/expat/ascii.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define ASCII_A 0x41 diff --git a/tools/sdk/include/expat/asciitab.h b/tools/sdk/include/expat/asciitab.h index 79a15c28..2f59fd92 100644 --- a/tools/sdk/include/expat/asciitab.h +++ b/tools/sdk/include/expat/asciitab.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, diff --git a/tools/sdk/include/expat/chardata.h b/tools/sdk/include/expat/chardata.h deleted file mode 100644 index e8dc4ce2..00000000 --- a/tools/sdk/include/expat/chardata.h +++ /dev/null @@ -1,40 +0,0 @@ -/* chardata.h - - Interface to some helper routines used to accumulate and check text - and attribute content. -*/ - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef XML_CHARDATA_H -#define XML_CHARDATA_H 1 - -#ifndef XML_VERSION -#include "expat.h" /* need XML_Char */ -#endif - - -typedef struct { - int count; /* # of chars, < 0 if not set */ - XML_Char data[1024]; -} CharData; - - -void CharData_Init(CharData *storage); - -void CharData_AppendString(CharData *storage, const char *s); - -void CharData_AppendXMLChars(CharData *storage, const XML_Char *s, int len); - -int CharData_CheckString(CharData *storage, const char *s); - -int CharData_CheckXMLChars(CharData *storage, const XML_Char *s); - - -#endif /* XML_CHARDATA_H */ - -#ifdef __cplusplus -} -#endif diff --git a/tools/sdk/include/expat/expat.h b/tools/sdk/include/expat/expat.h index 086e24b3..1f608c02 100644 --- a/tools/sdk/include/expat/expat.h +++ b/tools/sdk/include/expat/expat.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef Expat_INCLUDED @@ -24,7 +52,6 @@ extern "C" { struct XML_ParserStruct; typedef struct XML_ParserStruct *XML_Parser; -/* Should this be defined using stdbool.h when C99 is available? */ typedef unsigned char XML_Bool; #define XML_TRUE ((XML_Bool) 1) #define XML_FALSE ((XML_Bool) 0) @@ -95,7 +122,9 @@ enum XML_Error { /* Added in 2.0. */ XML_ERROR_RESERVED_PREFIX_XML, XML_ERROR_RESERVED_PREFIX_XMLNS, - XML_ERROR_RESERVED_NAMESPACE_URI + XML_ERROR_RESERVED_NAMESPACE_URI, + /* Added in 2.2.1. */ + XML_ERROR_INVALID_ARGUMENT }; enum XML_Content_Type { @@ -706,6 +735,7 @@ XML_UseParserAsHandlerArg(XML_Parser parser); be called, despite an external subset being parsed. Note: If XML_DTD is not defined when Expat is compiled, returns XML_ERROR_FEATURE_REQUIRES_XML_DTD. + Note: If parser == NULL, returns XML_ERROR_INVALID_ARGUMENT. */ XMLPARSEAPI(enum XML_Error) XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD); @@ -729,15 +759,16 @@ XML_GetBase(XML_Parser parser); to the XML_StartElementHandler that were specified in the start-tag rather than defaulted. Each attribute/value pair counts as 2; thus this correspondds to an index into the atts array passed to the - XML_StartElementHandler. + XML_StartElementHandler. Returns -1 if parser == NULL. */ XMLPARSEAPI(int) XML_GetSpecifiedAttributeCount(XML_Parser parser); /* Returns the index of the ID attribute passed in the last call to - XML_StartElementHandler, or -1 if there is no ID attribute. Each - attribute/value pair counts as 2; thus this correspondds to an - index into the atts array passed to the XML_StartElementHandler. + XML_StartElementHandler, or -1 if there is no ID attribute or + parser == NULL. Each attribute/value pair counts as 2; thus this + correspondds to an index into the atts array passed to the + XML_StartElementHandler. */ XMLPARSEAPI(int) XML_GetIdAttributeIndex(XML_Parser parser); @@ -901,6 +932,7 @@ enum XML_ParamEntityParsing { entities is requested; otherwise it will return non-zero. Note: If XML_SetParamEntityParsing is called after XML_Parse or XML_ParseBuffer, then it has no effect and will always return 0. + Note: If parser == NULL, the function will do nothing and return 0. */ XMLPARSEAPI(int) XML_SetParamEntityParsing(XML_Parser parser, @@ -910,6 +942,7 @@ XML_SetParamEntityParsing(XML_Parser parser, Helps in preventing DoS attacks based on predicting hash function behavior. This must be called before parsing is started. Returns 1 if successful, 0 when called after parsing has started. + Note: If parser == NULL, the function will do nothing and return 0. */ XMLPARSEAPI(int) XML_SetHashSalt(XML_Parser parser, @@ -936,6 +969,10 @@ XML_GetErrorCode(XML_Parser parser); the location is the location of the character at which the error was detected; otherwise the location is the location of the last parse event, as described above. + + Note: XML_GetCurrentLineNumber and XML_GetCurrentColumnNumber + return 0 to indicate an error. + Note: XML_GetCurrentByteIndex returns -1 to indicate an error. */ XMLPARSEAPI(XML_Size) XML_GetCurrentLineNumber(XML_Parser parser); XMLPARSEAPI(XML_Size) XML_GetCurrentColumnNumber(XML_Parser parser); @@ -1039,7 +1076,7 @@ XML_GetFeatureList(void); */ #define XML_MAJOR_VERSION 2 #define XML_MINOR_VERSION 2 -#define XML_MICRO_VERSION 0 +#define XML_MICRO_VERSION 5 #ifdef __cplusplus } diff --git a/tools/sdk/include/expat/expat.vcxproj b/tools/sdk/include/expat/expat.vcxproj new file mode 100644 index 00000000..66d646e7 --- /dev/null +++ b/tools/sdk/include/expat/expat.vcxproj @@ -0,0 +1,179 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Template + Win32 + + + + + + {45A5074D-66E8-44A4-A03F-018027B528D6} + 10.0.16299.0 + + + + Application + v141 + + + DynamicLibrary + v141 + false + MultiByte + + + DynamicLibrary + v141 + false + MultiByte + + + + + + + + + + + + + + + + + + .\..\win32\bin\Debug\ + .\..\win32\tmp\Debug\ + true + + + .\..\win32\bin\Release\ + .\..\win32\tmp\Release\ + false + + + + MultiThreadedDebug + Default + true + Disabled + true + Level3 + EditAndContinue + _DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + .\..\win32\tmp\Debug\ + true + .\..\win32\tmp\Debug\expat.pch + .\..\win32\tmp\Debug\ + .\..\win32\tmp\Debug\ + EnableFastChecks + + + true + _DEBUG;%(PreprocessorDefinitions) + .\..\win32\bin\Debug\expat.tlb + true + Win32 + + + 0x0409 + _DEBUG;%(PreprocessorDefinitions) + + + true + .\..\win32\bin\Debug\expat.bsc + + + true + true + true + Console + ..\win32\bin\Debug\libexpat.dll + .\..\win32\bin\Debug\libexpat.lib + .\libexpat.def + + + + + MultiThreaded + Default + true + true + MaxSpeed + true + Level3 + NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) + .\..\win32\tmp\Release\ + .\..\win32\tmp\Release\expat.pch + + .\..\win32\tmp\Release\ + .\..\win32\tmp\Release\ + + + true + NDEBUG;%(PreprocessorDefinitions) + .\..\win32\bin\Release\expat.tlb + true + Win32 + + + 0x0409 + NDEBUG;%(PreprocessorDefinitions) + + + true + .\..\win32\bin\Release\expat.bsc + + + true + true + Console + ..\win32\bin\Release\libexpat.dll + .\..\win32\bin\Release\libexpat.lib + .\libexpat.def + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tools/sdk/include/expat/expat.vcxproj.filters b/tools/sdk/include/expat/expat.vcxproj.filters new file mode 100644 index 00000000..61c52b58 --- /dev/null +++ b/tools/sdk/include/expat/expat.vcxproj.filters @@ -0,0 +1,83 @@ + + + + + {f01bb743-0ef8-4601-bc44-378fc0abe768} + cpp;c;cxx;rc;def;r;odl;idl;hpj;bat + + + {c22177dc-5748-4bb1-816e-df311093bf72} + h;hpp;hxx;hm;inl + + + {41146e15-3129-4e5e-bb0f-6b78bb4701b9} + ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + \ No newline at end of file diff --git a/tools/sdk/include/expat/expat_config.h b/tools/sdk/include/expat/expat_config.h index 207d1a77..b6b927a1 100644 --- a/tools/sdk/include/expat/expat_config.h +++ b/tools/sdk/include/expat/expat_config.h @@ -3,7 +3,6 @@ /* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */ #define BYTEORDER 1234 - /* Define to 1 if you have the `bcopy' function. */ #define HAVE_BCOPY 1 @@ -15,7 +14,6 @@ /* Define to 1 if you have the `getpagesize' function. */ #define HAVE_GETPAGESIZE 1 - /* Define to 1 if you have the header file. */ #define HAVE_INTTYPES_H 1 @@ -52,10 +50,12 @@ /* Define to 1 if you have the header file. */ #define HAVE_UNISTD_H 1 -/* Define to the sub-directory in which libtool stores uninstalled libraries. - */ +/* Define to the sub-directory where libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" +/* Name of package */ +#define PACKAGE "expat" + /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "expat-bugs@libexpat.org" @@ -63,7 +63,7 @@ #define PACKAGE_NAME "expat" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "expat 2.2.0" +#define PACKAGE_STRING "expat 2.2.5" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "expat" @@ -72,11 +72,14 @@ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "2.2.0" +#define PACKAGE_VERSION "2.2.5" /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 +/* Version number of package */ +#define VERSION "2.2.5" + /* whether byteorder is bigendian */ /* #undef WORDS_BIGENDIAN */ @@ -90,9 +93,6 @@ /* Define to make XML Namespaces functionality available. */ #define XML_NS 1 -/* Define to __FUNCTION__ or "" if `__func__' does not conform to ANSI C. */ -/* #undef __func__ */ - /* Define to empty if `const' does not conform to ANSI C. */ /* #undef const */ diff --git a/tools/sdk/include/expat/expat_external.h b/tools/sdk/include/expat/expat_external.h index aa08a2f8..629483a9 100644 --- a/tools/sdk/include/expat/expat_external.h +++ b/tools/sdk/include/expat/expat_external.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef Expat_External_INCLUDED @@ -8,7 +36,7 @@ /* External API definitions */ #if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__) -#define XML_USE_MSC_EXTENSIONS 1 +# define XML_USE_MSC_EXTENSIONS 1 #endif /* Expat tries very hard to make the API boundary very specifically @@ -34,11 +62,11 @@ system headers may assume the cdecl convention. */ #ifndef XMLCALL -#if defined(_MSC_VER) -#define XMLCALL __cdecl -#elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER) -#define XMLCALL __attribute__((cdecl)) -#else +# if defined(_MSC_VER) +# define XMLCALL __cdecl +# elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER) +# define XMLCALL __attribute__((cdecl)) +# else /* For any platform which uses this definition and supports more than one calling convention, we need to extend this definition to declare the convention used on that platform, if it's possible to @@ -49,41 +77,41 @@ pre-processor and how to specify the same calling convention as the platform's malloc() implementation. */ -#define XMLCALL -#endif +# define XMLCALL +# endif #endif /* not defined XMLCALL */ #if !defined(XML_STATIC) && !defined(XMLIMPORT) -#ifndef XML_BUILDING_EXPAT +# ifndef XML_BUILDING_EXPAT /* using Expat from an application */ -#ifdef XML_USE_MSC_EXTENSIONS -#define XMLIMPORT __declspec(dllimport) -#endif +# ifdef XML_USE_MSC_EXTENSIONS +# define XMLIMPORT __declspec(dllimport) +# endif -#endif +# endif #endif /* not defined XML_STATIC */ #if !defined(XMLIMPORT) && defined(__GNUC__) && (__GNUC__ >= 4) -#define XMLIMPORT __attribute__ ((visibility ("default"))) +# define XMLIMPORT __attribute__ ((visibility ("default"))) #endif /* If we didn't define it above, define it away: */ #ifndef XMLIMPORT -#define XMLIMPORT +# define XMLIMPORT #endif #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)) -#define XML_ATTR_MALLOC __attribute__((__malloc__)) +# define XML_ATTR_MALLOC __attribute__((__malloc__)) #else -#define XML_ATTR_MALLOC +# define XML_ATTR_MALLOC #endif #if defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) -#define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x))) +# define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x))) #else -#define XML_ATTR_ALLOC_SIZE(x) +# define XML_ATTR_ALLOC_SIZE(x) #endif #define XMLPARSEAPI(type) XMLIMPORT type XMLCALL @@ -93,30 +121,35 @@ extern "C" { #endif #ifdef XML_UNICODE_WCHAR_T -#define XML_UNICODE +# ifndef XML_UNICODE +# define XML_UNICODE +# endif +# if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2) +# error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc" +# endif #endif #ifdef XML_UNICODE /* Information is UTF-16 encoded. */ -#ifdef XML_UNICODE_WCHAR_T +# ifdef XML_UNICODE_WCHAR_T typedef wchar_t XML_Char; typedef wchar_t XML_LChar; -#else +# else typedef unsigned short XML_Char; typedef char XML_LChar; -#endif /* XML_UNICODE_WCHAR_T */ +# endif /* XML_UNICODE_WCHAR_T */ #else /* Information is UTF-8 encoded. */ typedef char XML_Char; typedef char XML_LChar; #endif /* XML_UNICODE */ #ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */ -#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400 +# if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400 typedef __int64 XML_Index; typedef unsigned __int64 XML_Size; -#else +# else typedef long long XML_Index; typedef unsigned long long XML_Size; -#endif +# endif #else typedef long XML_Index; typedef unsigned long XML_Size; diff --git a/tools/sdk/include/expat/expat_static.vcxproj b/tools/sdk/include/expat/expat_static.vcxproj new file mode 100644 index 00000000..b4265e01 --- /dev/null +++ b/tools/sdk/include/expat/expat_static.vcxproj @@ -0,0 +1,149 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Template + Win32 + + + + + + {58A821BC-E4AF-4DF4-9A54-2BAA22B92615} + 10.0.16299.0 + + + + Application + v141 + + + StaticLibrary + v141 + false + MultiByte + + + StaticLibrary + v141 + false + MultiByte + + + + + + + + + + + + + + + + + + .\..\win32\bin\Release\ + .\..\win32\tmp\Release_static\ + false + + + .\..\win32\bin\Debug\ + .\..\win32\tmp\Debug_static\ + true + + + + MultiThreaded + Default + true + true + MaxSpeed + true + Level3 + _WINDOWS;NDEBUG;_LIB;%(PreprocessorDefinitions) + .\..\win32\tmp\Release_static\ + .\..\win32\tmp\Release_static\expat_static.pch + .\..\win32\tmp\Release_static\ + .\..\win32\tmp\Release_static\ + + + 0x0409 + NDEBUG;%(PreprocessorDefinitions) + + + true + .\..\win32\bin\Release\expat_static.bsc + + + true + ..\win32\bin\Release\libexpatMT.lib + + + + + MultiThreadedDebug + Default + true + Disabled + true + Level3 + EditAndContinue + _DEBUG;_WINDOWS;_LIB;%(PreprocessorDefinitions) + .\..\win32\tmp\Debug_static\ + true + .\..\win32\tmp\Debug_static\expat_static.pch + .\..\win32\tmp\Debug_static\ + .\..\win32\tmp\Debug_static\ + EnableFastChecks + + + 0x0409 + _DEBUG;%(PreprocessorDefinitions) + + + true + .\..\win32\bin\Debug\expat_static.bsc + + + true + ..\win32\bin\Debug\libexpatMT.lib + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tools/sdk/include/expat/expat_static.vcxproj.filters b/tools/sdk/include/expat/expat_static.vcxproj.filters new file mode 100644 index 00000000..a2fe03e6 --- /dev/null +++ b/tools/sdk/include/expat/expat_static.vcxproj.filters @@ -0,0 +1,74 @@ + + + + + {ef375f25-3490-4376-8deb-a8a8bebc0194} + cpp;c;cxx;rc;def;r;odl;idl;hpj;bat + + + {f1cd6f85-7111-4c1b-abad-37c79851ca34} + h;hpp;hxx;hm;inl + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/tools/sdk/include/expat/expatw.vcxproj b/tools/sdk/include/expat/expatw.vcxproj new file mode 100644 index 00000000..c7083092 --- /dev/null +++ b/tools/sdk/include/expat/expatw.vcxproj @@ -0,0 +1,179 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Template + Win32 + + + + + + {C04F1C11-7079-48AD-A90B-6F59B7A55BEF} + 10.0.16299.0 + + + + Application + v141 + + + DynamicLibrary + v141 + false + MultiByte + + + DynamicLibrary + v141 + false + MultiByte + + + + + + + + + + + + + + + + + + .\..\win32\bin\Release\ + .\..\win32\tmp\Release-w\ + false + + + .\..\win32\bin\Debug\ + .\..\win32\tmp\Debug-w\ + true + + + + MultiThreaded + Default + true + true + MaxSpeed + true + Level3 + NDEBUG;_WINDOWS;_USRDLL;XML_UNICODE_WCHAR_T;%(PreprocessorDefinitions) + .\..\win32\tmp\Release-w\ + .\..\win32\tmp\Release-w\expatw.pch + + .\..\win32\tmp\Release-w\ + .\..\win32\tmp\Release-w\ + + + true + NDEBUG;%(PreprocessorDefinitions) + .\..\win32\bin\Release\expatw.tlb + true + Win32 + + + 0x0409 + NDEBUG;%(PreprocessorDefinitions) + + + true + .\..\win32\bin\Release\expatw.bsc + + + true + true + Console + ..\win32\bin\Release\libexpatw.dll + .\..\win32\bin\Release\libexpatw.lib + .\libexpatw.def + + + + + MultiThreadedDebug + Default + true + Disabled + true + Level3 + EditAndContinue + _DEBUG;_WINDOWS;_USRDLL;XML_UNICODE_WCHAR_T;%(PreprocessorDefinitions) + .\..\win32\tmp\Debug-w\ + true + .\..\win32\tmp\Debug-w\expatw.pch + .\..\win32\tmp\Debug-w\ + .\..\win32\tmp\Debug-w\ + EnableFastChecks + + + true + _DEBUG;%(PreprocessorDefinitions) + .\..\win32\bin\Debug\expatw.tlb + true + Win32 + + + 0x0409 + _DEBUG;%(PreprocessorDefinitions) + + + true + .\..\win32\bin\Debug\expatw.bsc + + + true + true + true + Console + ..\win32\bin\Debug\libexpatw.dll + .\..\win32\bin\Debug\libexpatw.lib + .\libexpatw.def + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tools/sdk/include/expat/expatw.vcxproj.filters b/tools/sdk/include/expat/expatw.vcxproj.filters new file mode 100644 index 00000000..fb3909c9 --- /dev/null +++ b/tools/sdk/include/expat/expatw.vcxproj.filters @@ -0,0 +1,83 @@ + + + + + {fea8fd20-7d6d-4664-a821-1ab5a29dadbd} + cpp;c;cxx;rc;def;r;odl;idl;hpj;bat + + + {0ceb9aa0-672d-4a6b-bff9-345c51aab04c} + h;hpp;hxx;hm;inl + + + {d62ff6fc-7f74-443d-a048-31ef02a6f99f} + ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + Source Files + + + \ No newline at end of file diff --git a/tools/sdk/include/expat/expatw_static.vcxproj b/tools/sdk/include/expat/expatw_static.vcxproj new file mode 100644 index 00000000..a917b48e --- /dev/null +++ b/tools/sdk/include/expat/expatw_static.vcxproj @@ -0,0 +1,149 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Template + Win32 + + + + + + {9220B0F2-C895-4CB2-91D1-1C16C4ECB759} + 10.0.16299.0 + + + + Application + v141 + + + StaticLibrary + v141 + false + MultiByte + + + StaticLibrary + v141 + false + MultiByte + + + + + + + + + + + + + + + + + + .\..\win32\bin\Debug\ + .\..\win32\tmp\Debug-w_static\ + true + + + .\..\win32\bin\Release\ + .\..\win32\tmp\Release-w_static\ + false + + + + MultiThreadedDebug + Default + true + Disabled + true + Level3 + EditAndContinue + _DEBUG;_WINDOWS;_LIB;XML_UNICODE_WCHAR_T;%(PreprocessorDefinitions) + .\..\win32\tmp\Debug-w_static\ + true + .\..\win32\tmp\Debug-w_static\expatw_static.pch + .\..\win32\tmp\Debug-w_static\ + .\..\win32\tmp\Debug-w_static\ + EnableFastChecks + + + 0x0409 + _DEBUG;%(PreprocessorDefinitions) + + + true + .\..\win32\bin\Debug\expatw_static.bsc + + + true + ..\win32\bin\Debug\libexpatwMT.lib + + + + + MultiThreaded + Default + true + true + MaxSpeed + true + Level3 + _WINDOWS;NDEBUG;_LIB;XML_UNICODE_WCHAR_T;%(PreprocessorDefinitions) + .\..\win32\tmp\Release-w_static\ + .\..\win32\tmp\Release-w_static\expatw_static.pch + .\..\win32\tmp\Release-w_static\ + .\..\win32\tmp\Release-w_static\ + + + 0x0409 + NDEBUG;%(PreprocessorDefinitions) + + + true + .\..\win32\bin\Release\expatw_static.bsc + + + true + ..\win32\bin\Release\libexpatwMT.lib + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tools/sdk/include/expat/expatw_static.vcxproj.filters b/tools/sdk/include/expat/expatw_static.vcxproj.filters new file mode 100644 index 00000000..724d9f8c --- /dev/null +++ b/tools/sdk/include/expat/expatw_static.vcxproj.filters @@ -0,0 +1,74 @@ + + + + + {c0226397-04be-42b5-ba75-257ac91ef7fa} + cpp;c;cxx;rc;def;r;odl;idl;hpj;bat + + + {3d74dc56-3aec-4ee9-b700-7203f44e015d} + h;hpp;hxx;hm;inl + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/tools/sdk/include/expat/iasciitab.h b/tools/sdk/include/expat/iasciitab.h index 24a1d5cc..ce4a4bf7 100644 --- a/tools/sdk/include/expat/iasciitab.h +++ b/tools/sdk/include/expat/iasciitab.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Like asciitab.h, except that 0xD has code BT_S rather than BT_CR */ diff --git a/tools/sdk/include/expat/internal.h b/tools/sdk/include/expat/internal.h index 94cb98e1..e33fdcb0 100644 --- a/tools/sdk/include/expat/internal.h +++ b/tools/sdk/include/expat/internal.h @@ -18,6 +18,35 @@ Note: Use of these macros is based on judgement, not hard rules, and therefore subject to change. + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if defined(__GNUC__) && defined(__i386__) && !defined(__MINGW32__) @@ -87,7 +116,7 @@ extern "C" { void -align_limit_to_full_utf8_characters(const char * from, const char ** fromLimRef); +_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef); #ifdef __cplusplus diff --git a/tools/sdk/include/expat/latin1tab.h b/tools/sdk/include/expat/latin1tab.h index 53c25d76..95dfa52b 100644 --- a/tools/sdk/include/expat/latin1tab.h +++ b/tools/sdk/include/expat/latin1tab.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* 0x80 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, diff --git a/tools/sdk/include/expat/libexpat.def b/tools/sdk/include/expat/libexpat.def new file mode 100644 index 00000000..d08f5b7c --- /dev/null +++ b/tools/sdk/include/expat/libexpat.def @@ -0,0 +1,78 @@ +; DEF file for MS VC++ + +LIBRARY +EXPORTS + XML_DefaultCurrent @1 + XML_ErrorString @2 + XML_ExpatVersion @3 + XML_ExpatVersionInfo @4 + XML_ExternalEntityParserCreate @5 + XML_GetBase @6 + XML_GetBuffer @7 + XML_GetCurrentByteCount @8 + XML_GetCurrentByteIndex @9 + XML_GetCurrentColumnNumber @10 + XML_GetCurrentLineNumber @11 + XML_GetErrorCode @12 + XML_GetIdAttributeIndex @13 + XML_GetInputContext @14 + XML_GetSpecifiedAttributeCount @15 + XML_Parse @16 + XML_ParseBuffer @17 + XML_ParserCreate @18 + XML_ParserCreateNS @19 + XML_ParserCreate_MM @20 + XML_ParserFree @21 + XML_SetAttlistDeclHandler @22 + XML_SetBase @23 + XML_SetCdataSectionHandler @24 + XML_SetCharacterDataHandler @25 + XML_SetCommentHandler @26 + XML_SetDefaultHandler @27 + XML_SetDefaultHandlerExpand @28 + XML_SetDoctypeDeclHandler @29 + XML_SetElementDeclHandler @30 + XML_SetElementHandler @31 + XML_SetEncoding @32 + XML_SetEndCdataSectionHandler @33 + XML_SetEndDoctypeDeclHandler @34 + XML_SetEndElementHandler @35 + XML_SetEndNamespaceDeclHandler @36 + XML_SetEntityDeclHandler @37 + XML_SetExternalEntityRefHandler @38 + XML_SetExternalEntityRefHandlerArg @39 + XML_SetNamespaceDeclHandler @40 + XML_SetNotStandaloneHandler @41 + XML_SetNotationDeclHandler @42 + XML_SetParamEntityParsing @43 + XML_SetProcessingInstructionHandler @44 + XML_SetReturnNSTriplet @45 + XML_SetStartCdataSectionHandler @46 + XML_SetStartDoctypeDeclHandler @47 + XML_SetStartElementHandler @48 + XML_SetStartNamespaceDeclHandler @49 + XML_SetUnknownEncodingHandler @50 + XML_SetUnparsedEntityDeclHandler @51 + XML_SetUserData @52 + XML_SetXmlDeclHandler @53 + XML_UseParserAsHandlerArg @54 +; added with version 1.95.3 + XML_ParserReset @55 + XML_SetSkippedEntityHandler @56 +; added with version 1.95.5 + XML_GetFeatureList @57 + XML_UseForeignDTD @58 +; added with version 1.95.6 + XML_FreeContentModel @59 + XML_MemMalloc @60 + XML_MemRealloc @61 + XML_MemFree @62 +; added with version 1.95.8 + XML_StopParser @63 + XML_ResumeParser @64 + XML_GetParsingStatus @65 +; added with version 2.1.1 +; XML_GetAttributeInfo @66 + XML_SetHashSalt @67@ +; added with version 2.2.5 + _INTERNAL_trim_to_complete_utf8_characters @68@ \ No newline at end of file diff --git a/tools/sdk/include/expat/libexpatw.def b/tools/sdk/include/expat/libexpatw.def new file mode 100644 index 00000000..928e01b1 --- /dev/null +++ b/tools/sdk/include/expat/libexpatw.def @@ -0,0 +1,78 @@ +; DEF file for MS VC++ + +LIBRARY +EXPORTS + XML_DefaultCurrent @1 + XML_ErrorString @2 + XML_ExpatVersion @3 + XML_ExpatVersionInfo @4 + XML_ExternalEntityParserCreate @5 + XML_GetBase @6 + XML_GetBuffer @7 + XML_GetCurrentByteCount @8 + XML_GetCurrentByteIndex @9 + XML_GetCurrentColumnNumber @10 + XML_GetCurrentLineNumber @11 + XML_GetErrorCode @12 + XML_GetIdAttributeIndex @13 + XML_GetInputContext @14 + XML_GetSpecifiedAttributeCount @15 + XML_Parse @16 + XML_ParseBuffer @17 + XML_ParserCreate @18 + XML_ParserCreateNS @19 + XML_ParserCreate_MM @20 + XML_ParserFree @21 + XML_SetAttlistDeclHandler @22 + XML_SetBase @23 + XML_SetCdataSectionHandler @24 + XML_SetCharacterDataHandler @25 + XML_SetCommentHandler @26 + XML_SetDefaultHandler @27 + XML_SetDefaultHandlerExpand @28 + XML_SetDoctypeDeclHandler @29 + XML_SetElementDeclHandler @30 + XML_SetElementHandler @31 + XML_SetEncoding @32 + XML_SetEndCdataSectionHandler @33 + XML_SetEndDoctypeDeclHandler @34 + XML_SetEndElementHandler @35 + XML_SetEndNamespaceDeclHandler @36 + XML_SetEntityDeclHandler @37 + XML_SetExternalEntityRefHandler @38 + XML_SetExternalEntityRefHandlerArg @39 + XML_SetNamespaceDeclHandler @40 + XML_SetNotStandaloneHandler @41 + XML_SetNotationDeclHandler @42 + XML_SetParamEntityParsing @43 + XML_SetProcessingInstructionHandler @44 + XML_SetReturnNSTriplet @45 + XML_SetStartCdataSectionHandler @46 + XML_SetStartDoctypeDeclHandler @47 + XML_SetStartElementHandler @48 + XML_SetStartNamespaceDeclHandler @49 + XML_SetUnknownEncodingHandler @50 + XML_SetUnparsedEntityDeclHandler @51 + XML_SetUserData @52 + XML_SetXmlDeclHandler @53 + XML_UseParserAsHandlerArg @54 +; added with version 1.95.3 + XML_ParserReset @55 + XML_SetSkippedEntityHandler @56 +; added with version 1.95.5 + XML_GetFeatureList @57 + XML_UseForeignDTD @58 +; added with version 1.95.6 + XML_FreeContentModel @59 + XML_MemMalloc @60 + XML_MemRealloc @61 + XML_MemFree @62 +; added with version 1.95.8 + XML_StopParser @63 + XML_ResumeParser @64 + XML_GetParsingStatus @65 +; added with version 2.1.1 +; XML_GetAttributeInfo @66 + XML_SetHashSalt @67@ +; added with version 2.2.5 + _INTERNAL_trim_to_complete_utf8_characters @68@ diff --git a/tools/sdk/include/expat/loadlibrary.c b/tools/sdk/include/expat/loadlibrary.c new file mode 100644 index 00000000..35fdf98b --- /dev/null +++ b/tools/sdk/include/expat/loadlibrary.c @@ -0,0 +1,143 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2016 - 2017, Steve Holme, . + * Copyright (C) 2017, Expat development team + * + * All rights reserved. + * Licensed under the MIT license: + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF + * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH + * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder shall + * not be used in advertising or otherwise to promote the sale, use or other + * dealings in this Software without prior written authorization of the + * copyright holder. + * + ***************************************************************************/ + +#if defined(_WIN32) + +#include +#include + + +HMODULE _Expat_LoadLibrary(LPCTSTR filename); + + +#if !defined(LOAD_WITH_ALTERED_SEARCH_PATH) +#define LOAD_WITH_ALTERED_SEARCH_PATH 0x00000008 +#endif + +#if !defined(LOAD_LIBRARY_SEARCH_SYSTEM32) +#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800 +#endif + +/* We use our own typedef here since some headers might lack these */ +typedef HMODULE (APIENTRY *LOADLIBRARYEX_FN)(LPCTSTR, HANDLE, DWORD); + +/* See function definitions in winbase.h */ +#ifdef UNICODE +# ifdef _WIN32_WCE +# define LOADLIBARYEX L"LoadLibraryExW" +# else +# define LOADLIBARYEX "LoadLibraryExW" +# endif +#else +# define LOADLIBARYEX "LoadLibraryExA" +#endif + + +/* + * _Expat_LoadLibrary() + * + * This is used to dynamically load DLLs using the most secure method available + * for the version of Windows that we are running on. + * + * Parameters: + * + * filename [in] - The filename or full path of the DLL to load. If only the + * filename is passed then the DLL will be loaded from the + * Windows system directory. + * + * Returns the handle of the module on success; otherwise NULL. + */ +HMODULE _Expat_LoadLibrary(LPCTSTR filename) +{ + HMODULE hModule = NULL; + LOADLIBRARYEX_FN pLoadLibraryEx = NULL; + + /* Get a handle to kernel32 so we can access it's functions at runtime */ + HMODULE hKernel32 = GetModuleHandle(TEXT("kernel32")); + if(!hKernel32) + return NULL; /* LCOV_EXCL_LINE */ + + /* Attempt to find LoadLibraryEx() which is only available on Windows 2000 + and above */ + pLoadLibraryEx = (LOADLIBRARYEX_FN) GetProcAddress(hKernel32, LOADLIBARYEX); + + /* Detect if there's already a path in the filename and load the library if + there is. Note: Both back slashes and forward slashes have been supported + since the earlier days of DOS at an API level although they are not + supported by command prompt */ + if(_tcspbrk(filename, TEXT("\\/"))) { + /** !checksrc! disable BANNEDFUNC 1 **/ + hModule = pLoadLibraryEx ? + pLoadLibraryEx(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) : + LoadLibrary(filename); + } + /* Detect if KB2533623 is installed, as LOAD_LIBARY_SEARCH_SYSTEM32 is only + supported on Windows Vista, Windows Server 2008, Windows 7 and Windows + Server 2008 R2 with this patch or natively on Windows 8 and above */ + else if(pLoadLibraryEx && GetProcAddress(hKernel32, "AddDllDirectory")) { + /* Load the DLL from the Windows system directory */ + hModule = pLoadLibraryEx(filename, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); + } + else { + /* Attempt to get the Windows system path */ + UINT systemdirlen = GetSystemDirectory(NULL, 0); + if(systemdirlen) { + /* Allocate space for the full DLL path (Room for the null terminator + is included in systemdirlen) */ + size_t filenamelen = _tcslen(filename); + TCHAR *path = malloc(sizeof(TCHAR) * (systemdirlen + 1 + filenamelen)); + if(path && GetSystemDirectory(path, systemdirlen)) { + /* Calculate the full DLL path */ + _tcscpy(path + _tcslen(path), TEXT("\\")); + _tcscpy(path + _tcslen(path), filename); + + /* Load the DLL from the Windows system directory */ + /** !checksrc! disable BANNEDFUNC 1 **/ + hModule = pLoadLibraryEx ? + pLoadLibraryEx(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) : + LoadLibrary(path); + + } + free(path); + } + } + + return hModule; +} + +#else /* defined(_WIN32) */ + +/* ISO C requires a translation unit to contain at least one declaration + [-Wempty-translation-unit] */ +typedef int _TRANSLATION_UNIT_LOAD_LIBRARY_C_NOT_EMTPY; + +#endif /* defined(_WIN32) */ diff --git a/tools/sdk/include/expat/minicheck.h b/tools/sdk/include/expat/minicheck.h deleted file mode 100644 index d54801d1..00000000 --- a/tools/sdk/include/expat/minicheck.h +++ /dev/null @@ -1,95 +0,0 @@ -/* Miniature re-implementation of the "check" library. - * - * This is intended to support just enough of check to run the Expat - * tests. This interface is based entirely on the portion of the - * check library being used. - * - * This is *source* compatible, but not necessary *link* compatible. - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#define CK_NOFORK 0 -#define CK_FORK 1 - -#define CK_SILENT 0 -#define CK_NORMAL 1 -#define CK_VERBOSE 2 - -/* Workaround for Microsoft's compiler and Tru64 Unix systems where the - C compiler has a working __func__, but the C++ compiler only has a - working __FUNCTION__. This could be fixed in configure.in, but it's - not worth it right now. */ -#if defined (_MSC_VER) || (defined(__osf__) && defined(__cplusplus)) -#define __func__ __FUNCTION__ -#endif - -/* ISO C90 does not support '__func__' predefined identifier */ -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ < 199901) -# define __func__ "(unknown)" -#endif - -#define START_TEST(testname) static void testname(void) { \ - _check_set_test_info(__func__, __FILE__, __LINE__); \ - { -#define END_TEST - -#define fail(msg) _fail_unless(0, __FILE__, __LINE__, msg) - -typedef void (*tcase_setup_function)(void); -typedef void (*tcase_teardown_function)(void); -typedef void (*tcase_test_function)(void); - -typedef struct SRunner SRunner; -typedef struct Suite Suite; -typedef struct TCase TCase; - -struct SRunner { - Suite *suite; - int nchecks; - int nfailures; -}; - -struct Suite { - const char *name; - TCase *tests; -}; - -struct TCase { - const char *name; - tcase_setup_function setup; - tcase_teardown_function teardown; - tcase_test_function *tests; - int ntests; - int allocated; - TCase *next_tcase; -}; - - -/* Internal helper. */ -void _check_set_test_info(char const *function, - char const *filename, int lineno); - - -/* - * Prototypes for the actual implementation. - */ - -void _fail_unless(int condition, const char *file, int line, const char *msg); -Suite *suite_create(const char *name); -TCase *tcase_create(const char *name); -void suite_add_tcase(Suite *suite, TCase *tc); -void tcase_add_checked_fixture(TCase *, - tcase_setup_function, - tcase_teardown_function); -void tcase_add_test(TCase *tc, tcase_test_function test); -SRunner *srunner_create(Suite *suite); -void srunner_run_all(SRunner *runner, int verbosity); -int srunner_ntests_failed(SRunner *runner); -void srunner_free(SRunner *runner); - -#ifdef __cplusplus -} -#endif diff --git a/tools/sdk/include/expat/nametab.h b/tools/sdk/include/expat/nametab.h index b05e62c7..bfa2bd38 100644 --- a/tools/sdk/include/expat/nametab.h +++ b/tools/sdk/include/expat/nametab.h @@ -1,3 +1,35 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + static const unsigned namingBitmap[] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, diff --git a/tools/sdk/include/expat/siphash.h b/tools/sdk/include/expat/siphash.h new file mode 100644 index 00000000..581872df --- /dev/null +++ b/tools/sdk/include/expat/siphash.h @@ -0,0 +1,374 @@ +/* ========================================================================== + * siphash.h - SipHash-2-4 in a single header file + * -------------------------------------------------------------------------- + * Derived by William Ahern from the reference implementation[1] published[2] + * by Jean-Philippe Aumasson and Daniel J. Berstein. + * Minimal changes by Sebastian Pipping and Victor Stinner on top, see below. + * Licensed under the CC0 Public Domain Dedication license. + * + * 1. https://www.131002.net/siphash/siphash24.c + * 2. https://www.131002.net/siphash/ + * -------------------------------------------------------------------------- + * HISTORY: + * + * 2017-07-25 (Vadim Zeitlin) + * - Fix use of SIPHASH_MAIN macro + * + * 2017-07-05 (Sebastian Pipping) + * - Use _SIP_ULL macro to not require a C++11 compiler if compiled as C++ + * - Add const qualifiers at two places + * - Ensure <=80 characters line length (assuming tab width 4) + * + * 2017-06-23 (Victor Stinner) + * - Address Win64 compile warnings + * + * 2017-06-18 (Sebastian Pipping) + * - Clarify license note in the header + * - Address C89 issues: + * - Stop using inline keyword (and let compiler decide) + * - Replace _Bool by int + * - Turn macro siphash24 into a function + * - Address invalid conversion (void pointer) by explicit cast + * - Address lack of stdint.h for Visual Studio 2003 to 2008 + * - Always expose sip24_valid (for self-tests) + * + * 2012-11-04 - Born. (William Ahern) + * -------------------------------------------------------------------------- + * USAGE: + * + * SipHash-2-4 takes as input two 64-bit words as the key, some number of + * message bytes, and outputs a 64-bit word as the message digest. This + * implementation employs two data structures: a struct sipkey for + * representing the key, and a struct siphash for representing the hash + * state. + * + * For converting a 16-byte unsigned char array to a key, use either the + * macro sip_keyof or the routine sip_tokey. The former instantiates a + * compound literal key, while the latter requires a key object as a + * parameter. + * + * unsigned char secret[16]; + * arc4random_buf(secret, sizeof secret); + * struct sipkey *key = sip_keyof(secret); + * + * For hashing a message, use either the convenience macro siphash24 or the + * routines sip24_init, sip24_update, and sip24_final. + * + * struct siphash state; + * void *msg; + * size_t len; + * uint64_t hash; + * + * sip24_init(&state, key); + * sip24_update(&state, msg, len); + * hash = sip24_final(&state); + * + * or + * + * hash = siphash24(msg, len, key); + * + * To convert the 64-bit hash value to a canonical 8-byte little-endian + * binary representation, use either the macro sip_binof or the routine + * sip_tobin. The former instantiates and returns a compound literal array, + * while the latter requires an array object as a parameter. + * -------------------------------------------------------------------------- + * NOTES: + * + * o Neither sip_keyof, sip_binof, nor siphash24 will work with compilers + * lacking compound literal support. Instead, you must use the lower-level + * interfaces which take as parameters the temporary state objects. + * + * o Uppercase macros may evaluate parameters more than once. Lowercase + * macros should not exhibit any such side effects. + * ========================================================================== + */ +#ifndef SIPHASH_H +#define SIPHASH_H + +#include /* size_t */ + +#if defined(_WIN32) && defined(_MSC_VER) && (_MSC_VER < 1600) + /* For vs2003/7.1 up to vs2008/9.0; _MSC_VER 1600 is vs2010/10.0 */ + typedef unsigned __int8 uint8_t; + typedef unsigned __int32 uint32_t; + typedef unsigned __int64 uint64_t; +#else + #include /* uint64_t uint32_t uint8_t */ +#endif + + +/* + * Workaround to not require a C++11 compiler for using ULL suffix + * if this code is included and compiled as C++; related GCC warning is: + * warning: use of C++11 long long integer constant [-Wlong-long] + */ +#define _SIP_ULL(high, low) (((uint64_t)high << 32) | low) + + +#define SIP_ROTL(x, b) (uint64_t)(((x) << (b)) | ( (x) >> (64 - (b)))) + +#define SIP_U32TO8_LE(p, v) \ + (p)[0] = (uint8_t)((v) >> 0); (p)[1] = (uint8_t)((v) >> 8); \ + (p)[2] = (uint8_t)((v) >> 16); (p)[3] = (uint8_t)((v) >> 24); + +#define SIP_U64TO8_LE(p, v) \ + SIP_U32TO8_LE((p) + 0, (uint32_t)((v) >> 0)); \ + SIP_U32TO8_LE((p) + 4, (uint32_t)((v) >> 32)); + +#define SIP_U8TO64_LE(p) \ + (((uint64_t)((p)[0]) << 0) | \ + ((uint64_t)((p)[1]) << 8) | \ + ((uint64_t)((p)[2]) << 16) | \ + ((uint64_t)((p)[3]) << 24) | \ + ((uint64_t)((p)[4]) << 32) | \ + ((uint64_t)((p)[5]) << 40) | \ + ((uint64_t)((p)[6]) << 48) | \ + ((uint64_t)((p)[7]) << 56)) + + +#define SIPHASH_INITIALIZER { 0, 0, 0, 0, { 0 }, 0, 0 } + +struct siphash { + uint64_t v0, v1, v2, v3; + + unsigned char buf[8], *p; + uint64_t c; +}; /* struct siphash */ + + +#define SIP_KEYLEN 16 + +struct sipkey { + uint64_t k[2]; +}; /* struct sipkey */ + +#define sip_keyof(k) sip_tokey(&(struct sipkey){ { 0 } }, (k)) + +static struct sipkey *sip_tokey(struct sipkey *key, const void *src) { + key->k[0] = SIP_U8TO64_LE((const unsigned char *)src); + key->k[1] = SIP_U8TO64_LE((const unsigned char *)src + 8); + return key; +} /* sip_tokey() */ + + +#define sip_binof(v) sip_tobin((unsigned char[8]){ 0 }, (v)) + +static void *sip_tobin(void *dst, uint64_t u64) { + SIP_U64TO8_LE((unsigned char *)dst, u64); + return dst; +} /* sip_tobin() */ + + +static void sip_round(struct siphash *H, const int rounds) { + int i; + + for (i = 0; i < rounds; i++) { + H->v0 += H->v1; + H->v1 = SIP_ROTL(H->v1, 13); + H->v1 ^= H->v0; + H->v0 = SIP_ROTL(H->v0, 32); + + H->v2 += H->v3; + H->v3 = SIP_ROTL(H->v3, 16); + H->v3 ^= H->v2; + + H->v0 += H->v3; + H->v3 = SIP_ROTL(H->v3, 21); + H->v3 ^= H->v0; + + H->v2 += H->v1; + H->v1 = SIP_ROTL(H->v1, 17); + H->v1 ^= H->v2; + H->v2 = SIP_ROTL(H->v2, 32); + } +} /* sip_round() */ + + +static struct siphash *sip24_init(struct siphash *H, + const struct sipkey *key) { + H->v0 = _SIP_ULL(0x736f6d65U, 0x70736575U) ^ key->k[0]; + H->v1 = _SIP_ULL(0x646f7261U, 0x6e646f6dU) ^ key->k[1]; + H->v2 = _SIP_ULL(0x6c796765U, 0x6e657261U) ^ key->k[0]; + H->v3 = _SIP_ULL(0x74656462U, 0x79746573U) ^ key->k[1]; + + H->p = H->buf; + H->c = 0; + + return H; +} /* sip24_init() */ + + +#define sip_endof(a) (&(a)[sizeof (a) / sizeof *(a)]) + +static struct siphash *sip24_update(struct siphash *H, const void *src, + size_t len) { + const unsigned char *p = (const unsigned char *)src, *pe = p + len; + uint64_t m; + + do { + while (p < pe && H->p < sip_endof(H->buf)) + *H->p++ = *p++; + + if (H->p < sip_endof(H->buf)) + break; + + m = SIP_U8TO64_LE(H->buf); + H->v3 ^= m; + sip_round(H, 2); + H->v0 ^= m; + + H->p = H->buf; + H->c += 8; + } while (p < pe); + + return H; +} /* sip24_update() */ + + +static uint64_t sip24_final(struct siphash *H) { + const char left = (char)(H->p - H->buf); + uint64_t b = (H->c + left) << 56; + + switch (left) { + case 7: b |= (uint64_t)H->buf[6] << 48; + case 6: b |= (uint64_t)H->buf[5] << 40; + case 5: b |= (uint64_t)H->buf[4] << 32; + case 4: b |= (uint64_t)H->buf[3] << 24; + case 3: b |= (uint64_t)H->buf[2] << 16; + case 2: b |= (uint64_t)H->buf[1] << 8; + case 1: b |= (uint64_t)H->buf[0] << 0; + case 0: break; + } + + H->v3 ^= b; + sip_round(H, 2); + H->v0 ^= b; + H->v2 ^= 0xff; + sip_round(H, 4); + + return H->v0 ^ H->v1 ^ H->v2 ^ H->v3; +} /* sip24_final() */ + + +static uint64_t siphash24(const void *src, size_t len, + const struct sipkey *key) { + struct siphash state = SIPHASH_INITIALIZER; + return sip24_final(sip24_update(sip24_init(&state, key), src, len)); +} /* siphash24() */ + + +/* + * SipHash-2-4 output with + * k = 00 01 02 ... + * and + * in = (empty string) + * in = 00 (1 byte) + * in = 00 01 (2 bytes) + * in = 00 01 02 (3 bytes) + * ... + * in = 00 01 02 ... 3e (63 bytes) + */ +static int sip24_valid(void) { + static const unsigned char vectors[64][8] = { + { 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, }, + { 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, }, + { 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, }, + { 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, }, + { 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, }, + { 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, }, + { 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, }, + { 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, }, + { 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, }, + { 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, }, + { 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, }, + { 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, }, + { 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, }, + { 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, }, + { 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, }, + { 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, }, + { 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, }, + { 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, }, + { 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, }, + { 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, }, + { 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, }, + { 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, }, + { 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, }, + { 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, }, + { 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, }, + { 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, }, + { 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, }, + { 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, }, + { 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, }, + { 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, }, + { 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, }, + { 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, }, + { 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, }, + { 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, }, + { 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, }, + { 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, }, + { 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, }, + { 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, }, + { 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, }, + { 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, }, + { 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, }, + { 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, }, + { 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, }, + { 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, }, + { 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, }, + { 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, }, + { 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, }, + { 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, }, + { 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, }, + { 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, }, + { 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, }, + { 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, }, + { 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, }, + { 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, }, + { 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, }, + { 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, }, + { 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, }, + { 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, }, + { 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, }, + { 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, }, + { 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, }, + { 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, }, + { 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, }, + { 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, } + }; + unsigned char in[64]; + struct sipkey k; + size_t i; + + sip_tokey(&k, "\000\001\002\003\004\005\006\007\010\011" + "\012\013\014\015\016\017"); + + for (i = 0; i < sizeof in; ++i) { + in[i] = (unsigned char)i; + + if (siphash24(in, i, &k) != SIP_U8TO64_LE(vectors[i])) + return 0; + } + + return 1; +} /* sip24_valid() */ + + +#ifdef SIPHASH_MAIN + +#include + +int main(void) { + const int ok = sip24_valid(); + + if (ok) + puts("OK"); + else + puts("FAIL"); + + return !ok; +} /* main() */ + +#endif /* SIPHASH_MAIN */ + + +#endif /* SIPHASH_H */ diff --git a/tools/sdk/include/expat/utf8tab.h b/tools/sdk/include/expat/utf8tab.h index 7bb3e776..fa0bed6f 100644 --- a/tools/sdk/include/expat/utf8tab.h +++ b/tools/sdk/include/expat/utf8tab.h @@ -1,7 +1,34 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. -*/ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ /* 0x80 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, /* 0x84 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, diff --git a/tools/sdk/include/expat/winconfig.h b/tools/sdk/include/expat/winconfig.h new file mode 100644 index 00000000..17fea468 --- /dev/null +++ b/tools/sdk/include/expat/winconfig.h @@ -0,0 +1,63 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef WINCONFIG_H +#define WINCONFIG_H + +#define WIN32_LEAN_AND_MEAN +#include +#undef WIN32_LEAN_AND_MEAN + +#include +#include + + +#if defined(HAVE_EXPAT_CONFIG_H) /* e.g. MinGW */ +# include +#else /* !defined(HAVE_EXPAT_CONFIG_H) */ + + +#define XML_NS 1 +#define XML_DTD 1 +#define XML_CONTEXT_BYTES 1024 + +/* we will assume all Windows platforms are little endian */ +#define BYTEORDER 1234 + +/* Windows has memmove() available. */ +#define HAVE_MEMMOVE + + +#endif /* !defined(HAVE_EXPAT_CONFIG_H) */ + + +#endif /* ndef WINCONFIG_H */ diff --git a/tools/sdk/include/expat/xmlparse.c b/tools/sdk/include/expat/xmlparse.c new file mode 100644 index 00000000..90a237f3 --- /dev/null +++ b/tools/sdk/include/expat/xmlparse.c @@ -0,0 +1,7195 @@ +/* 4b74aa710b4ed5ce464b0ce544852cb47bf905c85a49c7bae2749f5885cb966d (2.2.5+) + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#if !defined(_GNU_SOURCE) +# define _GNU_SOURCE 1 /* syscall prototype */ +#endif + +#include +#include /* memset(), memcpy() */ +#include +#include /* UINT_MAX */ +#include /* fprintf */ +#include /* getenv */ + +#ifdef _WIN32 +#define getpid GetCurrentProcessId +#else +#include /* gettimeofday() */ +#include /* getpid() */ +#include /* getpid() */ +#include /* O_RDONLY */ +#include +#endif + +#define XML_BUILDING_EXPAT 1 + +#ifdef _WIN32 +#include "winconfig.h" +#elif defined(HAVE_EXPAT_CONFIG_H) +#include +#endif /* ndef _WIN32 */ + +#include "ascii.h" +#include "expat.h" +#include "siphash.h" + +#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) +# if defined(HAVE_GETRANDOM) +# include /* getrandom */ +# else +# include /* syscall */ +# include /* SYS_getrandom */ +# endif +# if ! defined(GRND_NONBLOCK) +# define GRND_NONBLOCK 0x0001 +# endif /* defined(GRND_NONBLOCK) */ +#endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */ + +#if defined(HAVE_LIBBSD) \ + && (defined(HAVE_ARC4RANDOM_BUF) || defined(HAVE_ARC4RANDOM)) +# include +#endif + +#if defined(_WIN32) && !defined(LOAD_LIBRARY_SEARCH_SYSTEM32) +# define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800 +#endif + +#if !defined(HAVE_GETRANDOM) && !defined(HAVE_SYSCALL_GETRANDOM) \ + && !defined(HAVE_ARC4RANDOM_BUF) && !defined(HAVE_ARC4RANDOM) \ + && !defined(XML_DEV_URANDOM) \ + && !defined(_WIN32) \ + && !defined(XML_POOR_ENTROPY) +# error \ + You do not have support for any sources of high quality entropy \ + enabled. For end user security, that is probably not what you want. \ + \ + Your options include: \ + * Linux + glibc >=2.25 (getrandom): HAVE_GETRANDOM, \ + * Linux + glibc <2.25 (syscall SYS_getrandom): HAVE_SYSCALL_GETRANDOM, \ + * BSD / macOS >=10.7 (arc4random_buf): HAVE_ARC4RANDOM_BUF, \ + * BSD / macOS <10.7 (arc4random): HAVE_ARC4RANDOM, \ + * libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF + HAVE_LIBBSD, \ + * libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, \ + * Linux / BSD / macOS (/dev/urandom): XML_DEV_URANDOM \ + * Windows (RtlGenRandom): _WIN32. \ + \ + If insist on not using any of these, bypass this error by defining \ + XML_POOR_ENTROPY; you have been warned. \ + \ + If you have reasons to patch this detection code away or need changes \ + to the build system, please open a bug. Thank you! +#endif + + +#ifdef XML_UNICODE +#define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX +#define XmlConvert XmlUtf16Convert +#define XmlGetInternalEncoding XmlGetUtf16InternalEncoding +#define XmlGetInternalEncodingNS XmlGetUtf16InternalEncodingNS +#define XmlEncode XmlUtf16Encode +/* Using pointer subtraction to convert to integer type. */ +#define MUST_CONVERT(enc, s) (!(enc)->isUtf16 || (((char *)(s) - (char *)NULL) & 1)) +typedef unsigned short ICHAR; +#else +#define XML_ENCODE_MAX XML_UTF8_ENCODE_MAX +#define XmlConvert XmlUtf8Convert +#define XmlGetInternalEncoding XmlGetUtf8InternalEncoding +#define XmlGetInternalEncodingNS XmlGetUtf8InternalEncodingNS +#define XmlEncode XmlUtf8Encode +#define MUST_CONVERT(enc, s) (!(enc)->isUtf8) +typedef char ICHAR; +#endif + + +#ifndef XML_NS + +#define XmlInitEncodingNS XmlInitEncoding +#define XmlInitUnknownEncodingNS XmlInitUnknownEncoding +#undef XmlGetInternalEncodingNS +#define XmlGetInternalEncodingNS XmlGetInternalEncoding +#define XmlParseXmlDeclNS XmlParseXmlDecl + +#endif + +#ifdef XML_UNICODE + +#ifdef XML_UNICODE_WCHAR_T +#define XML_T(x) (const wchar_t)x +#define XML_L(x) L ## x +#else +#define XML_T(x) (const unsigned short)x +#define XML_L(x) x +#endif + +#else + +#define XML_T(x) x +#define XML_L(x) x + +#endif + +/* Round up n to be a multiple of sz, where sz is a power of 2. */ +#define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1)) + +/* Handle the case where memmove() doesn't exist. */ +#ifndef HAVE_MEMMOVE +#ifdef HAVE_BCOPY +#define memmove(d,s,l) bcopy((s),(d),(l)) +#else +#error memmove does not exist on this platform, nor is a substitute available +#endif /* HAVE_BCOPY */ +#endif /* HAVE_MEMMOVE */ + +#include "internal.h" +#include "xmltok.h" +#include "xmlrole.h" + +typedef const XML_Char *KEY; + +typedef struct { + KEY name; +} NAMED; + +typedef struct { + NAMED **v; + unsigned char power; + size_t size; + size_t used; + const XML_Memory_Handling_Suite *mem; +} HASH_TABLE; + +static size_t +keylen(KEY s); + +static void +copy_salt_to_sipkey(XML_Parser parser, struct sipkey * key); + +/* For probing (after a collision) we need a step size relative prime + to the hash table size, which is a power of 2. We use double-hashing, + since we can calculate a second hash value cheaply by taking those bits + of the first hash value that were discarded (masked out) when the table + index was calculated: index = hash & mask, where mask = table->size - 1. + We limit the maximum step size to table->size / 4 (mask >> 2) and make + it odd, since odd numbers are always relative prime to a power of 2. +*/ +#define SECOND_HASH(hash, mask, power) \ + ((((hash) & ~(mask)) >> ((power) - 1)) & ((mask) >> 2)) +#define PROBE_STEP(hash, mask, power) \ + ((unsigned char)((SECOND_HASH(hash, mask, power)) | 1)) + +typedef struct { + NAMED **p; + NAMED **end; +} HASH_TABLE_ITER; + +#define INIT_TAG_BUF_SIZE 32 /* must be a multiple of sizeof(XML_Char) */ +#define INIT_DATA_BUF_SIZE 1024 +#define INIT_ATTS_SIZE 16 +#define INIT_ATTS_VERSION 0xFFFFFFFF +#define INIT_BLOCK_SIZE 1024 +#define INIT_BUFFER_SIZE 1024 + +#define EXPAND_SPARE 24 + +typedef struct binding { + struct prefix *prefix; + struct binding *nextTagBinding; + struct binding *prevPrefixBinding; + const struct attribute_id *attId; + XML_Char *uri; + int uriLen; + int uriAlloc; +} BINDING; + +typedef struct prefix { + const XML_Char *name; + BINDING *binding; +} PREFIX; + +typedef struct { + const XML_Char *str; + const XML_Char *localPart; + const XML_Char *prefix; + int strLen; + int uriLen; + int prefixLen; +} TAG_NAME; + +/* TAG represents an open element. + The name of the element is stored in both the document and API + encodings. The memory buffer 'buf' is a separately-allocated + memory area which stores the name. During the XML_Parse()/ + XMLParseBuffer() when the element is open, the memory for the 'raw' + version of the name (in the document encoding) is shared with the + document buffer. If the element is open across calls to + XML_Parse()/XML_ParseBuffer(), the buffer is re-allocated to + contain the 'raw' name as well. + + A parser re-uses these structures, maintaining a list of allocated + TAG objects in a free list. +*/ +typedef struct tag { + struct tag *parent; /* parent of this element */ + const char *rawName; /* tagName in the original encoding */ + int rawNameLength; + TAG_NAME name; /* tagName in the API encoding */ + char *buf; /* buffer for name components */ + char *bufEnd; /* end of the buffer */ + BINDING *bindings; +} TAG; + +typedef struct { + const XML_Char *name; + const XML_Char *textPtr; + int textLen; /* length in XML_Chars */ + int processed; /* # of processed bytes - when suspended */ + const XML_Char *systemId; + const XML_Char *base; + const XML_Char *publicId; + const XML_Char *notation; + XML_Bool open; + XML_Bool is_param; + XML_Bool is_internal; /* true if declared in internal subset outside PE */ +} ENTITY; + +typedef struct { + enum XML_Content_Type type; + enum XML_Content_Quant quant; + const XML_Char * name; + int firstchild; + int lastchild; + int childcnt; + int nextsib; +} CONTENT_SCAFFOLD; + +#define INIT_SCAFFOLD_ELEMENTS 32 + +typedef struct block { + struct block *next; + int size; + XML_Char s[1]; +} BLOCK; + +typedef struct { + BLOCK *blocks; + BLOCK *freeBlocks; + const XML_Char *end; + XML_Char *ptr; + XML_Char *start; + const XML_Memory_Handling_Suite *mem; +} STRING_POOL; + +/* The XML_Char before the name is used to determine whether + an attribute has been specified. */ +typedef struct attribute_id { + XML_Char *name; + PREFIX *prefix; + XML_Bool maybeTokenized; + XML_Bool xmlns; +} ATTRIBUTE_ID; + +typedef struct { + const ATTRIBUTE_ID *id; + XML_Bool isCdata; + const XML_Char *value; +} DEFAULT_ATTRIBUTE; + +typedef struct { + unsigned long version; + unsigned long hash; + const XML_Char *uriName; +} NS_ATT; + +typedef struct { + const XML_Char *name; + PREFIX *prefix; + const ATTRIBUTE_ID *idAtt; + int nDefaultAtts; + int allocDefaultAtts; + DEFAULT_ATTRIBUTE *defaultAtts; +} ELEMENT_TYPE; + +typedef struct { + HASH_TABLE generalEntities; + HASH_TABLE elementTypes; + HASH_TABLE attributeIds; + HASH_TABLE prefixes; + STRING_POOL pool; + STRING_POOL entityValuePool; + /* false once a parameter entity reference has been skipped */ + XML_Bool keepProcessing; + /* true once an internal or external PE reference has been encountered; + this includes the reference to an external subset */ + XML_Bool hasParamEntityRefs; + XML_Bool standalone; +#ifdef XML_DTD + /* indicates if external PE has been read */ + XML_Bool paramEntityRead; + HASH_TABLE paramEntities; +#endif /* XML_DTD */ + PREFIX defaultPrefix; + /* === scaffolding for building content model === */ + XML_Bool in_eldecl; + CONTENT_SCAFFOLD *scaffold; + unsigned contentStringLen; + unsigned scaffSize; + unsigned scaffCount; + int scaffLevel; + int *scaffIndex; +} DTD; + +typedef struct open_internal_entity { + const char *internalEventPtr; + const char *internalEventEndPtr; + struct open_internal_entity *next; + ENTITY *entity; + int startTagLevel; + XML_Bool betweenDecl; /* WFC: PE Between Declarations */ +} OPEN_INTERNAL_ENTITY; + +typedef enum XML_Error PTRCALL Processor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr); + +static Processor prologProcessor; +static Processor prologInitProcessor; +static Processor contentProcessor; +static Processor cdataSectionProcessor; +#ifdef XML_DTD +static Processor ignoreSectionProcessor; +static Processor externalParEntProcessor; +static Processor externalParEntInitProcessor; +static Processor entityValueProcessor; +static Processor entityValueInitProcessor; +#endif /* XML_DTD */ +static Processor epilogProcessor; +static Processor errorProcessor; +static Processor externalEntityInitProcessor; +static Processor externalEntityInitProcessor2; +static Processor externalEntityInitProcessor3; +static Processor externalEntityContentProcessor; +static Processor internalEntityProcessor; + +static enum XML_Error +handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName); +static enum XML_Error +processXmlDecl(XML_Parser parser, int isGeneralTextEntity, + const char *s, const char *next); +static enum XML_Error +initializeEncoding(XML_Parser parser); +static enum XML_Error +doProlog(XML_Parser parser, const ENCODING *enc, const char *s, + const char *end, int tok, const char *next, const char **nextPtr, + XML_Bool haveMore); +static enum XML_Error +processInternalEntity(XML_Parser parser, ENTITY *entity, + XML_Bool betweenDecl); +static enum XML_Error +doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc, + const char *start, const char *end, const char **endPtr, + XML_Bool haveMore); +static enum XML_Error +doCdataSection(XML_Parser parser, const ENCODING *, const char **startPtr, + const char *end, const char **nextPtr, XML_Bool haveMore); +#ifdef XML_DTD +static enum XML_Error +doIgnoreSection(XML_Parser parser, const ENCODING *, const char **startPtr, + const char *end, const char **nextPtr, XML_Bool haveMore); +#endif /* XML_DTD */ + +static void +freeBindings(XML_Parser parser, BINDING *bindings); +static enum XML_Error +storeAtts(XML_Parser parser, const ENCODING *, const char *s, + TAG_NAME *tagNamePtr, BINDING **bindingsPtr); +static enum XML_Error +addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, + const XML_Char *uri, BINDING **bindingsPtr); +static int +defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *, XML_Bool isCdata, + XML_Bool isId, const XML_Char *dfltValue, XML_Parser parser); +static enum XML_Error +storeAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata, + const char *, const char *, STRING_POOL *); +static enum XML_Error +appendAttributeValue(XML_Parser parser, const ENCODING *, XML_Bool isCdata, + const char *, const char *, STRING_POOL *); +static ATTRIBUTE_ID * +getAttributeId(XML_Parser parser, const ENCODING *enc, const char *start, + const char *end); +static int +setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *); +static enum XML_Error +storeEntityValue(XML_Parser parser, const ENCODING *enc, const char *start, + const char *end); +static int +reportProcessingInstruction(XML_Parser parser, const ENCODING *enc, + const char *start, const char *end); +static int +reportComment(XML_Parser parser, const ENCODING *enc, const char *start, + const char *end); +static void +reportDefault(XML_Parser parser, const ENCODING *enc, const char *start, + const char *end); + +static const XML_Char * getContext(XML_Parser parser); +static XML_Bool +setContext(XML_Parser parser, const XML_Char *context); + +static void FASTCALL normalizePublicId(XML_Char *s); + +static DTD * dtdCreate(const XML_Memory_Handling_Suite *ms); +/* do not call if m_parentParser != NULL */ +static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms); +static void +dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms); +static int +dtdCopy(XML_Parser oldParser, + DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms); +static int +copyEntityTable(XML_Parser oldParser, + HASH_TABLE *, STRING_POOL *, const HASH_TABLE *); +static NAMED * +lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize); +static void FASTCALL +hashTableInit(HASH_TABLE *, const XML_Memory_Handling_Suite *ms); +static void FASTCALL hashTableClear(HASH_TABLE *); +static void FASTCALL hashTableDestroy(HASH_TABLE *); +static void FASTCALL +hashTableIterInit(HASH_TABLE_ITER *, const HASH_TABLE *); +static NAMED * FASTCALL hashTableIterNext(HASH_TABLE_ITER *); + +static void FASTCALL +poolInit(STRING_POOL *, const XML_Memory_Handling_Suite *ms); +static void FASTCALL poolClear(STRING_POOL *); +static void FASTCALL poolDestroy(STRING_POOL *); +static XML_Char * +poolAppend(STRING_POOL *pool, const ENCODING *enc, + const char *ptr, const char *end); +static XML_Char * +poolStoreString(STRING_POOL *pool, const ENCODING *enc, + const char *ptr, const char *end); +static XML_Bool FASTCALL poolGrow(STRING_POOL *pool); +static const XML_Char * FASTCALL +poolCopyString(STRING_POOL *pool, const XML_Char *s); +static const XML_Char * +poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n); +static const XML_Char * FASTCALL +poolAppendString(STRING_POOL *pool, const XML_Char *s); + +static int FASTCALL nextScaffoldPart(XML_Parser parser); +static XML_Content * build_model(XML_Parser parser); +static ELEMENT_TYPE * +getElementType(XML_Parser parser, const ENCODING *enc, + const char *ptr, const char *end); + +static XML_Char *copyString(const XML_Char *s, + const XML_Memory_Handling_Suite *memsuite); + +static unsigned long generate_hash_secret_salt(XML_Parser parser); +static XML_Bool startParsing(XML_Parser parser); + +static XML_Parser +parserCreate(const XML_Char *encodingName, + const XML_Memory_Handling_Suite *memsuite, + const XML_Char *nameSep, + DTD *dtd); + +static void +parserInit(XML_Parser parser, const XML_Char *encodingName); + +#define poolStart(pool) ((pool)->start) +#define poolEnd(pool) ((pool)->ptr) +#define poolLength(pool) ((pool)->ptr - (pool)->start) +#define poolChop(pool) ((void)--(pool->ptr)) +#define poolLastChar(pool) (((pool)->ptr)[-1]) +#define poolDiscard(pool) ((pool)->ptr = (pool)->start) +#define poolFinish(pool) ((pool)->start = (pool)->ptr) +#define poolAppendChar(pool, c) \ + (((pool)->ptr == (pool)->end && !poolGrow(pool)) \ + ? 0 \ + : ((*((pool)->ptr)++ = c), 1)) + +struct XML_ParserStruct { + /* The first member must be m_userData so that the XML_GetUserData + macro works. */ + void *m_userData; + void *m_handlerArg; + char *m_buffer; + const XML_Memory_Handling_Suite m_mem; + /* first character to be parsed */ + const char *m_bufferPtr; + /* past last character to be parsed */ + char *m_bufferEnd; + /* allocated end of m_buffer */ + const char *m_bufferLim; + XML_Index m_parseEndByteIndex; + const char *m_parseEndPtr; + XML_Char *m_dataBuf; + XML_Char *m_dataBufEnd; + XML_StartElementHandler m_startElementHandler; + XML_EndElementHandler m_endElementHandler; + XML_CharacterDataHandler m_characterDataHandler; + XML_ProcessingInstructionHandler m_processingInstructionHandler; + XML_CommentHandler m_commentHandler; + XML_StartCdataSectionHandler m_startCdataSectionHandler; + XML_EndCdataSectionHandler m_endCdataSectionHandler; + XML_DefaultHandler m_defaultHandler; + XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler; + XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler; + XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler; + XML_NotationDeclHandler m_notationDeclHandler; + XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler; + XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler; + XML_NotStandaloneHandler m_notStandaloneHandler; + XML_ExternalEntityRefHandler m_externalEntityRefHandler; + XML_Parser m_externalEntityRefHandlerArg; + XML_SkippedEntityHandler m_skippedEntityHandler; + XML_UnknownEncodingHandler m_unknownEncodingHandler; + XML_ElementDeclHandler m_elementDeclHandler; + XML_AttlistDeclHandler m_attlistDeclHandler; + XML_EntityDeclHandler m_entityDeclHandler; + XML_XmlDeclHandler m_xmlDeclHandler; + const ENCODING *m_encoding; + INIT_ENCODING m_initEncoding; + const ENCODING *m_internalEncoding; + const XML_Char *m_protocolEncodingName; + XML_Bool m_ns; + XML_Bool m_ns_triplets; + void *m_unknownEncodingMem; + void *m_unknownEncodingData; + void *m_unknownEncodingHandlerData; + void (XMLCALL *m_unknownEncodingRelease)(void *); + PROLOG_STATE m_prologState; + Processor *m_processor; + enum XML_Error m_errorCode; + const char *m_eventPtr; + const char *m_eventEndPtr; + const char *m_positionPtr; + OPEN_INTERNAL_ENTITY *m_openInternalEntities; + OPEN_INTERNAL_ENTITY *m_freeInternalEntities; + XML_Bool m_defaultExpandInternalEntities; + int m_tagLevel; + ENTITY *m_declEntity; + const XML_Char *m_doctypeName; + const XML_Char *m_doctypeSysid; + const XML_Char *m_doctypePubid; + const XML_Char *m_declAttributeType; + const XML_Char *m_declNotationName; + const XML_Char *m_declNotationPublicId; + ELEMENT_TYPE *m_declElementType; + ATTRIBUTE_ID *m_declAttributeId; + XML_Bool m_declAttributeIsCdata; + XML_Bool m_declAttributeIsId; + DTD *m_dtd; + const XML_Char *m_curBase; + TAG *m_tagStack; + TAG *m_freeTagList; + BINDING *m_inheritedBindings; + BINDING *m_freeBindingList; + int m_attsSize; + int m_nSpecifiedAtts; + int m_idAttIndex; + ATTRIBUTE *m_atts; + NS_ATT *m_nsAtts; + unsigned long m_nsAttsVersion; + unsigned char m_nsAttsPower; +#ifdef XML_ATTR_INFO + XML_AttrInfo *m_attInfo; +#endif + POSITION m_position; + STRING_POOL m_tempPool; + STRING_POOL m_temp2Pool; + char *m_groupConnector; + unsigned int m_groupSize; + XML_Char m_namespaceSeparator; + XML_Parser m_parentParser; + XML_ParsingStatus m_parsingStatus; +#ifdef XML_DTD + XML_Bool m_isParamEntity; + XML_Bool m_useForeignDTD; + enum XML_ParamEntityParsing m_paramEntityParsing; +#endif + unsigned long m_hash_secret_salt; +}; + +#define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s))) +#define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p),(s))) +#define FREE(parser, p) (parser->m_mem.free_fcn((p))) + + +XML_Parser XMLCALL +XML_ParserCreate(const XML_Char *encodingName) +{ + return XML_ParserCreate_MM(encodingName, NULL, NULL); +} + +XML_Parser XMLCALL +XML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep) +{ + XML_Char tmp[2]; + *tmp = nsSep; + return XML_ParserCreate_MM(encodingName, NULL, tmp); +} + +static const XML_Char implicitContext[] = { + ASCII_x, ASCII_m, ASCII_l, ASCII_EQUALS, ASCII_h, ASCII_t, ASCII_t, ASCII_p, + ASCII_COLON, ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, + ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, + ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, + ASCII_9, ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e, + ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e, '\0' +}; + + +/* To avoid warnings about unused functions: */ +#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) + +#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) + +/* Obtain entropy on Linux 3.17+ */ +static int +writeRandomBytes_getrandom_nonblock(void * target, size_t count) { + int success = 0; /* full count bytes written? */ + size_t bytesWrittenTotal = 0; + const unsigned int getrandomFlags = GRND_NONBLOCK; + + do { + void * const currentTarget = (void*)((char*)target + bytesWrittenTotal); + const size_t bytesToWrite = count - bytesWrittenTotal; + + const int bytesWrittenMore = +#if defined(HAVE_GETRANDOM) + getrandom(currentTarget, bytesToWrite, getrandomFlags); +#else + syscall(SYS_getrandom, currentTarget, bytesToWrite, getrandomFlags); +#endif + + if (bytesWrittenMore > 0) { + bytesWrittenTotal += bytesWrittenMore; + if (bytesWrittenTotal >= count) + success = 1; + } + } while (! success && (errno == EINTR)); + + return success; +} + +#endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */ + + +#if ! defined(_WIN32) && defined(XML_DEV_URANDOM) + +/* Extract entropy from /dev/urandom */ +static int +writeRandomBytes_dev_urandom(void * target, size_t count) { + int success = 0; /* full count bytes written? */ + size_t bytesWrittenTotal = 0; + + const int fd = open("/dev/urandom", O_RDONLY); + if (fd < 0) { + return 0; + } + + do { + void * const currentTarget = (void*)((char*)target + bytesWrittenTotal); + const size_t bytesToWrite = count - bytesWrittenTotal; + + const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite); + + if (bytesWrittenMore > 0) { + bytesWrittenTotal += bytesWrittenMore; + if (bytesWrittenTotal >= count) + success = 1; + } + } while (! success && (errno == EINTR)); + + close(fd); + return success; +} + +#endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */ + +#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */ + + +#if defined(HAVE_ARC4RANDOM) + +static void +writeRandomBytes_arc4random(void * target, size_t count) { + size_t bytesWrittenTotal = 0; + + while (bytesWrittenTotal < count) { + const uint32_t random32 = arc4random(); + size_t i = 0; + + for (; (i < sizeof(random32)) && (bytesWrittenTotal < count); + i++, bytesWrittenTotal++) { + const uint8_t random8 = (uint8_t)(random32 >> (i * 8)); + ((uint8_t *)target)[bytesWrittenTotal] = random8; + } + } +} + +#endif /* defined(HAVE_ARC4RANDOM) */ + + +#ifdef _WIN32 + +typedef BOOLEAN (APIENTRY *RTLGENRANDOM_FUNC)(PVOID, ULONG); +HMODULE _Expat_LoadLibrary(LPCTSTR filename); /* see loadlibrary.c */ + +/* Obtain entropy on Windows XP / Windows Server 2003 and later. + * Hint on RtlGenRandom and the following article from libsodium. + * + * Michael Howard: Cryptographically Secure Random number on Windows without using CryptoAPI + * https://blogs.msdn.microsoft.com/michael_howard/2005/01/14/cryptographically-secure-random-number-on-windows-without-using-cryptoapi/ + */ +static int +writeRandomBytes_RtlGenRandom(void * target, size_t count) { + int success = 0; /* full count bytes written? */ + const HMODULE advapi32 = _Expat_LoadLibrary(TEXT("ADVAPI32.DLL")); + + if (advapi32) { + const RTLGENRANDOM_FUNC RtlGenRandom + = (RTLGENRANDOM_FUNC)GetProcAddress(advapi32, "SystemFunction036"); + if (RtlGenRandom) { + if (RtlGenRandom((PVOID)target, (ULONG)count) == TRUE) { + success = 1; + } + } + FreeLibrary(advapi32); + } + + return success; +} + +#endif /* _WIN32 */ + + +#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) + +static unsigned long +gather_time_entropy(void) +{ +#ifdef _WIN32 + FILETIME ft; + GetSystemTimeAsFileTime(&ft); /* never fails */ + return ft.dwHighDateTime ^ ft.dwLowDateTime; +#else + struct timeval tv; + int gettimeofday_res; + + gettimeofday_res = gettimeofday(&tv, NULL); + +#if defined(NDEBUG) + (void)gettimeofday_res; +#else + assert (gettimeofday_res == 0); +#endif /* defined(NDEBUG) */ + + /* Microseconds time is <20 bits entropy */ + return tv.tv_usec; +#endif +} + +#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */ + + +static unsigned long +ENTROPY_DEBUG(const char * label, unsigned long entropy) { + const char * const EXPAT_ENTROPY_DEBUG = getenv("EXPAT_ENTROPY_DEBUG"); + if (EXPAT_ENTROPY_DEBUG && ! strcmp(EXPAT_ENTROPY_DEBUG, "1")) { + fprintf(stderr, "Entropy: %s --> 0x%0*lx (%lu bytes)\n", + label, + (int)sizeof(entropy) * 2, entropy, + (unsigned long)sizeof(entropy)); + } + return entropy; +} + +static unsigned long +generate_hash_secret_salt(XML_Parser parser) +{ + unsigned long entropy; + (void)parser; + + /* "Failproof" high quality providers: */ +#if defined(HAVE_ARC4RANDOM_BUF) + arc4random_buf(&entropy, sizeof(entropy)); + return ENTROPY_DEBUG("arc4random_buf", entropy); +#elif defined(HAVE_ARC4RANDOM) + writeRandomBytes_arc4random((void *)&entropy, sizeof(entropy)); + return ENTROPY_DEBUG("arc4random", entropy); +#else + /* Try high quality providers first .. */ +#ifdef _WIN32 + if (writeRandomBytes_RtlGenRandom((void *)&entropy, sizeof(entropy))) { + return ENTROPY_DEBUG("RtlGenRandom", entropy); + } +#elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) + if (writeRandomBytes_getrandom_nonblock((void *)&entropy, sizeof(entropy))) { + return ENTROPY_DEBUG("getrandom", entropy); + } +#endif +#if ! defined(_WIN32) && defined(XML_DEV_URANDOM) + if (writeRandomBytes_dev_urandom((void *)&entropy, sizeof(entropy))) { + return ENTROPY_DEBUG("/dev/urandom", entropy); + } +#endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */ + /* .. and self-made low quality for backup: */ + + /* Process ID is 0 bits entropy if attacker has local access */ + entropy = gather_time_entropy() ^ getpid(); + + /* Factors are 2^31-1 and 2^61-1 (Mersenne primes M31 and M61) */ + if (sizeof(unsigned long) == 4) { + return ENTROPY_DEBUG("fallback(4)", entropy * 2147483647); + } else { + return ENTROPY_DEBUG("fallback(8)", + entropy * (unsigned long)2305843009213693951ULL); + } +#endif +} + +static unsigned long +get_hash_secret_salt(XML_Parser parser) { + if (parser->m_parentParser != NULL) + return get_hash_secret_salt(parser->m_parentParser); + return parser->m_hash_secret_salt; +} + +static XML_Bool /* only valid for root parser */ +startParsing(XML_Parser parser) +{ + /* hash functions must be initialized before setContext() is called */ + if (parser->m_hash_secret_salt == 0) + parser->m_hash_secret_salt = generate_hash_secret_salt(parser); + if (parser->m_ns) { + /* implicit context only set for root parser, since child + parsers (i.e. external entity parsers) will inherit it + */ + return setContext(parser, implicitContext); + } + return XML_TRUE; +} + +XML_Parser XMLCALL +XML_ParserCreate_MM(const XML_Char *encodingName, + const XML_Memory_Handling_Suite *memsuite, + const XML_Char *nameSep) +{ + return parserCreate(encodingName, memsuite, nameSep, NULL); +} + +static XML_Parser +parserCreate(const XML_Char *encodingName, + const XML_Memory_Handling_Suite *memsuite, + const XML_Char *nameSep, + DTD *dtd) +{ + XML_Parser parser; + + if (memsuite) { + XML_Memory_Handling_Suite *mtemp; + parser = (XML_Parser) + memsuite->malloc_fcn(sizeof(struct XML_ParserStruct)); + if (parser != NULL) { + mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem); + mtemp->malloc_fcn = memsuite->malloc_fcn; + mtemp->realloc_fcn = memsuite->realloc_fcn; + mtemp->free_fcn = memsuite->free_fcn; + } + } + else { + XML_Memory_Handling_Suite *mtemp; + parser = (XML_Parser)malloc(sizeof(struct XML_ParserStruct)); + if (parser != NULL) { + mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem); + mtemp->malloc_fcn = malloc; + mtemp->realloc_fcn = realloc; + mtemp->free_fcn = free; + } + } + + if (!parser) + return parser; + + parser->m_buffer = NULL; + parser->m_bufferLim = NULL; + + parser->m_attsSize = INIT_ATTS_SIZE; + parser->m_atts = (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE)); + if (parser->m_atts == NULL) { + FREE(parser, parser); + return NULL; + } +#ifdef XML_ATTR_INFO + parser->m_attInfo = (XML_AttrInfo*)MALLOC(parser, parser->m_attsSize * sizeof(XML_AttrInfo)); + if (parser->m_attInfo == NULL) { + FREE(parser, parser->m_atts); + FREE(parser, parser); + return NULL; + } +#endif + parser->m_dataBuf = (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char)); + if (parser->m_dataBuf == NULL) { + FREE(parser, parser->m_atts); +#ifdef XML_ATTR_INFO + FREE(parser, parser->m_attInfo); +#endif + FREE(parser, parser); + return NULL; + } + parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE; + + if (dtd) + parser->m_dtd = dtd; + else { + parser->m_dtd = dtdCreate(&parser->m_mem); + if (parser->m_dtd == NULL) { + FREE(parser, parser->m_dataBuf); + FREE(parser, parser->m_atts); +#ifdef XML_ATTR_INFO + FREE(parser, parser->m_attInfo); +#endif + FREE(parser, parser); + return NULL; + } + } + + parser->m_freeBindingList = NULL; + parser->m_freeTagList = NULL; + parser->m_freeInternalEntities = NULL; + + parser->m_groupSize = 0; + parser->m_groupConnector = NULL; + + parser->m_unknownEncodingHandler = NULL; + parser->m_unknownEncodingHandlerData = NULL; + + parser->m_namespaceSeparator = ASCII_EXCL; + parser->m_ns = XML_FALSE; + parser->m_ns_triplets = XML_FALSE; + + parser->m_nsAtts = NULL; + parser->m_nsAttsVersion = 0; + parser->m_nsAttsPower = 0; + + parser->m_protocolEncodingName = NULL; + + poolInit(&parser->m_tempPool, &(parser->m_mem)); + poolInit(&parser->m_temp2Pool, &(parser->m_mem)); + parserInit(parser, encodingName); + + if (encodingName && !parser->m_protocolEncodingName) { + XML_ParserFree(parser); + return NULL; + } + + if (nameSep) { + parser->m_ns = XML_TRUE; + parser->m_internalEncoding = XmlGetInternalEncodingNS(); + parser->m_namespaceSeparator = *nameSep; + } + else { + parser->m_internalEncoding = XmlGetInternalEncoding(); + } + + return parser; +} + +static void +parserInit(XML_Parser parser, const XML_Char *encodingName) +{ + parser->m_processor = prologInitProcessor; + XmlPrologStateInit(&parser->m_prologState); + if (encodingName != NULL) { + parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem)); + } + parser->m_curBase = NULL; + XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0); + parser->m_userData = NULL; + parser->m_handlerArg = NULL; + parser->m_startElementHandler = NULL; + parser->m_endElementHandler = NULL; + parser->m_characterDataHandler = NULL; + parser->m_processingInstructionHandler = NULL; + parser->m_commentHandler = NULL; + parser->m_startCdataSectionHandler = NULL; + parser->m_endCdataSectionHandler = NULL; + parser->m_defaultHandler = NULL; + parser->m_startDoctypeDeclHandler = NULL; + parser->m_endDoctypeDeclHandler = NULL; + parser->m_unparsedEntityDeclHandler = NULL; + parser->m_notationDeclHandler = NULL; + parser->m_startNamespaceDeclHandler = NULL; + parser->m_endNamespaceDeclHandler = NULL; + parser->m_notStandaloneHandler = NULL; + parser->m_externalEntityRefHandler = NULL; + parser->m_externalEntityRefHandlerArg = parser; + parser->m_skippedEntityHandler = NULL; + parser->m_elementDeclHandler = NULL; + parser->m_attlistDeclHandler = NULL; + parser->m_entityDeclHandler = NULL; + parser->m_xmlDeclHandler = NULL; + parser->m_bufferPtr = parser->m_buffer; + parser->m_bufferEnd = parser->m_buffer; + parser->m_parseEndByteIndex = 0; + parser->m_parseEndPtr = NULL; + parser->m_declElementType = NULL; + parser->m_declAttributeId = NULL; + parser->m_declEntity = NULL; + parser->m_doctypeName = NULL; + parser->m_doctypeSysid = NULL; + parser->m_doctypePubid = NULL; + parser->m_declAttributeType = NULL; + parser->m_declNotationName = NULL; + parser->m_declNotationPublicId = NULL; + parser->m_declAttributeIsCdata = XML_FALSE; + parser->m_declAttributeIsId = XML_FALSE; + memset(&parser->m_position, 0, sizeof(POSITION)); + parser->m_errorCode = XML_ERROR_NONE; + parser->m_eventPtr = NULL; + parser->m_eventEndPtr = NULL; + parser->m_positionPtr = NULL; + parser->m_openInternalEntities = NULL; + parser->m_defaultExpandInternalEntities = XML_TRUE; + parser->m_tagLevel = 0; + parser->m_tagStack = NULL; + parser->m_inheritedBindings = NULL; + parser->m_nSpecifiedAtts = 0; + parser->m_unknownEncodingMem = NULL; + parser->m_unknownEncodingRelease = NULL; + parser->m_unknownEncodingData = NULL; + parser->m_parentParser = NULL; + parser->m_parsingStatus.parsing = XML_INITIALIZED; +#ifdef XML_DTD + parser->m_isParamEntity = XML_FALSE; + parser->m_useForeignDTD = XML_FALSE; + parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER; +#endif + parser->m_hash_secret_salt = 0; +} + +/* moves list of bindings to m_freeBindingList */ +static void FASTCALL +moveToFreeBindingList(XML_Parser parser, BINDING *bindings) +{ + while (bindings) { + BINDING *b = bindings; + bindings = bindings->nextTagBinding; + b->nextTagBinding = parser->m_freeBindingList; + parser->m_freeBindingList = b; + } +} + +XML_Bool XMLCALL +XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) +{ + TAG *tStk; + OPEN_INTERNAL_ENTITY *openEntityList; + + if (parser == NULL) + return XML_FALSE; + + if (parser->m_parentParser) + return XML_FALSE; + /* move m_tagStack to m_freeTagList */ + tStk = parser->m_tagStack; + while (tStk) { + TAG *tag = tStk; + tStk = tStk->parent; + tag->parent = parser->m_freeTagList; + moveToFreeBindingList(parser, tag->bindings); + tag->bindings = NULL; + parser->m_freeTagList = tag; + } + /* move m_openInternalEntities to m_freeInternalEntities */ + openEntityList = parser->m_openInternalEntities; + while (openEntityList) { + OPEN_INTERNAL_ENTITY *openEntity = openEntityList; + openEntityList = openEntity->next; + openEntity->next = parser->m_freeInternalEntities; + parser->m_freeInternalEntities = openEntity; + } + moveToFreeBindingList(parser, parser->m_inheritedBindings); + FREE(parser, parser->m_unknownEncodingMem); + if (parser->m_unknownEncodingRelease) + parser->m_unknownEncodingRelease(parser->m_unknownEncodingData); + poolClear(&parser->m_tempPool); + poolClear(&parser->m_temp2Pool); + FREE(parser, (void *)parser->m_protocolEncodingName); + parser->m_protocolEncodingName = NULL; + parserInit(parser, encodingName); + dtdReset(parser->m_dtd, &parser->m_mem); + return XML_TRUE; +} + +enum XML_Status XMLCALL +XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) +{ + if (parser == NULL) + return XML_STATUS_ERROR; + /* Block after XML_Parse()/XML_ParseBuffer() has been called. + XXX There's no way for the caller to determine which of the + XXX possible error cases caused the XML_STATUS_ERROR return. + */ + if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED) + return XML_STATUS_ERROR; + + /* Get rid of any previous encoding name */ + FREE(parser, (void *)parser->m_protocolEncodingName); + + if (encodingName == NULL) + /* No new encoding name */ + parser->m_protocolEncodingName = NULL; + else { + /* Copy the new encoding name into allocated memory */ + parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem)); + if (!parser->m_protocolEncodingName) + return XML_STATUS_ERROR; + } + return XML_STATUS_OK; +} + +XML_Parser XMLCALL +XML_ExternalEntityParserCreate(XML_Parser oldParser, + const XML_Char *context, + const XML_Char *encodingName) +{ + XML_Parser parser = oldParser; + DTD *newDtd = NULL; + DTD *oldDtd; + XML_StartElementHandler oldStartElementHandler; + XML_EndElementHandler oldEndElementHandler; + XML_CharacterDataHandler oldCharacterDataHandler; + XML_ProcessingInstructionHandler oldProcessingInstructionHandler; + XML_CommentHandler oldCommentHandler; + XML_StartCdataSectionHandler oldStartCdataSectionHandler; + XML_EndCdataSectionHandler oldEndCdataSectionHandler; + XML_DefaultHandler oldDefaultHandler; + XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler; + XML_NotationDeclHandler oldNotationDeclHandler; + XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler; + XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler; + XML_NotStandaloneHandler oldNotStandaloneHandler; + XML_ExternalEntityRefHandler oldExternalEntityRefHandler; + XML_SkippedEntityHandler oldSkippedEntityHandler; + XML_UnknownEncodingHandler oldUnknownEncodingHandler; + XML_ElementDeclHandler oldElementDeclHandler; + XML_AttlistDeclHandler oldAttlistDeclHandler; + XML_EntityDeclHandler oldEntityDeclHandler; + XML_XmlDeclHandler oldXmlDeclHandler; + ELEMENT_TYPE * oldDeclElementType; + + void *oldUserData; + void *oldHandlerArg; + XML_Bool oldDefaultExpandInternalEntities; + XML_Parser oldExternalEntityRefHandlerArg; +#ifdef XML_DTD + enum XML_ParamEntityParsing oldParamEntityParsing; + int oldInEntityValue; +#endif + XML_Bool oldns_triplets; + /* Note that the new parser shares the same hash secret as the old + parser, so that dtdCopy and copyEntityTable can lookup values + from hash tables associated with either parser without us having + to worry which hash secrets each table has. + */ + unsigned long oldhash_secret_salt; + + /* Validate the oldParser parameter before we pull everything out of it */ + if (oldParser == NULL) + return NULL; + + /* Stash the original parser contents on the stack */ + oldDtd = parser->m_dtd; + oldStartElementHandler = parser->m_startElementHandler; + oldEndElementHandler = parser->m_endElementHandler; + oldCharacterDataHandler = parser->m_characterDataHandler; + oldProcessingInstructionHandler = parser->m_processingInstructionHandler; + oldCommentHandler = parser->m_commentHandler; + oldStartCdataSectionHandler = parser->m_startCdataSectionHandler; + oldEndCdataSectionHandler = parser->m_endCdataSectionHandler; + oldDefaultHandler = parser->m_defaultHandler; + oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler; + oldNotationDeclHandler = parser->m_notationDeclHandler; + oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler; + oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler; + oldNotStandaloneHandler = parser->m_notStandaloneHandler; + oldExternalEntityRefHandler = parser->m_externalEntityRefHandler; + oldSkippedEntityHandler = parser->m_skippedEntityHandler; + oldUnknownEncodingHandler = parser->m_unknownEncodingHandler; + oldElementDeclHandler = parser->m_elementDeclHandler; + oldAttlistDeclHandler = parser->m_attlistDeclHandler; + oldEntityDeclHandler = parser->m_entityDeclHandler; + oldXmlDeclHandler = parser->m_xmlDeclHandler; + oldDeclElementType = parser->m_declElementType; + + oldUserData = parser->m_userData; + oldHandlerArg = parser->m_handlerArg; + oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities; + oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg; +#ifdef XML_DTD + oldParamEntityParsing = parser->m_paramEntityParsing; + oldInEntityValue = parser->m_prologState.inEntityValue; +#endif + oldns_triplets = parser->m_ns_triplets; + /* Note that the new parser shares the same hash secret as the old + parser, so that dtdCopy and copyEntityTable can lookup values + from hash tables associated with either parser without us having + to worry which hash secrets each table has. + */ + oldhash_secret_salt = parser->m_hash_secret_salt; + +#ifdef XML_DTD + if (!context) + newDtd = oldDtd; +#endif /* XML_DTD */ + + /* Note that the magical uses of the pre-processor to make field + access look more like C++ require that `parser' be overwritten + here. This makes this function more painful to follow than it + would be otherwise. + */ + if (parser->m_ns) { + XML_Char tmp[2]; + *tmp = parser->m_namespaceSeparator; + parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd); + } + else { + parser = parserCreate(encodingName, &parser->m_mem, NULL, newDtd); + } + + if (!parser) + return NULL; + + parser->m_startElementHandler = oldStartElementHandler; + parser->m_endElementHandler = oldEndElementHandler; + parser->m_characterDataHandler = oldCharacterDataHandler; + parser->m_processingInstructionHandler = oldProcessingInstructionHandler; + parser->m_commentHandler = oldCommentHandler; + parser->m_startCdataSectionHandler = oldStartCdataSectionHandler; + parser->m_endCdataSectionHandler = oldEndCdataSectionHandler; + parser->m_defaultHandler = oldDefaultHandler; + parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler; + parser->m_notationDeclHandler = oldNotationDeclHandler; + parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler; + parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler; + parser->m_notStandaloneHandler = oldNotStandaloneHandler; + parser->m_externalEntityRefHandler = oldExternalEntityRefHandler; + parser->m_skippedEntityHandler = oldSkippedEntityHandler; + parser->m_unknownEncodingHandler = oldUnknownEncodingHandler; + parser->m_elementDeclHandler = oldElementDeclHandler; + parser->m_attlistDeclHandler = oldAttlistDeclHandler; + parser->m_entityDeclHandler = oldEntityDeclHandler; + parser->m_xmlDeclHandler = oldXmlDeclHandler; + parser->m_declElementType = oldDeclElementType; + parser->m_userData = oldUserData; + if (oldUserData == oldHandlerArg) + parser->m_handlerArg = parser->m_userData; + else + parser->m_handlerArg = parser; + if (oldExternalEntityRefHandlerArg != oldParser) + parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg; + parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities; + parser->m_ns_triplets = oldns_triplets; + parser->m_hash_secret_salt = oldhash_secret_salt; + parser->m_parentParser = oldParser; +#ifdef XML_DTD + parser->m_paramEntityParsing = oldParamEntityParsing; + parser->m_prologState.inEntityValue = oldInEntityValue; + if (context) { +#endif /* XML_DTD */ + if (!dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem) + || !setContext(parser, context)) { + XML_ParserFree(parser); + return NULL; + } + parser->m_processor = externalEntityInitProcessor; +#ifdef XML_DTD + } + else { + /* The DTD instance referenced by parser->m_dtd is shared between the document's + root parser and external PE parsers, therefore one does not need to + call setContext. In addition, one also *must* not call setContext, + because this would overwrite existing prefix->binding pointers in + parser->m_dtd with ones that get destroyed with the external PE parser. + This would leave those prefixes with dangling pointers. + */ + parser->m_isParamEntity = XML_TRUE; + XmlPrologStateInitExternalEntity(&parser->m_prologState); + parser->m_processor = externalParEntInitProcessor; + } +#endif /* XML_DTD */ + return parser; +} + +static void FASTCALL +destroyBindings(BINDING *bindings, XML_Parser parser) +{ + for (;;) { + BINDING *b = bindings; + if (!b) + break; + bindings = b->nextTagBinding; + FREE(parser, b->uri); + FREE(parser, b); + } +} + +void XMLCALL +XML_ParserFree(XML_Parser parser) +{ + TAG *tagList; + OPEN_INTERNAL_ENTITY *entityList; + if (parser == NULL) + return; + /* free m_tagStack and m_freeTagList */ + tagList = parser->m_tagStack; + for (;;) { + TAG *p; + if (tagList == NULL) { + if (parser->m_freeTagList == NULL) + break; + tagList = parser->m_freeTagList; + parser->m_freeTagList = NULL; + } + p = tagList; + tagList = tagList->parent; + FREE(parser, p->buf); + destroyBindings(p->bindings, parser); + FREE(parser, p); + } + /* free m_openInternalEntities and m_freeInternalEntities */ + entityList = parser->m_openInternalEntities; + for (;;) { + OPEN_INTERNAL_ENTITY *openEntity; + if (entityList == NULL) { + if (parser->m_freeInternalEntities == NULL) + break; + entityList = parser->m_freeInternalEntities; + parser->m_freeInternalEntities = NULL; + } + openEntity = entityList; + entityList = entityList->next; + FREE(parser, openEntity); + } + + destroyBindings(parser->m_freeBindingList, parser); + destroyBindings(parser->m_inheritedBindings, parser); + poolDestroy(&parser->m_tempPool); + poolDestroy(&parser->m_temp2Pool); + FREE(parser, (void *)parser->m_protocolEncodingName); +#ifdef XML_DTD + /* external parameter entity parsers share the DTD structure + parser->m_dtd with the root parser, so we must not destroy it + */ + if (!parser->m_isParamEntity && parser->m_dtd) +#else + if (parser->m_dtd) +#endif /* XML_DTD */ + dtdDestroy(parser->m_dtd, (XML_Bool)!parser->m_parentParser, &parser->m_mem); + FREE(parser, (void *)parser->m_atts); +#ifdef XML_ATTR_INFO + FREE(parser, (void *)parser->m_attInfo); +#endif + FREE(parser, parser->m_groupConnector); + FREE(parser, parser->m_buffer); + FREE(parser, parser->m_dataBuf); + FREE(parser, parser->m_nsAtts); + FREE(parser, parser->m_unknownEncodingMem); + if (parser->m_unknownEncodingRelease) + parser->m_unknownEncodingRelease(parser->m_unknownEncodingData); + FREE(parser, parser); +} + +void XMLCALL +XML_UseParserAsHandlerArg(XML_Parser parser) +{ + if (parser != NULL) + parser->m_handlerArg = parser; +} + +enum XML_Error XMLCALL +XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD) +{ + if (parser == NULL) + return XML_ERROR_INVALID_ARGUMENT; +#ifdef XML_DTD + /* block after XML_Parse()/XML_ParseBuffer() has been called */ + if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED) + return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING; + parser->m_useForeignDTD = useDTD; + return XML_ERROR_NONE; +#else + return XML_ERROR_FEATURE_REQUIRES_XML_DTD; +#endif +} + +void XMLCALL +XML_SetReturnNSTriplet(XML_Parser parser, int do_nst) +{ + if (parser == NULL) + return; + /* block after XML_Parse()/XML_ParseBuffer() has been called */ + if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED) + return; + parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE; +} + +void XMLCALL +XML_SetUserData(XML_Parser parser, void *p) +{ + if (parser == NULL) + return; + if (parser->m_handlerArg == parser->m_userData) + parser->m_handlerArg = parser->m_userData = p; + else + parser->m_userData = p; +} + +enum XML_Status XMLCALL +XML_SetBase(XML_Parser parser, const XML_Char *p) +{ + if (parser == NULL) + return XML_STATUS_ERROR; + if (p) { + p = poolCopyString(&parser->m_dtd->pool, p); + if (!p) + return XML_STATUS_ERROR; + parser->m_curBase = p; + } + else + parser->m_curBase = NULL; + return XML_STATUS_OK; +} + +const XML_Char * XMLCALL +XML_GetBase(XML_Parser parser) +{ + if (parser == NULL) + return NULL; + return parser->m_curBase; +} + +int XMLCALL +XML_GetSpecifiedAttributeCount(XML_Parser parser) +{ + if (parser == NULL) + return -1; + return parser->m_nSpecifiedAtts; +} + +int XMLCALL +XML_GetIdAttributeIndex(XML_Parser parser) +{ + if (parser == NULL) + return -1; + return parser->m_idAttIndex; +} + +#ifdef XML_ATTR_INFO +const XML_AttrInfo * XMLCALL +XML_GetAttributeInfo(XML_Parser parser) +{ + if (parser == NULL) + return NULL; + return parser->m_attInfo; +} +#endif + +void XMLCALL +XML_SetElementHandler(XML_Parser parser, + XML_StartElementHandler start, + XML_EndElementHandler end) +{ + if (parser == NULL) + return; + parser->m_startElementHandler = start; + parser->m_endElementHandler = end; +} + +void XMLCALL +XML_SetStartElementHandler(XML_Parser parser, + XML_StartElementHandler start) { + if (parser != NULL) + parser->m_startElementHandler = start; +} + +void XMLCALL +XML_SetEndElementHandler(XML_Parser parser, + XML_EndElementHandler end) { + if (parser != NULL) + parser->m_endElementHandler = end; +} + +void XMLCALL +XML_SetCharacterDataHandler(XML_Parser parser, + XML_CharacterDataHandler handler) +{ + if (parser != NULL) + parser->m_characterDataHandler = handler; +} + +void XMLCALL +XML_SetProcessingInstructionHandler(XML_Parser parser, + XML_ProcessingInstructionHandler handler) +{ + if (parser != NULL) + parser->m_processingInstructionHandler = handler; +} + +void XMLCALL +XML_SetCommentHandler(XML_Parser parser, + XML_CommentHandler handler) +{ + if (parser != NULL) + parser->m_commentHandler = handler; +} + +void XMLCALL +XML_SetCdataSectionHandler(XML_Parser parser, + XML_StartCdataSectionHandler start, + XML_EndCdataSectionHandler end) +{ + if (parser == NULL) + return; + parser->m_startCdataSectionHandler = start; + parser->m_endCdataSectionHandler = end; +} + +void XMLCALL +XML_SetStartCdataSectionHandler(XML_Parser parser, + XML_StartCdataSectionHandler start) { + if (parser != NULL) + parser->m_startCdataSectionHandler = start; +} + +void XMLCALL +XML_SetEndCdataSectionHandler(XML_Parser parser, + XML_EndCdataSectionHandler end) { + if (parser != NULL) + parser->m_endCdataSectionHandler = end; +} + +void XMLCALL +XML_SetDefaultHandler(XML_Parser parser, + XML_DefaultHandler handler) +{ + if (parser == NULL) + return; + parser->m_defaultHandler = handler; + parser->m_defaultExpandInternalEntities = XML_FALSE; +} + +void XMLCALL +XML_SetDefaultHandlerExpand(XML_Parser parser, + XML_DefaultHandler handler) +{ + if (parser == NULL) + return; + parser->m_defaultHandler = handler; + parser->m_defaultExpandInternalEntities = XML_TRUE; +} + +void XMLCALL +XML_SetDoctypeDeclHandler(XML_Parser parser, + XML_StartDoctypeDeclHandler start, + XML_EndDoctypeDeclHandler end) +{ + if (parser == NULL) + return; + parser->m_startDoctypeDeclHandler = start; + parser->m_endDoctypeDeclHandler = end; +} + +void XMLCALL +XML_SetStartDoctypeDeclHandler(XML_Parser parser, + XML_StartDoctypeDeclHandler start) { + if (parser != NULL) + parser->m_startDoctypeDeclHandler = start; +} + +void XMLCALL +XML_SetEndDoctypeDeclHandler(XML_Parser parser, + XML_EndDoctypeDeclHandler end) { + if (parser != NULL) + parser->m_endDoctypeDeclHandler = end; +} + +void XMLCALL +XML_SetUnparsedEntityDeclHandler(XML_Parser parser, + XML_UnparsedEntityDeclHandler handler) +{ + if (parser != NULL) + parser->m_unparsedEntityDeclHandler = handler; +} + +void XMLCALL +XML_SetNotationDeclHandler(XML_Parser parser, + XML_NotationDeclHandler handler) +{ + if (parser != NULL) + parser->m_notationDeclHandler = handler; +} + +void XMLCALL +XML_SetNamespaceDeclHandler(XML_Parser parser, + XML_StartNamespaceDeclHandler start, + XML_EndNamespaceDeclHandler end) +{ + if (parser == NULL) + return; + parser->m_startNamespaceDeclHandler = start; + parser->m_endNamespaceDeclHandler = end; +} + +void XMLCALL +XML_SetStartNamespaceDeclHandler(XML_Parser parser, + XML_StartNamespaceDeclHandler start) { + if (parser != NULL) + parser->m_startNamespaceDeclHandler = start; +} + +void XMLCALL +XML_SetEndNamespaceDeclHandler(XML_Parser parser, + XML_EndNamespaceDeclHandler end) { + if (parser != NULL) + parser->m_endNamespaceDeclHandler = end; +} + +void XMLCALL +XML_SetNotStandaloneHandler(XML_Parser parser, + XML_NotStandaloneHandler handler) +{ + if (parser != NULL) + parser->m_notStandaloneHandler = handler; +} + +void XMLCALL +XML_SetExternalEntityRefHandler(XML_Parser parser, + XML_ExternalEntityRefHandler handler) +{ + if (parser != NULL) + parser->m_externalEntityRefHandler = handler; +} + +void XMLCALL +XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) +{ + if (parser == NULL) + return; + if (arg) + parser->m_externalEntityRefHandlerArg = (XML_Parser)arg; + else + parser->m_externalEntityRefHandlerArg = parser; +} + +void XMLCALL +XML_SetSkippedEntityHandler(XML_Parser parser, + XML_SkippedEntityHandler handler) +{ + if (parser != NULL) + parser->m_skippedEntityHandler = handler; +} + +void XMLCALL +XML_SetUnknownEncodingHandler(XML_Parser parser, + XML_UnknownEncodingHandler handler, + void *data) +{ + if (parser == NULL) + return; + parser->m_unknownEncodingHandler = handler; + parser->m_unknownEncodingHandlerData = data; +} + +void XMLCALL +XML_SetElementDeclHandler(XML_Parser parser, + XML_ElementDeclHandler eldecl) +{ + if (parser != NULL) + parser->m_elementDeclHandler = eldecl; +} + +void XMLCALL +XML_SetAttlistDeclHandler(XML_Parser parser, + XML_AttlistDeclHandler attdecl) +{ + if (parser != NULL) + parser->m_attlistDeclHandler = attdecl; +} + +void XMLCALL +XML_SetEntityDeclHandler(XML_Parser parser, + XML_EntityDeclHandler handler) +{ + if (parser != NULL) + parser->m_entityDeclHandler = handler; +} + +void XMLCALL +XML_SetXmlDeclHandler(XML_Parser parser, + XML_XmlDeclHandler handler) { + if (parser != NULL) + parser->m_xmlDeclHandler = handler; +} + +int XMLCALL +XML_SetParamEntityParsing(XML_Parser parser, + enum XML_ParamEntityParsing peParsing) +{ + if (parser == NULL) + return 0; + /* block after XML_Parse()/XML_ParseBuffer() has been called */ + if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED) + return 0; +#ifdef XML_DTD + parser->m_paramEntityParsing = peParsing; + return 1; +#else + return peParsing == XML_PARAM_ENTITY_PARSING_NEVER; +#endif +} + +int XMLCALL +XML_SetHashSalt(XML_Parser parser, + unsigned long hash_salt) +{ + if (parser == NULL) + return 0; + if (parser->m_parentParser) + return XML_SetHashSalt(parser->m_parentParser, hash_salt); + /* block after XML_Parse()/XML_ParseBuffer() has been called */ + if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED) + return 0; + parser->m_hash_secret_salt = hash_salt; + return 1; +} + +enum XML_Status XMLCALL +XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) +{ + if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) { + if (parser != NULL) + parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT; + return XML_STATUS_ERROR; + } + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + parser->m_errorCode = XML_ERROR_SUSPENDED; + return XML_STATUS_ERROR; + case XML_FINISHED: + parser->m_errorCode = XML_ERROR_FINISHED; + return XML_STATUS_ERROR; + case XML_INITIALIZED: + if (parser->m_parentParser == NULL && !startParsing(parser)) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + return XML_STATUS_ERROR; + } + default: + parser->m_parsingStatus.parsing = XML_PARSING; + } + + if (len == 0) { + parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; + if (!isFinal) + return XML_STATUS_OK; + parser->m_positionPtr = parser->m_bufferPtr; + parser->m_parseEndPtr = parser->m_bufferEnd; + + /* If data are left over from last buffer, and we now know that these + data are the final chunk of input, then we have to check them again + to detect errors based on that fact. + */ + parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr); + + if (parser->m_errorCode == XML_ERROR_NONE) { + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + /* It is hard to be certain, but it seems that this case + * cannot occur. This code is cleaning up a previous parse + * with no new data (since len == 0). Changing the parsing + * state requires getting to execute a handler function, and + * there doesn't seem to be an opportunity for that while in + * this circumstance. + * + * Given the uncertainty, we retain the code but exclude it + * from coverage tests. + * + * LCOV_EXCL_START + */ + XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position); + parser->m_positionPtr = parser->m_bufferPtr; + return XML_STATUS_SUSPENDED; + /* LCOV_EXCL_STOP */ + case XML_INITIALIZED: + case XML_PARSING: + parser->m_parsingStatus.parsing = XML_FINISHED; + /* fall through */ + default: + return XML_STATUS_OK; + } + } + parser->m_eventEndPtr = parser->m_eventPtr; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } +#ifndef XML_CONTEXT_BYTES + else if (parser->m_bufferPtr == parser->m_bufferEnd) { + const char *end; + int nLeftOver; + enum XML_Status result; + /* Detect overflow (a+b > MAX <==> b > MAX-a) */ + if (len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + parser->m_eventPtr = parser->m_eventEndPtr = NULL; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + parser->m_parseEndByteIndex += len; + parser->m_positionPtr = s; + parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; + + parser->m_errorCode = parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end); + + if (parser->m_errorCode != XML_ERROR_NONE) { + parser->m_eventEndPtr = parser->m_eventPtr; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + else { + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + result = XML_STATUS_SUSPENDED; + break; + case XML_INITIALIZED: + case XML_PARSING: + if (isFinal) { + parser->m_parsingStatus.parsing = XML_FINISHED; + return XML_STATUS_OK; + } + /* fall through */ + default: + result = XML_STATUS_OK; + } + } + + XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end, &parser->m_position); + nLeftOver = s + len - end; + if (nLeftOver) { + if (parser->m_buffer == NULL || nLeftOver > parser->m_bufferLim - parser->m_buffer) { + /* avoid _signed_ integer overflow */ + char *temp = NULL; + const int bytesToAllocate = (int)((unsigned)len * 2U); + if (bytesToAllocate > 0) { + temp = (char *)REALLOC(parser, parser->m_buffer, bytesToAllocate); + } + if (temp == NULL) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + parser->m_eventPtr = parser->m_eventEndPtr = NULL; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + parser->m_buffer = temp; + parser->m_bufferLim = parser->m_buffer + bytesToAllocate; + } + memcpy(parser->m_buffer, end, nLeftOver); + } + parser->m_bufferPtr = parser->m_buffer; + parser->m_bufferEnd = parser->m_buffer + nLeftOver; + parser->m_positionPtr = parser->m_bufferPtr; + parser->m_parseEndPtr = parser->m_bufferEnd; + parser->m_eventPtr = parser->m_bufferPtr; + parser->m_eventEndPtr = parser->m_bufferPtr; + return result; + } +#endif /* not defined XML_CONTEXT_BYTES */ + else { + void *buff = XML_GetBuffer(parser, len); + if (buff == NULL) + return XML_STATUS_ERROR; + else { + memcpy(buff, s, len); + return XML_ParseBuffer(parser, len, isFinal); + } + } +} + +enum XML_Status XMLCALL +XML_ParseBuffer(XML_Parser parser, int len, int isFinal) +{ + const char *start; + enum XML_Status result = XML_STATUS_OK; + + if (parser == NULL) + return XML_STATUS_ERROR; + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + parser->m_errorCode = XML_ERROR_SUSPENDED; + return XML_STATUS_ERROR; + case XML_FINISHED: + parser->m_errorCode = XML_ERROR_FINISHED; + return XML_STATUS_ERROR; + case XML_INITIALIZED: + if (parser->m_parentParser == NULL && !startParsing(parser)) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + return XML_STATUS_ERROR; + } + default: + parser->m_parsingStatus.parsing = XML_PARSING; + } + + start = parser->m_bufferPtr; + parser->m_positionPtr = start; + parser->m_bufferEnd += len; + parser->m_parseEndPtr = parser->m_bufferEnd; + parser->m_parseEndByteIndex += len; + parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; + + parser->m_errorCode = parser->m_processor(parser, start, parser->m_parseEndPtr, &parser->m_bufferPtr); + + if (parser->m_errorCode != XML_ERROR_NONE) { + parser->m_eventEndPtr = parser->m_eventPtr; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + else { + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + result = XML_STATUS_SUSPENDED; + break; + case XML_INITIALIZED: + case XML_PARSING: + if (isFinal) { + parser->m_parsingStatus.parsing = XML_FINISHED; + return result; + } + default: ; /* should not happen */ + } + } + + XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position); + parser->m_positionPtr = parser->m_bufferPtr; + return result; +} + +void * XMLCALL +XML_GetBuffer(XML_Parser parser, int len) +{ + if (parser == NULL) + return NULL; + if (len < 0) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + return NULL; + } + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + parser->m_errorCode = XML_ERROR_SUSPENDED; + return NULL; + case XML_FINISHED: + parser->m_errorCode = XML_ERROR_FINISHED; + return NULL; + default: ; + } + + if (len > parser->m_bufferLim - parser->m_bufferEnd) { +#ifdef XML_CONTEXT_BYTES + int keep; +#endif /* defined XML_CONTEXT_BYTES */ + /* Do not invoke signed arithmetic overflow: */ + int neededSize = (int) ((unsigned)len + (unsigned)(parser->m_bufferEnd - parser->m_bufferPtr)); + if (neededSize < 0) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + return NULL; + } +#ifdef XML_CONTEXT_BYTES + keep = (int)(parser->m_bufferPtr - parser->m_buffer); + if (keep > XML_CONTEXT_BYTES) + keep = XML_CONTEXT_BYTES; + neededSize += keep; +#endif /* defined XML_CONTEXT_BYTES */ + if (neededSize <= parser->m_bufferLim - parser->m_buffer) { +#ifdef XML_CONTEXT_BYTES + if (keep < parser->m_bufferPtr - parser->m_buffer) { + int offset = (int)(parser->m_bufferPtr - parser->m_buffer) - keep; + memmove(parser->m_buffer, &parser->m_buffer[offset], parser->m_bufferEnd - parser->m_bufferPtr + keep); + parser->m_bufferEnd -= offset; + parser->m_bufferPtr -= offset; + } +#else + memmove(parser->m_buffer, parser->m_bufferPtr, parser->m_bufferEnd - parser->m_bufferPtr); + parser->m_bufferEnd = parser->m_buffer + (parser->m_bufferEnd - parser->m_bufferPtr); + parser->m_bufferPtr = parser->m_buffer; +#endif /* not defined XML_CONTEXT_BYTES */ + } + else { + char *newBuf; + int bufferSize = (int)(parser->m_bufferLim - parser->m_bufferPtr); + if (bufferSize == 0) + bufferSize = INIT_BUFFER_SIZE; + do { + /* Do not invoke signed arithmetic overflow: */ + bufferSize = (int) (2U * (unsigned) bufferSize); + } while (bufferSize < neededSize && bufferSize > 0); + if (bufferSize <= 0) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + return NULL; + } + newBuf = (char *)MALLOC(parser, bufferSize); + if (newBuf == 0) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + return NULL; + } + parser->m_bufferLim = newBuf + bufferSize; +#ifdef XML_CONTEXT_BYTES + if (parser->m_bufferPtr) { + int keep = (int)(parser->m_bufferPtr - parser->m_buffer); + if (keep > XML_CONTEXT_BYTES) + keep = XML_CONTEXT_BYTES; + memcpy(newBuf, &parser->m_bufferPtr[-keep], parser->m_bufferEnd - parser->m_bufferPtr + keep); + FREE(parser, parser->m_buffer); + parser->m_buffer = newBuf; + parser->m_bufferEnd = parser->m_buffer + (parser->m_bufferEnd - parser->m_bufferPtr) + keep; + parser->m_bufferPtr = parser->m_buffer + keep; + } + else { + parser->m_bufferEnd = newBuf + (parser->m_bufferEnd - parser->m_bufferPtr); + parser->m_bufferPtr = parser->m_buffer = newBuf; + } +#else + if (parser->m_bufferPtr) { + memcpy(newBuf, parser->m_bufferPtr, parser->m_bufferEnd - parser->m_bufferPtr); + FREE(parser, parser->m_buffer); + } + parser->m_bufferEnd = newBuf + (parser->m_bufferEnd - parser->m_bufferPtr); + parser->m_bufferPtr = parser->m_buffer = newBuf; +#endif /* not defined XML_CONTEXT_BYTES */ + } + parser->m_eventPtr = parser->m_eventEndPtr = NULL; + parser->m_positionPtr = NULL; + } + return parser->m_bufferEnd; +} + +enum XML_Status XMLCALL +XML_StopParser(XML_Parser parser, XML_Bool resumable) +{ + if (parser == NULL) + return XML_STATUS_ERROR; + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + if (resumable) { + parser->m_errorCode = XML_ERROR_SUSPENDED; + return XML_STATUS_ERROR; + } + parser->m_parsingStatus.parsing = XML_FINISHED; + break; + case XML_FINISHED: + parser->m_errorCode = XML_ERROR_FINISHED; + return XML_STATUS_ERROR; + default: + if (resumable) { +#ifdef XML_DTD + if (parser->m_isParamEntity) { + parser->m_errorCode = XML_ERROR_SUSPEND_PE; + return XML_STATUS_ERROR; + } +#endif + parser->m_parsingStatus.parsing = XML_SUSPENDED; + } + else + parser->m_parsingStatus.parsing = XML_FINISHED; + } + return XML_STATUS_OK; +} + +enum XML_Status XMLCALL +XML_ResumeParser(XML_Parser parser) +{ + enum XML_Status result = XML_STATUS_OK; + + if (parser == NULL) + return XML_STATUS_ERROR; + if (parser->m_parsingStatus.parsing != XML_SUSPENDED) { + parser->m_errorCode = XML_ERROR_NOT_SUSPENDED; + return XML_STATUS_ERROR; + } + parser->m_parsingStatus.parsing = XML_PARSING; + + parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr); + + if (parser->m_errorCode != XML_ERROR_NONE) { + parser->m_eventEndPtr = parser->m_eventPtr; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + else { + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + result = XML_STATUS_SUSPENDED; + break; + case XML_INITIALIZED: + case XML_PARSING: + if (parser->m_parsingStatus.finalBuffer) { + parser->m_parsingStatus.parsing = XML_FINISHED; + return result; + } + default: ; + } + } + + XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position); + parser->m_positionPtr = parser->m_bufferPtr; + return result; +} + +void XMLCALL +XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status) +{ + if (parser == NULL) + return; + assert(status != NULL); + *status = parser->m_parsingStatus; +} + +enum XML_Error XMLCALL +XML_GetErrorCode(XML_Parser parser) +{ + if (parser == NULL) + return XML_ERROR_INVALID_ARGUMENT; + return parser->m_errorCode; +} + +XML_Index XMLCALL +XML_GetCurrentByteIndex(XML_Parser parser) +{ + if (parser == NULL) + return -1; + if (parser->m_eventPtr) + return (XML_Index)(parser->m_parseEndByteIndex - (parser->m_parseEndPtr - parser->m_eventPtr)); + return -1; +} + +int XMLCALL +XML_GetCurrentByteCount(XML_Parser parser) +{ + if (parser == NULL) + return 0; + if (parser->m_eventEndPtr && parser->m_eventPtr) + return (int)(parser->m_eventEndPtr - parser->m_eventPtr); + return 0; +} + +const char * XMLCALL +XML_GetInputContext(XML_Parser parser, int *offset, int *size) +{ +#ifdef XML_CONTEXT_BYTES + if (parser == NULL) + return NULL; + if (parser->m_eventPtr && parser->m_buffer) { + if (offset != NULL) + *offset = (int)(parser->m_eventPtr - parser->m_buffer); + if (size != NULL) + *size = (int)(parser->m_bufferEnd - parser->m_buffer); + return parser->m_buffer; + } +#else + (void)parser; + (void)offset; + (void)size; +#endif /* defined XML_CONTEXT_BYTES */ + return (char *) 0; +} + +XML_Size XMLCALL +XML_GetCurrentLineNumber(XML_Parser parser) +{ + if (parser == NULL) + return 0; + if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) { + XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position); + parser->m_positionPtr = parser->m_eventPtr; + } + return parser->m_position.lineNumber + 1; +} + +XML_Size XMLCALL +XML_GetCurrentColumnNumber(XML_Parser parser) +{ + if (parser == NULL) + return 0; + if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) { + XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position); + parser->m_positionPtr = parser->m_eventPtr; + } + return parser->m_position.columnNumber; +} + +void XMLCALL +XML_FreeContentModel(XML_Parser parser, XML_Content *model) +{ + if (parser != NULL) + FREE(parser, model); +} + +void * XMLCALL +XML_MemMalloc(XML_Parser parser, size_t size) +{ + if (parser == NULL) + return NULL; + return MALLOC(parser, size); +} + +void * XMLCALL +XML_MemRealloc(XML_Parser parser, void *ptr, size_t size) +{ + if (parser == NULL) + return NULL; + return REALLOC(parser, ptr, size); +} + +void XMLCALL +XML_MemFree(XML_Parser parser, void *ptr) +{ + if (parser != NULL) + FREE(parser, ptr); +} + +void XMLCALL +XML_DefaultCurrent(XML_Parser parser) +{ + if (parser == NULL) + return; + if (parser->m_defaultHandler) { + if (parser->m_openInternalEntities) + reportDefault(parser, + parser->m_internalEncoding, + parser->m_openInternalEntities->internalEventPtr, + parser->m_openInternalEntities->internalEventEndPtr); + else + reportDefault(parser, parser->m_encoding, parser->m_eventPtr, parser->m_eventEndPtr); + } +} + +const XML_LChar * XMLCALL +XML_ErrorString(enum XML_Error code) +{ + switch (code) { + case XML_ERROR_NONE: + return NULL; + case XML_ERROR_NO_MEMORY: + return XML_L("out of memory"); + case XML_ERROR_SYNTAX: + return XML_L("syntax error"); + case XML_ERROR_NO_ELEMENTS: + return XML_L("no element found"); + case XML_ERROR_INVALID_TOKEN: + return XML_L("not well-formed (invalid token)"); + case XML_ERROR_UNCLOSED_TOKEN: + return XML_L("unclosed token"); + case XML_ERROR_PARTIAL_CHAR: + return XML_L("partial character"); + case XML_ERROR_TAG_MISMATCH: + return XML_L("mismatched tag"); + case XML_ERROR_DUPLICATE_ATTRIBUTE: + return XML_L("duplicate attribute"); + case XML_ERROR_JUNK_AFTER_DOC_ELEMENT: + return XML_L("junk after document element"); + case XML_ERROR_PARAM_ENTITY_REF: + return XML_L("illegal parameter entity reference"); + case XML_ERROR_UNDEFINED_ENTITY: + return XML_L("undefined entity"); + case XML_ERROR_RECURSIVE_ENTITY_REF: + return XML_L("recursive entity reference"); + case XML_ERROR_ASYNC_ENTITY: + return XML_L("asynchronous entity"); + case XML_ERROR_BAD_CHAR_REF: + return XML_L("reference to invalid character number"); + case XML_ERROR_BINARY_ENTITY_REF: + return XML_L("reference to binary entity"); + case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: + return XML_L("reference to external entity in attribute"); + case XML_ERROR_MISPLACED_XML_PI: + return XML_L("XML or text declaration not at start of entity"); + case XML_ERROR_UNKNOWN_ENCODING: + return XML_L("unknown encoding"); + case XML_ERROR_INCORRECT_ENCODING: + return XML_L("encoding specified in XML declaration is incorrect"); + case XML_ERROR_UNCLOSED_CDATA_SECTION: + return XML_L("unclosed CDATA section"); + case XML_ERROR_EXTERNAL_ENTITY_HANDLING: + return XML_L("error in processing external entity reference"); + case XML_ERROR_NOT_STANDALONE: + return XML_L("document is not standalone"); + case XML_ERROR_UNEXPECTED_STATE: + return XML_L("unexpected parser state - please send a bug report"); + case XML_ERROR_ENTITY_DECLARED_IN_PE: + return XML_L("entity declared in parameter entity"); + case XML_ERROR_FEATURE_REQUIRES_XML_DTD: + return XML_L("requested feature requires XML_DTD support in Expat"); + case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING: + return XML_L("cannot change setting once parsing has begun"); + /* Added in 1.95.7. */ + case XML_ERROR_UNBOUND_PREFIX: + return XML_L("unbound prefix"); + /* Added in 1.95.8. */ + case XML_ERROR_UNDECLARING_PREFIX: + return XML_L("must not undeclare prefix"); + case XML_ERROR_INCOMPLETE_PE: + return XML_L("incomplete markup in parameter entity"); + case XML_ERROR_XML_DECL: + return XML_L("XML declaration not well-formed"); + case XML_ERROR_TEXT_DECL: + return XML_L("text declaration not well-formed"); + case XML_ERROR_PUBLICID: + return XML_L("illegal character(s) in public id"); + case XML_ERROR_SUSPENDED: + return XML_L("parser suspended"); + case XML_ERROR_NOT_SUSPENDED: + return XML_L("parser not suspended"); + case XML_ERROR_ABORTED: + return XML_L("parsing aborted"); + case XML_ERROR_FINISHED: + return XML_L("parsing finished"); + case XML_ERROR_SUSPEND_PE: + return XML_L("cannot suspend in external parameter entity"); + /* Added in 2.0.0. */ + case XML_ERROR_RESERVED_PREFIX_XML: + return XML_L("reserved prefix (xml) must not be undeclared or bound to another namespace name"); + case XML_ERROR_RESERVED_PREFIX_XMLNS: + return XML_L("reserved prefix (xmlns) must not be declared or undeclared"); + case XML_ERROR_RESERVED_NAMESPACE_URI: + return XML_L("prefix must not be bound to one of the reserved namespace names"); + /* Added in 2.2.5. */ + case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */ + return XML_L("invalid argument"); + } + return NULL; +} + +const XML_LChar * XMLCALL +XML_ExpatVersion(void) { + + /* V1 is used to string-ize the version number. However, it would + string-ize the actual version macro *names* unless we get them + substituted before being passed to V1. CPP is defined to expand + a macro, then rescan for more expansions. Thus, we use V2 to expand + the version macros, then CPP will expand the resulting V1() macro + with the correct numerals. */ + /* ### I'm assuming cpp is portable in this respect... */ + +#define V1(a,b,c) XML_L(#a)XML_L(".")XML_L(#b)XML_L(".")XML_L(#c) +#define V2(a,b,c) XML_L("expat_")V1(a,b,c) + + return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION); + +#undef V1 +#undef V2 +} + +XML_Expat_Version XMLCALL +XML_ExpatVersionInfo(void) +{ + XML_Expat_Version version; + + version.major = XML_MAJOR_VERSION; + version.minor = XML_MINOR_VERSION; + version.micro = XML_MICRO_VERSION; + + return version; +} + +const XML_Feature * XMLCALL +XML_GetFeatureList(void) +{ + static const XML_Feature features[] = { + {XML_FEATURE_SIZEOF_XML_CHAR, XML_L("sizeof(XML_Char)"), + sizeof(XML_Char)}, + {XML_FEATURE_SIZEOF_XML_LCHAR, XML_L("sizeof(XML_LChar)"), + sizeof(XML_LChar)}, +#ifdef XML_UNICODE + {XML_FEATURE_UNICODE, XML_L("XML_UNICODE"), 0}, +#endif +#ifdef XML_UNICODE_WCHAR_T + {XML_FEATURE_UNICODE_WCHAR_T, XML_L("XML_UNICODE_WCHAR_T"), 0}, +#endif +#ifdef XML_DTD + {XML_FEATURE_DTD, XML_L("XML_DTD"), 0}, +#endif +#ifdef XML_CONTEXT_BYTES + {XML_FEATURE_CONTEXT_BYTES, XML_L("XML_CONTEXT_BYTES"), + XML_CONTEXT_BYTES}, +#endif +#ifdef XML_MIN_SIZE + {XML_FEATURE_MIN_SIZE, XML_L("XML_MIN_SIZE"), 0}, +#endif +#ifdef XML_NS + {XML_FEATURE_NS, XML_L("XML_NS"), 0}, +#endif +#ifdef XML_LARGE_SIZE + {XML_FEATURE_LARGE_SIZE, XML_L("XML_LARGE_SIZE"), 0}, +#endif +#ifdef XML_ATTR_INFO + {XML_FEATURE_ATTR_INFO, XML_L("XML_ATTR_INFO"), 0}, +#endif + {XML_FEATURE_END, NULL, 0} + }; + + return features; +} + +/* Initially tag->rawName always points into the parse buffer; + for those TAG instances opened while the current parse buffer was + processed, and not yet closed, we need to store tag->rawName in a more + permanent location, since the parse buffer is about to be discarded. +*/ +static XML_Bool +storeRawNames(XML_Parser parser) +{ + TAG *tag = parser->m_tagStack; + while (tag) { + int bufSize; + int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1); + char *rawNameBuf = tag->buf + nameLen; + /* Stop if already stored. Since m_tagStack is a stack, we can stop + at the first entry that has already been copied; everything + below it in the stack is already been accounted for in a + previous call to this function. + */ + if (tag->rawName == rawNameBuf) + break; + /* For re-use purposes we need to ensure that the + size of tag->buf is a multiple of sizeof(XML_Char). + */ + bufSize = nameLen + ROUND_UP(tag->rawNameLength, sizeof(XML_Char)); + if (bufSize > tag->bufEnd - tag->buf) { + char *temp = (char *)REALLOC(parser, tag->buf, bufSize); + if (temp == NULL) + return XML_FALSE; + /* if tag->name.str points to tag->buf (only when namespace + processing is off) then we have to update it + */ + if (tag->name.str == (XML_Char *)tag->buf) + tag->name.str = (XML_Char *)temp; + /* if tag->name.localPart is set (when namespace processing is on) + then update it as well, since it will always point into tag->buf + */ + if (tag->name.localPart) + tag->name.localPart = (XML_Char *)temp + (tag->name.localPart - + (XML_Char *)tag->buf); + tag->buf = temp; + tag->bufEnd = temp + bufSize; + rawNameBuf = temp + nameLen; + } + memcpy(rawNameBuf, tag->rawName, tag->rawNameLength); + tag->rawName = rawNameBuf; + tag = tag->parent; + } + return XML_TRUE; +} + +static enum XML_Error PTRCALL +contentProcessor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + enum XML_Error result = doContent(parser, 0, parser->m_encoding, start, end, + endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + if (result == XML_ERROR_NONE) { + if (!storeRawNames(parser)) + return XML_ERROR_NO_MEMORY; + } + return result; +} + +static enum XML_Error PTRCALL +externalEntityInitProcessor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + enum XML_Error result = initializeEncoding(parser); + if (result != XML_ERROR_NONE) + return result; + parser->m_processor = externalEntityInitProcessor2; + return externalEntityInitProcessor2(parser, start, end, endPtr); +} + +static enum XML_Error PTRCALL +externalEntityInitProcessor2(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + const char *next = start; /* XmlContentTok doesn't always set the last arg */ + int tok = XmlContentTok(parser->m_encoding, start, end, &next); + switch (tok) { + case XML_TOK_BOM: + /* If we are at the end of the buffer, this would cause the next stage, + i.e. externalEntityInitProcessor3, to pass control directly to + doContent (by detecting XML_TOK_NONE) without processing any xml text + declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent. + */ + if (next == end && !parser->m_parsingStatus.finalBuffer) { + *endPtr = next; + return XML_ERROR_NONE; + } + start = next; + break; + case XML_TOK_PARTIAL: + if (!parser->m_parsingStatus.finalBuffer) { + *endPtr = start; + return XML_ERROR_NONE; + } + parser->m_eventPtr = start; + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (!parser->m_parsingStatus.finalBuffer) { + *endPtr = start; + return XML_ERROR_NONE; + } + parser->m_eventPtr = start; + return XML_ERROR_PARTIAL_CHAR; + } + parser->m_processor = externalEntityInitProcessor3; + return externalEntityInitProcessor3(parser, start, end, endPtr); +} + +static enum XML_Error PTRCALL +externalEntityInitProcessor3(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + int tok; + const char *next = start; /* XmlContentTok doesn't always set the last arg */ + parser->m_eventPtr = start; + tok = XmlContentTok(parser->m_encoding, start, end, &next); + parser->m_eventEndPtr = next; + + switch (tok) { + case XML_TOK_XML_DECL: + { + enum XML_Error result; + result = processXmlDecl(parser, 1, start, next); + if (result != XML_ERROR_NONE) + return result; + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + *endPtr = next; + return XML_ERROR_NONE; + case XML_FINISHED: + return XML_ERROR_ABORTED; + default: + start = next; + } + } + break; + case XML_TOK_PARTIAL: + if (!parser->m_parsingStatus.finalBuffer) { + *endPtr = start; + return XML_ERROR_NONE; + } + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (!parser->m_parsingStatus.finalBuffer) { + *endPtr = start; + return XML_ERROR_NONE; + } + return XML_ERROR_PARTIAL_CHAR; + } + parser->m_processor = externalEntityContentProcessor; + parser->m_tagLevel = 1; + return externalEntityContentProcessor(parser, start, end, endPtr); +} + +static enum XML_Error PTRCALL +externalEntityContentProcessor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + enum XML_Error result = doContent(parser, 1, parser->m_encoding, start, end, + endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + if (result == XML_ERROR_NONE) { + if (!storeRawNames(parser)) + return XML_ERROR_NO_MEMORY; + } + return result; +} + +static enum XML_Error +doContent(XML_Parser parser, + int startTagLevel, + const ENCODING *enc, + const char *s, + const char *end, + const char **nextPtr, + XML_Bool haveMore) +{ + /* save one level of indirection */ + DTD * const dtd = parser->m_dtd; + + const char **eventPP; + const char **eventEndPP; + if (enc == parser->m_encoding) { + eventPP = &parser->m_eventPtr; + eventEndPP = &parser->m_eventEndPtr; + } + else { + eventPP = &(parser->m_openInternalEntities->internalEventPtr); + eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); + } + *eventPP = s; + + for (;;) { + const char *next = s; /* XmlContentTok doesn't always set the last arg */ + int tok = XmlContentTok(enc, s, end, &next); + *eventEndPP = next; + switch (tok) { + case XML_TOK_TRAILING_CR: + if (haveMore) { + *nextPtr = s; + return XML_ERROR_NONE; + } + *eventEndPP = end; + if (parser->m_characterDataHandler) { + XML_Char c = 0xA; + parser->m_characterDataHandler(parser->m_handlerArg, &c, 1); + } + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, end); + /* We are at the end of the final buffer, should we check for + XML_SUSPENDED, XML_FINISHED? + */ + if (startTagLevel == 0) + return XML_ERROR_NO_ELEMENTS; + if (parser->m_tagLevel != startTagLevel) + return XML_ERROR_ASYNC_ENTITY; + *nextPtr = end; + return XML_ERROR_NONE; + case XML_TOK_NONE: + if (haveMore) { + *nextPtr = s; + return XML_ERROR_NONE; + } + if (startTagLevel > 0) { + if (parser->m_tagLevel != startTagLevel) + return XML_ERROR_ASYNC_ENTITY; + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_NO_ELEMENTS; + case XML_TOK_INVALID: + *eventPP = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: + if (haveMore) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (haveMore) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_ENTITY_REF: + { + const XML_Char *name; + ENTITY *entity; + XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (ch) { + if (parser->m_characterDataHandler) + parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1); + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + } + name = poolStoreString(&dtd->pool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!name) + return XML_ERROR_NO_MEMORY; + entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0); + poolDiscard(&dtd->pool); + /* First, determine if a check for an existing declaration is needed; + if yes, check that the entity exists, and that it is internal, + otherwise call the skipped entity or default handler. + */ + if (!dtd->hasParamEntityRefs || dtd->standalone) { + if (!entity) + return XML_ERROR_UNDEFINED_ENTITY; + else if (!entity->is_internal) + return XML_ERROR_ENTITY_DECLARED_IN_PE; + } + else if (!entity) { + if (parser->m_skippedEntityHandler) + parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0); + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + } + if (entity->open) + return XML_ERROR_RECURSIVE_ENTITY_REF; + if (entity->notation) + return XML_ERROR_BINARY_ENTITY_REF; + if (entity->textPtr) { + enum XML_Error result; + if (!parser->m_defaultExpandInternalEntities) { + if (parser->m_skippedEntityHandler) + parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name, 0); + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + } + result = processInternalEntity(parser, entity, XML_FALSE); + if (result != XML_ERROR_NONE) + return result; + } + else if (parser->m_externalEntityRefHandler) { + const XML_Char *context; + entity->open = XML_TRUE; + context = getContext(parser); + entity->open = XML_FALSE; + if (!context) + return XML_ERROR_NO_MEMORY; + if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg, + context, + entity->base, + entity->systemId, + entity->publicId)) + return XML_ERROR_EXTERNAL_ENTITY_HANDLING; + poolDiscard(&parser->m_tempPool); + } + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + } + case XML_TOK_START_TAG_NO_ATTS: + /* fall through */ + case XML_TOK_START_TAG_WITH_ATTS: + { + TAG *tag; + enum XML_Error result; + XML_Char *toPtr; + if (parser->m_freeTagList) { + tag = parser->m_freeTagList; + parser->m_freeTagList = parser->m_freeTagList->parent; + } + else { + tag = (TAG *)MALLOC(parser, sizeof(TAG)); + if (!tag) + return XML_ERROR_NO_MEMORY; + tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE); + if (!tag->buf) { + FREE(parser, tag); + return XML_ERROR_NO_MEMORY; + } + tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE; + } + tag->bindings = NULL; + tag->parent = parser->m_tagStack; + parser->m_tagStack = tag; + tag->name.localPart = NULL; + tag->name.prefix = NULL; + tag->rawName = s + enc->minBytesPerChar; + tag->rawNameLength = XmlNameLength(enc, tag->rawName); + ++parser->m_tagLevel; + { + const char *rawNameEnd = tag->rawName + tag->rawNameLength; + const char *fromPtr = tag->rawName; + toPtr = (XML_Char *)tag->buf; + for (;;) { + int bufSize; + int convLen; + const enum XML_Convert_Result convert_res = XmlConvert(enc, + &fromPtr, rawNameEnd, + (ICHAR **)&toPtr, (ICHAR *)tag->bufEnd - 1); + convLen = (int)(toPtr - (XML_Char *)tag->buf); + if ((fromPtr >= rawNameEnd) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) { + tag->name.strLen = convLen; + break; + } + bufSize = (int)(tag->bufEnd - tag->buf) << 1; + { + char *temp = (char *)REALLOC(parser, tag->buf, bufSize); + if (temp == NULL) + return XML_ERROR_NO_MEMORY; + tag->buf = temp; + tag->bufEnd = temp + bufSize; + toPtr = (XML_Char *)temp + convLen; + } + } + } + tag->name.str = (XML_Char *)tag->buf; + *toPtr = XML_T('\0'); + result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings)); + if (result) + return result; + if (parser->m_startElementHandler) + parser->m_startElementHandler(parser->m_handlerArg, tag->name.str, + (const XML_Char **)parser->m_atts); + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + poolClear(&parser->m_tempPool); + break; + } + case XML_TOK_EMPTY_ELEMENT_NO_ATTS: + /* fall through */ + case XML_TOK_EMPTY_ELEMENT_WITH_ATTS: + { + const char *rawName = s + enc->minBytesPerChar; + enum XML_Error result; + BINDING *bindings = NULL; + XML_Bool noElmHandlers = XML_TRUE; + TAG_NAME name; + name.str = poolStoreString(&parser->m_tempPool, enc, rawName, + rawName + XmlNameLength(enc, rawName)); + if (!name.str) + return XML_ERROR_NO_MEMORY; + poolFinish(&parser->m_tempPool); + result = storeAtts(parser, enc, s, &name, &bindings); + if (result != XML_ERROR_NONE) { + freeBindings(parser, bindings); + return result; + } + poolFinish(&parser->m_tempPool); + if (parser->m_startElementHandler) { + parser->m_startElementHandler(parser->m_handlerArg, name.str, (const XML_Char **)parser->m_atts); + noElmHandlers = XML_FALSE; + } + if (parser->m_endElementHandler) { + if (parser->m_startElementHandler) + *eventPP = *eventEndPP; + parser->m_endElementHandler(parser->m_handlerArg, name.str); + noElmHandlers = XML_FALSE; + } + if (noElmHandlers && parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + poolClear(&parser->m_tempPool); + freeBindings(parser, bindings); + } + if ((parser->m_tagLevel == 0) && + !((parser->m_parsingStatus.parsing == XML_FINISHED) || (parser->m_parsingStatus.parsing == XML_SUSPENDED))) { + return epilogProcessor(parser, next, end, nextPtr); + } + break; + case XML_TOK_END_TAG: + if (parser->m_tagLevel == startTagLevel) + return XML_ERROR_ASYNC_ENTITY; + else { + int len; + const char *rawName; + TAG *tag = parser->m_tagStack; + parser->m_tagStack = tag->parent; + tag->parent = parser->m_freeTagList; + parser->m_freeTagList = tag; + rawName = s + enc->minBytesPerChar*2; + len = XmlNameLength(enc, rawName); + if (len != tag->rawNameLength + || memcmp(tag->rawName, rawName, len) != 0) { + *eventPP = rawName; + return XML_ERROR_TAG_MISMATCH; + } + --parser->m_tagLevel; + if (parser->m_endElementHandler) { + const XML_Char *localPart; + const XML_Char *prefix; + XML_Char *uri; + localPart = tag->name.localPart; + if (parser->m_ns && localPart) { + /* localPart and prefix may have been overwritten in + tag->name.str, since this points to the binding->uri + buffer which gets re-used; so we have to add them again + */ + uri = (XML_Char *)tag->name.str + tag->name.uriLen; + /* don't need to check for space - already done in storeAtts() */ + while (*localPart) *uri++ = *localPart++; + prefix = (XML_Char *)tag->name.prefix; + if (parser->m_ns_triplets && prefix) { + *uri++ = parser->m_namespaceSeparator; + while (*prefix) *uri++ = *prefix++; + } + *uri = XML_T('\0'); + } + parser->m_endElementHandler(parser->m_handlerArg, tag->name.str); + } + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + while (tag->bindings) { + BINDING *b = tag->bindings; + if (parser->m_endNamespaceDeclHandler) + parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name); + tag->bindings = tag->bindings->nextTagBinding; + b->nextTagBinding = parser->m_freeBindingList; + parser->m_freeBindingList = b; + b->prefix->binding = b->prevPrefixBinding; + } + if (parser->m_tagLevel == 0) + return epilogProcessor(parser, next, end, nextPtr); + } + break; + case XML_TOK_CHAR_REF: + { + int n = XmlCharRefNumber(enc, s); + if (n < 0) + return XML_ERROR_BAD_CHAR_REF; + if (parser->m_characterDataHandler) { + XML_Char buf[XML_ENCODE_MAX]; + parser->m_characterDataHandler(parser->m_handlerArg, buf, XmlEncode(n, (ICHAR *)buf)); + } + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + } + break; + case XML_TOK_XML_DECL: + return XML_ERROR_MISPLACED_XML_PI; + case XML_TOK_DATA_NEWLINE: + if (parser->m_characterDataHandler) { + XML_Char c = 0xA; + parser->m_characterDataHandler(parser->m_handlerArg, &c, 1); + } + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + case XML_TOK_CDATA_SECT_OPEN: + { + enum XML_Error result; + if (parser->m_startCdataSectionHandler) + parser->m_startCdataSectionHandler(parser->m_handlerArg); +#if 0 + /* Suppose you doing a transformation on a document that involves + changing only the character data. You set up a defaultHandler + and a characterDataHandler. The defaultHandler simply copies + characters through. The characterDataHandler does the + transformation and writes the characters out escaping them as + necessary. This case will fail to work if we leave out the + following two lines (because & and < inside CDATA sections will + be incorrectly escaped). + + However, now we have a start/endCdataSectionHandler, so it seems + easier to let the user deal with this. + */ + else if (parser->m_characterDataHandler) + parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0); +#endif + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + result = doCdataSection(parser, enc, &next, end, nextPtr, haveMore); + if (result != XML_ERROR_NONE) + return result; + else if (!next) { + parser->m_processor = cdataSectionProcessor; + return result; + } + } + break; + case XML_TOK_TRAILING_RSQB: + if (haveMore) { + *nextPtr = s; + return XML_ERROR_NONE; + } + if (parser->m_characterDataHandler) { + if (MUST_CONVERT(enc, s)) { + ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf; + XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd); + parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, + (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); + } + else + parser->m_characterDataHandler(parser->m_handlerArg, + (XML_Char *)s, + (int)((XML_Char *)end - (XML_Char *)s)); + } + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, end); + /* We are at the end of the final buffer, should we check for + XML_SUSPENDED, XML_FINISHED? + */ + if (startTagLevel == 0) { + *eventPP = end; + return XML_ERROR_NO_ELEMENTS; + } + if (parser->m_tagLevel != startTagLevel) { + *eventPP = end; + return XML_ERROR_ASYNC_ENTITY; + } + *nextPtr = end; + return XML_ERROR_NONE; + case XML_TOK_DATA_CHARS: + { + XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler; + if (charDataHandler) { + if (MUST_CONVERT(enc, s)) { + for (;;) { + ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf; + const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd); + *eventEndPP = s; + charDataHandler(parser->m_handlerArg, parser->m_dataBuf, + (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); + if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) + break; + *eventPP = s; + } + } + else + charDataHandler(parser->m_handlerArg, + (XML_Char *)s, + (int)((XML_Char *)next - (XML_Char *)s)); + } + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + } + break; + case XML_TOK_PI: + if (!reportProcessingInstruction(parser, enc, s, next)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_COMMENT: + if (!reportComment(parser, enc, s, next)) + return XML_ERROR_NO_MEMORY; + break; + default: + /* All of the tokens produced by XmlContentTok() have their own + * explicit cases, so this default is not strictly necessary. + * However it is a useful safety net, so we retain the code and + * simply exclude it from the coverage tests. + * + * LCOV_EXCL_START + */ + if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + /* LCOV_EXCL_STOP */ + } + *eventPP = s = next; + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + *nextPtr = next; + return XML_ERROR_NONE; + case XML_FINISHED: + return XML_ERROR_ABORTED; + default: ; + } + } + /* not reached */ +} + +/* This function does not call free() on the allocated memory, merely + * moving it to the parser's m_freeBindingList where it can be freed or + * reused as appropriate. + */ +static void +freeBindings(XML_Parser parser, BINDING *bindings) +{ + while (bindings) { + BINDING *b = bindings; + + /* m_startNamespaceDeclHandler will have been called for this + * binding in addBindings(), so call the end handler now. + */ + if (parser->m_endNamespaceDeclHandler) + parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name); + + bindings = bindings->nextTagBinding; + b->nextTagBinding = parser->m_freeBindingList; + parser->m_freeBindingList = b; + b->prefix->binding = b->prevPrefixBinding; + } +} + +/* Precondition: all arguments must be non-NULL; + Purpose: + - normalize attributes + - check attributes for well-formedness + - generate namespace aware attribute names (URI, prefix) + - build list of attributes for startElementHandler + - default attributes + - process namespace declarations (check and report them) + - generate namespace aware element name (URI, prefix) +*/ +static enum XML_Error +storeAtts(XML_Parser parser, const ENCODING *enc, + const char *attStr, TAG_NAME *tagNamePtr, + BINDING **bindingsPtr) +{ + DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + ELEMENT_TYPE *elementType; + int nDefaultAtts; + const XML_Char **appAtts; /* the attribute list for the application */ + int attIndex = 0; + int prefixLen; + int i; + int n; + XML_Char *uri; + int nPrefixes = 0; + BINDING *binding; + const XML_Char *localPart; + + /* lookup the element type name */ + elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str,0); + if (!elementType) { + const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str); + if (!name) + return XML_ERROR_NO_MEMORY; + elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name, + sizeof(ELEMENT_TYPE)); + if (!elementType) + return XML_ERROR_NO_MEMORY; + if (parser->m_ns && !setElementTypePrefix(parser, elementType)) + return XML_ERROR_NO_MEMORY; + } + nDefaultAtts = elementType->nDefaultAtts; + + /* get the attributes from the tokenizer */ + n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts); + if (n + nDefaultAtts > parser->m_attsSize) { + int oldAttsSize = parser->m_attsSize; + ATTRIBUTE *temp; +#ifdef XML_ATTR_INFO + XML_AttrInfo *temp2; +#endif + parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE; + temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts, parser->m_attsSize * sizeof(ATTRIBUTE)); + if (temp == NULL) { + parser->m_attsSize = oldAttsSize; + return XML_ERROR_NO_MEMORY; + } + parser->m_atts = temp; +#ifdef XML_ATTR_INFO + temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo, parser->m_attsSize * sizeof(XML_AttrInfo)); + if (temp2 == NULL) { + parser->m_attsSize = oldAttsSize; + return XML_ERROR_NO_MEMORY; + } + parser->m_attInfo = temp2; +#endif + if (n > oldAttsSize) + XmlGetAttributes(enc, attStr, n, parser->m_atts); + } + + appAtts = (const XML_Char **)parser->m_atts; + for (i = 0; i < n; i++) { + ATTRIBUTE *currAtt = &parser->m_atts[i]; +#ifdef XML_ATTR_INFO + XML_AttrInfo *currAttInfo = &parser->m_attInfo[i]; +#endif + /* add the name and value to the attribute list */ + ATTRIBUTE_ID *attId = getAttributeId(parser, enc, currAtt->name, + currAtt->name + + XmlNameLength(enc, currAtt->name)); + if (!attId) + return XML_ERROR_NO_MEMORY; +#ifdef XML_ATTR_INFO + currAttInfo->nameStart = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name); + currAttInfo->nameEnd = currAttInfo->nameStart + + XmlNameLength(enc, currAtt->name); + currAttInfo->valueStart = parser->m_parseEndByteIndex - + (parser->m_parseEndPtr - currAtt->valuePtr); + currAttInfo->valueEnd = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->valueEnd); +#endif + /* Detect duplicate attributes by their QNames. This does not work when + namespace processing is turned on and different prefixes for the same + namespace are used. For this case we have a check further down. + */ + if ((attId->name)[-1]) { + if (enc == parser->m_encoding) + parser->m_eventPtr = parser->m_atts[i].name; + return XML_ERROR_DUPLICATE_ATTRIBUTE; + } + (attId->name)[-1] = 1; + appAtts[attIndex++] = attId->name; + if (!parser->m_atts[i].normalized) { + enum XML_Error result; + XML_Bool isCdata = XML_TRUE; + + /* figure out whether declared as other than CDATA */ + if (attId->maybeTokenized) { + int j; + for (j = 0; j < nDefaultAtts; j++) { + if (attId == elementType->defaultAtts[j].id) { + isCdata = elementType->defaultAtts[j].isCdata; + break; + } + } + } + + /* normalize the attribute value */ + result = storeAttributeValue(parser, enc, isCdata, + parser->m_atts[i].valuePtr, parser->m_atts[i].valueEnd, + &parser->m_tempPool); + if (result) + return result; + appAtts[attIndex] = poolStart(&parser->m_tempPool); + poolFinish(&parser->m_tempPool); + } + else { + /* the value did not need normalizing */ + appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc, parser->m_atts[i].valuePtr, + parser->m_atts[i].valueEnd); + if (appAtts[attIndex] == 0) + return XML_ERROR_NO_MEMORY; + poolFinish(&parser->m_tempPool); + } + /* handle prefixed attribute names */ + if (attId->prefix) { + if (attId->xmlns) { + /* deal with namespace declarations here */ + enum XML_Error result = addBinding(parser, attId->prefix, attId, + appAtts[attIndex], bindingsPtr); + if (result) + return result; + --attIndex; + } + else { + /* deal with other prefixed names later */ + attIndex++; + nPrefixes++; + (attId->name)[-1] = 2; + } + } + else + attIndex++; + } + + /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */ + parser->m_nSpecifiedAtts = attIndex; + if (elementType->idAtt && (elementType->idAtt->name)[-1]) { + for (i = 0; i < attIndex; i += 2) + if (appAtts[i] == elementType->idAtt->name) { + parser->m_idAttIndex = i; + break; + } + } + else + parser->m_idAttIndex = -1; + + /* do attribute defaulting */ + for (i = 0; i < nDefaultAtts; i++) { + const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i; + if (!(da->id->name)[-1] && da->value) { + if (da->id->prefix) { + if (da->id->xmlns) { + enum XML_Error result = addBinding(parser, da->id->prefix, da->id, + da->value, bindingsPtr); + if (result) + return result; + } + else { + (da->id->name)[-1] = 2; + nPrefixes++; + appAtts[attIndex++] = da->id->name; + appAtts[attIndex++] = da->value; + } + } + else { + (da->id->name)[-1] = 1; + appAtts[attIndex++] = da->id->name; + appAtts[attIndex++] = da->value; + } + } + } + appAtts[attIndex] = 0; + + /* expand prefixed attribute names, check for duplicates, + and clear flags that say whether attributes were specified */ + i = 0; + if (nPrefixes) { + int j; /* hash table index */ + unsigned long version = parser->m_nsAttsVersion; + int nsAttsSize = (int)1 << parser->m_nsAttsPower; + unsigned char oldNsAttsPower = parser->m_nsAttsPower; + /* size of hash table must be at least 2 * (# of prefixed attributes) */ + if ((nPrefixes << 1) >> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */ + NS_ATT *temp; + /* hash table size must also be a power of 2 and >= 8 */ + while (nPrefixes >> parser->m_nsAttsPower++); + if (parser->m_nsAttsPower < 3) + parser->m_nsAttsPower = 3; + nsAttsSize = (int)1 << parser->m_nsAttsPower; + temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts, nsAttsSize * sizeof(NS_ATT)); + if (!temp) { + /* Restore actual size of memory in m_nsAtts */ + parser->m_nsAttsPower = oldNsAttsPower; + return XML_ERROR_NO_MEMORY; + } + parser->m_nsAtts = temp; + version = 0; /* force re-initialization of m_nsAtts hash table */ + } + /* using a version flag saves us from initializing m_nsAtts every time */ + if (!version) { /* initialize version flags when version wraps around */ + version = INIT_ATTS_VERSION; + for (j = nsAttsSize; j != 0; ) + parser->m_nsAtts[--j].version = version; + } + parser->m_nsAttsVersion = --version; + + /* expand prefixed names and check for duplicates */ + for (; i < attIndex; i += 2) { + const XML_Char *s = appAtts[i]; + if (s[-1] == 2) { /* prefixed */ + ATTRIBUTE_ID *id; + const BINDING *b; + unsigned long uriHash; + struct siphash sip_state; + struct sipkey sip_key; + + copy_salt_to_sipkey(parser, &sip_key); + sip24_init(&sip_state, &sip_key); + + ((XML_Char *)s)[-1] = 0; /* clear flag */ + id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0); + if (!id || !id->prefix) { + /* This code is walking through the appAtts array, dealing + * with (in this case) a prefixed attribute name. To be in + * the array, the attribute must have already been bound, so + * has to have passed through the hash table lookup once + * already. That implies that an entry for it already + * exists, so the lookup above will return a pointer to + * already allocated memory. There is no opportunaity for + * the allocator to fail, so the condition above cannot be + * fulfilled. + * + * Since it is difficult to be certain that the above + * analysis is complete, we retain the test and merely + * remove the code from coverage tests. + */ + return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */ + } + b = id->prefix->binding; + if (!b) + return XML_ERROR_UNBOUND_PREFIX; + + for (j = 0; j < b->uriLen; j++) { + const XML_Char c = b->uri[j]; + if (!poolAppendChar(&parser->m_tempPool, c)) + return XML_ERROR_NO_MEMORY; + } + + sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char)); + + while (*s++ != XML_T(ASCII_COLON)) + ; + + sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char)); + + do { /* copies null terminator */ + if (!poolAppendChar(&parser->m_tempPool, *s)) + return XML_ERROR_NO_MEMORY; + } while (*s++); + + uriHash = (unsigned long)sip24_final(&sip_state); + + { /* Check hash table for duplicate of expanded name (uriName). + Derived from code in lookup(parser, HASH_TABLE *table, ...). + */ + unsigned char step = 0; + unsigned long mask = nsAttsSize - 1; + j = uriHash & mask; /* index into hash table */ + while (parser->m_nsAtts[j].version == version) { + /* for speed we compare stored hash values first */ + if (uriHash == parser->m_nsAtts[j].hash) { + const XML_Char *s1 = poolStart(&parser->m_tempPool); + const XML_Char *s2 = parser->m_nsAtts[j].uriName; + /* s1 is null terminated, but not s2 */ + for (; *s1 == *s2 && *s1 != 0; s1++, s2++); + if (*s1 == 0) + return XML_ERROR_DUPLICATE_ATTRIBUTE; + } + if (!step) + step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower); + j < step ? (j += nsAttsSize - step) : (j -= step); + } + } + + if (parser->m_ns_triplets) { /* append namespace separator and prefix */ + parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator; + s = b->prefix->name; + do { + if (!poolAppendChar(&parser->m_tempPool, *s)) + return XML_ERROR_NO_MEMORY; + } while (*s++); + } + + /* store expanded name in attribute list */ + s = poolStart(&parser->m_tempPool); + poolFinish(&parser->m_tempPool); + appAtts[i] = s; + + /* fill empty slot with new version, uriName and hash value */ + parser->m_nsAtts[j].version = version; + parser->m_nsAtts[j].hash = uriHash; + parser->m_nsAtts[j].uriName = s; + + if (!--nPrefixes) { + i += 2; + break; + } + } + else /* not prefixed */ + ((XML_Char *)s)[-1] = 0; /* clear flag */ + } + } + /* clear flags for the remaining attributes */ + for (; i < attIndex; i += 2) + ((XML_Char *)(appAtts[i]))[-1] = 0; + for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding) + binding->attId->name[-1] = 0; + + if (!parser->m_ns) + return XML_ERROR_NONE; + + /* expand the element type name */ + if (elementType->prefix) { + binding = elementType->prefix->binding; + if (!binding) + return XML_ERROR_UNBOUND_PREFIX; + localPart = tagNamePtr->str; + while (*localPart++ != XML_T(ASCII_COLON)) + ; + } + else if (dtd->defaultPrefix.binding) { + binding = dtd->defaultPrefix.binding; + localPart = tagNamePtr->str; + } + else + return XML_ERROR_NONE; + prefixLen = 0; + if (parser->m_ns_triplets && binding->prefix->name) { + for (; binding->prefix->name[prefixLen++];) + ; /* prefixLen includes null terminator */ + } + tagNamePtr->localPart = localPart; + tagNamePtr->uriLen = binding->uriLen; + tagNamePtr->prefix = binding->prefix->name; + tagNamePtr->prefixLen = prefixLen; + for (i = 0; localPart[i++];) + ; /* i includes null terminator */ + n = i + binding->uriLen + prefixLen; + if (n > binding->uriAlloc) { + TAG *p; + uri = (XML_Char *)MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char)); + if (!uri) + return XML_ERROR_NO_MEMORY; + binding->uriAlloc = n + EXPAND_SPARE; + memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char)); + for (p = parser->m_tagStack; p; p = p->parent) + if (p->name.str == binding->uri) + p->name.str = uri; + FREE(parser, binding->uri); + binding->uri = uri; + } + /* if m_namespaceSeparator != '\0' then uri includes it already */ + uri = binding->uri + binding->uriLen; + memcpy(uri, localPart, i * sizeof(XML_Char)); + /* we always have a namespace separator between localPart and prefix */ + if (prefixLen) { + uri += i - 1; + *uri = parser->m_namespaceSeparator; /* replace null terminator */ + memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char)); + } + tagNamePtr->str = binding->uri; + return XML_ERROR_NONE; +} + +/* addBinding() overwrites the value of prefix->binding without checking. + Therefore one must keep track of the old value outside of addBinding(). +*/ +static enum XML_Error +addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, + const XML_Char *uri, BINDING **bindingsPtr) +{ + static const XML_Char xmlNamespace[] = { + ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH, + ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, + ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L, + ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8, ASCII_SLASH, + ASCII_n, ASCII_a, ASCII_m, ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c, + ASCII_e, '\0' + }; + static const int xmlLen = + (int)sizeof(xmlNamespace)/sizeof(XML_Char) - 1; + static const XML_Char xmlnsNamespace[] = { + ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, ASCII_SLASH, + ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, + ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, ASCII_2, ASCII_0, ASCII_0, + ASCII_0, ASCII_SLASH, ASCII_x, ASCII_m, ASCII_l, ASCII_n, ASCII_s, + ASCII_SLASH, '\0' + }; + static const int xmlnsLen = + (int)sizeof(xmlnsNamespace)/sizeof(XML_Char) - 1; + + XML_Bool mustBeXML = XML_FALSE; + XML_Bool isXML = XML_TRUE; + XML_Bool isXMLNS = XML_TRUE; + + BINDING *b; + int len; + + /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */ + if (*uri == XML_T('\0') && prefix->name) + return XML_ERROR_UNDECLARING_PREFIX; + + if (prefix->name + && prefix->name[0] == XML_T(ASCII_x) + && prefix->name[1] == XML_T(ASCII_m) + && prefix->name[2] == XML_T(ASCII_l)) { + + /* Not allowed to bind xmlns */ + if (prefix->name[3] == XML_T(ASCII_n) + && prefix->name[4] == XML_T(ASCII_s) + && prefix->name[5] == XML_T('\0')) + return XML_ERROR_RESERVED_PREFIX_XMLNS; + + if (prefix->name[3] == XML_T('\0')) + mustBeXML = XML_TRUE; + } + + for (len = 0; uri[len]; len++) { + if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len])) + isXML = XML_FALSE; + + if (!mustBeXML && isXMLNS + && (len > xmlnsLen || uri[len] != xmlnsNamespace[len])) + isXMLNS = XML_FALSE; + } + isXML = isXML && len == xmlLen; + isXMLNS = isXMLNS && len == xmlnsLen; + + if (mustBeXML != isXML) + return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML + : XML_ERROR_RESERVED_NAMESPACE_URI; + + if (isXMLNS) + return XML_ERROR_RESERVED_NAMESPACE_URI; + + if (parser->m_namespaceSeparator) + len++; + if (parser->m_freeBindingList) { + b = parser->m_freeBindingList; + if (len > b->uriAlloc) { + XML_Char *temp = (XML_Char *)REALLOC(parser, b->uri, + sizeof(XML_Char) * (len + EXPAND_SPARE)); + if (temp == NULL) + return XML_ERROR_NO_MEMORY; + b->uri = temp; + b->uriAlloc = len + EXPAND_SPARE; + } + parser->m_freeBindingList = b->nextTagBinding; + } + else { + b = (BINDING *)MALLOC(parser, sizeof(BINDING)); + if (!b) + return XML_ERROR_NO_MEMORY; + b->uri = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE)); + if (!b->uri) { + FREE(parser, b); + return XML_ERROR_NO_MEMORY; + } + b->uriAlloc = len + EXPAND_SPARE; + } + b->uriLen = len; + memcpy(b->uri, uri, len * sizeof(XML_Char)); + if (parser->m_namespaceSeparator) + b->uri[len - 1] = parser->m_namespaceSeparator; + b->prefix = prefix; + b->attId = attId; + b->prevPrefixBinding = prefix->binding; + /* NULL binding when default namespace undeclared */ + if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix) + prefix->binding = NULL; + else + prefix->binding = b; + b->nextTagBinding = *bindingsPtr; + *bindingsPtr = b; + /* if attId == NULL then we are not starting a namespace scope */ + if (attId && parser->m_startNamespaceDeclHandler) + parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name, + prefix->binding ? uri : 0); + return XML_ERROR_NONE; +} + +/* The idea here is to avoid using stack for each CDATA section when + the whole file is parsed with one call. +*/ +static enum XML_Error PTRCALL +cdataSectionProcessor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + enum XML_Error result = doCdataSection(parser, parser->m_encoding, &start, end, + endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + if (result != XML_ERROR_NONE) + return result; + if (start) { + if (parser->m_parentParser) { /* we are parsing an external entity */ + parser->m_processor = externalEntityContentProcessor; + return externalEntityContentProcessor(parser, start, end, endPtr); + } + else { + parser->m_processor = contentProcessor; + return contentProcessor(parser, start, end, endPtr); + } + } + return result; +} + +/* startPtr gets set to non-null if the section is closed, and to null if + the section is not yet closed. +*/ +static enum XML_Error +doCdataSection(XML_Parser parser, + const ENCODING *enc, + const char **startPtr, + const char *end, + const char **nextPtr, + XML_Bool haveMore) +{ + const char *s = *startPtr; + const char **eventPP; + const char **eventEndPP; + if (enc == parser->m_encoding) { + eventPP = &parser->m_eventPtr; + *eventPP = s; + eventEndPP = &parser->m_eventEndPtr; + } + else { + eventPP = &(parser->m_openInternalEntities->internalEventPtr); + eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); + } + *eventPP = s; + *startPtr = NULL; + + for (;;) { + const char *next; + int tok = XmlCdataSectionTok(enc, s, end, &next); + *eventEndPP = next; + switch (tok) { + case XML_TOK_CDATA_SECT_CLOSE: + if (parser->m_endCdataSectionHandler) + parser->m_endCdataSectionHandler(parser->m_handlerArg); +#if 0 + /* see comment under XML_TOK_CDATA_SECT_OPEN */ + else if (parser->m_characterDataHandler) + parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0); +#endif + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + *startPtr = next; + *nextPtr = next; + if (parser->m_parsingStatus.parsing == XML_FINISHED) + return XML_ERROR_ABORTED; + else + return XML_ERROR_NONE; + case XML_TOK_DATA_NEWLINE: + if (parser->m_characterDataHandler) { + XML_Char c = 0xA; + parser->m_characterDataHandler(parser->m_handlerArg, &c, 1); + } + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + break; + case XML_TOK_DATA_CHARS: + { + XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler; + if (charDataHandler) { + if (MUST_CONVERT(enc, s)) { + for (;;) { + ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf; + const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd); + *eventEndPP = next; + charDataHandler(parser->m_handlerArg, parser->m_dataBuf, + (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); + if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) + break; + *eventPP = s; + } + } + else + charDataHandler(parser->m_handlerArg, + (XML_Char *)s, + (int)((XML_Char *)next - (XML_Char *)s)); + } + else if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + } + break; + case XML_TOK_INVALID: + *eventPP = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (haveMore) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_PARTIAL: + case XML_TOK_NONE: + if (haveMore) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_UNCLOSED_CDATA_SECTION; + default: + /* Every token returned by XmlCdataSectionTok() has its own + * explicit case, so this default case will never be executed. + * We retain it as a safety net and exclude it from the coverage + * statistics. + * + * LCOV_EXCL_START + */ + *eventPP = next; + return XML_ERROR_UNEXPECTED_STATE; + /* LCOV_EXCL_STOP */ + } + + *eventPP = s = next; + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + *nextPtr = next; + return XML_ERROR_NONE; + case XML_FINISHED: + return XML_ERROR_ABORTED; + default: ; + } + } + /* not reached */ +} + +#ifdef XML_DTD + +/* The idea here is to avoid using stack for each IGNORE section when + the whole file is parsed with one call. +*/ +static enum XML_Error PTRCALL +ignoreSectionProcessor(XML_Parser parser, + const char *start, + const char *end, + const char **endPtr) +{ + enum XML_Error result = doIgnoreSection(parser, parser->m_encoding, &start, end, + endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + if (result != XML_ERROR_NONE) + return result; + if (start) { + parser->m_processor = prologProcessor; + return prologProcessor(parser, start, end, endPtr); + } + return result; +} + +/* startPtr gets set to non-null is the section is closed, and to null + if the section is not yet closed. +*/ +static enum XML_Error +doIgnoreSection(XML_Parser parser, + const ENCODING *enc, + const char **startPtr, + const char *end, + const char **nextPtr, + XML_Bool haveMore) +{ + const char *next; + int tok; + const char *s = *startPtr; + const char **eventPP; + const char **eventEndPP; + if (enc == parser->m_encoding) { + eventPP = &parser->m_eventPtr; + *eventPP = s; + eventEndPP = &parser->m_eventEndPtr; + } + else { + /* It's not entirely clear, but it seems the following two lines + * of code cannot be executed. The only occasions on which 'enc' + * is not 'encoding' are when this function is called + * from the internal entity processing, and IGNORE sections are an + * error in internal entities. + * + * Since it really isn't clear that this is true, we keep the code + * and just remove it from our coverage tests. + * + * LCOV_EXCL_START + */ + eventPP = &(parser->m_openInternalEntities->internalEventPtr); + eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); + /* LCOV_EXCL_STOP */ + } + *eventPP = s; + *startPtr = NULL; + tok = XmlIgnoreSectionTok(enc, s, end, &next); + *eventEndPP = next; + switch (tok) { + case XML_TOK_IGNORE_SECT: + if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + *startPtr = next; + *nextPtr = next; + if (parser->m_parsingStatus.parsing == XML_FINISHED) + return XML_ERROR_ABORTED; + else + return XML_ERROR_NONE; + case XML_TOK_INVALID: + *eventPP = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (haveMore) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_PARTIAL: + case XML_TOK_NONE: + if (haveMore) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */ + default: + /* All of the tokens that XmlIgnoreSectionTok() returns have + * explicit cases to handle them, so this default case is never + * executed. We keep it as a safety net anyway, and remove it + * from our test coverage statistics. + * + * LCOV_EXCL_START + */ + *eventPP = next; + return XML_ERROR_UNEXPECTED_STATE; + /* LCOV_EXCL_STOP */ + } + /* not reached */ +} + +#endif /* XML_DTD */ + +static enum XML_Error +initializeEncoding(XML_Parser parser) +{ + const char *s; +#ifdef XML_UNICODE + char encodingBuf[128]; + /* See comments abount `protoclEncodingName` in parserInit() */ + if (!parser->m_protocolEncodingName) + s = NULL; + else { + int i; + for (i = 0; parser->m_protocolEncodingName[i]; i++) { + if (i == sizeof(encodingBuf) - 1 + || (parser->m_protocolEncodingName[i] & ~0x7f) != 0) { + encodingBuf[0] = '\0'; + break; + } + encodingBuf[i] = (char)parser->m_protocolEncodingName[i]; + } + encodingBuf[i] = '\0'; + s = encodingBuf; + } +#else + s = parser->m_protocolEncodingName; +#endif + if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(&parser->m_initEncoding, &parser->m_encoding, s)) + return XML_ERROR_NONE; + return handleUnknownEncoding(parser, parser->m_protocolEncodingName); +} + +static enum XML_Error +processXmlDecl(XML_Parser parser, int isGeneralTextEntity, + const char *s, const char *next) +{ + const char *encodingName = NULL; + const XML_Char *storedEncName = NULL; + const ENCODING *newEncoding = NULL; + const char *version = NULL; + const char *versionend; + const XML_Char *storedversion = NULL; + int standalone = -1; + if (!(parser->m_ns + ? XmlParseXmlDeclNS + : XmlParseXmlDecl)(isGeneralTextEntity, + parser->m_encoding, + s, + next, + &parser->m_eventPtr, + &version, + &versionend, + &encodingName, + &newEncoding, + &standalone)) { + if (isGeneralTextEntity) + return XML_ERROR_TEXT_DECL; + else + return XML_ERROR_XML_DECL; + } + if (!isGeneralTextEntity && standalone == 1) { + parser->m_dtd->standalone = XML_TRUE; +#ifdef XML_DTD + if (parser->m_paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE) + parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER; +#endif /* XML_DTD */ + } + if (parser->m_xmlDeclHandler) { + if (encodingName != NULL) { + storedEncName = poolStoreString(&parser->m_temp2Pool, + parser->m_encoding, + encodingName, + encodingName + + XmlNameLength(parser->m_encoding, encodingName)); + if (!storedEncName) + return XML_ERROR_NO_MEMORY; + poolFinish(&parser->m_temp2Pool); + } + if (version) { + storedversion = poolStoreString(&parser->m_temp2Pool, + parser->m_encoding, + version, + versionend - parser->m_encoding->minBytesPerChar); + if (!storedversion) + return XML_ERROR_NO_MEMORY; + } + parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName, standalone); + } + else if (parser->m_defaultHandler) + reportDefault(parser, parser->m_encoding, s, next); + if (parser->m_protocolEncodingName == NULL) { + if (newEncoding) { + /* Check that the specified encoding does not conflict with what + * the parser has already deduced. Do we have the same number + * of bytes in the smallest representation of a character? If + * this is UTF-16, is it the same endianness? + */ + if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar + || (newEncoding->minBytesPerChar == 2 && + newEncoding != parser->m_encoding)) { + parser->m_eventPtr = encodingName; + return XML_ERROR_INCORRECT_ENCODING; + } + parser->m_encoding = newEncoding; + } + else if (encodingName) { + enum XML_Error result; + if (!storedEncName) { + storedEncName = poolStoreString( + &parser->m_temp2Pool, parser->m_encoding, encodingName, + encodingName + XmlNameLength(parser->m_encoding, encodingName)); + if (!storedEncName) + return XML_ERROR_NO_MEMORY; + } + result = handleUnknownEncoding(parser, storedEncName); + poolClear(&parser->m_temp2Pool); + if (result == XML_ERROR_UNKNOWN_ENCODING) + parser->m_eventPtr = encodingName; + return result; + } + } + + if (storedEncName || storedversion) + poolClear(&parser->m_temp2Pool); + + return XML_ERROR_NONE; +} + +static enum XML_Error +handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) +{ + if (parser->m_unknownEncodingHandler) { + XML_Encoding info; + int i; + for (i = 0; i < 256; i++) + info.map[i] = -1; + info.convert = NULL; + info.data = NULL; + info.release = NULL; + if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData, encodingName, + &info)) { + ENCODING *enc; + parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding()); + if (!parser->m_unknownEncodingMem) { + if (info.release) + info.release(info.data); + return XML_ERROR_NO_MEMORY; + } + enc = (parser->m_ns + ? XmlInitUnknownEncodingNS + : XmlInitUnknownEncoding)(parser->m_unknownEncodingMem, + info.map, + info.convert, + info.data); + if (enc) { + parser->m_unknownEncodingData = info.data; + parser->m_unknownEncodingRelease = info.release; + parser->m_encoding = enc; + return XML_ERROR_NONE; + } + } + if (info.release != NULL) + info.release(info.data); + } + return XML_ERROR_UNKNOWN_ENCODING; +} + +static enum XML_Error PTRCALL +prologInitProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + enum XML_Error result = initializeEncoding(parser); + if (result != XML_ERROR_NONE) + return result; + parser->m_processor = prologProcessor; + return prologProcessor(parser, s, end, nextPtr); +} + +#ifdef XML_DTD + +static enum XML_Error PTRCALL +externalParEntInitProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + enum XML_Error result = initializeEncoding(parser); + if (result != XML_ERROR_NONE) + return result; + + /* we know now that XML_Parse(Buffer) has been called, + so we consider the external parameter entity read */ + parser->m_dtd->paramEntityRead = XML_TRUE; + + if (parser->m_prologState.inEntityValue) { + parser->m_processor = entityValueInitProcessor; + return entityValueInitProcessor(parser, s, end, nextPtr); + } + else { + parser->m_processor = externalParEntProcessor; + return externalParEntProcessor(parser, s, end, nextPtr); + } +} + +static enum XML_Error PTRCALL +entityValueInitProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + int tok; + const char *start = s; + const char *next = start; + parser->m_eventPtr = start; + + for (;;) { + tok = XmlPrologTok(parser->m_encoding, start, end, &next); + parser->m_eventEndPtr = next; + if (tok <= 0) { + if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { + *nextPtr = s; + return XML_ERROR_NONE; + } + switch (tok) { + case XML_TOK_INVALID: + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_NONE: /* start == end */ + default: + break; + } + /* found end of entity value - can store it now */ + return storeEntityValue(parser, parser->m_encoding, s, end); + } + else if (tok == XML_TOK_XML_DECL) { + enum XML_Error result; + result = processXmlDecl(parser, 0, start, next); + if (result != XML_ERROR_NONE) + return result; + /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For that + * to happen, a parameter entity parsing handler must have + * attempted to suspend the parser, which fails and raises an + * error. The parser can be aborted, but can't be suspended. + */ + if (parser->m_parsingStatus.parsing == XML_FINISHED) + return XML_ERROR_ABORTED; + *nextPtr = next; + /* stop scanning for text declaration - we found one */ + parser->m_processor = entityValueProcessor; + return entityValueProcessor(parser, next, end, nextPtr); + } + /* If we are at the end of the buffer, this would cause XmlPrologTok to + return XML_TOK_NONE on the next call, which would then cause the + function to exit with *nextPtr set to s - that is what we want for other + tokens, but not for the BOM - we would rather like to skip it; + then, when this routine is entered the next time, XmlPrologTok will + return XML_TOK_INVALID, since the BOM is still in the buffer + */ + else if (tok == XML_TOK_BOM && next == end && !parser->m_parsingStatus.finalBuffer) { + *nextPtr = next; + return XML_ERROR_NONE; + } + /* If we get this token, we have the start of what might be a + normal tag, but not a declaration (i.e. it doesn't begin with + "m_eventPtr = start; + } +} + +static enum XML_Error PTRCALL +externalParEntProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + const char *next = s; + int tok; + + tok = XmlPrologTok(parser->m_encoding, s, end, &next); + if (tok <= 0) { + if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { + *nextPtr = s; + return XML_ERROR_NONE; + } + switch (tok) { + case XML_TOK_INVALID: + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_NONE: /* start == end */ + default: + break; + } + } + /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM. + However, when parsing an external subset, doProlog will not accept a BOM + as valid, and report a syntax error, so we have to skip the BOM + */ + else if (tok == XML_TOK_BOM) { + s = next; + tok = XmlPrologTok(parser->m_encoding, s, end, &next); + } + + parser->m_processor = prologProcessor; + return doProlog(parser, parser->m_encoding, s, end, tok, next, + nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); +} + +static enum XML_Error PTRCALL +entityValueProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + const char *start = s; + const char *next = s; + const ENCODING *enc = parser->m_encoding; + int tok; + + for (;;) { + tok = XmlPrologTok(enc, start, end, &next); + if (tok <= 0) { + if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { + *nextPtr = s; + return XML_ERROR_NONE; + } + switch (tok) { + case XML_TOK_INVALID: + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + return XML_ERROR_PARTIAL_CHAR; + case XML_TOK_NONE: /* start == end */ + default: + break; + } + /* found end of entity value - can store it now */ + return storeEntityValue(parser, enc, s, end); + } + start = next; + } +} + +#endif /* XML_DTD */ + +static enum XML_Error PTRCALL +prologProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + const char *next = s; + int tok = XmlPrologTok(parser->m_encoding, s, end, &next); + return doProlog(parser, parser->m_encoding, s, end, tok, next, + nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); +} + +static enum XML_Error +doProlog(XML_Parser parser, + const ENCODING *enc, + const char *s, + const char *end, + int tok, + const char *next, + const char **nextPtr, + XML_Bool haveMore) +{ +#ifdef XML_DTD + static const XML_Char externalSubsetName[] = { ASCII_HASH , '\0' }; +#endif /* XML_DTD */ + static const XML_Char atypeCDATA[] = + { ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' }; + static const XML_Char atypeID[] = { ASCII_I, ASCII_D, '\0' }; + static const XML_Char atypeIDREF[] = + { ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0' }; + static const XML_Char atypeIDREFS[] = + { ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0' }; + static const XML_Char atypeENTITY[] = + { ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0' }; + static const XML_Char atypeENTITIES[] = { ASCII_E, ASCII_N, + ASCII_T, ASCII_I, ASCII_T, ASCII_I, ASCII_E, ASCII_S, '\0' }; + static const XML_Char atypeNMTOKEN[] = { + ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0' }; + static const XML_Char atypeNMTOKENS[] = { ASCII_N, ASCII_M, ASCII_T, + ASCII_O, ASCII_K, ASCII_E, ASCII_N, ASCII_S, '\0' }; + static const XML_Char notationPrefix[] = { ASCII_N, ASCII_O, ASCII_T, + ASCII_A, ASCII_T, ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0' }; + static const XML_Char enumValueSep[] = { ASCII_PIPE, '\0' }; + static const XML_Char enumValueStart[] = { ASCII_LPAREN, '\0' }; + + /* save one level of indirection */ + DTD * const dtd = parser->m_dtd; + + const char **eventPP; + const char **eventEndPP; + enum XML_Content_Quant quant; + + if (enc == parser->m_encoding) { + eventPP = &parser->m_eventPtr; + eventEndPP = &parser->m_eventEndPtr; + } + else { + eventPP = &(parser->m_openInternalEntities->internalEventPtr); + eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); + } + + for (;;) { + int role; + XML_Bool handleDefault = XML_TRUE; + *eventPP = s; + *eventEndPP = next; + if (tok <= 0) { + if (haveMore && tok != XML_TOK_INVALID) { + *nextPtr = s; + return XML_ERROR_NONE; + } + switch (tok) { + case XML_TOK_INVALID: + *eventPP = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + return XML_ERROR_PARTIAL_CHAR; + case -XML_TOK_PROLOG_S: + tok = -tok; + break; + case XML_TOK_NONE: +#ifdef XML_DTD + /* for internal PE NOT referenced between declarations */ + if (enc != parser->m_encoding && !parser->m_openInternalEntities->betweenDecl) { + *nextPtr = s; + return XML_ERROR_NONE; + } + /* WFC: PE Between Declarations - must check that PE contains + complete markup, not only for external PEs, but also for + internal PEs if the reference occurs between declarations. + */ + if (parser->m_isParamEntity || enc != parser->m_encoding) { + if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc) + == XML_ROLE_ERROR) + return XML_ERROR_INCOMPLETE_PE; + *nextPtr = s; + return XML_ERROR_NONE; + } +#endif /* XML_DTD */ + return XML_ERROR_NO_ELEMENTS; + default: + tok = -tok; + next = end; + break; + } + } + role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc); + switch (role) { + case XML_ROLE_XML_DECL: + { + enum XML_Error result = processXmlDecl(parser, 0, s, next); + if (result != XML_ERROR_NONE) + return result; + enc = parser->m_encoding; + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_DOCTYPE_NAME: + if (parser->m_startDoctypeDeclHandler) { + parser->m_doctypeName = poolStoreString(&parser->m_tempPool, enc, s, next); + if (!parser->m_doctypeName) + return XML_ERROR_NO_MEMORY; + poolFinish(&parser->m_tempPool); + parser->m_doctypePubid = NULL; + handleDefault = XML_FALSE; + } + parser->m_doctypeSysid = NULL; /* always initialize to NULL */ + break; + case XML_ROLE_DOCTYPE_INTERNAL_SUBSET: + if (parser->m_startDoctypeDeclHandler) { + parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid, + parser->m_doctypePubid, 1); + parser->m_doctypeName = NULL; + poolClear(&parser->m_tempPool); + handleDefault = XML_FALSE; + } + break; +#ifdef XML_DTD + case XML_ROLE_TEXT_DECL: + { + enum XML_Error result = processXmlDecl(parser, 1, s, next); + if (result != XML_ERROR_NONE) + return result; + enc = parser->m_encoding; + handleDefault = XML_FALSE; + } + break; +#endif /* XML_DTD */ + case XML_ROLE_DOCTYPE_PUBLIC_ID: +#ifdef XML_DTD + parser->m_useForeignDTD = XML_FALSE; + parser->m_declEntity = (ENTITY *)lookup(parser, + &dtd->paramEntities, + externalSubsetName, + sizeof(ENTITY)); + if (!parser->m_declEntity) + return XML_ERROR_NO_MEMORY; +#endif /* XML_DTD */ + dtd->hasParamEntityRefs = XML_TRUE; + if (parser->m_startDoctypeDeclHandler) { + XML_Char *pubId; + if (!XmlIsPublicId(enc, s, next, eventPP)) + return XML_ERROR_PUBLICID; + pubId = poolStoreString(&parser->m_tempPool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!pubId) + return XML_ERROR_NO_MEMORY; + normalizePublicId(pubId); + poolFinish(&parser->m_tempPool); + parser->m_doctypePubid = pubId; + handleDefault = XML_FALSE; + goto alreadyChecked; + } + /* fall through */ + case XML_ROLE_ENTITY_PUBLIC_ID: + if (!XmlIsPublicId(enc, s, next, eventPP)) + return XML_ERROR_PUBLICID; + alreadyChecked: + if (dtd->keepProcessing && parser->m_declEntity) { + XML_Char *tem = poolStoreString(&dtd->pool, + enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!tem) + return XML_ERROR_NO_MEMORY; + normalizePublicId(tem); + parser->m_declEntity->publicId = tem; + poolFinish(&dtd->pool); + /* Don't suppress the default handler if we fell through from + * the XML_ROLE_DOCTYPE_PUBLIC_ID case. + */ + if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID) + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_DOCTYPE_CLOSE: + if (parser->m_doctypeName) { + parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName, + parser->m_doctypeSysid, parser->m_doctypePubid, 0); + poolClear(&parser->m_tempPool); + handleDefault = XML_FALSE; + } + /* parser->m_doctypeSysid will be non-NULL in the case of a previous + XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler + was not set, indicating an external subset + */ +#ifdef XML_DTD + if (parser->m_doctypeSysid || parser->m_useForeignDTD) { + XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs; + dtd->hasParamEntityRefs = XML_TRUE; + if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) { + ENTITY *entity = (ENTITY *)lookup(parser, + &dtd->paramEntities, + externalSubsetName, + sizeof(ENTITY)); + if (!entity) { + /* The external subset name "#" will have already been + * inserted into the hash table at the start of the + * external entity parsing, so no allocation will happen + * and lookup() cannot fail. + */ + return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */ + } + if (parser->m_useForeignDTD) + entity->base = parser->m_curBase; + dtd->paramEntityRead = XML_FALSE; + if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg, + 0, + entity->base, + entity->systemId, + entity->publicId)) + return XML_ERROR_EXTERNAL_ENTITY_HANDLING; + if (dtd->paramEntityRead) { + if (!dtd->standalone && + parser->m_notStandaloneHandler && + !parser->m_notStandaloneHandler(parser->m_handlerArg)) + return XML_ERROR_NOT_STANDALONE; + } + /* if we didn't read the foreign DTD then this means that there + is no external subset and we must reset dtd->hasParamEntityRefs + */ + else if (!parser->m_doctypeSysid) + dtd->hasParamEntityRefs = hadParamEntityRefs; + /* end of DTD - no need to update dtd->keepProcessing */ + } + parser->m_useForeignDTD = XML_FALSE; + } +#endif /* XML_DTD */ + if (parser->m_endDoctypeDeclHandler) { + parser->m_endDoctypeDeclHandler(parser->m_handlerArg); + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_INSTANCE_START: +#ifdef XML_DTD + /* if there is no DOCTYPE declaration then now is the + last chance to read the foreign DTD + */ + if (parser->m_useForeignDTD) { + XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs; + dtd->hasParamEntityRefs = XML_TRUE; + if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) { + ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities, + externalSubsetName, + sizeof(ENTITY)); + if (!entity) + return XML_ERROR_NO_MEMORY; + entity->base = parser->m_curBase; + dtd->paramEntityRead = XML_FALSE; + if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg, + 0, + entity->base, + entity->systemId, + entity->publicId)) + return XML_ERROR_EXTERNAL_ENTITY_HANDLING; + if (dtd->paramEntityRead) { + if (!dtd->standalone && + parser->m_notStandaloneHandler && + !parser->m_notStandaloneHandler(parser->m_handlerArg)) + return XML_ERROR_NOT_STANDALONE; + } + /* if we didn't read the foreign DTD then this means that there + is no external subset and we must reset dtd->hasParamEntityRefs + */ + else + dtd->hasParamEntityRefs = hadParamEntityRefs; + /* end of DTD - no need to update dtd->keepProcessing */ + } + } +#endif /* XML_DTD */ + parser->m_processor = contentProcessor; + return contentProcessor(parser, s, end, nextPtr); + case XML_ROLE_ATTLIST_ELEMENT_NAME: + parser->m_declElementType = getElementType(parser, enc, s, next); + if (!parser->m_declElementType) + return XML_ERROR_NO_MEMORY; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_NAME: + parser->m_declAttributeId = getAttributeId(parser, enc, s, next); + if (!parser->m_declAttributeId) + return XML_ERROR_NO_MEMORY; + parser->m_declAttributeIsCdata = XML_FALSE; + parser->m_declAttributeType = NULL; + parser->m_declAttributeIsId = XML_FALSE; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_CDATA: + parser->m_declAttributeIsCdata = XML_TRUE; + parser->m_declAttributeType = atypeCDATA; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_ID: + parser->m_declAttributeIsId = XML_TRUE; + parser->m_declAttributeType = atypeID; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_IDREF: + parser->m_declAttributeType = atypeIDREF; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_IDREFS: + parser->m_declAttributeType = atypeIDREFS; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_ENTITY: + parser->m_declAttributeType = atypeENTITY; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES: + parser->m_declAttributeType = atypeENTITIES; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN: + parser->m_declAttributeType = atypeNMTOKEN; + goto checkAttListDeclHandler; + case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS: + parser->m_declAttributeType = atypeNMTOKENS; + checkAttListDeclHandler: + if (dtd->keepProcessing && parser->m_attlistDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_ATTRIBUTE_ENUM_VALUE: + case XML_ROLE_ATTRIBUTE_NOTATION_VALUE: + if (dtd->keepProcessing && parser->m_attlistDeclHandler) { + const XML_Char *prefix; + if (parser->m_declAttributeType) { + prefix = enumValueSep; + } + else { + prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE + ? notationPrefix + : enumValueStart); + } + if (!poolAppendString(&parser->m_tempPool, prefix)) + return XML_ERROR_NO_MEMORY; + if (!poolAppend(&parser->m_tempPool, enc, s, next)) + return XML_ERROR_NO_MEMORY; + parser->m_declAttributeType = parser->m_tempPool.start; + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE: + case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE: + if (dtd->keepProcessing) { + if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId, + parser->m_declAttributeIsCdata, parser->m_declAttributeIsId, + 0, parser)) + return XML_ERROR_NO_MEMORY; + if (parser->m_attlistDeclHandler && parser->m_declAttributeType) { + if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN) + || (*parser->m_declAttributeType == XML_T(ASCII_N) + && parser->m_declAttributeType[1] == XML_T(ASCII_O))) { + /* Enumerated or Notation type */ + if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN)) + || !poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return XML_ERROR_NO_MEMORY; + parser->m_declAttributeType = parser->m_tempPool.start; + poolFinish(&parser->m_tempPool); + } + *eventEndPP = s; + parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, + parser->m_declAttributeId->name, parser->m_declAttributeType, + 0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE); + poolClear(&parser->m_tempPool); + handleDefault = XML_FALSE; + } + } + break; + case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE: + case XML_ROLE_FIXED_ATTRIBUTE_VALUE: + if (dtd->keepProcessing) { + const XML_Char *attVal; + enum XML_Error result = + storeAttributeValue(parser, enc, parser->m_declAttributeIsCdata, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar, + &dtd->pool); + if (result) + return result; + attVal = poolStart(&dtd->pool); + poolFinish(&dtd->pool); + /* ID attributes aren't allowed to have a default */ + if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId, + parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser)) + return XML_ERROR_NO_MEMORY; + if (parser->m_attlistDeclHandler && parser->m_declAttributeType) { + if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN) + || (*parser->m_declAttributeType == XML_T(ASCII_N) + && parser->m_declAttributeType[1] == XML_T(ASCII_O))) { + /* Enumerated or Notation type */ + if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN)) + || !poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return XML_ERROR_NO_MEMORY; + parser->m_declAttributeType = parser->m_tempPool.start; + poolFinish(&parser->m_tempPool); + } + *eventEndPP = s; + parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, + parser->m_declAttributeId->name, parser->m_declAttributeType, + attVal, + role == XML_ROLE_FIXED_ATTRIBUTE_VALUE); + poolClear(&parser->m_tempPool); + handleDefault = XML_FALSE; + } + } + break; + case XML_ROLE_ENTITY_VALUE: + if (dtd->keepProcessing) { + enum XML_Error result = storeEntityValue(parser, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (parser->m_declEntity) { + parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool); + parser->m_declEntity->textLen = (int)(poolLength(&dtd->entityValuePool)); + poolFinish(&dtd->entityValuePool); + if (parser->m_entityDeclHandler) { + *eventEndPP = s; + parser->m_entityDeclHandler(parser->m_handlerArg, + parser->m_declEntity->name, + parser->m_declEntity->is_param, + parser->m_declEntity->textPtr, + parser->m_declEntity->textLen, + parser->m_curBase, 0, 0, 0); + handleDefault = XML_FALSE; + } + } + else + poolDiscard(&dtd->entityValuePool); + if (result != XML_ERROR_NONE) + return result; + } + break; + case XML_ROLE_DOCTYPE_SYSTEM_ID: +#ifdef XML_DTD + parser->m_useForeignDTD = XML_FALSE; +#endif /* XML_DTD */ + dtd->hasParamEntityRefs = XML_TRUE; + if (parser->m_startDoctypeDeclHandler) { + parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (parser->m_doctypeSysid == NULL) + return XML_ERROR_NO_MEMORY; + poolFinish(&parser->m_tempPool); + handleDefault = XML_FALSE; + } +#ifdef XML_DTD + else + /* use externalSubsetName to make parser->m_doctypeSysid non-NULL + for the case where no parser->m_startDoctypeDeclHandler is set */ + parser->m_doctypeSysid = externalSubsetName; +#endif /* XML_DTD */ + if (!dtd->standalone +#ifdef XML_DTD + && !parser->m_paramEntityParsing +#endif /* XML_DTD */ + && parser->m_notStandaloneHandler + && !parser->m_notStandaloneHandler(parser->m_handlerArg)) + return XML_ERROR_NOT_STANDALONE; +#ifndef XML_DTD + break; +#else /* XML_DTD */ + if (!parser->m_declEntity) { + parser->m_declEntity = (ENTITY *)lookup(parser, + &dtd->paramEntities, + externalSubsetName, + sizeof(ENTITY)); + if (!parser->m_declEntity) + return XML_ERROR_NO_MEMORY; + parser->m_declEntity->publicId = NULL; + } + /* fall through */ +#endif /* XML_DTD */ + case XML_ROLE_ENTITY_SYSTEM_ID: + if (dtd->keepProcessing && parser->m_declEntity) { + parser->m_declEntity->systemId = poolStoreString(&dtd->pool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!parser->m_declEntity->systemId) + return XML_ERROR_NO_MEMORY; + parser->m_declEntity->base = parser->m_curBase; + poolFinish(&dtd->pool); + /* Don't suppress the default handler if we fell through from + * the XML_ROLE_DOCTYPE_SYSTEM_ID case. + */ + if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID) + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_ENTITY_COMPLETE: + if (dtd->keepProcessing && parser->m_declEntity && parser->m_entityDeclHandler) { + *eventEndPP = s; + parser->m_entityDeclHandler(parser->m_handlerArg, + parser->m_declEntity->name, + parser->m_declEntity->is_param, + 0,0, + parser->m_declEntity->base, + parser->m_declEntity->systemId, + parser->m_declEntity->publicId, + 0); + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_ENTITY_NOTATION_NAME: + if (dtd->keepProcessing && parser->m_declEntity) { + parser->m_declEntity->notation = poolStoreString(&dtd->pool, enc, s, next); + if (!parser->m_declEntity->notation) + return XML_ERROR_NO_MEMORY; + poolFinish(&dtd->pool); + if (parser->m_unparsedEntityDeclHandler) { + *eventEndPP = s; + parser->m_unparsedEntityDeclHandler(parser->m_handlerArg, + parser->m_declEntity->name, + parser->m_declEntity->base, + parser->m_declEntity->systemId, + parser->m_declEntity->publicId, + parser->m_declEntity->notation); + handleDefault = XML_FALSE; + } + else if (parser->m_entityDeclHandler) { + *eventEndPP = s; + parser->m_entityDeclHandler(parser->m_handlerArg, + parser->m_declEntity->name, + 0,0,0, + parser->m_declEntity->base, + parser->m_declEntity->systemId, + parser->m_declEntity->publicId, + parser->m_declEntity->notation); + handleDefault = XML_FALSE; + } + } + break; + case XML_ROLE_GENERAL_ENTITY_NAME: + { + if (XmlPredefinedEntityName(enc, s, next)) { + parser->m_declEntity = NULL; + break; + } + if (dtd->keepProcessing) { + const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next); + if (!name) + return XML_ERROR_NO_MEMORY; + parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, + sizeof(ENTITY)); + if (!parser->m_declEntity) + return XML_ERROR_NO_MEMORY; + if (parser->m_declEntity->name != name) { + poolDiscard(&dtd->pool); + parser->m_declEntity = NULL; + } + else { + poolFinish(&dtd->pool); + parser->m_declEntity->publicId = NULL; + parser->m_declEntity->is_param = XML_FALSE; + /* if we have a parent parser or are reading an internal parameter + entity, then the entity declaration is not considered "internal" + */ + parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities); + if (parser->m_entityDeclHandler) + handleDefault = XML_FALSE; + } + } + else { + poolDiscard(&dtd->pool); + parser->m_declEntity = NULL; + } + } + break; + case XML_ROLE_PARAM_ENTITY_NAME: +#ifdef XML_DTD + if (dtd->keepProcessing) { + const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next); + if (!name) + return XML_ERROR_NO_MEMORY; + parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities, + name, sizeof(ENTITY)); + if (!parser->m_declEntity) + return XML_ERROR_NO_MEMORY; + if (parser->m_declEntity->name != name) { + poolDiscard(&dtd->pool); + parser->m_declEntity = NULL; + } + else { + poolFinish(&dtd->pool); + parser->m_declEntity->publicId = NULL; + parser->m_declEntity->is_param = XML_TRUE; + /* if we have a parent parser or are reading an internal parameter + entity, then the entity declaration is not considered "internal" + */ + parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities); + if (parser->m_entityDeclHandler) + handleDefault = XML_FALSE; + } + } + else { + poolDiscard(&dtd->pool); + parser->m_declEntity = NULL; + } +#else /* not XML_DTD */ + parser->m_declEntity = NULL; +#endif /* XML_DTD */ + break; + case XML_ROLE_NOTATION_NAME: + parser->m_declNotationPublicId = NULL; + parser->m_declNotationName = NULL; + if (parser->m_notationDeclHandler) { + parser->m_declNotationName = poolStoreString(&parser->m_tempPool, enc, s, next); + if (!parser->m_declNotationName) + return XML_ERROR_NO_MEMORY; + poolFinish(&parser->m_tempPool); + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_NOTATION_PUBLIC_ID: + if (!XmlIsPublicId(enc, s, next, eventPP)) + return XML_ERROR_PUBLICID; + if (parser->m_declNotationName) { /* means m_notationDeclHandler != NULL */ + XML_Char *tem = poolStoreString(&parser->m_tempPool, + enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!tem) + return XML_ERROR_NO_MEMORY; + normalizePublicId(tem); + parser->m_declNotationPublicId = tem; + poolFinish(&parser->m_tempPool); + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_NOTATION_SYSTEM_ID: + if (parser->m_declNotationName && parser->m_notationDeclHandler) { + const XML_Char *systemId + = poolStoreString(&parser->m_tempPool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!systemId) + return XML_ERROR_NO_MEMORY; + *eventEndPP = s; + parser->m_notationDeclHandler(parser->m_handlerArg, + parser->m_declNotationName, + parser->m_curBase, + systemId, + parser->m_declNotationPublicId); + handleDefault = XML_FALSE; + } + poolClear(&parser->m_tempPool); + break; + case XML_ROLE_NOTATION_NO_SYSTEM_ID: + if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) { + *eventEndPP = s; + parser->m_notationDeclHandler(parser->m_handlerArg, + parser->m_declNotationName, + parser->m_curBase, + 0, + parser->m_declNotationPublicId); + handleDefault = XML_FALSE; + } + poolClear(&parser->m_tempPool); + break; + case XML_ROLE_ERROR: + switch (tok) { + case XML_TOK_PARAM_ENTITY_REF: + /* PE references in internal subset are + not allowed within declarations. */ + return XML_ERROR_PARAM_ENTITY_REF; + case XML_TOK_XML_DECL: + return XML_ERROR_MISPLACED_XML_PI; + default: + return XML_ERROR_SYNTAX; + } +#ifdef XML_DTD + case XML_ROLE_IGNORE_SECT: + { + enum XML_Error result; + if (parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + handleDefault = XML_FALSE; + result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore); + if (result != XML_ERROR_NONE) + return result; + else if (!next) { + parser->m_processor = ignoreSectionProcessor; + return result; + } + } + break; +#endif /* XML_DTD */ + case XML_ROLE_GROUP_OPEN: + if (parser->m_prologState.level >= parser->m_groupSize) { + if (parser->m_groupSize) { + char *temp = (char *)REALLOC(parser, parser->m_groupConnector, parser->m_groupSize *= 2); + if (temp == NULL) { + parser->m_groupSize /= 2; + return XML_ERROR_NO_MEMORY; + } + parser->m_groupConnector = temp; + if (dtd->scaffIndex) { + int *temp = (int *)REALLOC(parser, dtd->scaffIndex, + parser->m_groupSize * sizeof(int)); + if (temp == NULL) + return XML_ERROR_NO_MEMORY; + dtd->scaffIndex = temp; + } + } + else { + parser->m_groupConnector = (char *)MALLOC(parser, parser->m_groupSize = 32); + if (!parser->m_groupConnector) { + parser->m_groupSize = 0; + return XML_ERROR_NO_MEMORY; + } + } + } + parser->m_groupConnector[parser->m_prologState.level] = 0; + if (dtd->in_eldecl) { + int myindex = nextScaffoldPart(parser); + if (myindex < 0) + return XML_ERROR_NO_MEMORY; + dtd->scaffIndex[dtd->scaffLevel] = myindex; + dtd->scaffLevel++; + dtd->scaffold[myindex].type = XML_CTYPE_SEQ; + if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + } + break; + case XML_ROLE_GROUP_SEQUENCE: + if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE) + return XML_ERROR_SYNTAX; + parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA; + if (dtd->in_eldecl && parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_GROUP_CHOICE: + if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA) + return XML_ERROR_SYNTAX; + if (dtd->in_eldecl + && !parser->m_groupConnector[parser->m_prologState.level] + && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type + != XML_CTYPE_MIXED) + ) { + dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type + = XML_CTYPE_CHOICE; + if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + } + parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE; + break; + case XML_ROLE_PARAM_ENTITY_REF: +#ifdef XML_DTD + case XML_ROLE_INNER_PARAM_ENTITY_REF: + dtd->hasParamEntityRefs = XML_TRUE; + if (!parser->m_paramEntityParsing) + dtd->keepProcessing = dtd->standalone; + else { + const XML_Char *name; + ENTITY *entity; + name = poolStoreString(&dtd->pool, enc, + s + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!name) + return XML_ERROR_NO_MEMORY; + entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0); + poolDiscard(&dtd->pool); + /* first, determine if a check for an existing declaration is needed; + if yes, check that the entity exists, and that it is internal, + otherwise call the skipped entity handler + */ + if (parser->m_prologState.documentEntity && + (dtd->standalone + ? !parser->m_openInternalEntities + : !dtd->hasParamEntityRefs)) { + if (!entity) + return XML_ERROR_UNDEFINED_ENTITY; + else if (!entity->is_internal) { + /* It's hard to exhaustively search the code to be sure, + * but there doesn't seem to be a way of executing the + * following line. There are two cases: + * + * If 'standalone' is false, the DTD must have no + * parameter entities or we wouldn't have passed the outer + * 'if' statement. That measn the only entity in the hash + * table is the external subset name "#" which cannot be + * given as a parameter entity name in XML syntax, so the + * lookup must have returned NULL and we don't even reach + * the test for an internal entity. + * + * If 'standalone' is true, it does not seem to be + * possible to create entities taking this code path that + * are not internal entities, so fail the test above. + * + * Because this analysis is very uncertain, the code is + * being left in place and merely removed from the + * coverage test statistics. + */ + return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */ + } + } + else if (!entity) { + dtd->keepProcessing = dtd->standalone; + /* cannot report skipped entities in declarations */ + if ((role == XML_ROLE_PARAM_ENTITY_REF) && parser->m_skippedEntityHandler) { + parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1); + handleDefault = XML_FALSE; + } + break; + } + if (entity->open) + return XML_ERROR_RECURSIVE_ENTITY_REF; + if (entity->textPtr) { + enum XML_Error result; + XML_Bool betweenDecl = + (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE); + result = processInternalEntity(parser, entity, betweenDecl); + if (result != XML_ERROR_NONE) + return result; + handleDefault = XML_FALSE; + break; + } + if (parser->m_externalEntityRefHandler) { + dtd->paramEntityRead = XML_FALSE; + entity->open = XML_TRUE; + if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg, + 0, + entity->base, + entity->systemId, + entity->publicId)) { + entity->open = XML_FALSE; + return XML_ERROR_EXTERNAL_ENTITY_HANDLING; + } + entity->open = XML_FALSE; + handleDefault = XML_FALSE; + if (!dtd->paramEntityRead) { + dtd->keepProcessing = dtd->standalone; + break; + } + } + else { + dtd->keepProcessing = dtd->standalone; + break; + } + } +#endif /* XML_DTD */ + if (!dtd->standalone && + parser->m_notStandaloneHandler && + !parser->m_notStandaloneHandler(parser->m_handlerArg)) + return XML_ERROR_NOT_STANDALONE; + break; + + /* Element declaration stuff */ + + case XML_ROLE_ELEMENT_NAME: + if (parser->m_elementDeclHandler) { + parser->m_declElementType = getElementType(parser, enc, s, next); + if (!parser->m_declElementType) + return XML_ERROR_NO_MEMORY; + dtd->scaffLevel = 0; + dtd->scaffCount = 0; + dtd->in_eldecl = XML_TRUE; + handleDefault = XML_FALSE; + } + break; + + case XML_ROLE_CONTENT_ANY: + case XML_ROLE_CONTENT_EMPTY: + if (dtd->in_eldecl) { + if (parser->m_elementDeclHandler) { + XML_Content * content = (XML_Content *) MALLOC(parser, sizeof(XML_Content)); + if (!content) + return XML_ERROR_NO_MEMORY; + content->quant = XML_CQUANT_NONE; + content->name = NULL; + content->numchildren = 0; + content->children = NULL; + content->type = ((role == XML_ROLE_CONTENT_ANY) ? + XML_CTYPE_ANY : + XML_CTYPE_EMPTY); + *eventEndPP = s; + parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, content); + handleDefault = XML_FALSE; + } + dtd->in_eldecl = XML_FALSE; + } + break; + + case XML_ROLE_CONTENT_PCDATA: + if (dtd->in_eldecl) { + dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type + = XML_CTYPE_MIXED; + if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + } + break; + + case XML_ROLE_CONTENT_ELEMENT: + quant = XML_CQUANT_NONE; + goto elementContent; + case XML_ROLE_CONTENT_ELEMENT_OPT: + quant = XML_CQUANT_OPT; + goto elementContent; + case XML_ROLE_CONTENT_ELEMENT_REP: + quant = XML_CQUANT_REP; + goto elementContent; + case XML_ROLE_CONTENT_ELEMENT_PLUS: + quant = XML_CQUANT_PLUS; + elementContent: + if (dtd->in_eldecl) { + ELEMENT_TYPE *el; + const XML_Char *name; + int nameLen; + const char *nxt = (quant == XML_CQUANT_NONE + ? next + : next - enc->minBytesPerChar); + int myindex = nextScaffoldPart(parser); + if (myindex < 0) + return XML_ERROR_NO_MEMORY; + dtd->scaffold[myindex].type = XML_CTYPE_NAME; + dtd->scaffold[myindex].quant = quant; + el = getElementType(parser, enc, s, nxt); + if (!el) + return XML_ERROR_NO_MEMORY; + name = el->name; + dtd->scaffold[myindex].name = name; + nameLen = 0; + for (; name[nameLen++]; ); + dtd->contentStringLen += nameLen; + if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + } + break; + + case XML_ROLE_GROUP_CLOSE: + quant = XML_CQUANT_NONE; + goto closeGroup; + case XML_ROLE_GROUP_CLOSE_OPT: + quant = XML_CQUANT_OPT; + goto closeGroup; + case XML_ROLE_GROUP_CLOSE_REP: + quant = XML_CQUANT_REP; + goto closeGroup; + case XML_ROLE_GROUP_CLOSE_PLUS: + quant = XML_CQUANT_PLUS; + closeGroup: + if (dtd->in_eldecl) { + if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + dtd->scaffLevel--; + dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant; + if (dtd->scaffLevel == 0) { + if (!handleDefault) { + XML_Content *model = build_model(parser); + if (!model) + return XML_ERROR_NO_MEMORY; + *eventEndPP = s; + parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, model); + } + dtd->in_eldecl = XML_FALSE; + dtd->contentStringLen = 0; + } + } + break; + /* End element declaration stuff */ + + case XML_ROLE_PI: + if (!reportProcessingInstruction(parser, enc, s, next)) + return XML_ERROR_NO_MEMORY; + handleDefault = XML_FALSE; + break; + case XML_ROLE_COMMENT: + if (!reportComment(parser, enc, s, next)) + return XML_ERROR_NO_MEMORY; + handleDefault = XML_FALSE; + break; + case XML_ROLE_NONE: + switch (tok) { + case XML_TOK_BOM: + handleDefault = XML_FALSE; + break; + } + break; + case XML_ROLE_DOCTYPE_NONE: + if (parser->m_startDoctypeDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_ENTITY_NONE: + if (dtd->keepProcessing && parser->m_entityDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_NOTATION_NONE: + if (parser->m_notationDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_ATTLIST_NONE: + if (dtd->keepProcessing && parser->m_attlistDeclHandler) + handleDefault = XML_FALSE; + break; + case XML_ROLE_ELEMENT_NONE: + if (parser->m_elementDeclHandler) + handleDefault = XML_FALSE; + break; + } /* end of big switch */ + + if (handleDefault && parser->m_defaultHandler) + reportDefault(parser, enc, s, next); + + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + *nextPtr = next; + return XML_ERROR_NONE; + case XML_FINISHED: + return XML_ERROR_ABORTED; + default: + s = next; + tok = XmlPrologTok(enc, s, end, &next); + } + } + /* not reached */ +} + +static enum XML_Error PTRCALL +epilogProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + parser->m_processor = epilogProcessor; + parser->m_eventPtr = s; + for (;;) { + const char *next = NULL; + int tok = XmlPrologTok(parser->m_encoding, s, end, &next); + parser->m_eventEndPtr = next; + switch (tok) { + /* report partial linebreak - it might be the last token */ + case -XML_TOK_PROLOG_S: + if (parser->m_defaultHandler) { + reportDefault(parser, parser->m_encoding, s, next); + if (parser->m_parsingStatus.parsing == XML_FINISHED) + return XML_ERROR_ABORTED; + } + *nextPtr = next; + return XML_ERROR_NONE; + case XML_TOK_NONE: + *nextPtr = s; + return XML_ERROR_NONE; + case XML_TOK_PROLOG_S: + if (parser->m_defaultHandler) + reportDefault(parser, parser->m_encoding, s, next); + break; + case XML_TOK_PI: + if (!reportProcessingInstruction(parser, parser->m_encoding, s, next)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_COMMENT: + if (!reportComment(parser, parser->m_encoding, s, next)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_INVALID: + parser->m_eventPtr = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: + if (!parser->m_parsingStatus.finalBuffer) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_UNCLOSED_TOKEN; + case XML_TOK_PARTIAL_CHAR: + if (!parser->m_parsingStatus.finalBuffer) { + *nextPtr = s; + return XML_ERROR_NONE; + } + return XML_ERROR_PARTIAL_CHAR; + default: + return XML_ERROR_JUNK_AFTER_DOC_ELEMENT; + } + parser->m_eventPtr = s = next; + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + *nextPtr = next; + return XML_ERROR_NONE; + case XML_FINISHED: + return XML_ERROR_ABORTED; + default: ; + } + } +} + +static enum XML_Error +processInternalEntity(XML_Parser parser, ENTITY *entity, + XML_Bool betweenDecl) +{ + const char *textStart, *textEnd; + const char *next; + enum XML_Error result; + OPEN_INTERNAL_ENTITY *openEntity; + + if (parser->m_freeInternalEntities) { + openEntity = parser->m_freeInternalEntities; + parser->m_freeInternalEntities = openEntity->next; + } + else { + openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY)); + if (!openEntity) + return XML_ERROR_NO_MEMORY; + } + entity->open = XML_TRUE; + entity->processed = 0; + openEntity->next = parser->m_openInternalEntities; + parser->m_openInternalEntities = openEntity; + openEntity->entity = entity; + openEntity->startTagLevel = parser->m_tagLevel; + openEntity->betweenDecl = betweenDecl; + openEntity->internalEventPtr = NULL; + openEntity->internalEventEndPtr = NULL; + textStart = (char *)entity->textPtr; + textEnd = (char *)(entity->textPtr + entity->textLen); + /* Set a safe default value in case 'next' does not get set */ + next = textStart; + +#ifdef XML_DTD + if (entity->is_param) { + int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); + result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok, + next, &next, XML_FALSE); + } + else +#endif /* XML_DTD */ + result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding, textStart, + textEnd, &next, XML_FALSE); + + if (result == XML_ERROR_NONE) { + if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) { + entity->processed = (int)(next - textStart); + parser->m_processor = internalEntityProcessor; + } + else { + entity->open = XML_FALSE; + parser->m_openInternalEntities = openEntity->next; + /* put openEntity back in list of free instances */ + openEntity->next = parser->m_freeInternalEntities; + parser->m_freeInternalEntities = openEntity; + } + } + return result; +} + +static enum XML_Error PTRCALL +internalEntityProcessor(XML_Parser parser, + const char *s, + const char *end, + const char **nextPtr) +{ + ENTITY *entity; + const char *textStart, *textEnd; + const char *next; + enum XML_Error result; + OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities; + if (!openEntity) + return XML_ERROR_UNEXPECTED_STATE; + + entity = openEntity->entity; + textStart = ((char *)entity->textPtr) + entity->processed; + textEnd = (char *)(entity->textPtr + entity->textLen); + /* Set a safe default value in case 'next' does not get set */ + next = textStart; + +#ifdef XML_DTD + if (entity->is_param) { + int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); + result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok, + next, &next, XML_FALSE); + } + else +#endif /* XML_DTD */ + result = doContent(parser, openEntity->startTagLevel, parser->m_internalEncoding, + textStart, textEnd, &next, XML_FALSE); + + if (result != XML_ERROR_NONE) + return result; + else if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) { + entity->processed = (int)(next - (char *)entity->textPtr); + return result; + } + else { + entity->open = XML_FALSE; + parser->m_openInternalEntities = openEntity->next; + /* put openEntity back in list of free instances */ + openEntity->next = parser->m_freeInternalEntities; + parser->m_freeInternalEntities = openEntity; + } + +#ifdef XML_DTD + if (entity->is_param) { + int tok; + parser->m_processor = prologProcessor; + tok = XmlPrologTok(parser->m_encoding, s, end, &next); + return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, + (XML_Bool)!parser->m_parsingStatus.finalBuffer); + } + else +#endif /* XML_DTD */ + { + parser->m_processor = contentProcessor; + /* see externalEntityContentProcessor vs contentProcessor */ + return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, s, end, + nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer); + } +} + +static enum XML_Error PTRCALL +errorProcessor(XML_Parser parser, + const char *UNUSED_P(s), + const char *UNUSED_P(end), + const char **UNUSED_P(nextPtr)) +{ + return parser->m_errorCode; +} + +static enum XML_Error +storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, + const char *ptr, const char *end, + STRING_POOL *pool) +{ + enum XML_Error result = appendAttributeValue(parser, enc, isCdata, ptr, + end, pool); + if (result) + return result; + if (!isCdata && poolLength(pool) && poolLastChar(pool) == 0x20) + poolChop(pool); + if (!poolAppendChar(pool, XML_T('\0'))) + return XML_ERROR_NO_MEMORY; + return XML_ERROR_NONE; +} + +static enum XML_Error +appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata, + const char *ptr, const char *end, + STRING_POOL *pool) +{ + DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + for (;;) { + const char *next; + int tok = XmlAttributeValueTok(enc, ptr, end, &next); + switch (tok) { + case XML_TOK_NONE: + return XML_ERROR_NONE; + case XML_TOK_INVALID: + if (enc == parser->m_encoding) + parser->m_eventPtr = next; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_PARTIAL: + if (enc == parser->m_encoding) + parser->m_eventPtr = ptr; + return XML_ERROR_INVALID_TOKEN; + case XML_TOK_CHAR_REF: + { + XML_Char buf[XML_ENCODE_MAX]; + int i; + int n = XmlCharRefNumber(enc, ptr); + if (n < 0) { + if (enc == parser->m_encoding) + parser->m_eventPtr = ptr; + return XML_ERROR_BAD_CHAR_REF; + } + if (!isCdata + && n == 0x20 /* space */ + && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20)) + break; + n = XmlEncode(n, (ICHAR *)buf); + /* The XmlEncode() functions can never return 0 here. That + * error return happens if the code point passed in is either + * negative or greater than or equal to 0x110000. The + * XmlCharRefNumber() functions will all return a number + * strictly less than 0x110000 or a negative value if an error + * occurred. The negative value is intercepted above, so + * XmlEncode() is never passed a value it might return an + * error for. + */ + for (i = 0; i < n; i++) { + if (!poolAppendChar(pool, buf[i])) + return XML_ERROR_NO_MEMORY; + } + } + break; + case XML_TOK_DATA_CHARS: + if (!poolAppend(pool, enc, ptr, next)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_TRAILING_CR: + next = ptr + enc->minBytesPerChar; + /* fall through */ + case XML_TOK_ATTRIBUTE_VALUE_S: + case XML_TOK_DATA_NEWLINE: + if (!isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20)) + break; + if (!poolAppendChar(pool, 0x20)) + return XML_ERROR_NO_MEMORY; + break; + case XML_TOK_ENTITY_REF: + { + const XML_Char *name; + ENTITY *entity; + char checkEntityDecl; + XML_Char ch = (XML_Char) XmlPredefinedEntityName(enc, + ptr + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (ch) { + if (!poolAppendChar(pool, ch)) + return XML_ERROR_NO_MEMORY; + break; + } + name = poolStoreString(&parser->m_temp2Pool, enc, + ptr + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!name) + return XML_ERROR_NO_MEMORY; + entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0); + poolDiscard(&parser->m_temp2Pool); + /* First, determine if a check for an existing declaration is needed; + if yes, check that the entity exists, and that it is internal. + */ + if (pool == &dtd->pool) /* are we called from prolog? */ + checkEntityDecl = +#ifdef XML_DTD + parser->m_prologState.documentEntity && +#endif /* XML_DTD */ + (dtd->standalone + ? !parser->m_openInternalEntities + : !dtd->hasParamEntityRefs); + else /* if (pool == &parser->m_tempPool): we are called from content */ + checkEntityDecl = !dtd->hasParamEntityRefs || dtd->standalone; + if (checkEntityDecl) { + if (!entity) + return XML_ERROR_UNDEFINED_ENTITY; + else if (!entity->is_internal) + return XML_ERROR_ENTITY_DECLARED_IN_PE; + } + else if (!entity) { + /* Cannot report skipped entity here - see comments on + parser->m_skippedEntityHandler. + if (parser->m_skippedEntityHandler) + parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0); + */ + /* Cannot call the default handler because this would be + out of sync with the call to the startElementHandler. + if ((pool == &parser->m_tempPool) && parser->m_defaultHandler) + reportDefault(parser, enc, ptr, next); + */ + break; + } + if (entity->open) { + if (enc == parser->m_encoding) { + /* It does not appear that this line can be executed. + * + * The "if (entity->open)" check catches recursive entity + * definitions. In order to be called with an open + * entity, it must have gone through this code before and + * been through the recursive call to + * appendAttributeValue() some lines below. That call + * sets the local encoding ("enc") to the parser's + * internal encoding (internal_utf8 or internal_utf16), + * which can never be the same as the principle encoding. + * It doesn't appear there is another code path that gets + * here with entity->open being TRUE. + * + * Since it is not certain that this logic is watertight, + * we keep the line and merely exclude it from coverage + * tests. + */ + parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */ + } + return XML_ERROR_RECURSIVE_ENTITY_REF; + } + if (entity->notation) { + if (enc == parser->m_encoding) + parser->m_eventPtr = ptr; + return XML_ERROR_BINARY_ENTITY_REF; + } + if (!entity->textPtr) { + if (enc == parser->m_encoding) + parser->m_eventPtr = ptr; + return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF; + } + else { + enum XML_Error result; + const XML_Char *textEnd = entity->textPtr + entity->textLen; + entity->open = XML_TRUE; + result = appendAttributeValue(parser, parser->m_internalEncoding, isCdata, + (char *)entity->textPtr, + (char *)textEnd, pool); + entity->open = XML_FALSE; + if (result) + return result; + } + } + break; + default: + /* The only token returned by XmlAttributeValueTok() that does + * not have an explicit case here is XML_TOK_PARTIAL_CHAR. + * Getting that would require an entity name to contain an + * incomplete XML character (e.g. \xE2\x82); however previous + * tokenisers will have already recognised and rejected such + * names before XmlAttributeValueTok() gets a look-in. This + * default case should be retained as a safety net, but the code + * excluded from coverage tests. + * + * LCOV_EXCL_START + */ + if (enc == parser->m_encoding) + parser->m_eventPtr = ptr; + return XML_ERROR_UNEXPECTED_STATE; + /* LCOV_EXCL_STOP */ + } + ptr = next; + } + /* not reached */ +} + +static enum XML_Error +storeEntityValue(XML_Parser parser, + const ENCODING *enc, + const char *entityTextPtr, + const char *entityTextEnd) +{ + DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + STRING_POOL *pool = &(dtd->entityValuePool); + enum XML_Error result = XML_ERROR_NONE; +#ifdef XML_DTD + int oldInEntityValue = parser->m_prologState.inEntityValue; + parser->m_prologState.inEntityValue = 1; +#endif /* XML_DTD */ + /* never return Null for the value argument in EntityDeclHandler, + since this would indicate an external entity; therefore we + have to make sure that entityValuePool.start is not null */ + if (!pool->blocks) { + if (!poolGrow(pool)) + return XML_ERROR_NO_MEMORY; + } + + for (;;) { + const char *next; + int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next); + switch (tok) { + case XML_TOK_PARAM_ENTITY_REF: +#ifdef XML_DTD + if (parser->m_isParamEntity || enc != parser->m_encoding) { + const XML_Char *name; + ENTITY *entity; + name = poolStoreString(&parser->m_tempPool, enc, + entityTextPtr + enc->minBytesPerChar, + next - enc->minBytesPerChar); + if (!name) { + result = XML_ERROR_NO_MEMORY; + goto endEntityValue; + } + entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0); + poolDiscard(&parser->m_tempPool); + if (!entity) { + /* not a well-formedness error - see XML 1.0: WFC Entity Declared */ + /* cannot report skipped entity here - see comments on + parser->m_skippedEntityHandler + if (parser->m_skippedEntityHandler) + parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0); + */ + dtd->keepProcessing = dtd->standalone; + goto endEntityValue; + } + if (entity->open) { + if (enc == parser->m_encoding) + parser->m_eventPtr = entityTextPtr; + result = XML_ERROR_RECURSIVE_ENTITY_REF; + goto endEntityValue; + } + if (entity->systemId) { + if (parser->m_externalEntityRefHandler) { + dtd->paramEntityRead = XML_FALSE; + entity->open = XML_TRUE; + if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg, + 0, + entity->base, + entity->systemId, + entity->publicId)) { + entity->open = XML_FALSE; + result = XML_ERROR_EXTERNAL_ENTITY_HANDLING; + goto endEntityValue; + } + entity->open = XML_FALSE; + if (!dtd->paramEntityRead) + dtd->keepProcessing = dtd->standalone; + } + else + dtd->keepProcessing = dtd->standalone; + } + else { + entity->open = XML_TRUE; + result = storeEntityValue(parser, + parser->m_internalEncoding, + (char *)entity->textPtr, + (char *)(entity->textPtr + + entity->textLen)); + entity->open = XML_FALSE; + if (result) + goto endEntityValue; + } + break; + } +#endif /* XML_DTD */ + /* In the internal subset, PE references are not legal + within markup declarations, e.g entity values in this case. */ + parser->m_eventPtr = entityTextPtr; + result = XML_ERROR_PARAM_ENTITY_REF; + goto endEntityValue; + case XML_TOK_NONE: + result = XML_ERROR_NONE; + goto endEntityValue; + case XML_TOK_ENTITY_REF: + case XML_TOK_DATA_CHARS: + if (!poolAppend(pool, enc, entityTextPtr, next)) { + result = XML_ERROR_NO_MEMORY; + goto endEntityValue; + } + break; + case XML_TOK_TRAILING_CR: + next = entityTextPtr + enc->minBytesPerChar; + /* fall through */ + case XML_TOK_DATA_NEWLINE: + if (pool->end == pool->ptr && !poolGrow(pool)) { + result = XML_ERROR_NO_MEMORY; + goto endEntityValue; + } + *(pool->ptr)++ = 0xA; + break; + case XML_TOK_CHAR_REF: + { + XML_Char buf[XML_ENCODE_MAX]; + int i; + int n = XmlCharRefNumber(enc, entityTextPtr); + if (n < 0) { + if (enc == parser->m_encoding) + parser->m_eventPtr = entityTextPtr; + result = XML_ERROR_BAD_CHAR_REF; + goto endEntityValue; + } + n = XmlEncode(n, (ICHAR *)buf); + /* The XmlEncode() functions can never return 0 here. That + * error return happens if the code point passed in is either + * negative or greater than or equal to 0x110000. The + * XmlCharRefNumber() functions will all return a number + * strictly less than 0x110000 or a negative value if an error + * occurred. The negative value is intercepted above, so + * XmlEncode() is never passed a value it might return an + * error for. + */ + for (i = 0; i < n; i++) { + if (pool->end == pool->ptr && !poolGrow(pool)) { + result = XML_ERROR_NO_MEMORY; + goto endEntityValue; + } + *(pool->ptr)++ = buf[i]; + } + } + break; + case XML_TOK_PARTIAL: + if (enc == parser->m_encoding) + parser->m_eventPtr = entityTextPtr; + result = XML_ERROR_INVALID_TOKEN; + goto endEntityValue; + case XML_TOK_INVALID: + if (enc == parser->m_encoding) + parser->m_eventPtr = next; + result = XML_ERROR_INVALID_TOKEN; + goto endEntityValue; + default: + /* This default case should be unnecessary -- all the tokens + * that XmlEntityValueTok() can return have their own explicit + * cases -- but should be retained for safety. We do however + * exclude it from the coverage statistics. + * + * LCOV_EXCL_START + */ + if (enc == parser->m_encoding) + parser->m_eventPtr = entityTextPtr; + result = XML_ERROR_UNEXPECTED_STATE; + goto endEntityValue; + /* LCOV_EXCL_STOP */ + } + entityTextPtr = next; + } +endEntityValue: +#ifdef XML_DTD + parser->m_prologState.inEntityValue = oldInEntityValue; +#endif /* XML_DTD */ + return result; +} + +static void FASTCALL +normalizeLines(XML_Char *s) +{ + XML_Char *p; + for (;; s++) { + if (*s == XML_T('\0')) + return; + if (*s == 0xD) + break; + } + p = s; + do { + if (*s == 0xD) { + *p++ = 0xA; + if (*++s == 0xA) + s++; + } + else + *p++ = *s++; + } while (*s); + *p = XML_T('\0'); +} + +static int +reportProcessingInstruction(XML_Parser parser, const ENCODING *enc, + const char *start, const char *end) +{ + const XML_Char *target; + XML_Char *data; + const char *tem; + if (!parser->m_processingInstructionHandler) { + if (parser->m_defaultHandler) + reportDefault(parser, enc, start, end); + return 1; + } + start += enc->minBytesPerChar * 2; + tem = start + XmlNameLength(enc, start); + target = poolStoreString(&parser->m_tempPool, enc, start, tem); + if (!target) + return 0; + poolFinish(&parser->m_tempPool); + data = poolStoreString(&parser->m_tempPool, enc, + XmlSkipS(enc, tem), + end - enc->minBytesPerChar*2); + if (!data) + return 0; + normalizeLines(data); + parser->m_processingInstructionHandler(parser->m_handlerArg, target, data); + poolClear(&parser->m_tempPool); + return 1; +} + +static int +reportComment(XML_Parser parser, const ENCODING *enc, + const char *start, const char *end) +{ + XML_Char *data; + if (!parser->m_commentHandler) { + if (parser->m_defaultHandler) + reportDefault(parser, enc, start, end); + return 1; + } + data = poolStoreString(&parser->m_tempPool, + enc, + start + enc->minBytesPerChar * 4, + end - enc->minBytesPerChar * 3); + if (!data) + return 0; + normalizeLines(data); + parser->m_commentHandler(parser->m_handlerArg, data); + poolClear(&parser->m_tempPool); + return 1; +} + +static void +reportDefault(XML_Parser parser, const ENCODING *enc, + const char *s, const char *end) +{ + if (MUST_CONVERT(enc, s)) { + enum XML_Convert_Result convert_res; + const char **eventPP; + const char **eventEndPP; + if (enc == parser->m_encoding) { + eventPP = &parser->m_eventPtr; + eventEndPP = &parser->m_eventEndPtr; + } + else { + /* To get here, two things must be true; the parser must be + * using a character encoding that is not the same as the + * encoding passed in, and the encoding passed in must need + * conversion to the internal format (UTF-8 unless XML_UNICODE + * is defined). The only occasions on which the encoding passed + * in is not the same as the parser's encoding are when it is + * the internal encoding (e.g. a previously defined parameter + * entity, already converted to internal format). This by + * definition doesn't need conversion, so the whole branch never + * gets executed. + * + * For safety's sake we don't delete these lines and merely + * exclude them from coverage statistics. + * + * LCOV_EXCL_START + */ + eventPP = &(parser->m_openInternalEntities->internalEventPtr); + eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); + /* LCOV_EXCL_STOP */ + } + do { + ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf; + convert_res = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd); + *eventEndPP = s; + parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf, (int)(dataPtr - (ICHAR *)parser->m_dataBuf)); + *eventPP = s; + } while ((convert_res != XML_CONVERT_COMPLETED) && (convert_res != XML_CONVERT_INPUT_INCOMPLETE)); + } + else + parser->m_defaultHandler(parser->m_handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s)); +} + + +static int +defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata, + XML_Bool isId, const XML_Char *value, XML_Parser parser) +{ + DEFAULT_ATTRIBUTE *att; + if (value || isId) { + /* The handling of default attributes gets messed up if we have + a default which duplicates a non-default. */ + int i; + for (i = 0; i < type->nDefaultAtts; i++) + if (attId == type->defaultAtts[i].id) + return 1; + if (isId && !type->idAtt && !attId->xmlns) + type->idAtt = attId; + } + if (type->nDefaultAtts == type->allocDefaultAtts) { + if (type->allocDefaultAtts == 0) { + type->allocDefaultAtts = 8; + type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(parser, type->allocDefaultAtts + * sizeof(DEFAULT_ATTRIBUTE)); + if (!type->defaultAtts) { + type->allocDefaultAtts = 0; + return 0; + } + } + else { + DEFAULT_ATTRIBUTE *temp; + int count = type->allocDefaultAtts * 2; + temp = (DEFAULT_ATTRIBUTE *) + REALLOC(parser, type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE))); + if (temp == NULL) + return 0; + type->allocDefaultAtts = count; + type->defaultAtts = temp; + } + } + att = type->defaultAtts + type->nDefaultAtts; + att->id = attId; + att->value = value; + att->isCdata = isCdata; + if (!isCdata) + attId->maybeTokenized = XML_TRUE; + type->nDefaultAtts += 1; + return 1; +} + +static int +setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) +{ + DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + const XML_Char *name; + for (name = elementType->name; *name; name++) { + if (*name == XML_T(ASCII_COLON)) { + PREFIX *prefix; + const XML_Char *s; + for (s = elementType->name; s != name; s++) { + if (!poolAppendChar(&dtd->pool, *s)) + return 0; + } + if (!poolAppendChar(&dtd->pool, XML_T('\0'))) + return 0; + prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool), + sizeof(PREFIX)); + if (!prefix) + return 0; + if (prefix->name == poolStart(&dtd->pool)) + poolFinish(&dtd->pool); + else + poolDiscard(&dtd->pool); + elementType->prefix = prefix; + + } + } + return 1; +} + +static ATTRIBUTE_ID * +getAttributeId(XML_Parser parser, const ENCODING *enc, + const char *start, const char *end) +{ + DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + ATTRIBUTE_ID *id; + const XML_Char *name; + if (!poolAppendChar(&dtd->pool, XML_T('\0'))) + return NULL; + name = poolStoreString(&dtd->pool, enc, start, end); + if (!name) + return NULL; + /* skip quotation mark - its storage will be re-used (like in name[-1]) */ + ++name; + id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name, sizeof(ATTRIBUTE_ID)); + if (!id) + return NULL; + if (id->name != name) + poolDiscard(&dtd->pool); + else { + poolFinish(&dtd->pool); + if (!parser->m_ns) + ; + else if (name[0] == XML_T(ASCII_x) + && name[1] == XML_T(ASCII_m) + && name[2] == XML_T(ASCII_l) + && name[3] == XML_T(ASCII_n) + && name[4] == XML_T(ASCII_s) + && (name[5] == XML_T('\0') || name[5] == XML_T(ASCII_COLON))) { + if (name[5] == XML_T('\0')) + id->prefix = &dtd->defaultPrefix; + else + id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6, sizeof(PREFIX)); + id->xmlns = XML_TRUE; + } + else { + int i; + for (i = 0; name[i]; i++) { + /* attributes without prefix are *not* in the default namespace */ + if (name[i] == XML_T(ASCII_COLON)) { + int j; + for (j = 0; j < i; j++) { + if (!poolAppendChar(&dtd->pool, name[j])) + return NULL; + } + if (!poolAppendChar(&dtd->pool, XML_T('\0'))) + return NULL; + id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool), + sizeof(PREFIX)); + if (!id->prefix) + return NULL; + if (id->prefix->name == poolStart(&dtd->pool)) + poolFinish(&dtd->pool); + else + poolDiscard(&dtd->pool); + break; + } + } + } + } + return id; +} + +#define CONTEXT_SEP XML_T(ASCII_FF) + +static const XML_Char * +getContext(XML_Parser parser) +{ + DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + HASH_TABLE_ITER iter; + XML_Bool needSep = XML_FALSE; + + if (dtd->defaultPrefix.binding) { + int i; + int len; + if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS))) + return NULL; + len = dtd->defaultPrefix.binding->uriLen; + if (parser->m_namespaceSeparator) + len--; + for (i = 0; i < len; i++) { + if (!poolAppendChar(&parser->m_tempPool, dtd->defaultPrefix.binding->uri[i])) { + /* Because of memory caching, I don't believe this line can be + * executed. + * + * This is part of a loop copying the default prefix binding + * URI into the parser's temporary string pool. Previously, + * that URI was copied into the same string pool, with a + * terminating NUL character, as part of setContext(). When + * the pool was cleared, that leaves a block definitely big + * enough to hold the URI on the free block list of the pool. + * The URI copy in getContext() therefore cannot run out of + * memory. + * + * If the pool is used between the setContext() and + * getContext() calls, the worst it can do is leave a bigger + * block on the front of the free list. Given that this is + * all somewhat inobvious and program logic can be changed, we + * don't delete the line but we do exclude it from the test + * coverage statistics. + */ + return NULL; /* LCOV_EXCL_LINE */ + } + } + needSep = XML_TRUE; + } + + hashTableIterInit(&iter, &(dtd->prefixes)); + for (;;) { + int i; + int len; + const XML_Char *s; + PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter); + if (!prefix) + break; + if (!prefix->binding) { + /* This test appears to be (justifiable) paranoia. There does + * not seem to be a way of injecting a prefix without a binding + * that doesn't get errored long before this function is called. + * The test should remain for safety's sake, so we instead + * exclude the following line from the coverage statistics. + */ + continue; /* LCOV_EXCL_LINE */ + } + if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP)) + return NULL; + for (s = prefix->name; *s; s++) + if (!poolAppendChar(&parser->m_tempPool, *s)) + return NULL; + if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS))) + return NULL; + len = prefix->binding->uriLen; + if (parser->m_namespaceSeparator) + len--; + for (i = 0; i < len; i++) + if (!poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i])) + return NULL; + needSep = XML_TRUE; + } + + + hashTableIterInit(&iter, &(dtd->generalEntities)); + for (;;) { + const XML_Char *s; + ENTITY *e = (ENTITY *)hashTableIterNext(&iter); + if (!e) + break; + if (!e->open) + continue; + if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP)) + return NULL; + for (s = e->name; *s; s++) + if (!poolAppendChar(&parser->m_tempPool, *s)) + return 0; + needSep = XML_TRUE; + } + + if (!poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return NULL; + return parser->m_tempPool.start; +} + +static XML_Bool +setContext(XML_Parser parser, const XML_Char *context) +{ + DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + const XML_Char *s = context; + + while (*context != XML_T('\0')) { + if (*s == CONTEXT_SEP || *s == XML_T('\0')) { + ENTITY *e; + if (!poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return XML_FALSE; + e = (ENTITY *)lookup(parser, &dtd->generalEntities, poolStart(&parser->m_tempPool), 0); + if (e) + e->open = XML_TRUE; + if (*s != XML_T('\0')) + s++; + context = s; + poolDiscard(&parser->m_tempPool); + } + else if (*s == XML_T(ASCII_EQUALS)) { + PREFIX *prefix; + if (poolLength(&parser->m_tempPool) == 0) + prefix = &dtd->defaultPrefix; + else { + if (!poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return XML_FALSE; + prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&parser->m_tempPool), + sizeof(PREFIX)); + if (!prefix) + return XML_FALSE; + if (prefix->name == poolStart(&parser->m_tempPool)) { + prefix->name = poolCopyString(&dtd->pool, prefix->name); + if (!prefix->name) + return XML_FALSE; + } + poolDiscard(&parser->m_tempPool); + } + for (context = s + 1; + *context != CONTEXT_SEP && *context != XML_T('\0'); + context++) + if (!poolAppendChar(&parser->m_tempPool, *context)) + return XML_FALSE; + if (!poolAppendChar(&parser->m_tempPool, XML_T('\0'))) + return XML_FALSE; + if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool), + &parser->m_inheritedBindings) != XML_ERROR_NONE) + return XML_FALSE; + poolDiscard(&parser->m_tempPool); + if (*context != XML_T('\0')) + ++context; + s = context; + } + else { + if (!poolAppendChar(&parser->m_tempPool, *s)) + return XML_FALSE; + s++; + } + } + return XML_TRUE; +} + +static void FASTCALL +normalizePublicId(XML_Char *publicId) +{ + XML_Char *p = publicId; + XML_Char *s; + for (s = publicId; *s; s++) { + switch (*s) { + case 0x20: + case 0xD: + case 0xA: + if (p != publicId && p[-1] != 0x20) + *p++ = 0x20; + break; + default: + *p++ = *s; + } + } + if (p != publicId && p[-1] == 0x20) + --p; + *p = XML_T('\0'); +} + +static DTD * +dtdCreate(const XML_Memory_Handling_Suite *ms) +{ + DTD *p = (DTD *)ms->malloc_fcn(sizeof(DTD)); + if (p == NULL) + return p; + poolInit(&(p->pool), ms); + poolInit(&(p->entityValuePool), ms); + hashTableInit(&(p->generalEntities), ms); + hashTableInit(&(p->elementTypes), ms); + hashTableInit(&(p->attributeIds), ms); + hashTableInit(&(p->prefixes), ms); +#ifdef XML_DTD + p->paramEntityRead = XML_FALSE; + hashTableInit(&(p->paramEntities), ms); +#endif /* XML_DTD */ + p->defaultPrefix.name = NULL; + p->defaultPrefix.binding = NULL; + + p->in_eldecl = XML_FALSE; + p->scaffIndex = NULL; + p->scaffold = NULL; + p->scaffLevel = 0; + p->scaffSize = 0; + p->scaffCount = 0; + p->contentStringLen = 0; + + p->keepProcessing = XML_TRUE; + p->hasParamEntityRefs = XML_FALSE; + p->standalone = XML_FALSE; + return p; +} + +static void +dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms) +{ + HASH_TABLE_ITER iter; + hashTableIterInit(&iter, &(p->elementTypes)); + for (;;) { + ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter); + if (!e) + break; + if (e->allocDefaultAtts != 0) + ms->free_fcn(e->defaultAtts); + } + hashTableClear(&(p->generalEntities)); +#ifdef XML_DTD + p->paramEntityRead = XML_FALSE; + hashTableClear(&(p->paramEntities)); +#endif /* XML_DTD */ + hashTableClear(&(p->elementTypes)); + hashTableClear(&(p->attributeIds)); + hashTableClear(&(p->prefixes)); + poolClear(&(p->pool)); + poolClear(&(p->entityValuePool)); + p->defaultPrefix.name = NULL; + p->defaultPrefix.binding = NULL; + + p->in_eldecl = XML_FALSE; + + ms->free_fcn(p->scaffIndex); + p->scaffIndex = NULL; + ms->free_fcn(p->scaffold); + p->scaffold = NULL; + + p->scaffLevel = 0; + p->scaffSize = 0; + p->scaffCount = 0; + p->contentStringLen = 0; + + p->keepProcessing = XML_TRUE; + p->hasParamEntityRefs = XML_FALSE; + p->standalone = XML_FALSE; +} + +static void +dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms) +{ + HASH_TABLE_ITER iter; + hashTableIterInit(&iter, &(p->elementTypes)); + for (;;) { + ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter); + if (!e) + break; + if (e->allocDefaultAtts != 0) + ms->free_fcn(e->defaultAtts); + } + hashTableDestroy(&(p->generalEntities)); +#ifdef XML_DTD + hashTableDestroy(&(p->paramEntities)); +#endif /* XML_DTD */ + hashTableDestroy(&(p->elementTypes)); + hashTableDestroy(&(p->attributeIds)); + hashTableDestroy(&(p->prefixes)); + poolDestroy(&(p->pool)); + poolDestroy(&(p->entityValuePool)); + if (isDocEntity) { + ms->free_fcn(p->scaffIndex); + ms->free_fcn(p->scaffold); + } + ms->free_fcn(p); +} + +/* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise. + The new DTD has already been initialized. +*/ +static int +dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd, const XML_Memory_Handling_Suite *ms) +{ + HASH_TABLE_ITER iter; + + /* Copy the prefix table. */ + + hashTableIterInit(&iter, &(oldDtd->prefixes)); + for (;;) { + const XML_Char *name; + const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter); + if (!oldP) + break; + name = poolCopyString(&(newDtd->pool), oldP->name); + if (!name) + return 0; + if (!lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX))) + return 0; + } + + hashTableIterInit(&iter, &(oldDtd->attributeIds)); + + /* Copy the attribute id table. */ + + for (;;) { + ATTRIBUTE_ID *newA; + const XML_Char *name; + const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter); + + if (!oldA) + break; + /* Remember to allocate the scratch byte before the name. */ + if (!poolAppendChar(&(newDtd->pool), XML_T('\0'))) + return 0; + name = poolCopyString(&(newDtd->pool), oldA->name); + if (!name) + return 0; + ++name; + newA = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds), name, + sizeof(ATTRIBUTE_ID)); + if (!newA) + return 0; + newA->maybeTokenized = oldA->maybeTokenized; + if (oldA->prefix) { + newA->xmlns = oldA->xmlns; + if (oldA->prefix == &oldDtd->defaultPrefix) + newA->prefix = &newDtd->defaultPrefix; + else + newA->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes), + oldA->prefix->name, 0); + } + } + + /* Copy the element type table. */ + + hashTableIterInit(&iter, &(oldDtd->elementTypes)); + + for (;;) { + int i; + ELEMENT_TYPE *newE; + const XML_Char *name; + const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter); + if (!oldE) + break; + name = poolCopyString(&(newDtd->pool), oldE->name); + if (!name) + return 0; + newE = (ELEMENT_TYPE *)lookup(oldParser, &(newDtd->elementTypes), name, + sizeof(ELEMENT_TYPE)); + if (!newE) + return 0; + if (oldE->nDefaultAtts) { + newE->defaultAtts = (DEFAULT_ATTRIBUTE *) + ms->malloc_fcn(oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE)); + if (!newE->defaultAtts) { + return 0; + } + } + if (oldE->idAtt) + newE->idAtt = (ATTRIBUTE_ID *) + lookup(oldParser, &(newDtd->attributeIds), oldE->idAtt->name, 0); + newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts; + if (oldE->prefix) + newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes), + oldE->prefix->name, 0); + for (i = 0; i < newE->nDefaultAtts; i++) { + newE->defaultAtts[i].id = (ATTRIBUTE_ID *) + lookup(oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0); + newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata; + if (oldE->defaultAtts[i].value) { + newE->defaultAtts[i].value + = poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value); + if (!newE->defaultAtts[i].value) + return 0; + } + else + newE->defaultAtts[i].value = NULL; + } + } + + /* Copy the entity tables. */ + if (!copyEntityTable(oldParser, + &(newDtd->generalEntities), + &(newDtd->pool), + &(oldDtd->generalEntities))) + return 0; + +#ifdef XML_DTD + if (!copyEntityTable(oldParser, + &(newDtd->paramEntities), + &(newDtd->pool), + &(oldDtd->paramEntities))) + return 0; + newDtd->paramEntityRead = oldDtd->paramEntityRead; +#endif /* XML_DTD */ + + newDtd->keepProcessing = oldDtd->keepProcessing; + newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs; + newDtd->standalone = oldDtd->standalone; + + /* Don't want deep copying for scaffolding */ + newDtd->in_eldecl = oldDtd->in_eldecl; + newDtd->scaffold = oldDtd->scaffold; + newDtd->contentStringLen = oldDtd->contentStringLen; + newDtd->scaffSize = oldDtd->scaffSize; + newDtd->scaffLevel = oldDtd->scaffLevel; + newDtd->scaffIndex = oldDtd->scaffIndex; + + return 1; +} /* End dtdCopy */ + +static int +copyEntityTable(XML_Parser oldParser, + HASH_TABLE *newTable, + STRING_POOL *newPool, + const HASH_TABLE *oldTable) +{ + HASH_TABLE_ITER iter; + const XML_Char *cachedOldBase = NULL; + const XML_Char *cachedNewBase = NULL; + + hashTableIterInit(&iter, oldTable); + + for (;;) { + ENTITY *newE; + const XML_Char *name; + const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter); + if (!oldE) + break; + name = poolCopyString(newPool, oldE->name); + if (!name) + return 0; + newE = (ENTITY *)lookup(oldParser, newTable, name, sizeof(ENTITY)); + if (!newE) + return 0; + if (oldE->systemId) { + const XML_Char *tem = poolCopyString(newPool, oldE->systemId); + if (!tem) + return 0; + newE->systemId = tem; + if (oldE->base) { + if (oldE->base == cachedOldBase) + newE->base = cachedNewBase; + else { + cachedOldBase = oldE->base; + tem = poolCopyString(newPool, cachedOldBase); + if (!tem) + return 0; + cachedNewBase = newE->base = tem; + } + } + if (oldE->publicId) { + tem = poolCopyString(newPool, oldE->publicId); + if (!tem) + return 0; + newE->publicId = tem; + } + } + else { + const XML_Char *tem = poolCopyStringN(newPool, oldE->textPtr, + oldE->textLen); + if (!tem) + return 0; + newE->textPtr = tem; + newE->textLen = oldE->textLen; + } + if (oldE->notation) { + const XML_Char *tem = poolCopyString(newPool, oldE->notation); + if (!tem) + return 0; + newE->notation = tem; + } + newE->is_param = oldE->is_param; + newE->is_internal = oldE->is_internal; + } + return 1; +} + +#define INIT_POWER 6 + +static XML_Bool FASTCALL +keyeq(KEY s1, KEY s2) +{ + for (; *s1 == *s2; s1++, s2++) + if (*s1 == 0) + return XML_TRUE; + return XML_FALSE; +} + +static size_t +keylen(KEY s) +{ + size_t len = 0; + for (; *s; s++, len++); + return len; +} + +static void +copy_salt_to_sipkey(XML_Parser parser, struct sipkey * key) +{ + key->k[0] = 0; + key->k[1] = get_hash_secret_salt(parser); +} + +static unsigned long FASTCALL +hash(XML_Parser parser, KEY s) +{ + struct siphash state; + struct sipkey key; + (void)sip_tobin; + (void)sip24_valid; + copy_salt_to_sipkey(parser, &key); + sip24_init(&state, &key); + sip24_update(&state, s, keylen(s) * sizeof(XML_Char)); + return (unsigned long)sip24_final(&state); +} + +static NAMED * +lookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize) +{ + size_t i; + if (table->size == 0) { + size_t tsize; + if (!createSize) + return NULL; + table->power = INIT_POWER; + /* table->size is a power of 2 */ + table->size = (size_t)1 << INIT_POWER; + tsize = table->size * sizeof(NAMED *); + table->v = (NAMED **)table->mem->malloc_fcn(tsize); + if (!table->v) { + table->size = 0; + return NULL; + } + memset(table->v, 0, tsize); + i = hash(parser, name) & ((unsigned long)table->size - 1); + } + else { + unsigned long h = hash(parser, name); + unsigned long mask = (unsigned long)table->size - 1; + unsigned char step = 0; + i = h & mask; + while (table->v[i]) { + if (keyeq(name, table->v[i]->name)) + return table->v[i]; + if (!step) + step = PROBE_STEP(h, mask, table->power); + i < step ? (i += table->size - step) : (i -= step); + } + if (!createSize) + return NULL; + + /* check for overflow (table is half full) */ + if (table->used >> (table->power - 1)) { + unsigned char newPower = table->power + 1; + size_t newSize = (size_t)1 << newPower; + unsigned long newMask = (unsigned long)newSize - 1; + size_t tsize = newSize * sizeof(NAMED *); + NAMED **newV = (NAMED **)table->mem->malloc_fcn(tsize); + if (!newV) + return NULL; + memset(newV, 0, tsize); + for (i = 0; i < table->size; i++) + if (table->v[i]) { + unsigned long newHash = hash(parser, table->v[i]->name); + size_t j = newHash & newMask; + step = 0; + while (newV[j]) { + if (!step) + step = PROBE_STEP(newHash, newMask, newPower); + j < step ? (j += newSize - step) : (j -= step); + } + newV[j] = table->v[i]; + } + table->mem->free_fcn(table->v); + table->v = newV; + table->power = newPower; + table->size = newSize; + i = h & newMask; + step = 0; + while (table->v[i]) { + if (!step) + step = PROBE_STEP(h, newMask, newPower); + i < step ? (i += newSize - step) : (i -= step); + } + } + } + table->v[i] = (NAMED *)table->mem->malloc_fcn(createSize); + if (!table->v[i]) + return NULL; + memset(table->v[i], 0, createSize); + table->v[i]->name = name; + (table->used)++; + return table->v[i]; +} + +static void FASTCALL +hashTableClear(HASH_TABLE *table) +{ + size_t i; + for (i = 0; i < table->size; i++) { + table->mem->free_fcn(table->v[i]); + table->v[i] = NULL; + } + table->used = 0; +} + +static void FASTCALL +hashTableDestroy(HASH_TABLE *table) +{ + size_t i; + for (i = 0; i < table->size; i++) + table->mem->free_fcn(table->v[i]); + table->mem->free_fcn(table->v); +} + +static void FASTCALL +hashTableInit(HASH_TABLE *p, const XML_Memory_Handling_Suite *ms) +{ + p->power = 0; + p->size = 0; + p->used = 0; + p->v = NULL; + p->mem = ms; +} + +static void FASTCALL +hashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table) +{ + iter->p = table->v; + iter->end = iter->p + table->size; +} + +static NAMED * FASTCALL +hashTableIterNext(HASH_TABLE_ITER *iter) +{ + while (iter->p != iter->end) { + NAMED *tem = *(iter->p)++; + if (tem) + return tem; + } + return NULL; +} + +static void FASTCALL +poolInit(STRING_POOL *pool, const XML_Memory_Handling_Suite *ms) +{ + pool->blocks = NULL; + pool->freeBlocks = NULL; + pool->start = NULL; + pool->ptr = NULL; + pool->end = NULL; + pool->mem = ms; +} + +static void FASTCALL +poolClear(STRING_POOL *pool) +{ + if (!pool->freeBlocks) + pool->freeBlocks = pool->blocks; + else { + BLOCK *p = pool->blocks; + while (p) { + BLOCK *tem = p->next; + p->next = pool->freeBlocks; + pool->freeBlocks = p; + p = tem; + } + } + pool->blocks = NULL; + pool->start = NULL; + pool->ptr = NULL; + pool->end = NULL; +} + +static void FASTCALL +poolDestroy(STRING_POOL *pool) +{ + BLOCK *p = pool->blocks; + while (p) { + BLOCK *tem = p->next; + pool->mem->free_fcn(p); + p = tem; + } + p = pool->freeBlocks; + while (p) { + BLOCK *tem = p->next; + pool->mem->free_fcn(p); + p = tem; + } +} + +static XML_Char * +poolAppend(STRING_POOL *pool, const ENCODING *enc, + const char *ptr, const char *end) +{ + if (!pool->ptr && !poolGrow(pool)) + return NULL; + for (;;) { + const enum XML_Convert_Result convert_res = XmlConvert(enc, &ptr, end, (ICHAR **)&(pool->ptr), (ICHAR *)pool->end); + if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) + break; + if (!poolGrow(pool)) + return NULL; + } + return pool->start; +} + +static const XML_Char * FASTCALL +poolCopyString(STRING_POOL *pool, const XML_Char *s) +{ + do { + if (!poolAppendChar(pool, *s)) + return NULL; + } while (*s++); + s = pool->start; + poolFinish(pool); + return s; +} + +static const XML_Char * +poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) +{ + if (!pool->ptr && !poolGrow(pool)) { + /* The following line is unreachable given the current usage of + * poolCopyStringN(). Currently it is called from exactly one + * place to copy the text of a simple general entity. By that + * point, the name of the entity is already stored in the pool, so + * pool->ptr cannot be NULL. + * + * If poolCopyStringN() is used elsewhere as it well might be, + * this line may well become executable again. Regardless, this + * sort of check shouldn't be removed lightly, so we just exclude + * it from the coverage statistics. + */ + return NULL; /* LCOV_EXCL_LINE */ + } + for (; n > 0; --n, s++) { + if (!poolAppendChar(pool, *s)) + return NULL; + } + s = pool->start; + poolFinish(pool); + return s; +} + +static const XML_Char * FASTCALL +poolAppendString(STRING_POOL *pool, const XML_Char *s) +{ + while (*s) { + if (!poolAppendChar(pool, *s)) + return NULL; + s++; + } + return pool->start; +} + +static XML_Char * +poolStoreString(STRING_POOL *pool, const ENCODING *enc, + const char *ptr, const char *end) +{ + if (!poolAppend(pool, enc, ptr, end)) + return NULL; + if (pool->ptr == pool->end && !poolGrow(pool)) + return NULL; + *(pool->ptr)++ = 0; + return pool->start; +} + +static size_t +poolBytesToAllocateFor(int blockSize) +{ + /* Unprotected math would be: + ** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char); + ** + ** Detect overflow, avoiding _signed_ overflow undefined behavior + ** For a + b * c we check b * c in isolation first, so that addition of a + ** on top has no chance of making us accept a small non-negative number + */ + const size_t stretch = sizeof(XML_Char); /* can be 4 bytes */ + + if (blockSize <= 0) + return 0; + + if (blockSize > (int)(INT_MAX / stretch)) + return 0; + + { + const int stretchedBlockSize = blockSize * (int)stretch; + const int bytesToAllocate = (int)( + offsetof(BLOCK, s) + (unsigned)stretchedBlockSize); + if (bytesToAllocate < 0) + return 0; + + return (size_t)bytesToAllocate; + } +} + +static XML_Bool FASTCALL +poolGrow(STRING_POOL *pool) +{ + if (pool->freeBlocks) { + if (pool->start == 0) { + pool->blocks = pool->freeBlocks; + pool->freeBlocks = pool->freeBlocks->next; + pool->blocks->next = NULL; + pool->start = pool->blocks->s; + pool->end = pool->start + pool->blocks->size; + pool->ptr = pool->start; + return XML_TRUE; + } + if (pool->end - pool->start < pool->freeBlocks->size) { + BLOCK *tem = pool->freeBlocks->next; + pool->freeBlocks->next = pool->blocks; + pool->blocks = pool->freeBlocks; + pool->freeBlocks = tem; + memcpy(pool->blocks->s, pool->start, + (pool->end - pool->start) * sizeof(XML_Char)); + pool->ptr = pool->blocks->s + (pool->ptr - pool->start); + pool->start = pool->blocks->s; + pool->end = pool->start + pool->blocks->size; + return XML_TRUE; + } + } + if (pool->blocks && pool->start == pool->blocks->s) { + BLOCK *temp; + int blockSize = (int)((unsigned)(pool->end - pool->start)*2U); + size_t bytesToAllocate; + + /* NOTE: Needs to be calculated prior to calling `realloc` + to avoid dangling pointers: */ + const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start; + + if (blockSize < 0) { + /* This condition traps a situation where either more than + * INT_MAX/2 bytes have already been allocated. This isn't + * readily testable, since it is unlikely that an average + * machine will have that much memory, so we exclude it from the + * coverage statistics. + */ + return XML_FALSE; /* LCOV_EXCL_LINE */ + } + + bytesToAllocate = poolBytesToAllocateFor(blockSize); + if (bytesToAllocate == 0) + return XML_FALSE; + + temp = (BLOCK *) + pool->mem->realloc_fcn(pool->blocks, (unsigned)bytesToAllocate); + if (temp == NULL) + return XML_FALSE; + pool->blocks = temp; + pool->blocks->size = blockSize; + pool->ptr = pool->blocks->s + offsetInsideBlock; + pool->start = pool->blocks->s; + pool->end = pool->start + blockSize; + } + else { + BLOCK *tem; + int blockSize = (int)(pool->end - pool->start); + size_t bytesToAllocate; + + if (blockSize < 0) { + /* This condition traps a situation where either more than + * INT_MAX bytes have already been allocated (which is prevented + * by various pieces of program logic, not least this one, never + * mind the unlikelihood of actually having that much memory) or + * the pool control fields have been corrupted (which could + * conceivably happen in an extremely buggy user handler + * function). Either way it isn't readily testable, so we + * exclude it from the coverage statistics. + */ + return XML_FALSE; /* LCOV_EXCL_LINE */ + } + + if (blockSize < INIT_BLOCK_SIZE) + blockSize = INIT_BLOCK_SIZE; + else { + /* Detect overflow, avoiding _signed_ overflow undefined behavior */ + if ((int)((unsigned)blockSize * 2U) < 0) { + return XML_FALSE; + } + blockSize *= 2; + } + + bytesToAllocate = poolBytesToAllocateFor(blockSize); + if (bytesToAllocate == 0) + return XML_FALSE; + + tem = (BLOCK *)pool->mem->malloc_fcn(bytesToAllocate); + if (!tem) + return XML_FALSE; + tem->size = blockSize; + tem->next = pool->blocks; + pool->blocks = tem; + if (pool->ptr != pool->start) + memcpy(tem->s, pool->start, + (pool->ptr - pool->start) * sizeof(XML_Char)); + pool->ptr = tem->s + (pool->ptr - pool->start); + pool->start = tem->s; + pool->end = tem->s + blockSize; + } + return XML_TRUE; +} + +static int FASTCALL +nextScaffoldPart(XML_Parser parser) +{ + DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + CONTENT_SCAFFOLD * me; + int next; + + if (!dtd->scaffIndex) { + dtd->scaffIndex = (int *)MALLOC(parser, parser->m_groupSize * sizeof(int)); + if (!dtd->scaffIndex) + return -1; + dtd->scaffIndex[0] = 0; + } + + if (dtd->scaffCount >= dtd->scaffSize) { + CONTENT_SCAFFOLD *temp; + if (dtd->scaffold) { + temp = (CONTENT_SCAFFOLD *) + REALLOC(parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD)); + if (temp == NULL) + return -1; + dtd->scaffSize *= 2; + } + else { + temp = (CONTENT_SCAFFOLD *)MALLOC(parser, INIT_SCAFFOLD_ELEMENTS + * sizeof(CONTENT_SCAFFOLD)); + if (temp == NULL) + return -1; + dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS; + } + dtd->scaffold = temp; + } + next = dtd->scaffCount++; + me = &dtd->scaffold[next]; + if (dtd->scaffLevel) { + CONTENT_SCAFFOLD *parent = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel-1]]; + if (parent->lastchild) { + dtd->scaffold[parent->lastchild].nextsib = next; + } + if (!parent->childcnt) + parent->firstchild = next; + parent->lastchild = next; + parent->childcnt++; + } + me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0; + return next; +} + +static void +build_node(XML_Parser parser, + int src_node, + XML_Content *dest, + XML_Content **contpos, + XML_Char **strpos) +{ + DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + dest->type = dtd->scaffold[src_node].type; + dest->quant = dtd->scaffold[src_node].quant; + if (dest->type == XML_CTYPE_NAME) { + const XML_Char *src; + dest->name = *strpos; + src = dtd->scaffold[src_node].name; + for (;;) { + *(*strpos)++ = *src; + if (!*src) + break; + src++; + } + dest->numchildren = 0; + dest->children = NULL; + } + else { + unsigned int i; + int cn; + dest->numchildren = dtd->scaffold[src_node].childcnt; + dest->children = *contpos; + *contpos += dest->numchildren; + for (i = 0, cn = dtd->scaffold[src_node].firstchild; + i < dest->numchildren; + i++, cn = dtd->scaffold[cn].nextsib) { + build_node(parser, cn, &(dest->children[i]), contpos, strpos); + } + dest->name = NULL; + } +} + +static XML_Content * +build_model (XML_Parser parser) +{ + DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + XML_Content *ret; + XML_Content *cpos; + XML_Char * str; + int allocsize = (dtd->scaffCount * sizeof(XML_Content) + + (dtd->contentStringLen * sizeof(XML_Char))); + + ret = (XML_Content *)MALLOC(parser, allocsize); + if (!ret) + return NULL; + + str = (XML_Char *) (&ret[dtd->scaffCount]); + cpos = &ret[1]; + + build_node(parser, 0, ret, &cpos, &str); + return ret; +} + +static ELEMENT_TYPE * +getElementType(XML_Parser parser, + const ENCODING *enc, + const char *ptr, + const char *end) +{ + DTD * const dtd = parser->m_dtd; /* save one level of indirection */ + const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end); + ELEMENT_TYPE *ret; + + if (!name) + return NULL; + ret = (ELEMENT_TYPE *) lookup(parser, &dtd->elementTypes, name, sizeof(ELEMENT_TYPE)); + if (!ret) + return NULL; + if (ret->name != name) + poolDiscard(&dtd->pool); + else { + poolFinish(&dtd->pool); + if (!setElementTypePrefix(parser, ret)) + return NULL; + } + return ret; +} + +static XML_Char * +copyString(const XML_Char *s, + const XML_Memory_Handling_Suite *memsuite) +{ + int charsRequired = 0; + XML_Char *result; + + /* First determine how long the string is */ + while (s[charsRequired] != 0) { + charsRequired++; + } + /* Include the terminator */ + charsRequired++; + + /* Now allocate space for the copy */ + result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char)); + if (result == NULL) + return NULL; + /* Copy the original into place */ + memcpy(result, s, charsRequired * sizeof(XML_Char)); + return result; +} diff --git a/tools/sdk/include/expat/xmlrole.c b/tools/sdk/include/expat/xmlrole.c new file mode 100644 index 00000000..708507d5 --- /dev/null +++ b/tools/sdk/include/expat/xmlrole.c @@ -0,0 +1,1386 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#include + +#ifdef _WIN32 +#include "winconfig.h" +#else +#ifdef HAVE_EXPAT_CONFIG_H +#include +#endif +#endif /* ndef _WIN32 */ + +#include "expat_external.h" +#include "internal.h" +#include "xmlrole.h" +#include "ascii.h" + +/* Doesn't check: + + that ,| are not mixed in a model group + content of literals + +*/ + +static const char KW_ANY[] = { + ASCII_A, ASCII_N, ASCII_Y, '\0' }; +static const char KW_ATTLIST[] = { + ASCII_A, ASCII_T, ASCII_T, ASCII_L, ASCII_I, ASCII_S, ASCII_T, '\0' }; +static const char KW_CDATA[] = { + ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' }; +static const char KW_DOCTYPE[] = { + ASCII_D, ASCII_O, ASCII_C, ASCII_T, ASCII_Y, ASCII_P, ASCII_E, '\0' }; +static const char KW_ELEMENT[] = { + ASCII_E, ASCII_L, ASCII_E, ASCII_M, ASCII_E, ASCII_N, ASCII_T, '\0' }; +static const char KW_EMPTY[] = { + ASCII_E, ASCII_M, ASCII_P, ASCII_T, ASCII_Y, '\0' }; +static const char KW_ENTITIES[] = { + ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_I, ASCII_E, ASCII_S, + '\0' }; +static const char KW_ENTITY[] = { + ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0' }; +static const char KW_FIXED[] = { + ASCII_F, ASCII_I, ASCII_X, ASCII_E, ASCII_D, '\0' }; +static const char KW_ID[] = { + ASCII_I, ASCII_D, '\0' }; +static const char KW_IDREF[] = { + ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0' }; +static const char KW_IDREFS[] = { + ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0' }; +#ifdef XML_DTD +static const char KW_IGNORE[] = { + ASCII_I, ASCII_G, ASCII_N, ASCII_O, ASCII_R, ASCII_E, '\0' }; +#endif +static const char KW_IMPLIED[] = { + ASCII_I, ASCII_M, ASCII_P, ASCII_L, ASCII_I, ASCII_E, ASCII_D, '\0' }; +#ifdef XML_DTD +static const char KW_INCLUDE[] = { + ASCII_I, ASCII_N, ASCII_C, ASCII_L, ASCII_U, ASCII_D, ASCII_E, '\0' }; +#endif +static const char KW_NDATA[] = { + ASCII_N, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' }; +static const char KW_NMTOKEN[] = { + ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0' }; +static const char KW_NMTOKENS[] = { + ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, ASCII_S, + '\0' }; +static const char KW_NOTATION[] = + { ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T, ASCII_I, ASCII_O, ASCII_N, + '\0' }; +static const char KW_PCDATA[] = { + ASCII_P, ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0' }; +static const char KW_PUBLIC[] = { + ASCII_P, ASCII_U, ASCII_B, ASCII_L, ASCII_I, ASCII_C, '\0' }; +static const char KW_REQUIRED[] = { + ASCII_R, ASCII_E, ASCII_Q, ASCII_U, ASCII_I, ASCII_R, ASCII_E, ASCII_D, + '\0' }; +static const char KW_SYSTEM[] = { + ASCII_S, ASCII_Y, ASCII_S, ASCII_T, ASCII_E, ASCII_M, '\0' }; + +#ifndef MIN_BYTES_PER_CHAR +#define MIN_BYTES_PER_CHAR(enc) ((enc)->minBytesPerChar) +#endif + +#ifdef XML_DTD +#define setTopLevel(state) \ + ((state)->handler = ((state)->documentEntity \ + ? internalSubset \ + : externalSubset1)) +#else /* not XML_DTD */ +#define setTopLevel(state) ((state)->handler = internalSubset) +#endif /* not XML_DTD */ + +typedef int PTRCALL PROLOG_HANDLER(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc); + +static PROLOG_HANDLER + prolog0, prolog1, prolog2, + doctype0, doctype1, doctype2, doctype3, doctype4, doctype5, + internalSubset, + entity0, entity1, entity2, entity3, entity4, entity5, entity6, + entity7, entity8, entity9, entity10, + notation0, notation1, notation2, notation3, notation4, + attlist0, attlist1, attlist2, attlist3, attlist4, attlist5, attlist6, + attlist7, attlist8, attlist9, + element0, element1, element2, element3, element4, element5, element6, + element7, +#ifdef XML_DTD + externalSubset0, externalSubset1, + condSect0, condSect1, condSect2, +#endif /* XML_DTD */ + declClose, + error; + +static int FASTCALL common(PROLOG_STATE *state, int tok); + +static int PTRCALL +prolog0(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + state->handler = prolog1; + return XML_ROLE_NONE; + case XML_TOK_XML_DECL: + state->handler = prolog1; + return XML_ROLE_XML_DECL; + case XML_TOK_PI: + state->handler = prolog1; + return XML_ROLE_PI; + case XML_TOK_COMMENT: + state->handler = prolog1; + return XML_ROLE_COMMENT; + case XML_TOK_BOM: + return XML_ROLE_NONE; + case XML_TOK_DECL_OPEN: + if (!XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_DOCTYPE)) + break; + state->handler = doctype0; + return XML_ROLE_DOCTYPE_NONE; + case XML_TOK_INSTANCE_START: + state->handler = error; + return XML_ROLE_INSTANCE_START; + } + return common(state, tok); +} + +static int PTRCALL +prolog1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_PI: + return XML_ROLE_PI; + case XML_TOK_COMMENT: + return XML_ROLE_COMMENT; + case XML_TOK_BOM: + /* This case can never arise. To reach this role function, the + * parse must have passed through prolog0 and therefore have had + * some form of input, even if only a space. At that point, a + * byte order mark is no longer a valid character (though + * technically it should be interpreted as a non-breaking space), + * so will be rejected by the tokenizing stages. + */ + return XML_ROLE_NONE; /* LCOV_EXCL_LINE */ + case XML_TOK_DECL_OPEN: + if (!XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_DOCTYPE)) + break; + state->handler = doctype0; + return XML_ROLE_DOCTYPE_NONE; + case XML_TOK_INSTANCE_START: + state->handler = error; + return XML_ROLE_INSTANCE_START; + } + return common(state, tok); +} + +static int PTRCALL +prolog2(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_PI: + return XML_ROLE_PI; + case XML_TOK_COMMENT: + return XML_ROLE_COMMENT; + case XML_TOK_INSTANCE_START: + state->handler = error; + return XML_ROLE_INSTANCE_START; + } + return common(state, tok); +} + +static int PTRCALL +doctype0(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_DOCTYPE_NONE; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = doctype1; + return XML_ROLE_DOCTYPE_NAME; + } + return common(state, tok); +} + +static int PTRCALL +doctype1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_DOCTYPE_NONE; + case XML_TOK_OPEN_BRACKET: + state->handler = internalSubset; + return XML_ROLE_DOCTYPE_INTERNAL_SUBSET; + case XML_TOK_DECL_CLOSE: + state->handler = prolog2; + return XML_ROLE_DOCTYPE_CLOSE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_SYSTEM)) { + state->handler = doctype3; + return XML_ROLE_DOCTYPE_NONE; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_PUBLIC)) { + state->handler = doctype2; + return XML_ROLE_DOCTYPE_NONE; + } + break; + } + return common(state, tok); +} + +static int PTRCALL +doctype2(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_DOCTYPE_NONE; + case XML_TOK_LITERAL: + state->handler = doctype3; + return XML_ROLE_DOCTYPE_PUBLIC_ID; + } + return common(state, tok); +} + +static int PTRCALL +doctype3(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_DOCTYPE_NONE; + case XML_TOK_LITERAL: + state->handler = doctype4; + return XML_ROLE_DOCTYPE_SYSTEM_ID; + } + return common(state, tok); +} + +static int PTRCALL +doctype4(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_DOCTYPE_NONE; + case XML_TOK_OPEN_BRACKET: + state->handler = internalSubset; + return XML_ROLE_DOCTYPE_INTERNAL_SUBSET; + case XML_TOK_DECL_CLOSE: + state->handler = prolog2; + return XML_ROLE_DOCTYPE_CLOSE; + } + return common(state, tok); +} + +static int PTRCALL +doctype5(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_DOCTYPE_NONE; + case XML_TOK_DECL_CLOSE: + state->handler = prolog2; + return XML_ROLE_DOCTYPE_CLOSE; + } + return common(state, tok); +} + +static int PTRCALL +internalSubset(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_DECL_OPEN: + if (XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_ENTITY)) { + state->handler = entity0; + return XML_ROLE_ENTITY_NONE; + } + if (XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_ATTLIST)) { + state->handler = attlist0; + return XML_ROLE_ATTLIST_NONE; + } + if (XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_ELEMENT)) { + state->handler = element0; + return XML_ROLE_ELEMENT_NONE; + } + if (XmlNameMatchesAscii(enc, + ptr + 2 * MIN_BYTES_PER_CHAR(enc), + end, + KW_NOTATION)) { + state->handler = notation0; + return XML_ROLE_NOTATION_NONE; + } + break; + case XML_TOK_PI: + return XML_ROLE_PI; + case XML_TOK_COMMENT: + return XML_ROLE_COMMENT; + case XML_TOK_PARAM_ENTITY_REF: + return XML_ROLE_PARAM_ENTITY_REF; + case XML_TOK_CLOSE_BRACKET: + state->handler = doctype5; + return XML_ROLE_DOCTYPE_NONE; + case XML_TOK_NONE: + return XML_ROLE_NONE; + } + return common(state, tok); +} + +#ifdef XML_DTD + +static int PTRCALL +externalSubset0(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + state->handler = externalSubset1; + if (tok == XML_TOK_XML_DECL) + return XML_ROLE_TEXT_DECL; + return externalSubset1(state, tok, ptr, end, enc); +} + +static int PTRCALL +externalSubset1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_COND_SECT_OPEN: + state->handler = condSect0; + return XML_ROLE_NONE; + case XML_TOK_COND_SECT_CLOSE: + if (state->includeLevel == 0) + break; + state->includeLevel -= 1; + return XML_ROLE_NONE; + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_CLOSE_BRACKET: + break; + case XML_TOK_NONE: + if (state->includeLevel) + break; + return XML_ROLE_NONE; + default: + return internalSubset(state, tok, ptr, end, enc); + } + return common(state, tok); +} + +#endif /* XML_DTD */ + +static int PTRCALL +entity0(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ENTITY_NONE; + case XML_TOK_PERCENT: + state->handler = entity1; + return XML_ROLE_ENTITY_NONE; + case XML_TOK_NAME: + state->handler = entity2; + return XML_ROLE_GENERAL_ENTITY_NAME; + } + return common(state, tok); +} + +static int PTRCALL +entity1(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ENTITY_NONE; + case XML_TOK_NAME: + state->handler = entity7; + return XML_ROLE_PARAM_ENTITY_NAME; + } + return common(state, tok); +} + +static int PTRCALL +entity2(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ENTITY_NONE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_SYSTEM)) { + state->handler = entity4; + return XML_ROLE_ENTITY_NONE; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_PUBLIC)) { + state->handler = entity3; + return XML_ROLE_ENTITY_NONE; + } + break; + case XML_TOK_LITERAL: + state->handler = declClose; + state->role_none = XML_ROLE_ENTITY_NONE; + return XML_ROLE_ENTITY_VALUE; + } + return common(state, tok); +} + +static int PTRCALL +entity3(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ENTITY_NONE; + case XML_TOK_LITERAL: + state->handler = entity4; + return XML_ROLE_ENTITY_PUBLIC_ID; + } + return common(state, tok); +} + +static int PTRCALL +entity4(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ENTITY_NONE; + case XML_TOK_LITERAL: + state->handler = entity5; + return XML_ROLE_ENTITY_SYSTEM_ID; + } + return common(state, tok); +} + +static int PTRCALL +entity5(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ENTITY_NONE; + case XML_TOK_DECL_CLOSE: + setTopLevel(state); + return XML_ROLE_ENTITY_COMPLETE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_NDATA)) { + state->handler = entity6; + return XML_ROLE_ENTITY_NONE; + } + break; + } + return common(state, tok); +} + +static int PTRCALL +entity6(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ENTITY_NONE; + case XML_TOK_NAME: + state->handler = declClose; + state->role_none = XML_ROLE_ENTITY_NONE; + return XML_ROLE_ENTITY_NOTATION_NAME; + } + return common(state, tok); +} + +static int PTRCALL +entity7(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ENTITY_NONE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_SYSTEM)) { + state->handler = entity9; + return XML_ROLE_ENTITY_NONE; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_PUBLIC)) { + state->handler = entity8; + return XML_ROLE_ENTITY_NONE; + } + break; + case XML_TOK_LITERAL: + state->handler = declClose; + state->role_none = XML_ROLE_ENTITY_NONE; + return XML_ROLE_ENTITY_VALUE; + } + return common(state, tok); +} + +static int PTRCALL +entity8(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ENTITY_NONE; + case XML_TOK_LITERAL: + state->handler = entity9; + return XML_ROLE_ENTITY_PUBLIC_ID; + } + return common(state, tok); +} + +static int PTRCALL +entity9(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ENTITY_NONE; + case XML_TOK_LITERAL: + state->handler = entity10; + return XML_ROLE_ENTITY_SYSTEM_ID; + } + return common(state, tok); +} + +static int PTRCALL +entity10(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ENTITY_NONE; + case XML_TOK_DECL_CLOSE: + setTopLevel(state); + return XML_ROLE_ENTITY_COMPLETE; + } + return common(state, tok); +} + +static int PTRCALL +notation0(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NOTATION_NONE; + case XML_TOK_NAME: + state->handler = notation1; + return XML_ROLE_NOTATION_NAME; + } + return common(state, tok); +} + +static int PTRCALL +notation1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NOTATION_NONE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_SYSTEM)) { + state->handler = notation3; + return XML_ROLE_NOTATION_NONE; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_PUBLIC)) { + state->handler = notation2; + return XML_ROLE_NOTATION_NONE; + } + break; + } + return common(state, tok); +} + +static int PTRCALL +notation2(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NOTATION_NONE; + case XML_TOK_LITERAL: + state->handler = notation4; + return XML_ROLE_NOTATION_PUBLIC_ID; + } + return common(state, tok); +} + +static int PTRCALL +notation3(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NOTATION_NONE; + case XML_TOK_LITERAL: + state->handler = declClose; + state->role_none = XML_ROLE_NOTATION_NONE; + return XML_ROLE_NOTATION_SYSTEM_ID; + } + return common(state, tok); +} + +static int PTRCALL +notation4(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NOTATION_NONE; + case XML_TOK_LITERAL: + state->handler = declClose; + state->role_none = XML_ROLE_NOTATION_NONE; + return XML_ROLE_NOTATION_SYSTEM_ID; + case XML_TOK_DECL_CLOSE: + setTopLevel(state); + return XML_ROLE_NOTATION_NO_SYSTEM_ID; + } + return common(state, tok); +} + +static int PTRCALL +attlist0(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = attlist1; + return XML_ROLE_ATTLIST_ELEMENT_NAME; + } + return common(state, tok); +} + +static int PTRCALL +attlist1(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_DECL_CLOSE: + setTopLevel(state); + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = attlist2; + return XML_ROLE_ATTRIBUTE_NAME; + } + return common(state, tok); +} + +static int PTRCALL +attlist2(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_NAME: + { + static const char * const types[] = { + KW_CDATA, + KW_ID, + KW_IDREF, + KW_IDREFS, + KW_ENTITY, + KW_ENTITIES, + KW_NMTOKEN, + KW_NMTOKENS, + }; + int i; + for (i = 0; i < (int)(sizeof(types)/sizeof(types[0])); i++) + if (XmlNameMatchesAscii(enc, ptr, end, types[i])) { + state->handler = attlist8; + return XML_ROLE_ATTRIBUTE_TYPE_CDATA + i; + } + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_NOTATION)) { + state->handler = attlist5; + return XML_ROLE_ATTLIST_NONE; + } + break; + case XML_TOK_OPEN_PAREN: + state->handler = attlist3; + return XML_ROLE_ATTLIST_NONE; + } + return common(state, tok); +} + +static int PTRCALL +attlist3(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_NMTOKEN: + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = attlist4; + return XML_ROLE_ATTRIBUTE_ENUM_VALUE; + } + return common(state, tok); +} + +static int PTRCALL +attlist4(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_CLOSE_PAREN: + state->handler = attlist8; + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_OR: + state->handler = attlist3; + return XML_ROLE_ATTLIST_NONE; + } + return common(state, tok); +} + +static int PTRCALL +attlist5(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_OPEN_PAREN: + state->handler = attlist6; + return XML_ROLE_ATTLIST_NONE; + } + return common(state, tok); +} + +static int PTRCALL +attlist6(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_NAME: + state->handler = attlist7; + return XML_ROLE_ATTRIBUTE_NOTATION_VALUE; + } + return common(state, tok); +} + +static int PTRCALL +attlist7(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_CLOSE_PAREN: + state->handler = attlist8; + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_OR: + state->handler = attlist6; + return XML_ROLE_ATTLIST_NONE; + } + return common(state, tok); +} + +/* default value */ +static int PTRCALL +attlist8(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_POUND_NAME: + if (XmlNameMatchesAscii(enc, + ptr + MIN_BYTES_PER_CHAR(enc), + end, + KW_IMPLIED)) { + state->handler = attlist1; + return XML_ROLE_IMPLIED_ATTRIBUTE_VALUE; + } + if (XmlNameMatchesAscii(enc, + ptr + MIN_BYTES_PER_CHAR(enc), + end, + KW_REQUIRED)) { + state->handler = attlist1; + return XML_ROLE_REQUIRED_ATTRIBUTE_VALUE; + } + if (XmlNameMatchesAscii(enc, + ptr + MIN_BYTES_PER_CHAR(enc), + end, + KW_FIXED)) { + state->handler = attlist9; + return XML_ROLE_ATTLIST_NONE; + } + break; + case XML_TOK_LITERAL: + state->handler = attlist1; + return XML_ROLE_DEFAULT_ATTRIBUTE_VALUE; + } + return common(state, tok); +} + +static int PTRCALL +attlist9(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ATTLIST_NONE; + case XML_TOK_LITERAL: + state->handler = attlist1; + return XML_ROLE_FIXED_ATTRIBUTE_VALUE; + } + return common(state, tok); +} + +static int PTRCALL +element0(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ELEMENT_NONE; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = element1; + return XML_ROLE_ELEMENT_NAME; + } + return common(state, tok); +} + +static int PTRCALL +element1(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ELEMENT_NONE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_EMPTY)) { + state->handler = declClose; + state->role_none = XML_ROLE_ELEMENT_NONE; + return XML_ROLE_CONTENT_EMPTY; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_ANY)) { + state->handler = declClose; + state->role_none = XML_ROLE_ELEMENT_NONE; + return XML_ROLE_CONTENT_ANY; + } + break; + case XML_TOK_OPEN_PAREN: + state->handler = element2; + state->level = 1; + return XML_ROLE_GROUP_OPEN; + } + return common(state, tok); +} + +static int PTRCALL +element2(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ELEMENT_NONE; + case XML_TOK_POUND_NAME: + if (XmlNameMatchesAscii(enc, + ptr + MIN_BYTES_PER_CHAR(enc), + end, + KW_PCDATA)) { + state->handler = element3; + return XML_ROLE_CONTENT_PCDATA; + } + break; + case XML_TOK_OPEN_PAREN: + state->level = 2; + state->handler = element6; + return XML_ROLE_GROUP_OPEN; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT; + case XML_TOK_NAME_QUESTION: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_OPT; + case XML_TOK_NAME_ASTERISK: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_REP; + case XML_TOK_NAME_PLUS: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_PLUS; + } + return common(state, tok); +} + +static int PTRCALL +element3(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ELEMENT_NONE; + case XML_TOK_CLOSE_PAREN: + state->handler = declClose; + state->role_none = XML_ROLE_ELEMENT_NONE; + return XML_ROLE_GROUP_CLOSE; + case XML_TOK_CLOSE_PAREN_ASTERISK: + state->handler = declClose; + state->role_none = XML_ROLE_ELEMENT_NONE; + return XML_ROLE_GROUP_CLOSE_REP; + case XML_TOK_OR: + state->handler = element4; + return XML_ROLE_ELEMENT_NONE; + } + return common(state, tok); +} + +static int PTRCALL +element4(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ELEMENT_NONE; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = element5; + return XML_ROLE_CONTENT_ELEMENT; + } + return common(state, tok); +} + +static int PTRCALL +element5(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ELEMENT_NONE; + case XML_TOK_CLOSE_PAREN_ASTERISK: + state->handler = declClose; + state->role_none = XML_ROLE_ELEMENT_NONE; + return XML_ROLE_GROUP_CLOSE_REP; + case XML_TOK_OR: + state->handler = element4; + return XML_ROLE_ELEMENT_NONE; + } + return common(state, tok); +} + +static int PTRCALL +element6(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ELEMENT_NONE; + case XML_TOK_OPEN_PAREN: + state->level += 1; + return XML_ROLE_GROUP_OPEN; + case XML_TOK_NAME: + case XML_TOK_PREFIXED_NAME: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT; + case XML_TOK_NAME_QUESTION: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_OPT; + case XML_TOK_NAME_ASTERISK: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_REP; + case XML_TOK_NAME_PLUS: + state->handler = element7; + return XML_ROLE_CONTENT_ELEMENT_PLUS; + } + return common(state, tok); +} + +static int PTRCALL +element7(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_ELEMENT_NONE; + case XML_TOK_CLOSE_PAREN: + state->level -= 1; + if (state->level == 0) { + state->handler = declClose; + state->role_none = XML_ROLE_ELEMENT_NONE; + } + return XML_ROLE_GROUP_CLOSE; + case XML_TOK_CLOSE_PAREN_ASTERISK: + state->level -= 1; + if (state->level == 0) { + state->handler = declClose; + state->role_none = XML_ROLE_ELEMENT_NONE; + } + return XML_ROLE_GROUP_CLOSE_REP; + case XML_TOK_CLOSE_PAREN_QUESTION: + state->level -= 1; + if (state->level == 0) { + state->handler = declClose; + state->role_none = XML_ROLE_ELEMENT_NONE; + } + return XML_ROLE_GROUP_CLOSE_OPT; + case XML_TOK_CLOSE_PAREN_PLUS: + state->level -= 1; + if (state->level == 0) { + state->handler = declClose; + state->role_none = XML_ROLE_ELEMENT_NONE; + } + return XML_ROLE_GROUP_CLOSE_PLUS; + case XML_TOK_COMMA: + state->handler = element6; + return XML_ROLE_GROUP_SEQUENCE; + case XML_TOK_OR: + state->handler = element6; + return XML_ROLE_GROUP_CHOICE; + } + return common(state, tok); +} + +#ifdef XML_DTD + +static int PTRCALL +condSect0(PROLOG_STATE *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_NAME: + if (XmlNameMatchesAscii(enc, ptr, end, KW_INCLUDE)) { + state->handler = condSect1; + return XML_ROLE_NONE; + } + if (XmlNameMatchesAscii(enc, ptr, end, KW_IGNORE)) { + state->handler = condSect2; + return XML_ROLE_NONE; + } + break; + } + return common(state, tok); +} + +static int PTRCALL +condSect1(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_OPEN_BRACKET: + state->handler = externalSubset1; + state->includeLevel += 1; + return XML_ROLE_NONE; + } + return common(state, tok); +} + +static int PTRCALL +condSect2(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return XML_ROLE_NONE; + case XML_TOK_OPEN_BRACKET: + state->handler = externalSubset1; + return XML_ROLE_IGNORE_SECT; + } + return common(state, tok); +} + +#endif /* XML_DTD */ + +static int PTRCALL +declClose(PROLOG_STATE *state, + int tok, + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + switch (tok) { + case XML_TOK_PROLOG_S: + return state->role_none; + case XML_TOK_DECL_CLOSE: + setTopLevel(state); + return state->role_none; + } + return common(state, tok); +} + +/* This function will only be invoked if the internal logic of the + * parser has broken down. It is used in two cases: + * + * 1: When the XML prolog has been finished. At this point the + * processor (the parser level above these role handlers) should + * switch from prologProcessor to contentProcessor and reinitialise + * the handler function. + * + * 2: When an error has been detected (via common() below). At this + * point again the processor should be switched to errorProcessor, + * which will never call a handler. + * + * The result of this is that error() can only be called if the + * processor switch failed to happen, which is an internal error and + * therefore we shouldn't be able to provoke it simply by using the + * library. It is a necessary backstop, however, so we merely exclude + * it from the coverage statistics. + * + * LCOV_EXCL_START + */ +static int PTRCALL +error(PROLOG_STATE *UNUSED_P(state), + int UNUSED_P(tok), + const char *UNUSED_P(ptr), + const char *UNUSED_P(end), + const ENCODING *UNUSED_P(enc)) +{ + return XML_ROLE_NONE; +} +/* LCOV_EXCL_STOP */ + +static int FASTCALL +common(PROLOG_STATE *state, int tok) +{ +#ifdef XML_DTD + if (!state->documentEntity && tok == XML_TOK_PARAM_ENTITY_REF) + return XML_ROLE_INNER_PARAM_ENTITY_REF; +#endif + state->handler = error; + return XML_ROLE_ERROR; +} + +void +XmlPrologStateInit(PROLOG_STATE *state) +{ + state->handler = prolog0; +#ifdef XML_DTD + state->documentEntity = 1; + state->includeLevel = 0; + state->inEntityValue = 0; +#endif /* XML_DTD */ +} + +#ifdef XML_DTD + +void +XmlPrologStateInitExternalEntity(PROLOG_STATE *state) +{ + state->handler = externalSubset0; + state->documentEntity = 0; + state->includeLevel = 0; +} + +#endif /* XML_DTD */ diff --git a/tools/sdk/include/expat/xmlrole.h b/tools/sdk/include/expat/xmlrole.h index 4dd9f06f..e5f048ea 100644 --- a/tools/sdk/include/expat/xmlrole.h +++ b/tools/sdk/include/expat/xmlrole.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef XmlRole_INCLUDED diff --git a/tools/sdk/include/expat/xmltok.c b/tools/sdk/include/expat/xmltok.c new file mode 100644 index 00000000..6b415d83 --- /dev/null +++ b/tools/sdk/include/expat/xmltok.c @@ -0,0 +1,1806 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#include +#include /* memcpy */ + +#if defined(_MSC_VER) && (_MSC_VER <= 1700) + /* for vs2012/11.0/1700 and earlier Visual Studio compilers */ +# define bool int +# define false 0 +# define true 1 +#else +# include +#endif + + +#ifdef _WIN32 +#include "winconfig.h" +#else +#ifdef HAVE_EXPAT_CONFIG_H +#include +#endif +#endif /* ndef _WIN32 */ + +#include "expat_external.h" +#include "internal.h" +#include "xmltok.h" +#include "nametab.h" + +#ifdef XML_DTD +#define IGNORE_SECTION_TOK_VTABLE , PREFIX(ignoreSectionTok) +#else +#define IGNORE_SECTION_TOK_VTABLE /* as nothing */ +#endif + +#define VTABLE1 \ + { PREFIX(prologTok), PREFIX(contentTok), \ + PREFIX(cdataSectionTok) IGNORE_SECTION_TOK_VTABLE }, \ + { PREFIX(attributeValueTok), PREFIX(entityValueTok) }, \ + PREFIX(nameMatchesAscii), \ + PREFIX(nameLength), \ + PREFIX(skipS), \ + PREFIX(getAtts), \ + PREFIX(charRefNumber), \ + PREFIX(predefinedEntityName), \ + PREFIX(updatePosition), \ + PREFIX(isPublicId) + +#define VTABLE VTABLE1, PREFIX(toUtf8), PREFIX(toUtf16) + +#define UCS2_GET_NAMING(pages, hi, lo) \ + (namingBitmap[(pages[hi] << 3) + ((lo) >> 5)] & (1u << ((lo) & 0x1F))) + +/* A 2 byte UTF-8 representation splits the characters 11 bits between + the bottom 5 and 6 bits of the bytes. We need 8 bits to index into + pages, 3 bits to add to that index and 5 bits to generate the mask. +*/ +#define UTF8_GET_NAMING2(pages, byte) \ + (namingBitmap[((pages)[(((byte)[0]) >> 2) & 7] << 3) \ + + ((((byte)[0]) & 3) << 1) \ + + ((((byte)[1]) >> 5) & 1)] \ + & (1u << (((byte)[1]) & 0x1F))) + +/* A 3 byte UTF-8 representation splits the characters 16 bits between + the bottom 4, 6 and 6 bits of the bytes. We need 8 bits to index + into pages, 3 bits to add to that index and 5 bits to generate the + mask. +*/ +#define UTF8_GET_NAMING3(pages, byte) \ + (namingBitmap[((pages)[((((byte)[0]) & 0xF) << 4) \ + + ((((byte)[1]) >> 2) & 0xF)] \ + << 3) \ + + ((((byte)[1]) & 3) << 1) \ + + ((((byte)[2]) >> 5) & 1)] \ + & (1u << (((byte)[2]) & 0x1F))) + +#define UTF8_GET_NAMING(pages, p, n) \ + ((n) == 2 \ + ? UTF8_GET_NAMING2(pages, (const unsigned char *)(p)) \ + : ((n) == 3 \ + ? UTF8_GET_NAMING3(pages, (const unsigned char *)(p)) \ + : 0)) + +/* Detection of invalid UTF-8 sequences is based on Table 3.1B + of Unicode 3.2: http://www.unicode.org/unicode/reports/tr28/ + with the additional restriction of not allowing the Unicode + code points 0xFFFF and 0xFFFE (sequences EF,BF,BF and EF,BF,BE). + Implementation details: + (A & 0x80) == 0 means A < 0x80 + and + (A & 0xC0) == 0xC0 means A > 0xBF +*/ + +#define UTF8_INVALID2(p) \ + ((*p) < 0xC2 || ((p)[1] & 0x80) == 0 || ((p)[1] & 0xC0) == 0xC0) + +#define UTF8_INVALID3(p) \ + (((p)[2] & 0x80) == 0 \ + || \ + ((*p) == 0xEF && (p)[1] == 0xBF \ + ? \ + (p)[2] > 0xBD \ + : \ + ((p)[2] & 0xC0) == 0xC0) \ + || \ + ((*p) == 0xE0 \ + ? \ + (p)[1] < 0xA0 || ((p)[1] & 0xC0) == 0xC0 \ + : \ + ((p)[1] & 0x80) == 0 \ + || \ + ((*p) == 0xED ? (p)[1] > 0x9F : ((p)[1] & 0xC0) == 0xC0))) + +#define UTF8_INVALID4(p) \ + (((p)[3] & 0x80) == 0 || ((p)[3] & 0xC0) == 0xC0 \ + || \ + ((p)[2] & 0x80) == 0 || ((p)[2] & 0xC0) == 0xC0 \ + || \ + ((*p) == 0xF0 \ + ? \ + (p)[1] < 0x90 || ((p)[1] & 0xC0) == 0xC0 \ + : \ + ((p)[1] & 0x80) == 0 \ + || \ + ((*p) == 0xF4 ? (p)[1] > 0x8F : ((p)[1] & 0xC0) == 0xC0))) + +static int PTRFASTCALL +isNever(const ENCODING *UNUSED_P(enc), const char *UNUSED_P(p)) +{ + return 0; +} + +static int PTRFASTCALL +utf8_isName2(const ENCODING *UNUSED_P(enc), const char *p) +{ + return UTF8_GET_NAMING2(namePages, (const unsigned char *)p); +} + +static int PTRFASTCALL +utf8_isName3(const ENCODING *UNUSED_P(enc), const char *p) +{ + return UTF8_GET_NAMING3(namePages, (const unsigned char *)p); +} + +#define utf8_isName4 isNever + +static int PTRFASTCALL +utf8_isNmstrt2(const ENCODING *UNUSED_P(enc), const char *p) +{ + return UTF8_GET_NAMING2(nmstrtPages, (const unsigned char *)p); +} + +static int PTRFASTCALL +utf8_isNmstrt3(const ENCODING *UNUSED_P(enc), const char *p) +{ + return UTF8_GET_NAMING3(nmstrtPages, (const unsigned char *)p); +} + +#define utf8_isNmstrt4 isNever + +static int PTRFASTCALL +utf8_isInvalid2(const ENCODING *UNUSED_P(enc), const char *p) +{ + return UTF8_INVALID2((const unsigned char *)p); +} + +static int PTRFASTCALL +utf8_isInvalid3(const ENCODING *UNUSED_P(enc), const char *p) +{ + return UTF8_INVALID3((const unsigned char *)p); +} + +static int PTRFASTCALL +utf8_isInvalid4(const ENCODING *UNUSED_P(enc), const char *p) +{ + return UTF8_INVALID4((const unsigned char *)p); +} + +struct normal_encoding { + ENCODING enc; + unsigned char type[256]; +#ifdef XML_MIN_SIZE + int (PTRFASTCALL *byteType)(const ENCODING *, const char *); + int (PTRFASTCALL *isNameMin)(const ENCODING *, const char *); + int (PTRFASTCALL *isNmstrtMin)(const ENCODING *, const char *); + int (PTRFASTCALL *byteToAscii)(const ENCODING *, const char *); + int (PTRCALL *charMatches)(const ENCODING *, const char *, int); +#endif /* XML_MIN_SIZE */ + int (PTRFASTCALL *isName2)(const ENCODING *, const char *); + int (PTRFASTCALL *isName3)(const ENCODING *, const char *); + int (PTRFASTCALL *isName4)(const ENCODING *, const char *); + int (PTRFASTCALL *isNmstrt2)(const ENCODING *, const char *); + int (PTRFASTCALL *isNmstrt3)(const ENCODING *, const char *); + int (PTRFASTCALL *isNmstrt4)(const ENCODING *, const char *); + int (PTRFASTCALL *isInvalid2)(const ENCODING *, const char *); + int (PTRFASTCALL *isInvalid3)(const ENCODING *, const char *); + int (PTRFASTCALL *isInvalid4)(const ENCODING *, const char *); +}; + +#define AS_NORMAL_ENCODING(enc) ((const struct normal_encoding *) (enc)) + +#ifdef XML_MIN_SIZE + +#define STANDARD_VTABLE(E) \ + E ## byteType, \ + E ## isNameMin, \ + E ## isNmstrtMin, \ + E ## byteToAscii, \ + E ## charMatches, + +#else + +#define STANDARD_VTABLE(E) /* as nothing */ + +#endif + +#define NORMAL_VTABLE(E) \ + E ## isName2, \ + E ## isName3, \ + E ## isName4, \ + E ## isNmstrt2, \ + E ## isNmstrt3, \ + E ## isNmstrt4, \ + E ## isInvalid2, \ + E ## isInvalid3, \ + E ## isInvalid4 + +#define NULL_VTABLE \ + /* isName2 */ NULL, \ + /* isName3 */ NULL, \ + /* isName4 */ NULL, \ + /* isNmstrt2 */ NULL, \ + /* isNmstrt3 */ NULL, \ + /* isNmstrt4 */ NULL, \ + /* isInvalid2 */ NULL, \ + /* isInvalid3 */ NULL, \ + /* isInvalid4 */ NULL + +static int FASTCALL checkCharRefNumber(int); + +#include "xmltok_impl.h" +#include "ascii.h" + +#ifdef XML_MIN_SIZE +#define sb_isNameMin isNever +#define sb_isNmstrtMin isNever +#endif + +#ifdef XML_MIN_SIZE +#define MINBPC(enc) ((enc)->minBytesPerChar) +#else +/* minimum bytes per character */ +#define MINBPC(enc) 1 +#endif + +#define SB_BYTE_TYPE(enc, p) \ + (((struct normal_encoding *)(enc))->type[(unsigned char)*(p)]) + +#ifdef XML_MIN_SIZE +static int PTRFASTCALL +sb_byteType(const ENCODING *enc, const char *p) +{ + return SB_BYTE_TYPE(enc, p); +} +#define BYTE_TYPE(enc, p) \ + (AS_NORMAL_ENCODING(enc)->byteType(enc, p)) +#else +#define BYTE_TYPE(enc, p) SB_BYTE_TYPE(enc, p) +#endif + +#ifdef XML_MIN_SIZE +#define BYTE_TO_ASCII(enc, p) \ + (AS_NORMAL_ENCODING(enc)->byteToAscii(enc, p)) +static int PTRFASTCALL +sb_byteToAscii(const ENCODING *enc, const char *p) +{ + return *p; +} +#else +#define BYTE_TO_ASCII(enc, p) (*(p)) +#endif + +#define IS_NAME_CHAR(enc, p, n) \ + (AS_NORMAL_ENCODING(enc)->isName ## n(enc, p)) +#define IS_NMSTRT_CHAR(enc, p, n) \ + (AS_NORMAL_ENCODING(enc)->isNmstrt ## n(enc, p)) +#define IS_INVALID_CHAR(enc, p, n) \ + (AS_NORMAL_ENCODING(enc)->isInvalid ## n(enc, p)) + +#ifdef XML_MIN_SIZE +#define IS_NAME_CHAR_MINBPC(enc, p) \ + (AS_NORMAL_ENCODING(enc)->isNameMin(enc, p)) +#define IS_NMSTRT_CHAR_MINBPC(enc, p) \ + (AS_NORMAL_ENCODING(enc)->isNmstrtMin(enc, p)) +#else +#define IS_NAME_CHAR_MINBPC(enc, p) (0) +#define IS_NMSTRT_CHAR_MINBPC(enc, p) (0) +#endif + +#ifdef XML_MIN_SIZE +#define CHAR_MATCHES(enc, p, c) \ + (AS_NORMAL_ENCODING(enc)->charMatches(enc, p, c)) +static int PTRCALL +sb_charMatches(const ENCODING *enc, const char *p, int c) +{ + return *p == c; +} +#else +/* c is an ASCII character */ +#define CHAR_MATCHES(enc, p, c) (*(p) == c) +#endif + +#define PREFIX(ident) normal_ ## ident +#define XML_TOK_IMPL_C +#include "xmltok_impl.c" +#undef XML_TOK_IMPL_C + +#undef MINBPC +#undef BYTE_TYPE +#undef BYTE_TO_ASCII +#undef CHAR_MATCHES +#undef IS_NAME_CHAR +#undef IS_NAME_CHAR_MINBPC +#undef IS_NMSTRT_CHAR +#undef IS_NMSTRT_CHAR_MINBPC +#undef IS_INVALID_CHAR + +enum { /* UTF8_cvalN is value of masked first byte of N byte sequence */ + UTF8_cval1 = 0x00, + UTF8_cval2 = 0xc0, + UTF8_cval3 = 0xe0, + UTF8_cval4 = 0xf0 +}; + +void +_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef) +{ + const char * fromLim = *fromLimRef; + size_t walked = 0; + for (; fromLim > from; fromLim--, walked++) { + const unsigned char prev = (unsigned char)fromLim[-1]; + if ((prev & 0xf8u) == 0xf0u) { /* 4-byte character, lead by 0b11110xxx byte */ + if (walked + 1 >= 4) { + fromLim += 4 - 1; + break; + } else { + walked = 0; + } + } else if ((prev & 0xf0u) == 0xe0u) { /* 3-byte character, lead by 0b1110xxxx byte */ + if (walked + 1 >= 3) { + fromLim += 3 - 1; + break; + } else { + walked = 0; + } + } else if ((prev & 0xe0u) == 0xc0u) { /* 2-byte character, lead by 0b110xxxxx byte */ + if (walked + 1 >= 2) { + fromLim += 2 - 1; + break; + } else { + walked = 0; + } + } else if ((prev & 0x80u) == 0x00u) { /* 1-byte character, matching 0b0xxxxxxx */ + break; + } + } + *fromLimRef = fromLim; +} + +static enum XML_Convert_Result PTRCALL +utf8_toUtf8(const ENCODING *UNUSED_P(enc), + const char **fromP, const char *fromLim, + char **toP, const char *toLim) +{ + bool input_incomplete = false; + bool output_exhausted = false; + + /* Avoid copying partial characters (due to limited space). */ + const ptrdiff_t bytesAvailable = fromLim - *fromP; + const ptrdiff_t bytesStorable = toLim - *toP; + if (bytesAvailable > bytesStorable) { + fromLim = *fromP + bytesStorable; + output_exhausted = true; + } + + /* Avoid copying partial characters (from incomplete input). */ + { + const char * const fromLimBefore = fromLim; + _INTERNAL_trim_to_complete_utf8_characters(*fromP, &fromLim); + if (fromLim < fromLimBefore) { + input_incomplete = true; + } + } + + { + const ptrdiff_t bytesToCopy = fromLim - *fromP; + memcpy(*toP, *fromP, bytesToCopy); + *fromP += bytesToCopy; + *toP += bytesToCopy; + } + + if (output_exhausted) /* needs to go first */ + return XML_CONVERT_OUTPUT_EXHAUSTED; + else if (input_incomplete) + return XML_CONVERT_INPUT_INCOMPLETE; + else + return XML_CONVERT_COMPLETED; +} + +static enum XML_Convert_Result PTRCALL +utf8_toUtf16(const ENCODING *enc, + const char **fromP, const char *fromLim, + unsigned short **toP, const unsigned short *toLim) +{ + enum XML_Convert_Result res = XML_CONVERT_COMPLETED; + unsigned short *to = *toP; + const char *from = *fromP; + while (from < fromLim && to < toLim) { + switch (((struct normal_encoding *)enc)->type[(unsigned char)*from]) { + case BT_LEAD2: + if (fromLim - from < 2) { + res = XML_CONVERT_INPUT_INCOMPLETE; + goto after; + } + *to++ = (unsigned short)(((from[0] & 0x1f) << 6) | (from[1] & 0x3f)); + from += 2; + break; + case BT_LEAD3: + if (fromLim - from < 3) { + res = XML_CONVERT_INPUT_INCOMPLETE; + goto after; + } + *to++ = (unsigned short)(((from[0] & 0xf) << 12) + | ((from[1] & 0x3f) << 6) | (from[2] & 0x3f)); + from += 3; + break; + case BT_LEAD4: + { + unsigned long n; + if (toLim - to < 2) { + res = XML_CONVERT_OUTPUT_EXHAUSTED; + goto after; + } + if (fromLim - from < 4) { + res = XML_CONVERT_INPUT_INCOMPLETE; + goto after; + } + n = ((from[0] & 0x7) << 18) | ((from[1] & 0x3f) << 12) + | ((from[2] & 0x3f) << 6) | (from[3] & 0x3f); + n -= 0x10000; + to[0] = (unsigned short)((n >> 10) | 0xD800); + to[1] = (unsigned short)((n & 0x3FF) | 0xDC00); + to += 2; + from += 4; + } + break; + default: + *to++ = *from++; + break; + } + } + if (from < fromLim) + res = XML_CONVERT_OUTPUT_EXHAUSTED; +after: + *fromP = from; + *toP = to; + return res; +} + +#ifdef XML_NS +static const struct normal_encoding utf8_encoding_ns = { + { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 }, + { +#include "asciitab.h" +#include "utf8tab.h" + }, + STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_) +}; +#endif + +static const struct normal_encoding utf8_encoding = { + { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 }, + { +#define BT_COLON BT_NMSTRT +#include "asciitab.h" +#undef BT_COLON +#include "utf8tab.h" + }, + STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_) +}; + +#ifdef XML_NS + +static const struct normal_encoding internal_utf8_encoding_ns = { + { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 }, + { +#include "iasciitab.h" +#include "utf8tab.h" + }, + STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_) +}; + +#endif + +static const struct normal_encoding internal_utf8_encoding = { + { VTABLE1, utf8_toUtf8, utf8_toUtf16, 1, 1, 0 }, + { +#define BT_COLON BT_NMSTRT +#include "iasciitab.h" +#undef BT_COLON +#include "utf8tab.h" + }, + STANDARD_VTABLE(sb_) NORMAL_VTABLE(utf8_) +}; + +static enum XML_Convert_Result PTRCALL +latin1_toUtf8(const ENCODING *UNUSED_P(enc), + const char **fromP, const char *fromLim, + char **toP, const char *toLim) +{ + for (;;) { + unsigned char c; + if (*fromP == fromLim) + return XML_CONVERT_COMPLETED; + c = (unsigned char)**fromP; + if (c & 0x80) { + if (toLim - *toP < 2) + return XML_CONVERT_OUTPUT_EXHAUSTED; + *(*toP)++ = (char)((c >> 6) | UTF8_cval2); + *(*toP)++ = (char)((c & 0x3f) | 0x80); + (*fromP)++; + } + else { + if (*toP == toLim) + return XML_CONVERT_OUTPUT_EXHAUSTED; + *(*toP)++ = *(*fromP)++; + } + } +} + +static enum XML_Convert_Result PTRCALL +latin1_toUtf16(const ENCODING *UNUSED_P(enc), + const char **fromP, const char *fromLim, + unsigned short **toP, const unsigned short *toLim) +{ + while (*fromP < fromLim && *toP < toLim) + *(*toP)++ = (unsigned char)*(*fromP)++; + + if ((*toP == toLim) && (*fromP < fromLim)) + return XML_CONVERT_OUTPUT_EXHAUSTED; + else + return XML_CONVERT_COMPLETED; +} + +#ifdef XML_NS + +static const struct normal_encoding latin1_encoding_ns = { + { VTABLE1, latin1_toUtf8, latin1_toUtf16, 1, 0, 0 }, + { +#include "asciitab.h" +#include "latin1tab.h" + }, + STANDARD_VTABLE(sb_) NULL_VTABLE +}; + +#endif + +static const struct normal_encoding latin1_encoding = { + { VTABLE1, latin1_toUtf8, latin1_toUtf16, 1, 0, 0 }, + { +#define BT_COLON BT_NMSTRT +#include "asciitab.h" +#undef BT_COLON +#include "latin1tab.h" + }, + STANDARD_VTABLE(sb_) NULL_VTABLE +}; + +static enum XML_Convert_Result PTRCALL +ascii_toUtf8(const ENCODING *UNUSED_P(enc), + const char **fromP, const char *fromLim, + char **toP, const char *toLim) +{ + while (*fromP < fromLim && *toP < toLim) + *(*toP)++ = *(*fromP)++; + + if ((*toP == toLim) && (*fromP < fromLim)) + return XML_CONVERT_OUTPUT_EXHAUSTED; + else + return XML_CONVERT_COMPLETED; +} + +#ifdef XML_NS + +static const struct normal_encoding ascii_encoding_ns = { + { VTABLE1, ascii_toUtf8, latin1_toUtf16, 1, 1, 0 }, + { +#include "asciitab.h" +/* BT_NONXML == 0 */ + }, + STANDARD_VTABLE(sb_) NULL_VTABLE +}; + +#endif + +static const struct normal_encoding ascii_encoding = { + { VTABLE1, ascii_toUtf8, latin1_toUtf16, 1, 1, 0 }, + { +#define BT_COLON BT_NMSTRT +#include "asciitab.h" +#undef BT_COLON +/* BT_NONXML == 0 */ + }, + STANDARD_VTABLE(sb_) NULL_VTABLE +}; + +static int PTRFASTCALL +unicode_byte_type(char hi, char lo) +{ + switch ((unsigned char)hi) { + case 0xD8: case 0xD9: case 0xDA: case 0xDB: + return BT_LEAD4; + case 0xDC: case 0xDD: case 0xDE: case 0xDF: + return BT_TRAIL; + case 0xFF: + switch ((unsigned char)lo) { + case 0xFF: + case 0xFE: + return BT_NONXML; + } + break; + } + return BT_NONASCII; +} + +#define DEFINE_UTF16_TO_UTF8(E) \ +static enum XML_Convert_Result PTRCALL \ +E ## toUtf8(const ENCODING *UNUSED_P(enc), \ + const char **fromP, const char *fromLim, \ + char **toP, const char *toLim) \ +{ \ + const char *from = *fromP; \ + fromLim = from + (((fromLim - from) >> 1) << 1); /* shrink to even */ \ + for (; from < fromLim; from += 2) { \ + int plane; \ + unsigned char lo2; \ + unsigned char lo = GET_LO(from); \ + unsigned char hi = GET_HI(from); \ + switch (hi) { \ + case 0: \ + if (lo < 0x80) { \ + if (*toP == toLim) { \ + *fromP = from; \ + return XML_CONVERT_OUTPUT_EXHAUSTED; \ + } \ + *(*toP)++ = lo; \ + break; \ + } \ + /* fall through */ \ + case 0x1: case 0x2: case 0x3: \ + case 0x4: case 0x5: case 0x6: case 0x7: \ + if (toLim - *toP < 2) { \ + *fromP = from; \ + return XML_CONVERT_OUTPUT_EXHAUSTED; \ + } \ + *(*toP)++ = ((lo >> 6) | (hi << 2) | UTF8_cval2); \ + *(*toP)++ = ((lo & 0x3f) | 0x80); \ + break; \ + default: \ + if (toLim - *toP < 3) { \ + *fromP = from; \ + return XML_CONVERT_OUTPUT_EXHAUSTED; \ + } \ + /* 16 bits divided 4, 6, 6 amongst 3 bytes */ \ + *(*toP)++ = ((hi >> 4) | UTF8_cval3); \ + *(*toP)++ = (((hi & 0xf) << 2) | (lo >> 6) | 0x80); \ + *(*toP)++ = ((lo & 0x3f) | 0x80); \ + break; \ + case 0xD8: case 0xD9: case 0xDA: case 0xDB: \ + if (toLim - *toP < 4) { \ + *fromP = from; \ + return XML_CONVERT_OUTPUT_EXHAUSTED; \ + } \ + if (fromLim - from < 4) { \ + *fromP = from; \ + return XML_CONVERT_INPUT_INCOMPLETE; \ + } \ + plane = (((hi & 0x3) << 2) | ((lo >> 6) & 0x3)) + 1; \ + *(*toP)++ = ((plane >> 2) | UTF8_cval4); \ + *(*toP)++ = (((lo >> 2) & 0xF) | ((plane & 0x3) << 4) | 0x80); \ + from += 2; \ + lo2 = GET_LO(from); \ + *(*toP)++ = (((lo & 0x3) << 4) \ + | ((GET_HI(from) & 0x3) << 2) \ + | (lo2 >> 6) \ + | 0x80); \ + *(*toP)++ = ((lo2 & 0x3f) | 0x80); \ + break; \ + } \ + } \ + *fromP = from; \ + if (from < fromLim) \ + return XML_CONVERT_INPUT_INCOMPLETE; \ + else \ + return XML_CONVERT_COMPLETED; \ +} + +#define DEFINE_UTF16_TO_UTF16(E) \ +static enum XML_Convert_Result PTRCALL \ +E ## toUtf16(const ENCODING *UNUSED_P(enc), \ + const char **fromP, const char *fromLim, \ + unsigned short **toP, const unsigned short *toLim) \ +{ \ + enum XML_Convert_Result res = XML_CONVERT_COMPLETED; \ + fromLim = *fromP + (((fromLim - *fromP) >> 1) << 1); /* shrink to even */ \ + /* Avoid copying first half only of surrogate */ \ + if (fromLim - *fromP > ((toLim - *toP) << 1) \ + && (GET_HI(fromLim - 2) & 0xF8) == 0xD8) { \ + fromLim -= 2; \ + res = XML_CONVERT_INPUT_INCOMPLETE; \ + } \ + for (; *fromP < fromLim && *toP < toLim; *fromP += 2) \ + *(*toP)++ = (GET_HI(*fromP) << 8) | GET_LO(*fromP); \ + if ((*toP == toLim) && (*fromP < fromLim)) \ + return XML_CONVERT_OUTPUT_EXHAUSTED; \ + else \ + return res; \ +} + +#define SET2(ptr, ch) \ + (((ptr)[0] = ((ch) & 0xff)), ((ptr)[1] = ((ch) >> 8))) +#define GET_LO(ptr) ((unsigned char)(ptr)[0]) +#define GET_HI(ptr) ((unsigned char)(ptr)[1]) + +DEFINE_UTF16_TO_UTF8(little2_) +DEFINE_UTF16_TO_UTF16(little2_) + +#undef SET2 +#undef GET_LO +#undef GET_HI + +#define SET2(ptr, ch) \ + (((ptr)[0] = ((ch) >> 8)), ((ptr)[1] = ((ch) & 0xFF))) +#define GET_LO(ptr) ((unsigned char)(ptr)[1]) +#define GET_HI(ptr) ((unsigned char)(ptr)[0]) + +DEFINE_UTF16_TO_UTF8(big2_) +DEFINE_UTF16_TO_UTF16(big2_) + +#undef SET2 +#undef GET_LO +#undef GET_HI + +#define LITTLE2_BYTE_TYPE(enc, p) \ + ((p)[1] == 0 \ + ? ((struct normal_encoding *)(enc))->type[(unsigned char)*(p)] \ + : unicode_byte_type((p)[1], (p)[0])) +#define LITTLE2_BYTE_TO_ASCII(enc, p) ((p)[1] == 0 ? (p)[0] : -1) +#define LITTLE2_CHAR_MATCHES(enc, p, c) ((p)[1] == 0 && (p)[0] == c) +#define LITTLE2_IS_NAME_CHAR_MINBPC(enc, p) \ + UCS2_GET_NAMING(namePages, (unsigned char)p[1], (unsigned char)p[0]) +#define LITTLE2_IS_NMSTRT_CHAR_MINBPC(enc, p) \ + UCS2_GET_NAMING(nmstrtPages, (unsigned char)p[1], (unsigned char)p[0]) + +#ifdef XML_MIN_SIZE + +static int PTRFASTCALL +little2_byteType(const ENCODING *enc, const char *p) +{ + return LITTLE2_BYTE_TYPE(enc, p); +} + +static int PTRFASTCALL +little2_byteToAscii(const ENCODING *enc, const char *p) +{ + return LITTLE2_BYTE_TO_ASCII(enc, p); +} + +static int PTRCALL +little2_charMatches(const ENCODING *enc, const char *p, int c) +{ + return LITTLE2_CHAR_MATCHES(enc, p, c); +} + +static int PTRFASTCALL +little2_isNameMin(const ENCODING *enc, const char *p) +{ + return LITTLE2_IS_NAME_CHAR_MINBPC(enc, p); +} + +static int PTRFASTCALL +little2_isNmstrtMin(const ENCODING *enc, const char *p) +{ + return LITTLE2_IS_NMSTRT_CHAR_MINBPC(enc, p); +} + +#undef VTABLE +#define VTABLE VTABLE1, little2_toUtf8, little2_toUtf16 + +#else /* not XML_MIN_SIZE */ + +#undef PREFIX +#define PREFIX(ident) little2_ ## ident +#define MINBPC(enc) 2 +/* CHAR_MATCHES is guaranteed to have MINBPC bytes available. */ +#define BYTE_TYPE(enc, p) LITTLE2_BYTE_TYPE(enc, p) +#define BYTE_TO_ASCII(enc, p) LITTLE2_BYTE_TO_ASCII(enc, p) +#define CHAR_MATCHES(enc, p, c) LITTLE2_CHAR_MATCHES(enc, p, c) +#define IS_NAME_CHAR(enc, p, n) 0 +#define IS_NAME_CHAR_MINBPC(enc, p) LITTLE2_IS_NAME_CHAR_MINBPC(enc, p) +#define IS_NMSTRT_CHAR(enc, p, n) (0) +#define IS_NMSTRT_CHAR_MINBPC(enc, p) LITTLE2_IS_NMSTRT_CHAR_MINBPC(enc, p) + +#define XML_TOK_IMPL_C +#include "xmltok_impl.c" +#undef XML_TOK_IMPL_C + +#undef MINBPC +#undef BYTE_TYPE +#undef BYTE_TO_ASCII +#undef CHAR_MATCHES +#undef IS_NAME_CHAR +#undef IS_NAME_CHAR_MINBPC +#undef IS_NMSTRT_CHAR +#undef IS_NMSTRT_CHAR_MINBPC +#undef IS_INVALID_CHAR + +#endif /* not XML_MIN_SIZE */ + +#ifdef XML_NS + +static const struct normal_encoding little2_encoding_ns = { + { VTABLE, 2, 0, +#if BYTEORDER == 1234 + 1 +#else + 0 +#endif + }, + { +#include "asciitab.h" +#include "latin1tab.h" + }, + STANDARD_VTABLE(little2_) NULL_VTABLE +}; + +#endif + +static const struct normal_encoding little2_encoding = { + { VTABLE, 2, 0, +#if BYTEORDER == 1234 + 1 +#else + 0 +#endif + }, + { +#define BT_COLON BT_NMSTRT +#include "asciitab.h" +#undef BT_COLON +#include "latin1tab.h" + }, + STANDARD_VTABLE(little2_) NULL_VTABLE +}; + +#if BYTEORDER != 4321 + +#ifdef XML_NS + +static const struct normal_encoding internal_little2_encoding_ns = { + { VTABLE, 2, 0, 1 }, + { +#include "iasciitab.h" +#include "latin1tab.h" + }, + STANDARD_VTABLE(little2_) NULL_VTABLE +}; + +#endif + +static const struct normal_encoding internal_little2_encoding = { + { VTABLE, 2, 0, 1 }, + { +#define BT_COLON BT_NMSTRT +#include "iasciitab.h" +#undef BT_COLON +#include "latin1tab.h" + }, + STANDARD_VTABLE(little2_) NULL_VTABLE +}; + +#endif + + +#define BIG2_BYTE_TYPE(enc, p) \ + ((p)[0] == 0 \ + ? ((struct normal_encoding *)(enc))->type[(unsigned char)(p)[1]] \ + : unicode_byte_type((p)[0], (p)[1])) +#define BIG2_BYTE_TO_ASCII(enc, p) ((p)[0] == 0 ? (p)[1] : -1) +#define BIG2_CHAR_MATCHES(enc, p, c) ((p)[0] == 0 && (p)[1] == c) +#define BIG2_IS_NAME_CHAR_MINBPC(enc, p) \ + UCS2_GET_NAMING(namePages, (unsigned char)p[0], (unsigned char)p[1]) +#define BIG2_IS_NMSTRT_CHAR_MINBPC(enc, p) \ + UCS2_GET_NAMING(nmstrtPages, (unsigned char)p[0], (unsigned char)p[1]) + +#ifdef XML_MIN_SIZE + +static int PTRFASTCALL +big2_byteType(const ENCODING *enc, const char *p) +{ + return BIG2_BYTE_TYPE(enc, p); +} + +static int PTRFASTCALL +big2_byteToAscii(const ENCODING *enc, const char *p) +{ + return BIG2_BYTE_TO_ASCII(enc, p); +} + +static int PTRCALL +big2_charMatches(const ENCODING *enc, const char *p, int c) +{ + return BIG2_CHAR_MATCHES(enc, p, c); +} + +static int PTRFASTCALL +big2_isNameMin(const ENCODING *enc, const char *p) +{ + return BIG2_IS_NAME_CHAR_MINBPC(enc, p); +} + +static int PTRFASTCALL +big2_isNmstrtMin(const ENCODING *enc, const char *p) +{ + return BIG2_IS_NMSTRT_CHAR_MINBPC(enc, p); +} + +#undef VTABLE +#define VTABLE VTABLE1, big2_toUtf8, big2_toUtf16 + +#else /* not XML_MIN_SIZE */ + +#undef PREFIX +#define PREFIX(ident) big2_ ## ident +#define MINBPC(enc) 2 +/* CHAR_MATCHES is guaranteed to have MINBPC bytes available. */ +#define BYTE_TYPE(enc, p) BIG2_BYTE_TYPE(enc, p) +#define BYTE_TO_ASCII(enc, p) BIG2_BYTE_TO_ASCII(enc, p) +#define CHAR_MATCHES(enc, p, c) BIG2_CHAR_MATCHES(enc, p, c) +#define IS_NAME_CHAR(enc, p, n) 0 +#define IS_NAME_CHAR_MINBPC(enc, p) BIG2_IS_NAME_CHAR_MINBPC(enc, p) +#define IS_NMSTRT_CHAR(enc, p, n) (0) +#define IS_NMSTRT_CHAR_MINBPC(enc, p) BIG2_IS_NMSTRT_CHAR_MINBPC(enc, p) + +#define XML_TOK_IMPL_C +#include "xmltok_impl.c" +#undef XML_TOK_IMPL_C + +#undef MINBPC +#undef BYTE_TYPE +#undef BYTE_TO_ASCII +#undef CHAR_MATCHES +#undef IS_NAME_CHAR +#undef IS_NAME_CHAR_MINBPC +#undef IS_NMSTRT_CHAR +#undef IS_NMSTRT_CHAR_MINBPC +#undef IS_INVALID_CHAR + +#endif /* not XML_MIN_SIZE */ + +#ifdef XML_NS + +static const struct normal_encoding big2_encoding_ns = { + { VTABLE, 2, 0, +#if BYTEORDER == 4321 + 1 +#else + 0 +#endif + }, + { +#include "asciitab.h" +#include "latin1tab.h" + }, + STANDARD_VTABLE(big2_) NULL_VTABLE +}; + +#endif + +static const struct normal_encoding big2_encoding = { + { VTABLE, 2, 0, +#if BYTEORDER == 4321 + 1 +#else + 0 +#endif + }, + { +#define BT_COLON BT_NMSTRT +#include "asciitab.h" +#undef BT_COLON +#include "latin1tab.h" + }, + STANDARD_VTABLE(big2_) NULL_VTABLE +}; + +#if BYTEORDER != 1234 + +#ifdef XML_NS + +static const struct normal_encoding internal_big2_encoding_ns = { + { VTABLE, 2, 0, 1 }, + { +#include "iasciitab.h" +#include "latin1tab.h" + }, + STANDARD_VTABLE(big2_) NULL_VTABLE +}; + +#endif + +static const struct normal_encoding internal_big2_encoding = { + { VTABLE, 2, 0, 1 }, + { +#define BT_COLON BT_NMSTRT +#include "iasciitab.h" +#undef BT_COLON +#include "latin1tab.h" + }, + STANDARD_VTABLE(big2_) NULL_VTABLE +}; + +#endif + +#undef PREFIX + +static int FASTCALL +streqci(const char *s1, const char *s2) +{ + for (;;) { + char c1 = *s1++; + char c2 = *s2++; + if (ASCII_a <= c1 && c1 <= ASCII_z) + c1 += ASCII_A - ASCII_a; + if (ASCII_a <= c2 && c2 <= ASCII_z) + /* The following line will never get executed. streqci() is + * only called from two places, both of which guarantee to put + * upper-case strings into s2. + */ + c2 += ASCII_A - ASCII_a; /* LCOV_EXCL_LINE */ + if (c1 != c2) + return 0; + if (!c1) + break; + } + return 1; +} + +static void PTRCALL +initUpdatePosition(const ENCODING *UNUSED_P(enc), const char *ptr, + const char *end, POSITION *pos) +{ + normal_updatePosition(&utf8_encoding.enc, ptr, end, pos); +} + +static int +toAscii(const ENCODING *enc, const char *ptr, const char *end) +{ + char buf[1]; + char *p = buf; + XmlUtf8Convert(enc, &ptr, end, &p, p + 1); + if (p == buf) + return -1; + else + return buf[0]; +} + +static int FASTCALL +isSpace(int c) +{ + switch (c) { + case 0x20: + case 0xD: + case 0xA: + case 0x9: + return 1; + } + return 0; +} + +/* Return 1 if there's just optional white space or there's an S + followed by name=val. +*/ +static int +parsePseudoAttribute(const ENCODING *enc, + const char *ptr, + const char *end, + const char **namePtr, + const char **nameEndPtr, + const char **valPtr, + const char **nextTokPtr) +{ + int c; + char open; + if (ptr == end) { + *namePtr = NULL; + return 1; + } + if (!isSpace(toAscii(enc, ptr, end))) { + *nextTokPtr = ptr; + return 0; + } + do { + ptr += enc->minBytesPerChar; + } while (isSpace(toAscii(enc, ptr, end))); + if (ptr == end) { + *namePtr = NULL; + return 1; + } + *namePtr = ptr; + for (;;) { + c = toAscii(enc, ptr, end); + if (c == -1) { + *nextTokPtr = ptr; + return 0; + } + if (c == ASCII_EQUALS) { + *nameEndPtr = ptr; + break; + } + if (isSpace(c)) { + *nameEndPtr = ptr; + do { + ptr += enc->minBytesPerChar; + } while (isSpace(c = toAscii(enc, ptr, end))); + if (c != ASCII_EQUALS) { + *nextTokPtr = ptr; + return 0; + } + break; + } + ptr += enc->minBytesPerChar; + } + if (ptr == *namePtr) { + *nextTokPtr = ptr; + return 0; + } + ptr += enc->minBytesPerChar; + c = toAscii(enc, ptr, end); + while (isSpace(c)) { + ptr += enc->minBytesPerChar; + c = toAscii(enc, ptr, end); + } + if (c != ASCII_QUOT && c != ASCII_APOS) { + *nextTokPtr = ptr; + return 0; + } + open = (char)c; + ptr += enc->minBytesPerChar; + *valPtr = ptr; + for (;; ptr += enc->minBytesPerChar) { + c = toAscii(enc, ptr, end); + if (c == open) + break; + if (!(ASCII_a <= c && c <= ASCII_z) + && !(ASCII_A <= c && c <= ASCII_Z) + && !(ASCII_0 <= c && c <= ASCII_9) + && c != ASCII_PERIOD + && c != ASCII_MINUS + && c != ASCII_UNDERSCORE) { + *nextTokPtr = ptr; + return 0; + } + } + *nextTokPtr = ptr + enc->minBytesPerChar; + return 1; +} + +static const char KW_version[] = { + ASCII_v, ASCII_e, ASCII_r, ASCII_s, ASCII_i, ASCII_o, ASCII_n, '\0' +}; + +static const char KW_encoding[] = { + ASCII_e, ASCII_n, ASCII_c, ASCII_o, ASCII_d, ASCII_i, ASCII_n, ASCII_g, '\0' +}; + +static const char KW_standalone[] = { + ASCII_s, ASCII_t, ASCII_a, ASCII_n, ASCII_d, ASCII_a, ASCII_l, ASCII_o, + ASCII_n, ASCII_e, '\0' +}; + +static const char KW_yes[] = { + ASCII_y, ASCII_e, ASCII_s, '\0' +}; + +static const char KW_no[] = { + ASCII_n, ASCII_o, '\0' +}; + +static int +doParseXmlDecl(const ENCODING *(*encodingFinder)(const ENCODING *, + const char *, + const char *), + int isGeneralTextEntity, + const ENCODING *enc, + const char *ptr, + const char *end, + const char **badPtr, + const char **versionPtr, + const char **versionEndPtr, + const char **encodingName, + const ENCODING **encoding, + int *standalone) +{ + const char *val = NULL; + const char *name = NULL; + const char *nameEnd = NULL; + ptr += 5 * enc->minBytesPerChar; + end -= 2 * enc->minBytesPerChar; + if (!parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr) + || !name) { + *badPtr = ptr; + return 0; + } + if (!XmlNameMatchesAscii(enc, name, nameEnd, KW_version)) { + if (!isGeneralTextEntity) { + *badPtr = name; + return 0; + } + } + else { + if (versionPtr) + *versionPtr = val; + if (versionEndPtr) + *versionEndPtr = ptr; + if (!parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr)) { + *badPtr = ptr; + return 0; + } + if (!name) { + if (isGeneralTextEntity) { + /* a TextDecl must have an EncodingDecl */ + *badPtr = ptr; + return 0; + } + return 1; + } + } + if (XmlNameMatchesAscii(enc, name, nameEnd, KW_encoding)) { + int c = toAscii(enc, val, end); + if (!(ASCII_a <= c && c <= ASCII_z) && !(ASCII_A <= c && c <= ASCII_Z)) { + *badPtr = val; + return 0; + } + if (encodingName) + *encodingName = val; + if (encoding) + *encoding = encodingFinder(enc, val, ptr - enc->minBytesPerChar); + if (!parsePseudoAttribute(enc, ptr, end, &name, &nameEnd, &val, &ptr)) { + *badPtr = ptr; + return 0; + } + if (!name) + return 1; + } + if (!XmlNameMatchesAscii(enc, name, nameEnd, KW_standalone) + || isGeneralTextEntity) { + *badPtr = name; + return 0; + } + if (XmlNameMatchesAscii(enc, val, ptr - enc->minBytesPerChar, KW_yes)) { + if (standalone) + *standalone = 1; + } + else if (XmlNameMatchesAscii(enc, val, ptr - enc->minBytesPerChar, KW_no)) { + if (standalone) + *standalone = 0; + } + else { + *badPtr = val; + return 0; + } + while (isSpace(toAscii(enc, ptr, end))) + ptr += enc->minBytesPerChar; + if (ptr != end) { + *badPtr = ptr; + return 0; + } + return 1; +} + +static int FASTCALL +checkCharRefNumber(int result) +{ + switch (result >> 8) { + case 0xD8: case 0xD9: case 0xDA: case 0xDB: + case 0xDC: case 0xDD: case 0xDE: case 0xDF: + return -1; + case 0: + if (latin1_encoding.type[result] == BT_NONXML) + return -1; + break; + case 0xFF: + if (result == 0xFFFE || result == 0xFFFF) + return -1; + break; + } + return result; +} + +int FASTCALL +XmlUtf8Encode(int c, char *buf) +{ + enum { + /* minN is minimum legal resulting value for N byte sequence */ + min2 = 0x80, + min3 = 0x800, + min4 = 0x10000 + }; + + if (c < 0) + return 0; /* LCOV_EXCL_LINE: this case is always eliminated beforehand */ + if (c < min2) { + buf[0] = (char)(c | UTF8_cval1); + return 1; + } + if (c < min3) { + buf[0] = (char)((c >> 6) | UTF8_cval2); + buf[1] = (char)((c & 0x3f) | 0x80); + return 2; + } + if (c < min4) { + buf[0] = (char)((c >> 12) | UTF8_cval3); + buf[1] = (char)(((c >> 6) & 0x3f) | 0x80); + buf[2] = (char)((c & 0x3f) | 0x80); + return 3; + } + if (c < 0x110000) { + buf[0] = (char)((c >> 18) | UTF8_cval4); + buf[1] = (char)(((c >> 12) & 0x3f) | 0x80); + buf[2] = (char)(((c >> 6) & 0x3f) | 0x80); + buf[3] = (char)((c & 0x3f) | 0x80); + return 4; + } + return 0; /* LCOV_EXCL_LINE: this case too is eliminated before calling */ +} + +int FASTCALL +XmlUtf16Encode(int charNum, unsigned short *buf) +{ + if (charNum < 0) + return 0; + if (charNum < 0x10000) { + buf[0] = (unsigned short)charNum; + return 1; + } + if (charNum < 0x110000) { + charNum -= 0x10000; + buf[0] = (unsigned short)((charNum >> 10) + 0xD800); + buf[1] = (unsigned short)((charNum & 0x3FF) + 0xDC00); + return 2; + } + return 0; +} + +struct unknown_encoding { + struct normal_encoding normal; + CONVERTER convert; + void *userData; + unsigned short utf16[256]; + char utf8[256][4]; +}; + +#define AS_UNKNOWN_ENCODING(enc) ((const struct unknown_encoding *) (enc)) + +int +XmlSizeOfUnknownEncoding(void) +{ + return sizeof(struct unknown_encoding); +} + +static int PTRFASTCALL +unknown_isName(const ENCODING *enc, const char *p) +{ + const struct unknown_encoding *uenc = AS_UNKNOWN_ENCODING(enc); + int c = uenc->convert(uenc->userData, p); + if (c & ~0xFFFF) + return 0; + return UCS2_GET_NAMING(namePages, c >> 8, c & 0xFF); +} + +static int PTRFASTCALL +unknown_isNmstrt(const ENCODING *enc, const char *p) +{ + const struct unknown_encoding *uenc = AS_UNKNOWN_ENCODING(enc); + int c = uenc->convert(uenc->userData, p); + if (c & ~0xFFFF) + return 0; + return UCS2_GET_NAMING(nmstrtPages, c >> 8, c & 0xFF); +} + +static int PTRFASTCALL +unknown_isInvalid(const ENCODING *enc, const char *p) +{ + const struct unknown_encoding *uenc = AS_UNKNOWN_ENCODING(enc); + int c = uenc->convert(uenc->userData, p); + return (c & ~0xFFFF) || checkCharRefNumber(c) < 0; +} + +static enum XML_Convert_Result PTRCALL +unknown_toUtf8(const ENCODING *enc, + const char **fromP, const char *fromLim, + char **toP, const char *toLim) +{ + const struct unknown_encoding *uenc = AS_UNKNOWN_ENCODING(enc); + char buf[XML_UTF8_ENCODE_MAX]; + for (;;) { + const char *utf8; + int n; + if (*fromP == fromLim) + return XML_CONVERT_COMPLETED; + utf8 = uenc->utf8[(unsigned char)**fromP]; + n = *utf8++; + if (n == 0) { + int c = uenc->convert(uenc->userData, *fromP); + n = XmlUtf8Encode(c, buf); + if (n > toLim - *toP) + return XML_CONVERT_OUTPUT_EXHAUSTED; + utf8 = buf; + *fromP += (AS_NORMAL_ENCODING(enc)->type[(unsigned char)**fromP] + - (BT_LEAD2 - 2)); + } + else { + if (n > toLim - *toP) + return XML_CONVERT_OUTPUT_EXHAUSTED; + (*fromP)++; + } + memcpy(*toP, utf8, n); + *toP += n; + } +} + +static enum XML_Convert_Result PTRCALL +unknown_toUtf16(const ENCODING *enc, + const char **fromP, const char *fromLim, + unsigned short **toP, const unsigned short *toLim) +{ + const struct unknown_encoding *uenc = AS_UNKNOWN_ENCODING(enc); + while (*fromP < fromLim && *toP < toLim) { + unsigned short c = uenc->utf16[(unsigned char)**fromP]; + if (c == 0) { + c = (unsigned short) + uenc->convert(uenc->userData, *fromP); + *fromP += (AS_NORMAL_ENCODING(enc)->type[(unsigned char)**fromP] + - (BT_LEAD2 - 2)); + } + else + (*fromP)++; + *(*toP)++ = c; + } + + if ((*toP == toLim) && (*fromP < fromLim)) + return XML_CONVERT_OUTPUT_EXHAUSTED; + else + return XML_CONVERT_COMPLETED; +} + +ENCODING * +XmlInitUnknownEncoding(void *mem, + int *table, + CONVERTER convert, + void *userData) +{ + int i; + struct unknown_encoding *e = (struct unknown_encoding *)mem; + for (i = 0; i < (int)sizeof(struct normal_encoding); i++) + ((char *)mem)[i] = ((char *)&latin1_encoding)[i]; + for (i = 0; i < 128; i++) + if (latin1_encoding.type[i] != BT_OTHER + && latin1_encoding.type[i] != BT_NONXML + && table[i] != i) + return 0; + for (i = 0; i < 256; i++) { + int c = table[i]; + if (c == -1) { + e->normal.type[i] = BT_MALFORM; + /* This shouldn't really get used. */ + e->utf16[i] = 0xFFFF; + e->utf8[i][0] = 1; + e->utf8[i][1] = 0; + } + else if (c < 0) { + if (c < -4) + return 0; + /* Multi-byte sequences need a converter function */ + if (!convert) + return 0; + e->normal.type[i] = (unsigned char)(BT_LEAD2 - (c + 2)); + e->utf8[i][0] = 0; + e->utf16[i] = 0; + } + else if (c < 0x80) { + if (latin1_encoding.type[c] != BT_OTHER + && latin1_encoding.type[c] != BT_NONXML + && c != i) + return 0; + e->normal.type[i] = latin1_encoding.type[c]; + e->utf8[i][0] = 1; + e->utf8[i][1] = (char)c; + e->utf16[i] = (unsigned short)(c == 0 ? 0xFFFF : c); + } + else if (checkCharRefNumber(c) < 0) { + e->normal.type[i] = BT_NONXML; + /* This shouldn't really get used. */ + e->utf16[i] = 0xFFFF; + e->utf8[i][0] = 1; + e->utf8[i][1] = 0; + } + else { + if (c > 0xFFFF) + return 0; + if (UCS2_GET_NAMING(nmstrtPages, c >> 8, c & 0xff)) + e->normal.type[i] = BT_NMSTRT; + else if (UCS2_GET_NAMING(namePages, c >> 8, c & 0xff)) + e->normal.type[i] = BT_NAME; + else + e->normal.type[i] = BT_OTHER; + e->utf8[i][0] = (char)XmlUtf8Encode(c, e->utf8[i] + 1); + e->utf16[i] = (unsigned short)c; + } + } + e->userData = userData; + e->convert = convert; + if (convert) { + e->normal.isName2 = unknown_isName; + e->normal.isName3 = unknown_isName; + e->normal.isName4 = unknown_isName; + e->normal.isNmstrt2 = unknown_isNmstrt; + e->normal.isNmstrt3 = unknown_isNmstrt; + e->normal.isNmstrt4 = unknown_isNmstrt; + e->normal.isInvalid2 = unknown_isInvalid; + e->normal.isInvalid3 = unknown_isInvalid; + e->normal.isInvalid4 = unknown_isInvalid; + } + e->normal.enc.utf8Convert = unknown_toUtf8; + e->normal.enc.utf16Convert = unknown_toUtf16; + return &(e->normal.enc); +} + +/* If this enumeration is changed, getEncodingIndex and encodings +must also be changed. */ +enum { + UNKNOWN_ENC = -1, + ISO_8859_1_ENC = 0, + US_ASCII_ENC, + UTF_8_ENC, + UTF_16_ENC, + UTF_16BE_ENC, + UTF_16LE_ENC, + /* must match encodingNames up to here */ + NO_ENC +}; + +static const char KW_ISO_8859_1[] = { + ASCII_I, ASCII_S, ASCII_O, ASCII_MINUS, ASCII_8, ASCII_8, ASCII_5, ASCII_9, + ASCII_MINUS, ASCII_1, '\0' +}; +static const char KW_US_ASCII[] = { + ASCII_U, ASCII_S, ASCII_MINUS, ASCII_A, ASCII_S, ASCII_C, ASCII_I, ASCII_I, + '\0' +}; +static const char KW_UTF_8[] = { + ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_8, '\0' +}; +static const char KW_UTF_16[] = { + ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1, ASCII_6, '\0' +}; +static const char KW_UTF_16BE[] = { + ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1, ASCII_6, ASCII_B, ASCII_E, + '\0' +}; +static const char KW_UTF_16LE[] = { + ASCII_U, ASCII_T, ASCII_F, ASCII_MINUS, ASCII_1, ASCII_6, ASCII_L, ASCII_E, + '\0' +}; + +static int FASTCALL +getEncodingIndex(const char *name) +{ + static const char * const encodingNames[] = { + KW_ISO_8859_1, + KW_US_ASCII, + KW_UTF_8, + KW_UTF_16, + KW_UTF_16BE, + KW_UTF_16LE, + }; + int i; + if (name == NULL) + return NO_ENC; + for (i = 0; i < (int)(sizeof(encodingNames)/sizeof(encodingNames[0])); i++) + if (streqci(name, encodingNames[i])) + return i; + return UNKNOWN_ENC; +} + +/* For binary compatibility, we store the index of the encoding + specified at initialization in the isUtf16 member. +*/ + +#define INIT_ENC_INDEX(enc) ((int)(enc)->initEnc.isUtf16) +#define SET_INIT_ENC_INDEX(enc, i) ((enc)->initEnc.isUtf16 = (char)i) + +/* This is what detects the encoding. encodingTable maps from + encoding indices to encodings; INIT_ENC_INDEX(enc) is the index of + the external (protocol) specified encoding; state is + XML_CONTENT_STATE if we're parsing an external text entity, and + XML_PROLOG_STATE otherwise. +*/ + + +static int +initScan(const ENCODING * const *encodingTable, + const INIT_ENCODING *enc, + int state, + const char *ptr, + const char *end, + const char **nextTokPtr) +{ + const ENCODING **encPtr; + + if (ptr >= end) + return XML_TOK_NONE; + encPtr = enc->encPtr; + if (ptr + 1 == end) { + /* only a single byte available for auto-detection */ +#ifndef XML_DTD /* FIXME */ + /* a well-formed document entity must have more than one byte */ + if (state != XML_CONTENT_STATE) + return XML_TOK_PARTIAL; +#endif + /* so we're parsing an external text entity... */ + /* if UTF-16 was externally specified, then we need at least 2 bytes */ + switch (INIT_ENC_INDEX(enc)) { + case UTF_16_ENC: + case UTF_16LE_ENC: + case UTF_16BE_ENC: + return XML_TOK_PARTIAL; + } + switch ((unsigned char)*ptr) { + case 0xFE: + case 0xFF: + case 0xEF: /* possibly first byte of UTF-8 BOM */ + if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC + && state == XML_CONTENT_STATE) + break; + /* fall through */ + case 0x00: + case 0x3C: + return XML_TOK_PARTIAL; + } + } + else { + switch (((unsigned char)ptr[0] << 8) | (unsigned char)ptr[1]) { + case 0xFEFF: + if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC + && state == XML_CONTENT_STATE) + break; + *nextTokPtr = ptr + 2; + *encPtr = encodingTable[UTF_16BE_ENC]; + return XML_TOK_BOM; + /* 00 3C is handled in the default case */ + case 0x3C00: + if ((INIT_ENC_INDEX(enc) == UTF_16BE_ENC + || INIT_ENC_INDEX(enc) == UTF_16_ENC) + && state == XML_CONTENT_STATE) + break; + *encPtr = encodingTable[UTF_16LE_ENC]; + return XmlTok(*encPtr, state, ptr, end, nextTokPtr); + case 0xFFFE: + if (INIT_ENC_INDEX(enc) == ISO_8859_1_ENC + && state == XML_CONTENT_STATE) + break; + *nextTokPtr = ptr + 2; + *encPtr = encodingTable[UTF_16LE_ENC]; + return XML_TOK_BOM; + case 0xEFBB: + /* Maybe a UTF-8 BOM (EF BB BF) */ + /* If there's an explicitly specified (external) encoding + of ISO-8859-1 or some flavour of UTF-16 + and this is an external text entity, + don't look for the BOM, + because it might be a legal data. + */ + if (state == XML_CONTENT_STATE) { + int e = INIT_ENC_INDEX(enc); + if (e == ISO_8859_1_ENC || e == UTF_16BE_ENC + || e == UTF_16LE_ENC || e == UTF_16_ENC) + break; + } + if (ptr + 2 == end) + return XML_TOK_PARTIAL; + if ((unsigned char)ptr[2] == 0xBF) { + *nextTokPtr = ptr + 3; + *encPtr = encodingTable[UTF_8_ENC]; + return XML_TOK_BOM; + } + break; + default: + if (ptr[0] == '\0') { + /* 0 isn't a legal data character. Furthermore a document + entity can only start with ASCII characters. So the only + way this can fail to be big-endian UTF-16 if it it's an + external parsed general entity that's labelled as + UTF-16LE. + */ + if (state == XML_CONTENT_STATE && INIT_ENC_INDEX(enc) == UTF_16LE_ENC) + break; + *encPtr = encodingTable[UTF_16BE_ENC]; + return XmlTok(*encPtr, state, ptr, end, nextTokPtr); + } + else if (ptr[1] == '\0') { + /* We could recover here in the case: + - parsing an external entity + - second byte is 0 + - no externally specified encoding + - no encoding declaration + by assuming UTF-16LE. But we don't, because this would mean when + presented just with a single byte, we couldn't reliably determine + whether we needed further bytes. + */ + if (state == XML_CONTENT_STATE) + break; + *encPtr = encodingTable[UTF_16LE_ENC]; + return XmlTok(*encPtr, state, ptr, end, nextTokPtr); + } + break; + } + } + *encPtr = encodingTable[INIT_ENC_INDEX(enc)]; + return XmlTok(*encPtr, state, ptr, end, nextTokPtr); +} + + +#define NS(x) x +#define ns(x) x +#define XML_TOK_NS_C +#include "xmltok_ns.c" +#undef XML_TOK_NS_C +#undef NS +#undef ns + +#ifdef XML_NS + +#define NS(x) x ## NS +#define ns(x) x ## _ns + +#define XML_TOK_NS_C +#include "xmltok_ns.c" +#undef XML_TOK_NS_C + +#undef NS +#undef ns + +ENCODING * +XmlInitUnknownEncodingNS(void *mem, + int *table, + CONVERTER convert, + void *userData) +{ + ENCODING *enc = XmlInitUnknownEncoding(mem, table, convert, userData); + if (enc) + ((struct normal_encoding *)enc)->type[ASCII_COLON] = BT_COLON; + return enc; +} + +#endif /* XML_NS */ diff --git a/tools/sdk/include/expat/xmltok.h b/tools/sdk/include/expat/xmltok.h index 752007e8..50926f38 100644 --- a/tools/sdk/include/expat/xmltok.h +++ b/tools/sdk/include/expat/xmltok.h @@ -1,5 +1,33 @@ -/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd - See the file COPYING for copying permission. +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef XmlTok_INCLUDED @@ -139,9 +167,6 @@ enum XML_Convert_Result { struct encoding { SCANNER scanners[XML_N_STATES]; SCANNER literalScanners[XML_N_LITERAL_TYPES]; - int (PTRCALL *sameName)(const ENCODING *, - const char *, - const char *); int (PTRCALL *nameMatchesAscii)(const ENCODING *, const char *, const char *, @@ -232,8 +257,6 @@ struct encoding { #define XmlEntityValueTok(enc, ptr, end, nextTokPtr) \ XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr) -#define XmlSameName(enc, ptr1, ptr2) (((enc)->sameName)(enc, ptr1, ptr2)) - #define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) \ (((enc)->nameMatchesAscii)(enc, ptr1, end1, ptr2)) diff --git a/tools/sdk/include/expat/xmltok_impl.c b/tools/sdk/include/expat/xmltok_impl.c new file mode 100644 index 00000000..0403dd3d --- /dev/null +++ b/tools/sdk/include/expat/xmltok_impl.c @@ -0,0 +1,1760 @@ +/* This file is included! + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifdef XML_TOK_IMPL_C + +#ifndef IS_INVALID_CHAR +#define IS_INVALID_CHAR(enc, ptr, n) (0) +#endif + +#define INVALID_LEAD_CASE(n, ptr, nextTokPtr) \ + case BT_LEAD ## n: \ + if (end - ptr < n) \ + return XML_TOK_PARTIAL_CHAR; \ + if (IS_INVALID_CHAR(enc, ptr, n)) { \ + *(nextTokPtr) = (ptr); \ + return XML_TOK_INVALID; \ + } \ + ptr += n; \ + break; + +#define INVALID_CASES(ptr, nextTokPtr) \ + INVALID_LEAD_CASE(2, ptr, nextTokPtr) \ + INVALID_LEAD_CASE(3, ptr, nextTokPtr) \ + INVALID_LEAD_CASE(4, ptr, nextTokPtr) \ + case BT_NONXML: \ + case BT_MALFORM: \ + case BT_TRAIL: \ + *(nextTokPtr) = (ptr); \ + return XML_TOK_INVALID; + +#define CHECK_NAME_CASE(n, enc, ptr, end, nextTokPtr) \ + case BT_LEAD ## n: \ + if (end - ptr < n) \ + return XML_TOK_PARTIAL_CHAR; \ + if (!IS_NAME_CHAR(enc, ptr, n)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; \ + } \ + ptr += n; \ + break; + +#define CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) \ + case BT_NONASCII: \ + if (!IS_NAME_CHAR_MINBPC(enc, ptr)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; \ + } \ + case BT_NMSTRT: \ + case BT_HEX: \ + case BT_DIGIT: \ + case BT_NAME: \ + case BT_MINUS: \ + ptr += MINBPC(enc); \ + break; \ + CHECK_NAME_CASE(2, enc, ptr, end, nextTokPtr) \ + CHECK_NAME_CASE(3, enc, ptr, end, nextTokPtr) \ + CHECK_NAME_CASE(4, enc, ptr, end, nextTokPtr) + +#define CHECK_NMSTRT_CASE(n, enc, ptr, end, nextTokPtr) \ + case BT_LEAD ## n: \ + if (end - ptr < n) \ + return XML_TOK_PARTIAL_CHAR; \ + if (!IS_NMSTRT_CHAR(enc, ptr, n)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; \ + } \ + ptr += n; \ + break; + +#define CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) \ + case BT_NONASCII: \ + if (!IS_NMSTRT_CHAR_MINBPC(enc, ptr)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; \ + } \ + case BT_NMSTRT: \ + case BT_HEX: \ + ptr += MINBPC(enc); \ + break; \ + CHECK_NMSTRT_CASE(2, enc, ptr, end, nextTokPtr) \ + CHECK_NMSTRT_CASE(3, enc, ptr, end, nextTokPtr) \ + CHECK_NMSTRT_CASE(4, enc, ptr, end, nextTokPtr) + +#ifndef PREFIX +#define PREFIX(ident) ident +#endif + + +#define HAS_CHARS(enc, ptr, end, count) \ + (end - ptr >= count * MINBPC(enc)) + +#define HAS_CHAR(enc, ptr, end) \ + HAS_CHARS(enc, ptr, end, 1) + +#define REQUIRE_CHARS(enc, ptr, end, count) \ + { \ + if (! HAS_CHARS(enc, ptr, end, count)) { \ + return XML_TOK_PARTIAL; \ + } \ + } + +#define REQUIRE_CHAR(enc, ptr, end) \ + REQUIRE_CHARS(enc, ptr, end, 1) + + +/* ptr points to character following " */ + switch (BYTE_TYPE(enc, ptr + MINBPC(enc))) { + case BT_S: case BT_CR: case BT_LF: case BT_PERCNT: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + /* fall through */ + case BT_S: case BT_CR: case BT_LF: + *nextTokPtr = ptr; + return XML_TOK_DECL_OPEN; + case BT_NMSTRT: + case BT_HEX: + ptr += MINBPC(enc); + break; + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + } + return XML_TOK_PARTIAL; +} + +static int PTRCALL +PREFIX(checkPiTarget)(const ENCODING *UNUSED_P(enc), const char *ptr, + const char *end, int *tokPtr) +{ + int upper = 0; + *tokPtr = XML_TOK_PI; + if (end - ptr != MINBPC(enc)*3) + return 1; + switch (BYTE_TO_ASCII(enc, ptr)) { + case ASCII_x: + break; + case ASCII_X: + upper = 1; + break; + default: + return 1; + } + ptr += MINBPC(enc); + switch (BYTE_TO_ASCII(enc, ptr)) { + case ASCII_m: + break; + case ASCII_M: + upper = 1; + break; + default: + return 1; + } + ptr += MINBPC(enc); + switch (BYTE_TO_ASCII(enc, ptr)) { + case ASCII_l: + break; + case ASCII_L: + upper = 1; + break; + default: + return 1; + } + if (upper) + return 0; + *tokPtr = XML_TOK_XML_DECL; + return 1; +} + +/* ptr points to character following "= end) + return XML_TOK_NONE; + if (MINBPC(enc) > 1) { + size_t n = end - ptr; + if (n & (MINBPC(enc) - 1)) { + n &= ~(MINBPC(enc) - 1); + if (n == 0) + return XML_TOK_PARTIAL; + end = ptr + n; + } + } + switch (BYTE_TYPE(enc, ptr)) { + case BT_RSQB: + ptr += MINBPC(enc); + REQUIRE_CHAR(enc, ptr, end); + if (!CHAR_MATCHES(enc, ptr, ASCII_RSQB)) + break; + ptr += MINBPC(enc); + REQUIRE_CHAR(enc, ptr, end); + if (!CHAR_MATCHES(enc, ptr, ASCII_GT)) { + ptr -= MINBPC(enc); + break; + } + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_CDATA_SECT_CLOSE; + case BT_CR: + ptr += MINBPC(enc); + REQUIRE_CHAR(enc, ptr, end); + if (BYTE_TYPE(enc, ptr) == BT_LF) + ptr += MINBPC(enc); + *nextTokPtr = ptr; + return XML_TOK_DATA_NEWLINE; + case BT_LF: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_DATA_NEWLINE; + INVALID_CASES(ptr, nextTokPtr) + default: + ptr += MINBPC(enc); + break; + } + while (HAS_CHAR(enc, ptr, end)) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: \ + if (end - ptr < n || IS_INVALID_CHAR(enc, ptr, n)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_DATA_CHARS; \ + } \ + ptr += n; \ + break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_NONXML: + case BT_MALFORM: + case BT_TRAIL: + case BT_CR: + case BT_LF: + case BT_RSQB: + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + default: + ptr += MINBPC(enc); + break; + } + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; +} + +/* ptr points to character following "= end) + return XML_TOK_NONE; + if (MINBPC(enc) > 1) { + size_t n = end - ptr; + if (n & (MINBPC(enc) - 1)) { + n &= ~(MINBPC(enc) - 1); + if (n == 0) + return XML_TOK_PARTIAL; + end = ptr + n; + } + } + switch (BYTE_TYPE(enc, ptr)) { + case BT_LT: + return PREFIX(scanLt)(enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_AMP: + return PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_CR: + ptr += MINBPC(enc); + if (! HAS_CHAR(enc, ptr, end)) + return XML_TOK_TRAILING_CR; + if (BYTE_TYPE(enc, ptr) == BT_LF) + ptr += MINBPC(enc); + *nextTokPtr = ptr; + return XML_TOK_DATA_NEWLINE; + case BT_LF: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_DATA_NEWLINE; + case BT_RSQB: + ptr += MINBPC(enc); + if (! HAS_CHAR(enc, ptr, end)) + return XML_TOK_TRAILING_RSQB; + if (!CHAR_MATCHES(enc, ptr, ASCII_RSQB)) + break; + ptr += MINBPC(enc); + if (! HAS_CHAR(enc, ptr, end)) + return XML_TOK_TRAILING_RSQB; + if (!CHAR_MATCHES(enc, ptr, ASCII_GT)) { + ptr -= MINBPC(enc); + break; + } + *nextTokPtr = ptr; + return XML_TOK_INVALID; + INVALID_CASES(ptr, nextTokPtr) + default: + ptr += MINBPC(enc); + break; + } + while (HAS_CHAR(enc, ptr, end)) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: \ + if (end - ptr < n || IS_INVALID_CHAR(enc, ptr, n)) { \ + *nextTokPtr = ptr; \ + return XML_TOK_DATA_CHARS; \ + } \ + ptr += n; \ + break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_RSQB: + if (HAS_CHARS(enc, ptr, end, 2)) { + if (!CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_RSQB)) { + ptr += MINBPC(enc); + break; + } + if (HAS_CHARS(enc, ptr, end, 3)) { + if (!CHAR_MATCHES(enc, ptr + 2*MINBPC(enc), ASCII_GT)) { + ptr += MINBPC(enc); + break; + } + *nextTokPtr = ptr + 2*MINBPC(enc); + return XML_TOK_INVALID; + } + } + /* fall through */ + case BT_AMP: + case BT_LT: + case BT_NONXML: + case BT_MALFORM: + case BT_TRAIL: + case BT_CR: + case BT_LF: + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + default: + ptr += MINBPC(enc); + break; + } + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; +} + +/* ptr points to character following "%" */ + +static int PTRCALL +PREFIX(scanPercent)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + REQUIRE_CHAR(enc, ptr, end); + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) + case BT_S: case BT_LF: case BT_CR: case BT_PERCNT: + *nextTokPtr = ptr; + return XML_TOK_PERCENT; + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + while (HAS_CHAR(enc, ptr, end)) { + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) + case BT_SEMI: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_PARAM_ENTITY_REF; + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + } + return XML_TOK_PARTIAL; +} + +static int PTRCALL +PREFIX(scanPoundName)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + REQUIRE_CHAR(enc, ptr, end); + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + while (HAS_CHAR(enc, ptr, end)) { + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) + case BT_CR: case BT_LF: case BT_S: + case BT_RPAR: case BT_GT: case BT_PERCNT: case BT_VERBAR: + *nextTokPtr = ptr; + return XML_TOK_POUND_NAME; + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + } + return -XML_TOK_POUND_NAME; +} + +static int PTRCALL +PREFIX(scanLit)(int open, const ENCODING *enc, + const char *ptr, const char *end, + const char **nextTokPtr) +{ + while (HAS_CHAR(enc, ptr, end)) { + int t = BYTE_TYPE(enc, ptr); + switch (t) { + INVALID_CASES(ptr, nextTokPtr) + case BT_QUOT: + case BT_APOS: + ptr += MINBPC(enc); + if (t != open) + break; + if (! HAS_CHAR(enc, ptr, end)) + return -XML_TOK_LITERAL; + *nextTokPtr = ptr; + switch (BYTE_TYPE(enc, ptr)) { + case BT_S: case BT_CR: case BT_LF: + case BT_GT: case BT_PERCNT: case BT_LSQB: + return XML_TOK_LITERAL; + default: + return XML_TOK_INVALID; + } + default: + ptr += MINBPC(enc); + break; + } + } + return XML_TOK_PARTIAL; +} + +static int PTRCALL +PREFIX(prologTok)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + int tok; + if (ptr >= end) + return XML_TOK_NONE; + if (MINBPC(enc) > 1) { + size_t n = end - ptr; + if (n & (MINBPC(enc) - 1)) { + n &= ~(MINBPC(enc) - 1); + if (n == 0) + return XML_TOK_PARTIAL; + end = ptr + n; + } + } + switch (BYTE_TYPE(enc, ptr)) { + case BT_QUOT: + return PREFIX(scanLit)(BT_QUOT, enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_APOS: + return PREFIX(scanLit)(BT_APOS, enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_LT: + { + ptr += MINBPC(enc); + REQUIRE_CHAR(enc, ptr, end); + switch (BYTE_TYPE(enc, ptr)) { + case BT_EXCL: + return PREFIX(scanDecl)(enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_QUEST: + return PREFIX(scanPi)(enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_NMSTRT: + case BT_HEX: + case BT_NONASCII: + case BT_LEAD2: + case BT_LEAD3: + case BT_LEAD4: + *nextTokPtr = ptr - MINBPC(enc); + return XML_TOK_INSTANCE_START; + } + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + case BT_CR: + if (ptr + MINBPC(enc) == end) { + *nextTokPtr = end; + /* indicate that this might be part of a CR/LF pair */ + return -XML_TOK_PROLOG_S; + } + /* fall through */ + case BT_S: case BT_LF: + for (;;) { + ptr += MINBPC(enc); + if (! HAS_CHAR(enc, ptr, end)) + break; + switch (BYTE_TYPE(enc, ptr)) { + case BT_S: case BT_LF: + break; + case BT_CR: + /* don't split CR/LF pair */ + if (ptr + MINBPC(enc) != end) + break; + /* fall through */ + default: + *nextTokPtr = ptr; + return XML_TOK_PROLOG_S; + } + } + *nextTokPtr = ptr; + return XML_TOK_PROLOG_S; + case BT_PERCNT: + return PREFIX(scanPercent)(enc, ptr + MINBPC(enc), end, nextTokPtr); + case BT_COMMA: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_COMMA; + case BT_LSQB: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_OPEN_BRACKET; + case BT_RSQB: + ptr += MINBPC(enc); + if (! HAS_CHAR(enc, ptr, end)) + return -XML_TOK_CLOSE_BRACKET; + if (CHAR_MATCHES(enc, ptr, ASCII_RSQB)) { + REQUIRE_CHARS(enc, ptr, end, 2); + if (CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_GT)) { + *nextTokPtr = ptr + 2*MINBPC(enc); + return XML_TOK_COND_SECT_CLOSE; + } + } + *nextTokPtr = ptr; + return XML_TOK_CLOSE_BRACKET; + case BT_LPAR: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_OPEN_PAREN; + case BT_RPAR: + ptr += MINBPC(enc); + if (! HAS_CHAR(enc, ptr, end)) + return -XML_TOK_CLOSE_PAREN; + switch (BYTE_TYPE(enc, ptr)) { + case BT_AST: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_CLOSE_PAREN_ASTERISK; + case BT_QUEST: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_CLOSE_PAREN_QUESTION; + case BT_PLUS: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_CLOSE_PAREN_PLUS; + case BT_CR: case BT_LF: case BT_S: + case BT_GT: case BT_COMMA: case BT_VERBAR: + case BT_RPAR: + *nextTokPtr = ptr; + return XML_TOK_CLOSE_PAREN; + } + *nextTokPtr = ptr; + return XML_TOK_INVALID; + case BT_VERBAR: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_OR; + case BT_GT: + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_DECL_CLOSE; + case BT_NUM: + return PREFIX(scanPoundName)(enc, ptr + MINBPC(enc), end, nextTokPtr); +#define LEAD_CASE(n) \ + case BT_LEAD ## n: \ + if (end - ptr < n) \ + return XML_TOK_PARTIAL_CHAR; \ + if (IS_NMSTRT_CHAR(enc, ptr, n)) { \ + ptr += n; \ + tok = XML_TOK_NAME; \ + break; \ + } \ + if (IS_NAME_CHAR(enc, ptr, n)) { \ + ptr += n; \ + tok = XML_TOK_NMTOKEN; \ + break; \ + } \ + *nextTokPtr = ptr; \ + return XML_TOK_INVALID; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_NMSTRT: + case BT_HEX: + tok = XML_TOK_NAME; + ptr += MINBPC(enc); + break; + case BT_DIGIT: + case BT_NAME: + case BT_MINUS: +#ifdef XML_NS + case BT_COLON: +#endif + tok = XML_TOK_NMTOKEN; + ptr += MINBPC(enc); + break; + case BT_NONASCII: + if (IS_NMSTRT_CHAR_MINBPC(enc, ptr)) { + ptr += MINBPC(enc); + tok = XML_TOK_NAME; + break; + } + if (IS_NAME_CHAR_MINBPC(enc, ptr)) { + ptr += MINBPC(enc); + tok = XML_TOK_NMTOKEN; + break; + } + /* fall through */ + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + while (HAS_CHAR(enc, ptr, end)) { + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) + case BT_GT: case BT_RPAR: case BT_COMMA: + case BT_VERBAR: case BT_LSQB: case BT_PERCNT: + case BT_S: case BT_CR: case BT_LF: + *nextTokPtr = ptr; + return tok; +#ifdef XML_NS + case BT_COLON: + ptr += MINBPC(enc); + switch (tok) { + case XML_TOK_NAME: + REQUIRE_CHAR(enc, ptr, end); + tok = XML_TOK_PREFIXED_NAME; + switch (BYTE_TYPE(enc, ptr)) { + CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) + default: + tok = XML_TOK_NMTOKEN; + break; + } + break; + case XML_TOK_PREFIXED_NAME: + tok = XML_TOK_NMTOKEN; + break; + } + break; +#endif + case BT_PLUS: + if (tok == XML_TOK_NMTOKEN) { + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_NAME_PLUS; + case BT_AST: + if (tok == XML_TOK_NMTOKEN) { + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_NAME_ASTERISK; + case BT_QUEST: + if (tok == XML_TOK_NMTOKEN) { + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_NAME_QUESTION; + default: + *nextTokPtr = ptr; + return XML_TOK_INVALID; + } + } + return -tok; +} + +static int PTRCALL +PREFIX(attributeValueTok)(const ENCODING *enc, const char *ptr, + const char *end, const char **nextTokPtr) +{ + const char *start; + if (ptr >= end) + return XML_TOK_NONE; + else if (! HAS_CHAR(enc, ptr, end)) { + /* This line cannot be executed. The incoming data has already + * been tokenized once, so incomplete characters like this have + * already been eliminated from the input. Retaining the paranoia + * check is still valuable, however. + */ + return XML_TOK_PARTIAL; /* LCOV_EXCL_LINE */ + } + start = ptr; + while (HAS_CHAR(enc, ptr, end)) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: ptr += n; break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_AMP: + if (ptr == start) + return PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, nextTokPtr); + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_LT: + /* this is for inside entity references */ + *nextTokPtr = ptr; + return XML_TOK_INVALID; + case BT_LF: + if (ptr == start) { + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_DATA_NEWLINE; + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_CR: + if (ptr == start) { + ptr += MINBPC(enc); + if (! HAS_CHAR(enc, ptr, end)) + return XML_TOK_TRAILING_CR; + if (BYTE_TYPE(enc, ptr) == BT_LF) + ptr += MINBPC(enc); + *nextTokPtr = ptr; + return XML_TOK_DATA_NEWLINE; + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_S: + if (ptr == start) { + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_ATTRIBUTE_VALUE_S; + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + default: + ptr += MINBPC(enc); + break; + } + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; +} + +static int PTRCALL +PREFIX(entityValueTok)(const ENCODING *enc, const char *ptr, + const char *end, const char **nextTokPtr) +{ + const char *start; + if (ptr >= end) + return XML_TOK_NONE; + else if (! HAS_CHAR(enc, ptr, end)) { + /* This line cannot be executed. The incoming data has already + * been tokenized once, so incomplete characters like this have + * already been eliminated from the input. Retaining the paranoia + * check is still valuable, however. + */ + return XML_TOK_PARTIAL; /* LCOV_EXCL_LINE */ + } + start = ptr; + while (HAS_CHAR(enc, ptr, end)) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: ptr += n; break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_AMP: + if (ptr == start) + return PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, nextTokPtr); + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_PERCNT: + if (ptr == start) { + int tok = PREFIX(scanPercent)(enc, ptr + MINBPC(enc), + end, nextTokPtr); + return (tok == XML_TOK_PERCENT) ? XML_TOK_INVALID : tok; + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_LF: + if (ptr == start) { + *nextTokPtr = ptr + MINBPC(enc); + return XML_TOK_DATA_NEWLINE; + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + case BT_CR: + if (ptr == start) { + ptr += MINBPC(enc); + if (! HAS_CHAR(enc, ptr, end)) + return XML_TOK_TRAILING_CR; + if (BYTE_TYPE(enc, ptr) == BT_LF) + ptr += MINBPC(enc); + *nextTokPtr = ptr; + return XML_TOK_DATA_NEWLINE; + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; + default: + ptr += MINBPC(enc); + break; + } + } + *nextTokPtr = ptr; + return XML_TOK_DATA_CHARS; +} + +#ifdef XML_DTD + +static int PTRCALL +PREFIX(ignoreSectionTok)(const ENCODING *enc, const char *ptr, + const char *end, const char **nextTokPtr) +{ + int level = 0; + if (MINBPC(enc) > 1) { + size_t n = end - ptr; + if (n & (MINBPC(enc) - 1)) { + n &= ~(MINBPC(enc) - 1); + end = ptr + n; + } + } + while (HAS_CHAR(enc, ptr, end)) { + switch (BYTE_TYPE(enc, ptr)) { + INVALID_CASES(ptr, nextTokPtr) + case BT_LT: + ptr += MINBPC(enc); + REQUIRE_CHAR(enc, ptr, end); + if (CHAR_MATCHES(enc, ptr, ASCII_EXCL)) { + ptr += MINBPC(enc); + REQUIRE_CHAR(enc, ptr, end); + if (CHAR_MATCHES(enc, ptr, ASCII_LSQB)) { + ++level; + ptr += MINBPC(enc); + } + } + break; + case BT_RSQB: + ptr += MINBPC(enc); + REQUIRE_CHAR(enc, ptr, end); + if (CHAR_MATCHES(enc, ptr, ASCII_RSQB)) { + ptr += MINBPC(enc); + REQUIRE_CHAR(enc, ptr, end); + if (CHAR_MATCHES(enc, ptr, ASCII_GT)) { + ptr += MINBPC(enc); + if (level == 0) { + *nextTokPtr = ptr; + return XML_TOK_IGNORE_SECT; + } + --level; + } + } + break; + default: + ptr += MINBPC(enc); + break; + } + } + return XML_TOK_PARTIAL; +} + +#endif /* XML_DTD */ + +static int PTRCALL +PREFIX(isPublicId)(const ENCODING *enc, const char *ptr, const char *end, + const char **badPtr) +{ + ptr += MINBPC(enc); + end -= MINBPC(enc); + for (; HAS_CHAR(enc, ptr, end); ptr += MINBPC(enc)) { + switch (BYTE_TYPE(enc, ptr)) { + case BT_DIGIT: + case BT_HEX: + case BT_MINUS: + case BT_APOS: + case BT_LPAR: + case BT_RPAR: + case BT_PLUS: + case BT_COMMA: + case BT_SOL: + case BT_EQUALS: + case BT_QUEST: + case BT_CR: + case BT_LF: + case BT_SEMI: + case BT_EXCL: + case BT_AST: + case BT_PERCNT: + case BT_NUM: +#ifdef XML_NS + case BT_COLON: +#endif + break; + case BT_S: + if (CHAR_MATCHES(enc, ptr, ASCII_TAB)) { + *badPtr = ptr; + return 0; + } + break; + case BT_NAME: + case BT_NMSTRT: + if (!(BYTE_TO_ASCII(enc, ptr) & ~0x7f)) + break; + default: + switch (BYTE_TO_ASCII(enc, ptr)) { + case 0x24: /* $ */ + case 0x40: /* @ */ + break; + default: + *badPtr = ptr; + return 0; + } + break; + } + } + return 1; +} + +/* This must only be called for a well-formed start-tag or empty + element tag. Returns the number of attributes. Pointers to the + first attsMax attributes are stored in atts. +*/ + +static int PTRCALL +PREFIX(getAtts)(const ENCODING *enc, const char *ptr, + int attsMax, ATTRIBUTE *atts) +{ + enum { other, inName, inValue } state = inName; + int nAtts = 0; + int open = 0; /* defined when state == inValue; + initialization just to shut up compilers */ + + for (ptr += MINBPC(enc);; ptr += MINBPC(enc)) { + switch (BYTE_TYPE(enc, ptr)) { +#define START_NAME \ + if (state == other) { \ + if (nAtts < attsMax) { \ + atts[nAtts].name = ptr; \ + atts[nAtts].normalized = 1; \ + } \ + state = inName; \ + } +#define LEAD_CASE(n) \ + case BT_LEAD ## n: START_NAME ptr += (n - MINBPC(enc)); break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_NONASCII: + case BT_NMSTRT: + case BT_HEX: + START_NAME + break; +#undef START_NAME + case BT_QUOT: + if (state != inValue) { + if (nAtts < attsMax) + atts[nAtts].valuePtr = ptr + MINBPC(enc); + state = inValue; + open = BT_QUOT; + } + else if (open == BT_QUOT) { + state = other; + if (nAtts < attsMax) + atts[nAtts].valueEnd = ptr; + nAtts++; + } + break; + case BT_APOS: + if (state != inValue) { + if (nAtts < attsMax) + atts[nAtts].valuePtr = ptr + MINBPC(enc); + state = inValue; + open = BT_APOS; + } + else if (open == BT_APOS) { + state = other; + if (nAtts < attsMax) + atts[nAtts].valueEnd = ptr; + nAtts++; + } + break; + case BT_AMP: + if (nAtts < attsMax) + atts[nAtts].normalized = 0; + break; + case BT_S: + if (state == inName) + state = other; + else if (state == inValue + && nAtts < attsMax + && atts[nAtts].normalized + && (ptr == atts[nAtts].valuePtr + || BYTE_TO_ASCII(enc, ptr) != ASCII_SPACE + || BYTE_TO_ASCII(enc, ptr + MINBPC(enc)) == ASCII_SPACE + || BYTE_TYPE(enc, ptr + MINBPC(enc)) == open)) + atts[nAtts].normalized = 0; + break; + case BT_CR: case BT_LF: + /* This case ensures that the first attribute name is counted + Apart from that we could just change state on the quote. */ + if (state == inName) + state = other; + else if (state == inValue && nAtts < attsMax) + atts[nAtts].normalized = 0; + break; + case BT_GT: + case BT_SOL: + if (state != inValue) + return nAtts; + break; + default: + break; + } + } + /* not reached */ +} + +static int PTRFASTCALL +PREFIX(charRefNumber)(const ENCODING *UNUSED_P(enc), const char *ptr) +{ + int result = 0; + /* skip &# */ + ptr += 2*MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_x)) { + for (ptr += MINBPC(enc); + !CHAR_MATCHES(enc, ptr, ASCII_SEMI); + ptr += MINBPC(enc)) { + int c = BYTE_TO_ASCII(enc, ptr); + switch (c) { + case ASCII_0: case ASCII_1: case ASCII_2: case ASCII_3: case ASCII_4: + case ASCII_5: case ASCII_6: case ASCII_7: case ASCII_8: case ASCII_9: + result <<= 4; + result |= (c - ASCII_0); + break; + case ASCII_A: case ASCII_B: case ASCII_C: + case ASCII_D: case ASCII_E: case ASCII_F: + result <<= 4; + result += 10 + (c - ASCII_A); + break; + case ASCII_a: case ASCII_b: case ASCII_c: + case ASCII_d: case ASCII_e: case ASCII_f: + result <<= 4; + result += 10 + (c - ASCII_a); + break; + } + if (result >= 0x110000) + return -1; + } + } + else { + for (; !CHAR_MATCHES(enc, ptr, ASCII_SEMI); ptr += MINBPC(enc)) { + int c = BYTE_TO_ASCII(enc, ptr); + result *= 10; + result += (c - ASCII_0); + if (result >= 0x110000) + return -1; + } + } + return checkCharRefNumber(result); +} + +static int PTRCALL +PREFIX(predefinedEntityName)(const ENCODING *UNUSED_P(enc), const char *ptr, + const char *end) +{ + switch ((end - ptr)/MINBPC(enc)) { + case 2: + if (CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_t)) { + switch (BYTE_TO_ASCII(enc, ptr)) { + case ASCII_l: + return ASCII_LT; + case ASCII_g: + return ASCII_GT; + } + } + break; + case 3: + if (CHAR_MATCHES(enc, ptr, ASCII_a)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_m)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_p)) + return ASCII_AMP; + } + } + break; + case 4: + switch (BYTE_TO_ASCII(enc, ptr)) { + case ASCII_q: + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_u)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_o)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_t)) + return ASCII_QUOT; + } + } + break; + case ASCII_a: + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_p)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_o)) { + ptr += MINBPC(enc); + if (CHAR_MATCHES(enc, ptr, ASCII_s)) + return ASCII_APOS; + } + } + break; + } + } + return 0; +} + +static int PTRCALL +PREFIX(nameMatchesAscii)(const ENCODING *UNUSED_P(enc), const char *ptr1, + const char *end1, const char *ptr2) +{ + for (; *ptr2; ptr1 += MINBPC(enc), ptr2++) { + if (end1 - ptr1 < MINBPC(enc)) { + /* This line cannot be executed. THe incoming data has already + * been tokenized once, so imcomplete characters like this have + * already been eliminated from the input. Retaining the + * paranoia check is still valuable, however. + */ + return 0; /* LCOV_EXCL_LINE */ + } + if (!CHAR_MATCHES(enc, ptr1, *ptr2)) + return 0; + } + return ptr1 == end1; +} + +static int PTRFASTCALL +PREFIX(nameLength)(const ENCODING *enc, const char *ptr) +{ + const char *start = ptr; + for (;;) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: ptr += n; break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_NONASCII: + case BT_NMSTRT: +#ifdef XML_NS + case BT_COLON: +#endif + case BT_HEX: + case BT_DIGIT: + case BT_NAME: + case BT_MINUS: + ptr += MINBPC(enc); + break; + default: + return (int)(ptr - start); + } + } +} + +static const char * PTRFASTCALL +PREFIX(skipS)(const ENCODING *enc, const char *ptr) +{ + for (;;) { + switch (BYTE_TYPE(enc, ptr)) { + case BT_LF: + case BT_CR: + case BT_S: + ptr += MINBPC(enc); + break; + default: + return ptr; + } + } +} + +static void PTRCALL +PREFIX(updatePosition)(const ENCODING *enc, + const char *ptr, + const char *end, + POSITION *pos) +{ + while (HAS_CHAR(enc, ptr, end)) { + switch (BYTE_TYPE(enc, ptr)) { +#define LEAD_CASE(n) \ + case BT_LEAD ## n: \ + ptr += n; \ + break; + LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) +#undef LEAD_CASE + case BT_LF: + pos->columnNumber = (XML_Size)-1; + pos->lineNumber++; + ptr += MINBPC(enc); + break; + case BT_CR: + pos->lineNumber++; + ptr += MINBPC(enc); + if (HAS_CHAR(enc, ptr, end) && BYTE_TYPE(enc, ptr) == BT_LF) + ptr += MINBPC(enc); + pos->columnNumber = (XML_Size)-1; + break; + default: + ptr += MINBPC(enc); + break; + } + pos->columnNumber++; + } +} + +#undef DO_LEAD_CASE +#undef MULTIBYTE_CASES +#undef INVALID_CASES +#undef CHECK_NAME_CASE +#undef CHECK_NAME_CASES +#undef CHECK_NMSTRT_CASE +#undef CHECK_NMSTRT_CASES + +#endif /* XML_TOK_IMPL_C */ diff --git a/tools/sdk/include/expat/xmltok_impl.h b/tools/sdk/include/expat/xmltok_impl.h index da0ea60a..a6420f48 100644 --- a/tools/sdk/include/expat/xmltok_impl.h +++ b/tools/sdk/include/expat/xmltok_impl.h @@ -1,6 +1,33 @@ /* -Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd -See the file COPYING for copying permission. + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. */ enum { diff --git a/tools/sdk/include/expat/xmltok_ns.c b/tools/sdk/include/expat/xmltok_ns.c new file mode 100644 index 00000000..23d31e8e --- /dev/null +++ b/tools/sdk/include/expat/xmltok_ns.c @@ -0,0 +1,142 @@ +/* This file is included! + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifdef XML_TOK_NS_C + +const ENCODING * +NS(XmlGetUtf8InternalEncoding)(void) +{ + return &ns(internal_utf8_encoding).enc; +} + +const ENCODING * +NS(XmlGetUtf16InternalEncoding)(void) +{ +#if BYTEORDER == 1234 + return &ns(internal_little2_encoding).enc; +#elif BYTEORDER == 4321 + return &ns(internal_big2_encoding).enc; +#else + const short n = 1; + return (*(const char *)&n + ? &ns(internal_little2_encoding).enc + : &ns(internal_big2_encoding).enc); +#endif +} + +static const ENCODING * const NS(encodings)[] = { + &ns(latin1_encoding).enc, + &ns(ascii_encoding).enc, + &ns(utf8_encoding).enc, + &ns(big2_encoding).enc, + &ns(big2_encoding).enc, + &ns(little2_encoding).enc, + &ns(utf8_encoding).enc /* NO_ENC */ +}; + +static int PTRCALL +NS(initScanProlog)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + return initScan(NS(encodings), (const INIT_ENCODING *)enc, + XML_PROLOG_STATE, ptr, end, nextTokPtr); +} + +static int PTRCALL +NS(initScanContent)(const ENCODING *enc, const char *ptr, const char *end, + const char **nextTokPtr) +{ + return initScan(NS(encodings), (const INIT_ENCODING *)enc, + XML_CONTENT_STATE, ptr, end, nextTokPtr); +} + +int +NS(XmlInitEncoding)(INIT_ENCODING *p, const ENCODING **encPtr, + const char *name) +{ + int i = getEncodingIndex(name); + if (i == UNKNOWN_ENC) + return 0; + SET_INIT_ENC_INDEX(p, i); + p->initEnc.scanners[XML_PROLOG_STATE] = NS(initScanProlog); + p->initEnc.scanners[XML_CONTENT_STATE] = NS(initScanContent); + p->initEnc.updatePosition = initUpdatePosition; + p->encPtr = encPtr; + *encPtr = &(p->initEnc); + return 1; +} + +static const ENCODING * +NS(findEncoding)(const ENCODING *enc, const char *ptr, const char *end) +{ +#define ENCODING_MAX 128 + char buf[ENCODING_MAX]; + char *p = buf; + int i; + XmlUtf8Convert(enc, &ptr, end, &p, p + ENCODING_MAX - 1); + if (ptr != end) + return 0; + *p = 0; + if (streqci(buf, KW_UTF_16) && enc->minBytesPerChar == 2) + return enc; + i = getEncodingIndex(buf); + if (i == UNKNOWN_ENC) + return 0; + return NS(encodings)[i]; +} + +int +NS(XmlParseXmlDecl)(int isGeneralTextEntity, + const ENCODING *enc, + const char *ptr, + const char *end, + const char **badPtr, + const char **versionPtr, + const char **versionEndPtr, + const char **encodingName, + const ENCODING **encoding, + int *standalone) +{ + return doParseXmlDecl(NS(findEncoding), + isGeneralTextEntity, + enc, + ptr, + end, + badPtr, + versionPtr, + versionEndPtr, + encodingName, + encoding, + standalone); +} + +#endif /* XML_TOK_NS_C */ diff --git a/tools/sdk/include/fatfs/diskio.h b/tools/sdk/include/fatfs/diskio.h index 64d5d5b8..572f03dc 100644 --- a/tools/sdk/include/fatfs/diskio.h +++ b/tools/sdk/include/fatfs/diskio.h @@ -1,133 +1,133 @@ -/*-----------------------------------------------------------------------/ -/ Low level disk interface modlue include file (C)ChaN, 2014 / -/-----------------------------------------------------------------------*/ - -#ifndef _DISKIO_DEFINED -#define _DISKIO_DEFINED - -#ifdef __cplusplus -extern "C" { -#endif - -#include "integer.h" -#include "sdmmc_cmd.h" -#include "driver/sdmmc_host.h" - -/* Status of Disk Functions */ -typedef BYTE DSTATUS; - -/* Results of Disk Functions */ -typedef enum { - RES_OK = 0, /* 0: Successful */ - RES_ERROR, /* 1: R/W Error */ - RES_WRPRT, /* 2: Write Protected */ - RES_NOTRDY, /* 3: Not Ready */ - RES_PARERR /* 4: Invalid Parameter */ -} DRESULT; - - -/*---------------------------------------*/ -/* Prototypes for disk control functions */ - - -/* Redefine names of disk IO functions to prevent name collisions */ -#define disk_initialize ff_disk_initialize -#define disk_status ff_disk_status -#define disk_read ff_disk_read -#define disk_write ff_disk_write -#define disk_ioctl ff_disk_ioctl - - -DSTATUS disk_initialize (BYTE pdrv); -DSTATUS disk_status (BYTE pdrv); -DRESULT disk_read (BYTE pdrv, BYTE* buff, DWORD sector, UINT count); -DRESULT disk_write (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count); -DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff); - -/** - * Structure of pointers to disk IO driver functions. - * - * See FatFs documentation for details about these functions - */ -typedef struct { - DSTATUS (*init) (BYTE pdrv); /*!< disk initialization function */ - DSTATUS (*status) (BYTE pdrv); /*!< disk status check function */ - DRESULT (*read) (BYTE pdrv, BYTE* buff, DWORD sector, UINT count); /*!< sector read function */ - DRESULT (*write) (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count); /*!< sector write function */ - DRESULT (*ioctl) (BYTE pdrv, BYTE cmd, void* buff); /*!< function to get info about disk and do some misc operations */ -} ff_diskio_impl_t; - -/** - * Register or unregister diskio driver for given drive number. - * - * When FATFS library calls one of disk_xxx functions for driver number pdrv, - * corresponding function in discio_impl for given pdrv will be called. - * - * @param pdrv drive number - * @param discio_impl pointer to ff_diskio_impl_t structure with diskio functions - * or NULL to unregister and free previously registered drive - */ -void ff_diskio_register(BYTE pdrv, const ff_diskio_impl_t* discio_impl); - -#define ff_diskio_unregister(pdrv_) ff_diskio_register(pdrv_, NULL) - -/** - * Register SD/MMC diskio driver - * - * @param pdrv drive number - * @param card pointer to sdmmc_card_t structure describing a card; card should be initialized before calling f_mount. - */ -void ff_diskio_register_sdmmc(BYTE pdrv, sdmmc_card_t* card); - -/** - * Get next available drive number - * - * @param out_pdrv pointer to the byte to set if successful - * - * @return ESP_OK on success - * ESP_ERR_NOT_FOUND if all drives are attached - */ -esp_err_t ff_diskio_get_drive(BYTE* out_pdrv); - -/* Disk Status Bits (DSTATUS) */ - -#define STA_NOINIT 0x01 /* Drive not initialized */ -#define STA_NODISK 0x02 /* No medium in the drive */ -#define STA_PROTECT 0x04 /* Write protected */ - - -/* Command code for disk_ioctrl fucntion */ - -/* Generic command (Used by FatFs) */ -#define CTRL_SYNC 0 /* Complete pending write process (needed at _FS_READONLY == 0) */ -#define GET_SECTOR_COUNT 1 /* Get media size (needed at _USE_MKFS == 1) */ -#define GET_SECTOR_SIZE 2 /* Get sector size (needed at _MAX_SS != _MIN_SS) */ -#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at _USE_MKFS == 1) */ -#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at _USE_TRIM == 1) */ - -/* Generic command (Not used by FatFs) */ -#define CTRL_POWER 5 /* Get/Set power status */ -#define CTRL_LOCK 6 /* Lock/Unlock media removal */ -#define CTRL_EJECT 7 /* Eject media */ -#define CTRL_FORMAT 8 /* Create physical format on the media */ - -/* MMC/SDC specific ioctl command */ -#define MMC_GET_TYPE 10 /* Get card type */ -#define MMC_GET_CSD 11 /* Get CSD */ -#define MMC_GET_CID 12 /* Get CID */ -#define MMC_GET_OCR 13 /* Get OCR */ -#define MMC_GET_SDSTAT 14 /* Get SD status */ -#define ISDIO_READ 55 /* Read data form SD iSDIO register */ -#define ISDIO_WRITE 56 /* Write data to SD iSDIO register */ -#define ISDIO_MRITE 57 /* Masked write data to SD iSDIO register */ - -/* ATA/CF specific ioctl command */ -#define ATA_GET_REV 20 /* Get F/W revision */ -#define ATA_GET_MODEL 21 /* Get model name */ -#define ATA_GET_SN 22 /* Get serial number */ - -#ifdef __cplusplus -} -#endif - -#endif +/*-----------------------------------------------------------------------/ +/ Low level disk interface modlue include file (C)ChaN, 2014 / +/-----------------------------------------------------------------------*/ + +#ifndef _DISKIO_DEFINED +#define _DISKIO_DEFINED + +#ifdef __cplusplus +extern "C" { +#endif + +#include "integer.h" +#include "sdmmc_cmd.h" +#include "driver/sdmmc_host.h" + +/* Status of Disk Functions */ +typedef BYTE DSTATUS; + +/* Results of Disk Functions */ +typedef enum { + RES_OK = 0, /* 0: Successful */ + RES_ERROR, /* 1: R/W Error */ + RES_WRPRT, /* 2: Write Protected */ + RES_NOTRDY, /* 3: Not Ready */ + RES_PARERR /* 4: Invalid Parameter */ +} DRESULT; + + +/*---------------------------------------*/ +/* Prototypes for disk control functions */ + + +/* Redefine names of disk IO functions to prevent name collisions */ +#define disk_initialize ff_disk_initialize +#define disk_status ff_disk_status +#define disk_read ff_disk_read +#define disk_write ff_disk_write +#define disk_ioctl ff_disk_ioctl + + +DSTATUS disk_initialize (BYTE pdrv); +DSTATUS disk_status (BYTE pdrv); +DRESULT disk_read (BYTE pdrv, BYTE* buff, DWORD sector, UINT count); +DRESULT disk_write (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count); +DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff); + +/** + * Structure of pointers to disk IO driver functions. + * + * See FatFs documentation for details about these functions + */ +typedef struct { + DSTATUS (*init) (BYTE pdrv); /*!< disk initialization function */ + DSTATUS (*status) (BYTE pdrv); /*!< disk status check function */ + DRESULT (*read) (BYTE pdrv, BYTE* buff, DWORD sector, UINT count); /*!< sector read function */ + DRESULT (*write) (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count); /*!< sector write function */ + DRESULT (*ioctl) (BYTE pdrv, BYTE cmd, void* buff); /*!< function to get info about disk and do some misc operations */ +} ff_diskio_impl_t; + +/** + * Register or unregister diskio driver for given drive number. + * + * When FATFS library calls one of disk_xxx functions for driver number pdrv, + * corresponding function in discio_impl for given pdrv will be called. + * + * @param pdrv drive number + * @param discio_impl pointer to ff_diskio_impl_t structure with diskio functions + * or NULL to unregister and free previously registered drive + */ +void ff_diskio_register(BYTE pdrv, const ff_diskio_impl_t* discio_impl); + +#define ff_diskio_unregister(pdrv_) ff_diskio_register(pdrv_, NULL) + +/** + * Register SD/MMC diskio driver + * + * @param pdrv drive number + * @param card pointer to sdmmc_card_t structure describing a card; card should be initialized before calling f_mount. + */ +void ff_diskio_register_sdmmc(BYTE pdrv, sdmmc_card_t* card); + +/** + * Get next available drive number + * + * @param out_pdrv pointer to the byte to set if successful + * + * @return ESP_OK on success + * ESP_ERR_NOT_FOUND if all drives are attached + */ +esp_err_t ff_diskio_get_drive(BYTE* out_pdrv); + +/* Disk Status Bits (DSTATUS) */ + +#define STA_NOINIT 0x01 /* Drive not initialized */ +#define STA_NODISK 0x02 /* No medium in the drive */ +#define STA_PROTECT 0x04 /* Write protected */ + + +/* Command code for disk_ioctrl fucntion */ + +/* Generic command (Used by FatFs) */ +#define CTRL_SYNC 0 /* Complete pending write process (needed at _FS_READONLY == 0) */ +#define GET_SECTOR_COUNT 1 /* Get media size (needed at _USE_MKFS == 1) */ +#define GET_SECTOR_SIZE 2 /* Get sector size (needed at _MAX_SS != _MIN_SS) */ +#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at _USE_MKFS == 1) */ +#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at _USE_TRIM == 1) */ + +/* Generic command (Not used by FatFs) */ +#define CTRL_POWER 5 /* Get/Set power status */ +#define CTRL_LOCK 6 /* Lock/Unlock media removal */ +#define CTRL_EJECT 7 /* Eject media */ +#define CTRL_FORMAT 8 /* Create physical format on the media */ + +/* MMC/SDC specific ioctl command */ +#define MMC_GET_TYPE 10 /* Get card type */ +#define MMC_GET_CSD 11 /* Get CSD */ +#define MMC_GET_CID 12 /* Get CID */ +#define MMC_GET_OCR 13 /* Get OCR */ +#define MMC_GET_SDSTAT 14 /* Get SD status */ +#define ISDIO_READ 55 /* Read data form SD iSDIO register */ +#define ISDIO_WRITE 56 /* Write data to SD iSDIO register */ +#define ISDIO_MRITE 57 /* Masked write data to SD iSDIO register */ + +/* ATA/CF specific ioctl command */ +#define ATA_GET_REV 20 /* Get F/W revision */ +#define ATA_GET_MODEL 21 /* Get model name */ +#define ATA_GET_SN 22 /* Get serial number */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/fatfs/diskio_rawflash.h b/tools/sdk/include/fatfs/diskio_rawflash.h index 389c3bd8..a7b61a47 100644 --- a/tools/sdk/include/fatfs/diskio_rawflash.h +++ b/tools/sdk/include/fatfs/diskio_rawflash.h @@ -1,38 +1,38 @@ -// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _DISKIO_RAWFLASH_DEFINED -#define _DISKIO_RAWFLASH_DEFINED - -#ifdef __cplusplus -extern "C" { -#endif - -#include "integer.h" -#include "esp_partition.h" - -/** - * Register spi flash partition - * - * @param pdrv drive number - * @param part_handle pointer to raw flash partition. - */ -esp_err_t ff_diskio_register_raw_partition(BYTE pdrv, const esp_partition_t* part_handle); -BYTE ff_diskio_get_pdrv_raw(const esp_partition_t* part_handle); - -#ifdef __cplusplus -} -#endif - -#endif // _DISKIO_RAWFLASH_DEFINED +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _DISKIO_RAWFLASH_DEFINED +#define _DISKIO_RAWFLASH_DEFINED + +#ifdef __cplusplus +extern "C" { +#endif + +#include "integer.h" +#include "esp_partition.h" + +/** + * Register spi flash partition + * + * @param pdrv drive number + * @param part_handle pointer to raw flash partition. + */ +esp_err_t ff_diskio_register_raw_partition(BYTE pdrv, const esp_partition_t* part_handle); +BYTE ff_diskio_get_pdrv_raw(const esp_partition_t* part_handle); + +#ifdef __cplusplus +} +#endif + +#endif // _DISKIO_RAWFLASH_DEFINED diff --git a/tools/sdk/include/fatfs/diskio_wl.h b/tools/sdk/include/fatfs/diskio_wl.h index c2ed07dc..9abff7ae 100644 --- a/tools/sdk/include/fatfs/diskio_wl.h +++ b/tools/sdk/include/fatfs/diskio_wl.h @@ -1,39 +1,40 @@ -// Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _DISKIO_WL_DEFINED -#define _DISKIO_WL_DEFINED - -#ifdef __cplusplus -extern "C" { -#endif - -#include "integer.h" -#include "wear_levelling.h" - - -/** - * Register spi flash partition - * - * @param pdrv drive number - * @param flash_handle handle of the wear levelling partition. - */ -esp_err_t ff_diskio_register_wl_partition(BYTE pdrv, wl_handle_t flash_handle); -BYTE ff_diskio_get_pdrv_wl(wl_handle_t flash_handle); - -#ifdef __cplusplus -} -#endif - -#endif // _DISKIO_WL_DEFINED +// Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _DISKIO_WL_DEFINED +#define _DISKIO_WL_DEFINED + +#ifdef __cplusplus +extern "C" { +#endif + +#include "integer.h" +#include "wear_levelling.h" + + +/** + * Register spi flash partition + * + * @param pdrv drive number + * @param flash_handle handle of the wear levelling partition. + */ +esp_err_t ff_diskio_register_wl_partition(BYTE pdrv, wl_handle_t flash_handle); +BYTE ff_diskio_get_pdrv_wl(wl_handle_t flash_handle); +void ff_diskio_clear_pdrv_wl(wl_handle_t flash_handle); + +#ifdef __cplusplus +} +#endif + +#endif // _DISKIO_WL_DEFINED diff --git a/tools/sdk/include/fatfs/ff.h b/tools/sdk/include/fatfs/ff.h index d36815fc..55c13298 100644 --- a/tools/sdk/include/fatfs/ff.h +++ b/tools/sdk/include/fatfs/ff.h @@ -1,369 +1,369 @@ -/*----------------------------------------------------------------------------/ -/ FatFs - Generic FAT Filesystem module R0.13a / -/-----------------------------------------------------------------------------/ -/ -/ Copyright (C) 2017, ChaN, all right reserved. -/ -/ FatFs module is an open source software. Redistribution and use of FatFs in -/ source and binary forms, with or without modification, are permitted provided -/ that the following condition is met: - -/ 1. Redistributions of source code must retain the above copyright notice, -/ this condition and the following disclaimer. -/ -/ This software is provided by the copyright holder and contributors "AS IS" -/ and any warranties related to this software are DISCLAIMED. -/ The copyright owner or contributors be NOT LIABLE for any damages caused -/ by use of this software. -/ -/----------------------------------------------------------------------------*/ - - -#ifndef FF_DEFINED -#define FF_DEFINED 89352 /* Revision ID */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "integer.h" /* Basic integer types */ -#include "ffconf.h" /* FatFs configuration options */ - -#if FF_DEFINED != FFCONF_DEF -#error Wrong configuration file (ffconf.h). -#endif - -#ifdef FF_DEFINE_DIR -#define FF_DIR DIR -#endif - - -/* Definitions of volume management */ - -#if FF_MULTI_PARTITION /* Multiple partition configuration */ -typedef struct { - BYTE pd; /* Physical drive number */ - BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */ -} PARTITION; -extern PARTITION VolToPart[]; /* Volume - Partition resolution table */ -#endif - - - -/* Type of path name strings on FatFs API */ - -#ifndef _INC_TCHAR -#define _INC_TCHAR - -#if FF_USE_LFN && FF_LFN_UNICODE == 1 /* Unicode in UTF-16 encoding */ -typedef WCHAR TCHAR; -#define _T(x) L ## x -#define _TEXT(x) L ## x -#elif FF_USE_LFN && FF_LFN_UNICODE == 2 /* Unicode in UTF-8 encoding */ -typedef char TCHAR; -#define _T(x) u8 ## x -#define _TEXT(x) u8 ## x -#elif FF_USE_LFN && (FF_LFN_UNICODE < 0 || FF_LFN_UNICODE > 2) -#error Wrong FF_LFN_UNICODE setting -#else /* ANSI/OEM code in SBCS/DBCS */ -typedef char TCHAR; -#define _T(x) x -#define _TEXT(x) x -#endif - -#endif - - - -/* Type of file size variables */ - -#if FF_FS_EXFAT -typedef QWORD FSIZE_t; -#else -typedef DWORD FSIZE_t; -#endif - - - -/* Filesystem object structure (FATFS) */ - -typedef struct { - BYTE fs_type; /* Filesystem type (0:N/A) */ - BYTE pdrv; /* Physical drive number */ - BYTE n_fats; /* Number of FATs (1 or 2) */ - BYTE wflag; /* win[] flag (b0:dirty) */ - BYTE fsi_flag; /* FSINFO flags (b7:disabled, b0:dirty) */ - WORD id; /* Volume mount ID */ - WORD n_rootdir; /* Number of root directory entries (FAT12/16) */ - WORD csize; /* Cluster size [sectors] */ -#if FF_MAX_SS != FF_MIN_SS - WORD ssize; /* Sector size (512, 1024, 2048 or 4096) */ -#endif -#if FF_USE_LFN - WCHAR* lfnbuf; /* LFN working buffer */ -#endif -#if FF_FS_EXFAT - BYTE* dirbuf; /* Directory entry block scratchpad buffer for exFAT */ -#endif -#if FF_FS_REENTRANT - FF_SYNC_t sobj; /* Identifier of sync object */ -#endif -#if !FF_FS_READONLY - DWORD last_clst; /* Last allocated cluster */ - DWORD free_clst; /* Number of free clusters */ -#endif -#if FF_FS_RPATH - DWORD cdir; /* Current directory start cluster (0:root) */ -#if FF_FS_EXFAT - DWORD cdc_scl; /* Containing directory start cluster (invalid when cdir is 0) */ - DWORD cdc_size; /* b31-b8:Size of containing directory, b7-b0: Chain status */ - DWORD cdc_ofs; /* Offset in the containing directory (invalid when cdir is 0) */ -#endif -#endif - DWORD n_fatent; /* Number of FAT entries (number of clusters + 2) */ - DWORD fsize; /* Size of an FAT [sectors] */ - DWORD volbase; /* Volume base sector */ - DWORD fatbase; /* FAT base sector */ - DWORD dirbase; /* Root directory base sector/cluster */ - DWORD database; /* Data base sector */ - DWORD winsect; /* Current sector appearing in the win[] */ - BYTE win[FF_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */ -} FATFS; - - - -/* Object ID and allocation information (FFOBJID) */ - -typedef struct { - FATFS* fs; /* Pointer to the hosting volume of this object */ - WORD id; /* Hosting volume mount ID */ - BYTE attr; /* Object attribute */ - BYTE stat; /* Object chain status (b1-0: =0:not contiguous, =2:contiguous, =3:flagmented in this session, b2:sub-directory stretched) */ - DWORD sclust; /* Object data start cluster (0:no cluster or root directory) */ - FSIZE_t objsize; /* Object size (valid when sclust != 0) */ -#if FF_FS_EXFAT - DWORD n_cont; /* Size of first fragment - 1 (valid when stat == 3) */ - DWORD n_frag; /* Size of last fragment needs to be written to FAT (valid when not zero) */ - DWORD c_scl; /* Containing directory start cluster (valid when sclust != 0) */ - DWORD c_size; /* b31-b8:Size of containing directory, b7-b0: Chain status (valid when c_scl != 0) */ - DWORD c_ofs; /* Offset in the containing directory (valid when file object and sclust != 0) */ -#endif -#if FF_FS_LOCK - UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */ -#endif -} FFOBJID; - - - -/* File object structure (FIL) */ - -typedef struct { - FFOBJID obj; /* Object identifier (must be the 1st member to detect invalid object pointer) */ - BYTE flag; /* File status flags */ - BYTE err; /* Abort flag (error code) */ - FSIZE_t fptr; /* File read/write pointer (Zeroed on file open) */ - DWORD clust; /* Current cluster of fpter (invalid when fptr is 0) */ - DWORD sect; /* Sector number appearing in buf[] (0:invalid) */ -#if !FF_FS_READONLY - DWORD dir_sect; /* Sector number containing the directory entry (not used at exFAT) */ - BYTE* dir_ptr; /* Pointer to the directory entry in the win[] (not used at exFAT) */ -#endif -#if FF_USE_FASTSEEK - DWORD* cltbl; /* Pointer to the cluster link map table (nulled on open, set by application) */ -#endif -#if !FF_FS_TINY - BYTE buf[FF_MAX_SS]; /* File private data read/write window */ -#endif -} FIL; - - - -/* Directory object structure (FF_DIR) */ - -typedef struct { - FFOBJID obj; /* Object identifier */ - DWORD dptr; /* Current read/write offset */ - DWORD clust; /* Current cluster */ - DWORD sect; /* Current sector (0:Read operation has terminated) */ - BYTE* dir; /* Pointer to the directory item in the win[] */ - BYTE fn[12]; /* SFN (in/out) {body[8],ext[3],status[1]} */ -#if FF_USE_LFN - DWORD blk_ofs; /* Offset of current entry block being processed (0xFFFFFFFF:Invalid) */ -#endif -#if FF_USE_FIND - const TCHAR* pat; /* Pointer to the name matching pattern */ -#endif -} FF_DIR; - - - -/* File information structure (FILINFO) */ - -typedef struct { - FSIZE_t fsize; /* File size */ - WORD fdate; /* Modified date */ - WORD ftime; /* Modified time */ - BYTE fattrib; /* File attribute */ -#if FF_USE_LFN - TCHAR altname[FF_SFN_BUF + 1];/* Altenative file name */ - TCHAR fname[FF_LFN_BUF + 1]; /* Primary file name */ -#else - TCHAR fname[12 + 1]; /* File name */ -#endif -} FILINFO; - - - -/* File function return code (FRESULT) */ - -typedef enum { - FR_OK = 0, /* (0) Succeeded */ - FR_DISK_ERR, /* (1) A hard error occurred in the low level disk I/O layer */ - FR_INT_ERR, /* (2) Assertion failed */ - FR_NOT_READY, /* (3) The physical drive cannot work */ - FR_NO_FILE, /* (4) Could not find the file */ - FR_NO_PATH, /* (5) Could not find the path */ - FR_INVALID_NAME, /* (6) The path name format is invalid */ - FR_DENIED, /* (7) Access denied due to prohibited access or directory full */ - FR_EXIST, /* (8) Access denied due to prohibited access */ - FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */ - FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */ - FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */ - FR_NOT_ENABLED, /* (12) The volume has no work area */ - FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume */ - FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any problem */ - FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */ - FR_LOCKED, /* (16) The operation is rejected according to the file sharing policy */ - FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */ - FR_TOO_MANY_OPEN_FILES, /* (18) Number of open files > FF_FS_LOCK */ - FR_INVALID_PARAMETER /* (19) Given parameter is invalid */ -} FRESULT; - - - -/*--------------------------------------------------------------*/ -/* FatFs module application interface */ - -FRESULT f_open (FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */ -FRESULT f_close (FIL* fp); /* Close an open file object */ -FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from the file */ -FRESULT f_write (FIL* fp, const void* buff, UINT btw, UINT* bw); /* Write data to the file */ -FRESULT f_lseek (FIL* fp, FSIZE_t ofs); /* Move file pointer of the file object */ -FRESULT f_truncate (FIL* fp); /* Truncate the file */ -FRESULT f_sync (FIL* fp); /* Flush cached data of the writing file */ -FRESULT f_opendir (FF_DIR* dp, const TCHAR* path); /* Open a directory */ -FRESULT f_closedir (FF_DIR* dp); /* Close an open directory */ -FRESULT f_readdir (FF_DIR* dp, FILINFO* fno); /* Read a directory item */ -FRESULT f_findfirst (FF_DIR* dp, FILINFO* fno, const TCHAR* path, const TCHAR* pattern); /* Find first file */ -FRESULT f_findnext (FF_DIR* dp, FILINFO* fno); /* Find next file */ -FRESULT f_mkdir (const TCHAR* path); /* Create a sub directory */ -FRESULT f_unlink (const TCHAR* path); /* Delete an existing file or directory */ -FRESULT f_rename (const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */ -FRESULT f_stat (const TCHAR* path, FILINFO* fno); /* Get file status */ -FRESULT f_chmod (const TCHAR* path, BYTE attr, BYTE mask); /* Change attribute of a file/dir */ -FRESULT f_utime (const TCHAR* path, const FILINFO* fno); /* Change timestamp of a file/dir */ -FRESULT f_chdir (const TCHAR* path); /* Change current directory */ -FRESULT f_chdrive (const TCHAR* path); /* Change current drive */ -FRESULT f_getcwd (TCHAR* buff, UINT len); /* Get current directory */ -FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */ -FRESULT f_getlabel (const TCHAR* path, TCHAR* label, DWORD* vsn); /* Get volume label */ -FRESULT f_setlabel (const TCHAR* label); /* Set volume label */ -FRESULT f_forward (FIL* fp, UINT(*func)(const BYTE*,UINT), UINT btf, UINT* bf); /* Forward data to the stream */ -FRESULT f_expand (FIL* fp, FSIZE_t szf, BYTE opt); /* Allocate a contiguous block to the file */ -FRESULT f_mount (FATFS* fs, const TCHAR* path, BYTE opt); /* Mount/Unmount a logical drive */ -FRESULT f_mkfs (const TCHAR* path, BYTE opt, DWORD au, void* work, UINT len); /* Create a FAT volume */ -FRESULT f_fdisk (BYTE pdrv, const DWORD* szt, void* work); /* Divide a physical drive into some partitions */ -FRESULT f_setcp (WORD cp); /* Set current code page */ -int f_putc (TCHAR c, FIL* fp); /* Put a character to the file */ -int f_puts (const TCHAR* str, FIL* cp); /* Put a string to the file */ -int f_printf (FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */ -TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the file */ - -#define f_eof(fp) ((int)((fp)->fptr == (fp)->obj.objsize)) -#define f_error(fp) ((fp)->err) -#define f_tell(fp) ((fp)->fptr) -#define f_size(fp) ((fp)->obj.objsize) -#define f_rewind(fp) f_lseek((fp), 0) -#define f_rewinddir(dp) f_readdir((dp), 0) -#define f_rmdir(path) f_unlink(path) -#define f_unmount(path) f_mount(0, path, 0) - -#ifndef EOF -#define EOF (-1) -#endif - - - - -/*--------------------------------------------------------------*/ -/* Additional user defined functions */ - -/* RTC function */ -#if !FF_FS_READONLY && !FF_FS_NORTC -DWORD get_fattime (void); -#endif - -/* LFN support functions */ -#if FF_USE_LFN >= 1 /* Code conversion (defined in unicode.c) */ -WCHAR ff_oem2uni (WCHAR oem, WORD cp); /* OEM code to Unicode conversion */ -WCHAR ff_uni2oem (DWORD uni, WORD cp); /* Unicode to OEM code conversion */ -DWORD ff_wtoupper (DWORD uni); /* Unicode upper-case conversion */ -#endif -#if FF_USE_LFN == 3 /* Dynamic memory allocation */ -void* ff_memalloc (UINT msize); /* Allocate memory block */ -void ff_memfree (void* mblock); /* Free memory block */ -#endif - -/* Sync functions */ -#if FF_FS_REENTRANT -int ff_cre_syncobj (BYTE vol, FF_SYNC_t* sobj); /* Create a sync object */ -int ff_req_grant (FF_SYNC_t sobj); /* Lock sync object */ -void ff_rel_grant (FF_SYNC_t sobj); /* Unlock sync object */ -int ff_del_syncobj (FF_SYNC_t sobj); /* Delete a sync object */ -#endif - - - - -/*--------------------------------------------------------------*/ -/* Flags and offset address */ - - -/* File access mode and open method flags (3rd argument of f_open) */ -#define FA_READ 0x01 -#define FA_WRITE 0x02 -#define FA_OPEN_EXISTING 0x00 -#define FA_CREATE_NEW 0x04 -#define FA_CREATE_ALWAYS 0x08 -#define FA_OPEN_ALWAYS 0x10 -#define FA_OPEN_APPEND 0x30 - -/* Fast seek controls (2nd argument of f_lseek) */ -#define CREATE_LINKMAP ((FSIZE_t)0 - 1) - -/* Format options (2nd argument of f_mkfs) */ -#define FM_FAT 0x01 -#define FM_FAT32 0x02 -#define FM_EXFAT 0x04 -#define FM_ANY 0x07 -#define FM_SFD 0x08 - -/* Filesystem type (FATFS.fs_type) */ -#define FS_FAT12 1 -#define FS_FAT16 2 -#define FS_FAT32 3 -#define FS_EXFAT 4 - -/* File attribute bits for directory entry (FILINFO.fattrib) */ -#define AM_RDO 0x01 /* Read only */ -#define AM_HID 0x02 /* Hidden */ -#define AM_SYS 0x04 /* System */ -#define AM_DIR 0x10 /* Directory */ -#define AM_ARC 0x20 /* Archive */ - - -#ifdef __cplusplus -} -#endif - -#endif /* FF_DEFINED */ +/*----------------------------------------------------------------------------/ +/ FatFs - Generic FAT Filesystem module R0.13a / +/-----------------------------------------------------------------------------/ +/ +/ Copyright (C) 2017, ChaN, all right reserved. +/ +/ FatFs module is an open source software. Redistribution and use of FatFs in +/ source and binary forms, with or without modification, are permitted provided +/ that the following condition is met: + +/ 1. Redistributions of source code must retain the above copyright notice, +/ this condition and the following disclaimer. +/ +/ This software is provided by the copyright holder and contributors "AS IS" +/ and any warranties related to this software are DISCLAIMED. +/ The copyright owner or contributors be NOT LIABLE for any damages caused +/ by use of this software. +/ +/----------------------------------------------------------------------------*/ + + +#ifndef FF_DEFINED +#define FF_DEFINED 89352 /* Revision ID */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "integer.h" /* Basic integer types */ +#include "ffconf.h" /* FatFs configuration options */ + +#if FF_DEFINED != FFCONF_DEF +#error Wrong configuration file (ffconf.h). +#endif + +#ifdef FF_DEFINE_DIR +#define FF_DIR DIR +#endif + + +/* Definitions of volume management */ + +#if FF_MULTI_PARTITION /* Multiple partition configuration */ +typedef struct { + BYTE pd; /* Physical drive number */ + BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */ +} PARTITION; +extern PARTITION VolToPart[]; /* Volume - Partition resolution table */ +#endif + + + +/* Type of path name strings on FatFs API */ + +#ifndef _INC_TCHAR +#define _INC_TCHAR + +#if FF_USE_LFN && FF_LFN_UNICODE == 1 /* Unicode in UTF-16 encoding */ +typedef WCHAR TCHAR; +#define _T(x) L ## x +#define _TEXT(x) L ## x +#elif FF_USE_LFN && FF_LFN_UNICODE == 2 /* Unicode in UTF-8 encoding */ +typedef char TCHAR; +#define _T(x) u8 ## x +#define _TEXT(x) u8 ## x +#elif FF_USE_LFN && (FF_LFN_UNICODE < 0 || FF_LFN_UNICODE > 2) +#error Wrong FF_LFN_UNICODE setting +#else /* ANSI/OEM code in SBCS/DBCS */ +typedef char TCHAR; +#define _T(x) x +#define _TEXT(x) x +#endif + +#endif + + + +/* Type of file size variables */ + +#if FF_FS_EXFAT +typedef QWORD FSIZE_t; +#else +typedef DWORD FSIZE_t; +#endif + + + +/* Filesystem object structure (FATFS) */ + +typedef struct { + BYTE fs_type; /* Filesystem type (0:N/A) */ + BYTE pdrv; /* Physical drive number */ + BYTE n_fats; /* Number of FATs (1 or 2) */ + BYTE wflag; /* win[] flag (b0:dirty) */ + BYTE fsi_flag; /* FSINFO flags (b7:disabled, b0:dirty) */ + WORD id; /* Volume mount ID */ + WORD n_rootdir; /* Number of root directory entries (FAT12/16) */ + WORD csize; /* Cluster size [sectors] */ +#if FF_MAX_SS != FF_MIN_SS + WORD ssize; /* Sector size (512, 1024, 2048 or 4096) */ +#endif +#if FF_USE_LFN + WCHAR* lfnbuf; /* LFN working buffer */ +#endif +#if FF_FS_EXFAT + BYTE* dirbuf; /* Directory entry block scratchpad buffer for exFAT */ +#endif +#if FF_FS_REENTRANT + FF_SYNC_t sobj; /* Identifier of sync object */ +#endif +#if !FF_FS_READONLY + DWORD last_clst; /* Last allocated cluster */ + DWORD free_clst; /* Number of free clusters */ +#endif +#if FF_FS_RPATH + DWORD cdir; /* Current directory start cluster (0:root) */ +#if FF_FS_EXFAT + DWORD cdc_scl; /* Containing directory start cluster (invalid when cdir is 0) */ + DWORD cdc_size; /* b31-b8:Size of containing directory, b7-b0: Chain status */ + DWORD cdc_ofs; /* Offset in the containing directory (invalid when cdir is 0) */ +#endif +#endif + DWORD n_fatent; /* Number of FAT entries (number of clusters + 2) */ + DWORD fsize; /* Size of an FAT [sectors] */ + DWORD volbase; /* Volume base sector */ + DWORD fatbase; /* FAT base sector */ + DWORD dirbase; /* Root directory base sector/cluster */ + DWORD database; /* Data base sector */ + DWORD winsect; /* Current sector appearing in the win[] */ + BYTE win[FF_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */ +} FATFS; + + + +/* Object ID and allocation information (FFOBJID) */ + +typedef struct { + FATFS* fs; /* Pointer to the hosting volume of this object */ + WORD id; /* Hosting volume mount ID */ + BYTE attr; /* Object attribute */ + BYTE stat; /* Object chain status (b1-0: =0:not contiguous, =2:contiguous, =3:flagmented in this session, b2:sub-directory stretched) */ + DWORD sclust; /* Object data start cluster (0:no cluster or root directory) */ + FSIZE_t objsize; /* Object size (valid when sclust != 0) */ +#if FF_FS_EXFAT + DWORD n_cont; /* Size of first fragment - 1 (valid when stat == 3) */ + DWORD n_frag; /* Size of last fragment needs to be written to FAT (valid when not zero) */ + DWORD c_scl; /* Containing directory start cluster (valid when sclust != 0) */ + DWORD c_size; /* b31-b8:Size of containing directory, b7-b0: Chain status (valid when c_scl != 0) */ + DWORD c_ofs; /* Offset in the containing directory (valid when file object and sclust != 0) */ +#endif +#if FF_FS_LOCK + UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */ +#endif +} FFOBJID; + + + +/* File object structure (FIL) */ + +typedef struct { + FFOBJID obj; /* Object identifier (must be the 1st member to detect invalid object pointer) */ + BYTE flag; /* File status flags */ + BYTE err; /* Abort flag (error code) */ + FSIZE_t fptr; /* File read/write pointer (Zeroed on file open) */ + DWORD clust; /* Current cluster of fpter (invalid when fptr is 0) */ + DWORD sect; /* Sector number appearing in buf[] (0:invalid) */ +#if !FF_FS_READONLY + DWORD dir_sect; /* Sector number containing the directory entry (not used at exFAT) */ + BYTE* dir_ptr; /* Pointer to the directory entry in the win[] (not used at exFAT) */ +#endif +#if FF_USE_FASTSEEK + DWORD* cltbl; /* Pointer to the cluster link map table (nulled on open, set by application) */ +#endif +#if !FF_FS_TINY + BYTE buf[FF_MAX_SS]; /* File private data read/write window */ +#endif +} FIL; + + + +/* Directory object structure (FF_DIR) */ + +typedef struct { + FFOBJID obj; /* Object identifier */ + DWORD dptr; /* Current read/write offset */ + DWORD clust; /* Current cluster */ + DWORD sect; /* Current sector (0:Read operation has terminated) */ + BYTE* dir; /* Pointer to the directory item in the win[] */ + BYTE fn[12]; /* SFN (in/out) {body[8],ext[3],status[1]} */ +#if FF_USE_LFN + DWORD blk_ofs; /* Offset of current entry block being processed (0xFFFFFFFF:Invalid) */ +#endif +#if FF_USE_FIND + const TCHAR* pat; /* Pointer to the name matching pattern */ +#endif +} FF_DIR; + + + +/* File information structure (FILINFO) */ + +typedef struct { + FSIZE_t fsize; /* File size */ + WORD fdate; /* Modified date */ + WORD ftime; /* Modified time */ + BYTE fattrib; /* File attribute */ +#if FF_USE_LFN + TCHAR altname[FF_SFN_BUF + 1];/* Altenative file name */ + TCHAR fname[FF_LFN_BUF + 1]; /* Primary file name */ +#else + TCHAR fname[12 + 1]; /* File name */ +#endif +} FILINFO; + + + +/* File function return code (FRESULT) */ + +typedef enum { + FR_OK = 0, /* (0) Succeeded */ + FR_DISK_ERR, /* (1) A hard error occurred in the low level disk I/O layer */ + FR_INT_ERR, /* (2) Assertion failed */ + FR_NOT_READY, /* (3) The physical drive cannot work */ + FR_NO_FILE, /* (4) Could not find the file */ + FR_NO_PATH, /* (5) Could not find the path */ + FR_INVALID_NAME, /* (6) The path name format is invalid */ + FR_DENIED, /* (7) Access denied due to prohibited access or directory full */ + FR_EXIST, /* (8) Access denied due to prohibited access */ + FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */ + FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */ + FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */ + FR_NOT_ENABLED, /* (12) The volume has no work area */ + FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume */ + FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any problem */ + FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */ + FR_LOCKED, /* (16) The operation is rejected according to the file sharing policy */ + FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */ + FR_TOO_MANY_OPEN_FILES, /* (18) Number of open files > FF_FS_LOCK */ + FR_INVALID_PARAMETER /* (19) Given parameter is invalid */ +} FRESULT; + + + +/*--------------------------------------------------------------*/ +/* FatFs module application interface */ + +FRESULT f_open (FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */ +FRESULT f_close (FIL* fp); /* Close an open file object */ +FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from the file */ +FRESULT f_write (FIL* fp, const void* buff, UINT btw, UINT* bw); /* Write data to the file */ +FRESULT f_lseek (FIL* fp, FSIZE_t ofs); /* Move file pointer of the file object */ +FRESULT f_truncate (FIL* fp); /* Truncate the file */ +FRESULT f_sync (FIL* fp); /* Flush cached data of the writing file */ +FRESULT f_opendir (FF_DIR* dp, const TCHAR* path); /* Open a directory */ +FRESULT f_closedir (FF_DIR* dp); /* Close an open directory */ +FRESULT f_readdir (FF_DIR* dp, FILINFO* fno); /* Read a directory item */ +FRESULT f_findfirst (FF_DIR* dp, FILINFO* fno, const TCHAR* path, const TCHAR* pattern); /* Find first file */ +FRESULT f_findnext (FF_DIR* dp, FILINFO* fno); /* Find next file */ +FRESULT f_mkdir (const TCHAR* path); /* Create a sub directory */ +FRESULT f_unlink (const TCHAR* path); /* Delete an existing file or directory */ +FRESULT f_rename (const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */ +FRESULT f_stat (const TCHAR* path, FILINFO* fno); /* Get file status */ +FRESULT f_chmod (const TCHAR* path, BYTE attr, BYTE mask); /* Change attribute of a file/dir */ +FRESULT f_utime (const TCHAR* path, const FILINFO* fno); /* Change timestamp of a file/dir */ +FRESULT f_chdir (const TCHAR* path); /* Change current directory */ +FRESULT f_chdrive (const TCHAR* path); /* Change current drive */ +FRESULT f_getcwd (TCHAR* buff, UINT len); /* Get current directory */ +FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */ +FRESULT f_getlabel (const TCHAR* path, TCHAR* label, DWORD* vsn); /* Get volume label */ +FRESULT f_setlabel (const TCHAR* label); /* Set volume label */ +FRESULT f_forward (FIL* fp, UINT(*func)(const BYTE*,UINT), UINT btf, UINT* bf); /* Forward data to the stream */ +FRESULT f_expand (FIL* fp, FSIZE_t szf, BYTE opt); /* Allocate a contiguous block to the file */ +FRESULT f_mount (FATFS* fs, const TCHAR* path, BYTE opt); /* Mount/Unmount a logical drive */ +FRESULT f_mkfs (const TCHAR* path, BYTE opt, DWORD au, void* work, UINT len); /* Create a FAT volume */ +FRESULT f_fdisk (BYTE pdrv, const DWORD* szt, void* work); /* Divide a physical drive into some partitions */ +FRESULT f_setcp (WORD cp); /* Set current code page */ +int f_putc (TCHAR c, FIL* fp); /* Put a character to the file */ +int f_puts (const TCHAR* str, FIL* cp); /* Put a string to the file */ +int f_printf (FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */ +TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the file */ + +#define f_eof(fp) ((int)((fp)->fptr == (fp)->obj.objsize)) +#define f_error(fp) ((fp)->err) +#define f_tell(fp) ((fp)->fptr) +#define f_size(fp) ((fp)->obj.objsize) +#define f_rewind(fp) f_lseek((fp), 0) +#define f_rewinddir(dp) f_readdir((dp), 0) +#define f_rmdir(path) f_unlink(path) +#define f_unmount(path) f_mount(0, path, 0) + +#ifndef EOF +#define EOF (-1) +#endif + + + + +/*--------------------------------------------------------------*/ +/* Additional user defined functions */ + +/* RTC function */ +#if !FF_FS_READONLY && !FF_FS_NORTC +DWORD get_fattime (void); +#endif + +/* LFN support functions */ +#if FF_USE_LFN >= 1 /* Code conversion (defined in unicode.c) */ +WCHAR ff_oem2uni (WCHAR oem, WORD cp); /* OEM code to Unicode conversion */ +WCHAR ff_uni2oem (DWORD uni, WORD cp); /* Unicode to OEM code conversion */ +DWORD ff_wtoupper (DWORD uni); /* Unicode upper-case conversion */ +#endif +#if FF_USE_LFN == 3 /* Dynamic memory allocation */ +void* ff_memalloc (UINT msize); /* Allocate memory block */ +void ff_memfree (void* mblock); /* Free memory block */ +#endif + +/* Sync functions */ +#if FF_FS_REENTRANT +int ff_cre_syncobj (BYTE vol, FF_SYNC_t* sobj); /* Create a sync object */ +int ff_req_grant (FF_SYNC_t sobj); /* Lock sync object */ +void ff_rel_grant (FF_SYNC_t sobj); /* Unlock sync object */ +int ff_del_syncobj (FF_SYNC_t sobj); /* Delete a sync object */ +#endif + + + + +/*--------------------------------------------------------------*/ +/* Flags and offset address */ + + +/* File access mode and open method flags (3rd argument of f_open) */ +#define FA_READ 0x01 +#define FA_WRITE 0x02 +#define FA_OPEN_EXISTING 0x00 +#define FA_CREATE_NEW 0x04 +#define FA_CREATE_ALWAYS 0x08 +#define FA_OPEN_ALWAYS 0x10 +#define FA_OPEN_APPEND 0x30 + +/* Fast seek controls (2nd argument of f_lseek) */ +#define CREATE_LINKMAP ((FSIZE_t)0 - 1) + +/* Format options (2nd argument of f_mkfs) */ +#define FM_FAT 0x01 +#define FM_FAT32 0x02 +#define FM_EXFAT 0x04 +#define FM_ANY 0x07 +#define FM_SFD 0x08 + +/* Filesystem type (FATFS.fs_type) */ +#define FS_FAT12 1 +#define FS_FAT16 2 +#define FS_FAT32 3 +#define FS_EXFAT 4 + +/* File attribute bits for directory entry (FILINFO.fattrib) */ +#define AM_RDO 0x01 /* Read only */ +#define AM_HID 0x02 /* Hidden */ +#define AM_SYS 0x04 /* System */ +#define AM_DIR 0x10 /* Directory */ +#define AM_ARC 0x20 /* Archive */ + + +#ifdef __cplusplus +} +#endif + +#endif /* FF_DEFINED */ diff --git a/tools/sdk/include/fatfs/ffconf.h b/tools/sdk/include/fatfs/ffconf.h index 7a491655..1b1cf8c8 100644 --- a/tools/sdk/include/fatfs/ffconf.h +++ b/tools/sdk/include/fatfs/ffconf.h @@ -1,304 +1,304 @@ -#include -#include "sdkconfig.h" -/*---------------------------------------------------------------------------/ -/ FatFs - Configuration file -/---------------------------------------------------------------------------*/ - -#define FFCONF_DEF 89352 /* Revision ID */ - -/*---------------------------------------------------------------------------/ -/ Function Configurations -/---------------------------------------------------------------------------*/ - -#define FF_FS_READONLY 0 -/* This option switches read-only configuration. (0:Read/Write or 1:Read-only) -/ Read-only configuration removes writing API functions, f_write(), f_sync(), -/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree() -/ and optional writing functions as well. */ - - -#define FF_FS_MINIMIZE 0 -/* This option defines minimization level to remove some basic API functions. -/ -/ 0: Basic functions are fully enabled. -/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename() -/ are removed. -/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1. -/ 3: f_lseek() function is removed in addition to 2. */ - - -#define FF_USE_STRFUNC 0 -/* This option switches string functions, f_gets(), f_putc(), f_puts() and f_printf(). -/ -/ 0: Disable string functions. -/ 1: Enable without LF-CRLF conversion. -/ 2: Enable with LF-CRLF conversion. */ - - -#define FF_USE_FIND 0 -/* This option switches filtered directory read functions, f_findfirst() and -/ f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */ - - -#define FF_USE_MKFS 1 -/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */ - - -#define FF_USE_FASTSEEK 0 -/* This option switches fast seek function. (0:Disable or 1:Enable) */ - - -#define FF_USE_EXPAND 0 -/* This option switches f_expand function. (0:Disable or 1:Enable) */ - - -#define FF_USE_CHMOD 0 -/* This option switches attribute manipulation functions, f_chmod() and f_utime(). -/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */ - - -#define FF_USE_LABEL 0 -/* This option switches volume label functions, f_getlabel() and f_setlabel(). -/ (0:Disable or 1:Enable) */ - - -#define FF_USE_FORWARD 0 -/* This option switches f_forward() function. (0:Disable or 1:Enable) */ - - -/*---------------------------------------------------------------------------/ -/ Locale and Namespace Configurations -/---------------------------------------------------------------------------*/ - -#define FF_CODE_PAGE CONFIG_FATFS_CODEPAGE -/* This option specifies the OEM code page to be used on the target system. -/ Incorrect code page setting can cause a file open failure. -/ -/ 437 - U.S. -/ 720 - Arabic -/ 737 - Greek -/ 771 - KBL -/ 775 - Baltic -/ 850 - Latin 1 -/ 852 - Latin 2 -/ 855 - Cyrillic -/ 857 - Turkish -/ 860 - Portuguese -/ 861 - Icelandic -/ 862 - Hebrew -/ 863 - Canadian French -/ 864 - Arabic -/ 865 - Nordic -/ 866 - Russian -/ 869 - Greek 2 -/ 932 - Japanese (DBCS) -/ 936 - Simplified Chinese (DBCS) -/ 949 - Korean (DBCS) -/ 950 - Traditional Chinese (DBCS) -/ 0 - Include all code pages above and configured by f_setcp() -*/ - - -#if defined(CONFIG_FATFS_LFN_STACK) -#define FF_USE_LFN 2 -#elif defined(CONFIG_FATFS_LFN_HEAP) -#define FF_USE_LFN 3 -#else /* CONFIG_FATFS_LFN_NONE */ -#define FF_USE_LFN 0 -#endif - -#ifdef CONFIG_FATFS_MAX_LFN -#define FF_MAX_LFN CONFIG_FATFS_MAX_LFN -#endif - -/* The FF_USE_LFN switches the support for LFN (long file name). -/ -/ 0: Disable LFN. FF_MAX_LFN has no effect. -/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe. -/ 2: Enable LFN with dynamic working buffer on the STACK. -/ 3: Enable LFN with dynamic working buffer on the HEAP. -/ -/ To enable the LFN, ffunicode.c needs to be added to the project. The LFN function -/ requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and -/ additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled. -/ The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can -/ be in range of 12 to 255. It is recommended to be set 255 to fully support LFN -/ specification. -/ When use stack for the working buffer, take care on stack overflow. When use heap -/ memory for the working buffer, memory management functions, ff_memalloc() and -/ ff_memfree() in ffsystem.c, need to be added to the project. */ - - -#ifdef CONFIG_FATFS_API_ENCODING_UTF_8 -#define FF_LFN_UNICODE 2 -#elif defined(CONFIG_FATFS_API_ENCODING_UTF_16) -#define FF_LFN_UNICODE 1 -#else /* CONFIG_FATFS_API_ENCODING_ANSI_OEM */ -#define FF_LFN_UNICODE 0 -#endif -/* This option switches the character encoding on the API when LFN is enabled. -/ -/ 0: ANSI/OEM in current CP (TCHAR = char) -/ 1: Unicode in UTF-16 (TCHAR = WCHAR) -/ 2: Unicode in UTF-8 (TCHAR = char) -/ -/ Also behavior of string I/O functions will be affected by this option. -/ When LFN is not enabled, this option has no effect. */ - - -#define FF_LFN_BUF 255 -#define FF_SFN_BUF 12 -/* This set of options defines size of file name members in the FILINFO structure -/ which is used to read out directory items. These values should be suffcient for -/ the file names to read. The maximum possible length of the read file name depends -/ on character encoding. When LFN is not enabled, these options have no effect. */ - - -#define FF_STRF_ENCODE 3 -/* When FF_LFN_UNICODE >= 1 with LFN enabled, string I/O functions, f_gets(), -/ f_putc(), f_puts and f_printf() convert the character encoding in it. -/ This option selects assumption of character encoding ON THE FILE to be -/ read/written via those functions. -/ -/ 0: ANSI/OEM in current CP -/ 1: Unicode in UTF-16LE -/ 2: Unicode in UTF-16BE -/ 3: Unicode in UTF-8 -*/ - - -#define FF_FS_RPATH 0 -/* This option configures support for relative path. -/ -/ 0: Disable relative path and remove related functions. -/ 1: Enable relative path. f_chdir() and f_chdrive() are available. -/ 2: f_getcwd() function is available in addition to 1. -*/ - - -/*---------------------------------------------------------------------------/ -/ Drive/Volume Configurations -/---------------------------------------------------------------------------*/ - -#define FF_VOLUMES 2 -/* Number of volumes (logical drives) to be used. (1-10) */ - - -#define FF_STR_VOLUME_ID 0 -#define FF_VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3" -/* FF_STR_VOLUME_ID switches string support for volume ID. -/ When FF_STR_VOLUME_ID is set to 1, also pre-defined strings can be used as drive -/ number in the path name. FF_VOLUME_STRS defines the drive ID strings for each -/ logical drives. Number of items must be equal to FF_VOLUMES. Valid characters for -/ the drive ID strings are: A-Z and 0-9. */ - - -#define FF_MULTI_PARTITION 1 -/* This option switches support for multiple volumes on the physical drive. -/ By default (0), each logical drive number is bound to the same physical drive -/ number and only an FAT volume found on the physical drive will be mounted. -/ When this function is enabled (1), each logical drive number can be bound to -/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk() -/ funciton will be available. */ - -/* SD card sector size */ -#define FF_SS_SDCARD 512 -/* wear_levelling library sector size */ -#define FF_SS_WL CONFIG_WL_SECTOR_SIZE - -#define FF_MIN_SS MIN(FF_SS_SDCARD, FF_SS_WL) -#define FF_MAX_SS MAX(FF_SS_SDCARD, FF_SS_WL) -/* This set of options configures the range of sector size to be supported. (512, -/ 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and -/ harddisk. But a larger value may be required for on-board flash memory and some -/ type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured -/ for variable sector size mode and disk_ioctl() function needs to implement -/ GET_SECTOR_SIZE command. */ - - -#define FF_USE_TRIM 0 -/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable) -/ To enable Trim function, also CTRL_TRIM command should be implemented to the -/ disk_ioctl() function. */ - - -#define FF_FS_NOFSINFO 0 -/* If you need to know correct free space on the FAT32 volume, set bit 0 of this -/ option, and f_getfree() function at first time after volume mount will force -/ a full FAT scan. Bit 1 controls the use of last allocated cluster number. -/ -/ bit0=0: Use free cluster count in the FSINFO if available. -/ bit0=1: Do not trust free cluster count in the FSINFO. -/ bit1=0: Use last allocated cluster number in the FSINFO if available. -/ bit1=1: Do not trust last allocated cluster number in the FSINFO. -*/ - - - -/*---------------------------------------------------------------------------/ -/ System Configurations -/---------------------------------------------------------------------------*/ - -#define FF_FS_TINY (!CONFIG_FATFS_PER_FILE_CACHE) -/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny) -/ At the tiny configuration, size of file object (FIL) is shrinked FF_MAX_SS bytes. -/ Instead of private sector buffer eliminated from the file object, common sector -/ buffer in the filesystem object (FATFS) is used for the file data transfer. */ - - -#define FF_FS_EXFAT 0 -/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable) -/ When enable exFAT, also LFN needs to be enabled. -/ Note that enabling exFAT discards ANSI C (C89) compatibility. */ - - -#define FF_FS_NORTC 0 -#define FF_NORTC_MON 1 -#define FF_NORTC_MDAY 1 -#define FF_NORTC_YEAR 2017 -/* The option FF_FS_NORTC switches timestamp functiton. If the system does not have -/ any RTC function or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable -/ the timestamp function. All objects modified by FatFs will have a fixed timestamp -/ defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time. -/ To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be -/ added to the project to read current time form real-time clock. FF_NORTC_MON, -/ FF_NORTC_MDAY and FF_NORTC_YEAR have no effect. -/ These options have no effect at read-only configuration (FF_FS_READONLY = 1). */ - - -#define FF_FS_LOCK CONFIG_FATFS_FS_LOCK -/* The option FF_FS_LOCK switches file lock function to control duplicated file open -/ and illegal operation to open objects. This option must be 0 when FF_FS_READONLY -/ is 1. -/ -/ 0: Disable file lock function. To avoid volume corruption, application program -/ should avoid illegal open, remove and rename to the open objects. -/ >0: Enable file lock function. The value defines how many files/sub-directories -/ can be opened simultaneously under file lock control. Note that the file -/ lock control is independent of re-entrancy. */ - - -#define FF_FS_REENTRANT 1 -#define FF_FS_TIMEOUT (CONFIG_FATFS_TIMEOUT_MS / portTICK_PERIOD_MS) -#define FF_SYNC_t SemaphoreHandle_t -/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs -/ module itself. Note that regardless of this option, file access to different -/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs() -/ and f_fdisk() function, are always not re-entrant. Only file/directory access -/ to the same volume is under control of this function. -/ -/ 0: Disable re-entrancy. FF_FS_TIMEOUT and FF_SYNC_t have no effect. -/ 1: Enable re-entrancy. Also user provided synchronization handlers, -/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj() -/ function, must be added to the project. Samples are available in -/ option/syscall.c. -/ -/ The FF_FS_TIMEOUT defines timeout period in unit of time tick. -/ The FF_SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*, -/ SemaphoreHandle_t and etc. A header file for O/S definitions needs to be -/ included somewhere in the scope of ff.h. */ - -#include "freertos/FreeRTOS.h" -#include "freertos/semphr.h" - -/*--- End of configuration options ---*/ +#include +#include "sdkconfig.h" +/*---------------------------------------------------------------------------/ +/ FatFs - Configuration file +/---------------------------------------------------------------------------*/ + +#define FFCONF_DEF 89352 /* Revision ID */ + +/*---------------------------------------------------------------------------/ +/ Function Configurations +/---------------------------------------------------------------------------*/ + +#define FF_FS_READONLY 0 +/* This option switches read-only configuration. (0:Read/Write or 1:Read-only) +/ Read-only configuration removes writing API functions, f_write(), f_sync(), +/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree() +/ and optional writing functions as well. */ + + +#define FF_FS_MINIMIZE 0 +/* This option defines minimization level to remove some basic API functions. +/ +/ 0: Basic functions are fully enabled. +/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename() +/ are removed. +/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1. +/ 3: f_lseek() function is removed in addition to 2. */ + + +#define FF_USE_STRFUNC 0 +/* This option switches string functions, f_gets(), f_putc(), f_puts() and f_printf(). +/ +/ 0: Disable string functions. +/ 1: Enable without LF-CRLF conversion. +/ 2: Enable with LF-CRLF conversion. */ + + +#define FF_USE_FIND 0 +/* This option switches filtered directory read functions, f_findfirst() and +/ f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */ + + +#define FF_USE_MKFS 1 +/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */ + + +#define FF_USE_FASTSEEK 0 +/* This option switches fast seek function. (0:Disable or 1:Enable) */ + + +#define FF_USE_EXPAND 0 +/* This option switches f_expand function. (0:Disable or 1:Enable) */ + + +#define FF_USE_CHMOD 0 +/* This option switches attribute manipulation functions, f_chmod() and f_utime(). +/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */ + + +#define FF_USE_LABEL 0 +/* This option switches volume label functions, f_getlabel() and f_setlabel(). +/ (0:Disable or 1:Enable) */ + + +#define FF_USE_FORWARD 0 +/* This option switches f_forward() function. (0:Disable or 1:Enable) */ + + +/*---------------------------------------------------------------------------/ +/ Locale and Namespace Configurations +/---------------------------------------------------------------------------*/ + +#define FF_CODE_PAGE CONFIG_FATFS_CODEPAGE +/* This option specifies the OEM code page to be used on the target system. +/ Incorrect code page setting can cause a file open failure. +/ +/ 437 - U.S. +/ 720 - Arabic +/ 737 - Greek +/ 771 - KBL +/ 775 - Baltic +/ 850 - Latin 1 +/ 852 - Latin 2 +/ 855 - Cyrillic +/ 857 - Turkish +/ 860 - Portuguese +/ 861 - Icelandic +/ 862 - Hebrew +/ 863 - Canadian French +/ 864 - Arabic +/ 865 - Nordic +/ 866 - Russian +/ 869 - Greek 2 +/ 932 - Japanese (DBCS) +/ 936 - Simplified Chinese (DBCS) +/ 949 - Korean (DBCS) +/ 950 - Traditional Chinese (DBCS) +/ 0 - Include all code pages above and configured by f_setcp() +*/ + + +#if defined(CONFIG_FATFS_LFN_STACK) +#define FF_USE_LFN 2 +#elif defined(CONFIG_FATFS_LFN_HEAP) +#define FF_USE_LFN 3 +#else /* CONFIG_FATFS_LFN_NONE */ +#define FF_USE_LFN 0 +#endif + +#ifdef CONFIG_FATFS_MAX_LFN +#define FF_MAX_LFN CONFIG_FATFS_MAX_LFN +#endif + +/* The FF_USE_LFN switches the support for LFN (long file name). +/ +/ 0: Disable LFN. FF_MAX_LFN has no effect. +/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe. +/ 2: Enable LFN with dynamic working buffer on the STACK. +/ 3: Enable LFN with dynamic working buffer on the HEAP. +/ +/ To enable the LFN, ffunicode.c needs to be added to the project. The LFN function +/ requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and +/ additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled. +/ The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can +/ be in range of 12 to 255. It is recommended to be set 255 to fully support LFN +/ specification. +/ When use stack for the working buffer, take care on stack overflow. When use heap +/ memory for the working buffer, memory management functions, ff_memalloc() and +/ ff_memfree() in ffsystem.c, need to be added to the project. */ + + +#ifdef CONFIG_FATFS_API_ENCODING_UTF_8 +#define FF_LFN_UNICODE 2 +#elif defined(CONFIG_FATFS_API_ENCODING_UTF_16) +#define FF_LFN_UNICODE 1 +#else /* CONFIG_FATFS_API_ENCODING_ANSI_OEM */ +#define FF_LFN_UNICODE 0 +#endif +/* This option switches the character encoding on the API when LFN is enabled. +/ +/ 0: ANSI/OEM in current CP (TCHAR = char) +/ 1: Unicode in UTF-16 (TCHAR = WCHAR) +/ 2: Unicode in UTF-8 (TCHAR = char) +/ +/ Also behavior of string I/O functions will be affected by this option. +/ When LFN is not enabled, this option has no effect. */ + + +#define FF_LFN_BUF 255 +#define FF_SFN_BUF 12 +/* This set of options defines size of file name members in the FILINFO structure +/ which is used to read out directory items. These values should be suffcient for +/ the file names to read. The maximum possible length of the read file name depends +/ on character encoding. When LFN is not enabled, these options have no effect. */ + + +#define FF_STRF_ENCODE 3 +/* When FF_LFN_UNICODE >= 1 with LFN enabled, string I/O functions, f_gets(), +/ f_putc(), f_puts and f_printf() convert the character encoding in it. +/ This option selects assumption of character encoding ON THE FILE to be +/ read/written via those functions. +/ +/ 0: ANSI/OEM in current CP +/ 1: Unicode in UTF-16LE +/ 2: Unicode in UTF-16BE +/ 3: Unicode in UTF-8 +*/ + + +#define FF_FS_RPATH 0 +/* This option configures support for relative path. +/ +/ 0: Disable relative path and remove related functions. +/ 1: Enable relative path. f_chdir() and f_chdrive() are available. +/ 2: f_getcwd() function is available in addition to 1. +*/ + + +/*---------------------------------------------------------------------------/ +/ Drive/Volume Configurations +/---------------------------------------------------------------------------*/ + +#define FF_VOLUMES 2 +/* Number of volumes (logical drives) to be used. (1-10) */ + + +#define FF_STR_VOLUME_ID 0 +#define FF_VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3" +/* FF_STR_VOLUME_ID switches string support for volume ID. +/ When FF_STR_VOLUME_ID is set to 1, also pre-defined strings can be used as drive +/ number in the path name. FF_VOLUME_STRS defines the drive ID strings for each +/ logical drives. Number of items must be equal to FF_VOLUMES. Valid characters for +/ the drive ID strings are: A-Z and 0-9. */ + + +#define FF_MULTI_PARTITION 1 +/* This option switches support for multiple volumes on the physical drive. +/ By default (0), each logical drive number is bound to the same physical drive +/ number and only an FAT volume found on the physical drive will be mounted. +/ When this function is enabled (1), each logical drive number can be bound to +/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk() +/ funciton will be available. */ + +/* SD card sector size */ +#define FF_SS_SDCARD 512 +/* wear_levelling library sector size */ +#define FF_SS_WL CONFIG_WL_SECTOR_SIZE + +#define FF_MIN_SS MIN(FF_SS_SDCARD, FF_SS_WL) +#define FF_MAX_SS MAX(FF_SS_SDCARD, FF_SS_WL) +/* This set of options configures the range of sector size to be supported. (512, +/ 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and +/ harddisk. But a larger value may be required for on-board flash memory and some +/ type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured +/ for variable sector size mode and disk_ioctl() function needs to implement +/ GET_SECTOR_SIZE command. */ + + +#define FF_USE_TRIM 0 +/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable) +/ To enable Trim function, also CTRL_TRIM command should be implemented to the +/ disk_ioctl() function. */ + + +#define FF_FS_NOFSINFO 0 +/* If you need to know correct free space on the FAT32 volume, set bit 0 of this +/ option, and f_getfree() function at first time after volume mount will force +/ a full FAT scan. Bit 1 controls the use of last allocated cluster number. +/ +/ bit0=0: Use free cluster count in the FSINFO if available. +/ bit0=1: Do not trust free cluster count in the FSINFO. +/ bit1=0: Use last allocated cluster number in the FSINFO if available. +/ bit1=1: Do not trust last allocated cluster number in the FSINFO. +*/ + + + +/*---------------------------------------------------------------------------/ +/ System Configurations +/---------------------------------------------------------------------------*/ + +#define FF_FS_TINY (!CONFIG_FATFS_PER_FILE_CACHE) +/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny) +/ At the tiny configuration, size of file object (FIL) is shrinked FF_MAX_SS bytes. +/ Instead of private sector buffer eliminated from the file object, common sector +/ buffer in the filesystem object (FATFS) is used for the file data transfer. */ + + +#define FF_FS_EXFAT 0 +/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable) +/ When enable exFAT, also LFN needs to be enabled. +/ Note that enabling exFAT discards ANSI C (C89) compatibility. */ + + +#define FF_FS_NORTC 0 +#define FF_NORTC_MON 1 +#define FF_NORTC_MDAY 1 +#define FF_NORTC_YEAR 2017 +/* The option FF_FS_NORTC switches timestamp functiton. If the system does not have +/ any RTC function or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable +/ the timestamp function. All objects modified by FatFs will have a fixed timestamp +/ defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time. +/ To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be +/ added to the project to read current time form real-time clock. FF_NORTC_MON, +/ FF_NORTC_MDAY and FF_NORTC_YEAR have no effect. +/ These options have no effect at read-only configuration (FF_FS_READONLY = 1). */ + + +#define FF_FS_LOCK CONFIG_FATFS_FS_LOCK +/* The option FF_FS_LOCK switches file lock function to control duplicated file open +/ and illegal operation to open objects. This option must be 0 when FF_FS_READONLY +/ is 1. +/ +/ 0: Disable file lock function. To avoid volume corruption, application program +/ should avoid illegal open, remove and rename to the open objects. +/ >0: Enable file lock function. The value defines how many files/sub-directories +/ can be opened simultaneously under file lock control. Note that the file +/ lock control is independent of re-entrancy. */ + + +#define FF_FS_REENTRANT 1 +#define FF_FS_TIMEOUT (CONFIG_FATFS_TIMEOUT_MS / portTICK_PERIOD_MS) +#define FF_SYNC_t SemaphoreHandle_t +/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs +/ module itself. Note that regardless of this option, file access to different +/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs() +/ and f_fdisk() function, are always not re-entrant. Only file/directory access +/ to the same volume is under control of this function. +/ +/ 0: Disable re-entrancy. FF_FS_TIMEOUT and FF_SYNC_t have no effect. +/ 1: Enable re-entrancy. Also user provided synchronization handlers, +/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj() +/ function, must be added to the project. Samples are available in +/ option/syscall.c. +/ +/ The FF_FS_TIMEOUT defines timeout period in unit of time tick. +/ The FF_SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*, +/ SemaphoreHandle_t and etc. A header file for O/S definitions needs to be +/ included somewhere in the scope of ff.h. */ + +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" + +/*--- End of configuration options ---*/ diff --git a/tools/sdk/include/fatfs/integer.h b/tools/sdk/include/fatfs/integer.h index 850dbf14..4fcf5c44 100644 --- a/tools/sdk/include/fatfs/integer.h +++ b/tools/sdk/include/fatfs/integer.h @@ -1,38 +1,38 @@ -/*-------------------------------------------*/ -/* Integer type definitions for FatFs module */ -/*-------------------------------------------*/ - -#ifndef FF_INTEGER -#define FF_INTEGER - -#ifdef _WIN32 /* FatFs development platform */ - -#include -#include -typedef unsigned __int64 QWORD; - - -#else /* Embedded platform */ - -/* These types MUST be 16-bit or 32-bit */ -typedef int INT; -typedef unsigned int UINT; - -/* This type MUST be 8-bit */ -typedef unsigned char BYTE; - -/* These types MUST be 16-bit */ -typedef short SHORT; -typedef unsigned short WORD; -typedef unsigned short WCHAR; - -/* These types MUST be 32-bit */ -typedef long LONG; -typedef unsigned long DWORD; - -/* This type MUST be 64-bit (Remove this for ANSI C (C89) compatibility) */ -typedef unsigned long long QWORD; - -#endif - -#endif +/*-------------------------------------------*/ +/* Integer type definitions for FatFs module */ +/*-------------------------------------------*/ + +#ifndef FF_INTEGER +#define FF_INTEGER + +#ifdef _WIN32 /* FatFs development platform */ + +#include +#include +typedef unsigned __int64 QWORD; + + +#else /* Embedded platform */ + +/* These types MUST be 16-bit or 32-bit */ +typedef int INT; +typedef unsigned int UINT; + +/* This type MUST be 8-bit */ +typedef unsigned char BYTE; + +/* These types MUST be 16-bit */ +typedef short SHORT; +typedef unsigned short WORD; +typedef unsigned short WCHAR; + +/* These types MUST be 32-bit */ +typedef long LONG; +typedef unsigned long DWORD; + +/* This type MUST be 64-bit (Remove this for ANSI C (C89) compatibility) */ +typedef unsigned long long QWORD; + +#endif + +#endif diff --git a/tools/sdk/include/freertos/freertos/FreeRTOS.h b/tools/sdk/include/freertos/freertos/FreeRTOS.h index 1bc93175..486d9c32 100644 --- a/tools/sdk/include/freertos/freertos/FreeRTOS.h +++ b/tools/sdk/include/freertos/freertos/FreeRTOS.h @@ -740,6 +740,10 @@ extern "C" { #define configUSE_STATS_FORMATTING_FUNCTIONS 0 #endif +#ifndef configTASKLIST_INCLUDE_COREID + #define configTASKLIST_INCLUDE_COREID 0 +#endif + #ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() #endif diff --git a/tools/sdk/include/freertos/freertos/FreeRTOSConfig.h b/tools/sdk/include/freertos/freertos/FreeRTOSConfig.h index c52bc927..aa33917e 100644 --- a/tools/sdk/include/freertos/freertos/FreeRTOSConfig.h +++ b/tools/sdk/include/freertos/freertos/FreeRTOSConfig.h @@ -159,9 +159,8 @@ int xt_clock_freq(void) __attribute__((deprecated)); *----------------------------------------------------------*/ #define configUSE_PREEMPTION 1 -#define configUSE_IDLE_HOOK ( CONFIG_FREERTOS_LEGACY_IDLE_HOOK ) - -#define configUSE_TICK_HOOK ( CONFIG_FREERTOS_LEGACY_TICK_HOOK ) +#define configUSE_IDLE_HOOK 1 +#define configUSE_TICK_HOOK 1 #define configTICK_RATE_HZ ( CONFIG_FREERTOS_HZ ) @@ -211,6 +210,10 @@ int xt_clock_freq(void) __attribute__((deprecated)); #define configUSE_STATS_FORMATTING_FUNCTIONS 1 /* Used by vTaskList() */ #endif +#ifdef CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID +#define configTASKLIST_INCLUDE_COREID 1 +#endif + #ifdef CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS #define configGENERATE_RUN_TIME_STATS 1 /* Used by vTaskGetRunTimeStats() */ #endif diff --git a/tools/sdk/include/freertos/freertos/portmacro.h b/tools/sdk/include/freertos/freertos/portmacro.h index 6b98b826..adeb3bb0 100644 --- a/tools/sdk/include/freertos/freertos/portmacro.h +++ b/tools/sdk/include/freertos/freertos/portmacro.h @@ -258,8 +258,11 @@ static inline unsigned portENTER_CRITICAL_NESTED() { //Because the ROM routines don't necessarily handle a stack in external RAM correctly, we force //the stack memory to always be internal. -#define pvPortMallocTcbMem(size) heap_caps_malloc(size, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT) -#define pvPortMallocStackMem(size) heap_caps_malloc(size, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT) +#define portTcbMemoryCaps (MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT) +#define portStackMemoryCaps (MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT) + +#define pvPortMallocTcbMem(size) heap_caps_malloc(size, portTcbMemoryCaps) +#define pvPortMallocStackMem(size) heap_caps_malloc(size, portStackMemoryCaps) //xTaskCreateStatic uses these functions to check incoming memory. #define portVALID_TCB_MEM(ptr) (esp_ptr_internal(ptr) && esp_ptr_byte_accessible(ptr)) @@ -365,10 +368,15 @@ typedef struct { #endif extern void esp_vApplicationIdleHook( void ); -extern void esp_vApplicationWaitiHook( void ); +extern void esp_vApplicationTickHook( void ); + +#ifndef CONFIG_FREERTOS_LEGACY_HOOKS +#define vApplicationIdleHook esp_vApplicationIdleHook +#define vApplicationTickHook esp_vApplicationTickHook +#endif /* !CONFIG_FREERTOS_LEGACY_HOOKS */ void _xt_coproc_release(volatile void * coproc_sa_base); -bool vApplicationSleep( TickType_t xExpectedIdleTime ); +void vApplicationSleep( TickType_t xExpectedIdleTime ); #define portSUPPRESS_TICKS_AND_SLEEP( idleTime ) vApplicationSleep( idleTime ) diff --git a/tools/sdk/include/freertos/freertos/task.h b/tools/sdk/include/freertos/freertos/task.h index ab605bb3..31df0bdd 100644 --- a/tools/sdk/include/freertos/freertos/task.h +++ b/tools/sdk/include/freertos/freertos/task.h @@ -181,6 +181,9 @@ typedef struct xTASK_STATUS uint32_t ulRunTimeCounter; /*!< The total run time allocated to the task so far, as defined by the run time stats clock. See http://www.freertos.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */ StackType_t *pxStackBase; /*!< Points to the lowest address of the task's stack area. */ uint32_t usStackHighWaterMark; /*!< The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. */ +#if configTASKLIST_INCLUDE_COREID + BaseType_t xCoreID; /*!< Core this task is pinned to. This field is present if CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID is set. */ +#endif } TaskStatus_t; /** diff --git a/tools/sdk/include/heap/esp_heap_caps_init.h b/tools/sdk/include/heap/esp_heap_caps_init.h index 3cf23ff7..3ae6b8e4 100644 --- a/tools/sdk/include/heap/esp_heap_caps_init.h +++ b/tools/sdk/include/heap/esp_heap_caps_init.h @@ -81,6 +81,7 @@ esp_err_t heap_caps_add_region(intptr_t start, intptr_t end); * - ESP_OK on success * - ESP_ERR_INVALID_ARG if a parameter is invalid * - ESP_ERR_NO_MEM if no memory to register new heap. + * - ESP_ERR_INVALID_SIZE if the memory region is too small to fit a heap * - ESP_FAIL if region overlaps the start and/or end of an existing region */ esp_err_t heap_caps_add_region_with_caps(const uint32_t caps[], intptr_t start, intptr_t end); diff --git a/tools/sdk/include/heap/esp_heap_trace.h b/tools/sdk/include/heap/esp_heap_trace.h index 08b8caa2..5573d5e5 100644 --- a/tools/sdk/include/heap/esp_heap_trace.h +++ b/tools/sdk/include/heap/esp_heap_trace.h @@ -38,7 +38,7 @@ typedef enum { * @brief Trace record data type. Stores information about an allocated region of memory. */ typedef struct { - uint32_t ccount; ///< CCOUNT of the CPU when the allocation was made. LSB (bit value 1) is the CPU number (0 or 1). */ + uint32_t ccount; ///< CCOUNT of the CPU when the allocation was made. LSB (bit value 1) is the CPU number (0 or 1). void *address; ///< Address which was allocated size_t size; ///< Size of the allocation void *alloced_by[CONFIG_HEAP_TRACING_STACK_DEPTH]; ///< Call stack of the caller which allocated the memory. diff --git a/tools/sdk/include/http_server/http_server.h b/tools/sdk/include/http_server/http_server.h new file mode 100644 index 00000000..cdbd039c --- /dev/null +++ b/tools/sdk/include/http_server/http_server.h @@ -0,0 +1,924 @@ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _HTTP_SERVER_H_ +#define _HTTP_SERVER_H_ + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define HTTPD_DEFAULT_CONFIG() { \ + .task_priority = tskIDLE_PRIORITY+5, \ + .stack_size = 4096, \ + .server_port = 80, \ + .ctrl_port = 32768, \ + .max_open_sockets = 7, \ + .max_uri_handlers = 8, \ + .max_resp_headers = 8, \ + .backlog_conn = 5, \ + .lru_purge_enable = false, \ + .recv_wait_timeout = 5, \ + .send_wait_timeout = 5, \ +}; + +#define ESP_ERR_HTTPD_BASE (0x8000) /*!< Starting number of HTTPD error codes */ +#define ESP_ERR_HTTPD_HANDLERS_FULL (ESP_ERR_HTTPD_BASE + 1) /*!< All slots for registering URI handlers have been consumed */ +#define ESP_ERR_HTTPD_HANDLER_EXISTS (ESP_ERR_HTTPD_BASE + 2) /*!< URI handler with same method and target URI already registered */ +#define ESP_ERR_HTTPD_INVALID_REQ (ESP_ERR_HTTPD_BASE + 3) /*!< Invalid request pointer */ +#define ESP_ERR_HTTPD_RESULT_TRUNC (ESP_ERR_HTTPD_BASE + 4) /*!< Result string truncated */ +#define ESP_ERR_HTTPD_RESP_HDR (ESP_ERR_HTTPD_BASE + 5) /*!< Response header field larger than supported */ +#define ESP_ERR_HTTPD_RESP_SEND (ESP_ERR_HTTPD_BASE + 6) /*!< Error occured while sending response packet */ +#define ESP_ERR_HTTPD_ALLOC_MEM (ESP_ERR_HTTPD_BASE + 7) /*!< Failed to dynamically allocate memory for resource */ +#define ESP_ERR_HTTPD_TASK (ESP_ERR_HTTPD_BASE + 8) /*!< Failed to launch server task/thread */ + +/* ************** Group: Initialization ************** */ +/** @name Initialization + * APIs related to the Initialization of the web server + * @{ + */ + +/** + * @brief HTTP Server Instance Handle + * + * Every instance of the server will have a unique handle. + */ +typedef void* httpd_handle_t; + +/** + * @brief HTTP Method Type wrapper over "enum http_method" + * available in "http_parser" library + */ +typedef enum http_method httpd_method_t; + +/** + * @brief HTTP Server Configuration Structure + * + * @note Use HTTPD_DEFAULT_CONFIG() to initialize the configuration + * to a default value and then modify only those fields that are + * specifically determined by the use case. + */ +typedef struct httpd_config { + unsigned task_priority; /*!< Priority of FreeRTOS task which runs the server */ + size_t stack_size; /*!< The maximum stack size allowed for the server task */ + + /** + * TCP Port number for receiving and transmitting HTTP traffic + */ + uint16_t server_port; + + /** + * UDP Port number for asynchronously exchanging control signals + * between various components of the server + */ + uint16_t ctrl_port; + + uint16_t max_open_sockets; /*!< Max number of sockets/clients connected at any time*/ + uint16_t max_uri_handlers; /*!< Maximum allowed uri handlers */ + uint16_t max_resp_headers; /*!< Maximum allowed additional headers in HTTP response */ + uint16_t backlog_conn; /*!< Number of backlog connections */ + bool lru_purge_enable; /*!< Purge "Least Recently Used" connection */ + uint16_t recv_wait_timeout; /*!< Timeout for recv function (in seconds)*/ + uint16_t send_wait_timeout; /*!< Timeout for send function (in seconds)*/ +} httpd_config_t; + +/** + * @brief Starts the web server + * + * Create an instance of HTTP server and allocate memory/resources for it + * depending upon the specified configuration. + * + * Example usage: + * @code{c} + * + * //Function for starting the webserver + * httpd_handle_t start_webserver(void) + * { + * // Generate default configuration + * httpd_config_t config = HTTPD_DEFAULT_CONFIG(); + * + * // Empty handle to http_server + * httpd_handle_t server = NULL; + * + * // Start the httpd server + * if (httpd_start(&server, &config) == ESP_OK) { + * // Register URI handlers + * httpd_register_uri_handler(server, &uri_get); + * httpd_register_uri_handler(server, &uri_post); + * } + * // If server failed to start, handle will be NULL + * return server; + * } + * + * @endcode + * + * @param[in] config : Configuration for new instance of the server + * @param[out] handle : Handle to newly created instance of the server. NULL on error + * @return + * - ESP_OK : Instance created successfully + * - ESP_ERR_INVALID_ARG : Null argument(s) + * - ESP_ERR_HTTPD_ALLOC_MEM : Failed to allocate memory for instance + * - ESP_ERR_HTTPD_TASK : Failed to launch server task + */ +esp_err_t httpd_start(httpd_handle_t *handle, const httpd_config_t *config); + +/** + * @brief Stops the web server + * + * Deallocates memory/resources used by an HTTP server instance and + * deletes it. Once deleted the handle can no longer be used for accessing + * the instance. + * + * Example usage: + * @code{c} + * + * // Function for stopping the webserver + * void stop_webserver(httpd_handle_t server) + * { + * // Ensure handle is non NULL + * if (server != NULL) { + * // Stop the httpd server + * httpd_stop(server); + * } + * } + * + * @endcode + * + * @param[in] handle Handle to server returned by httpd_start + * @return + * - ESP_OK : Server stopped successfully + * - ESP_ERR_INVALID_ARG : Handle argument is Null + */ +esp_err_t httpd_stop(httpd_handle_t handle); + +/** End of Group Initialization + * @} + */ + +/* ************** Group: URI Handlers ************** */ +/** @name URI Handlers + * APIs related to the URI handlers + * @{ + */ + +/** + * @brief Function type for freeing context data (if any) + */ +typedef void (*httpd_free_sess_ctx_fn_t)(void *sess_ctx); + +/* Max supported HTTP request header length */ +#define HTTPD_MAX_REQ_HDR_LEN CONFIG_HTTPD_MAX_REQ_HDR_LEN + +/* Max supported HTTP request URI length */ +#define HTTPD_MAX_URI_LEN CONFIG_HTTPD_MAX_URI_LEN + +/** + * @brief HTTP Request Data Structure + */ +typedef struct httpd_req { + httpd_handle_t handle; /*!< Handle to server instance */ + int method; /*!< The type of HTTP request, -1 if unsupported method */ + const char uri[HTTPD_MAX_URI_LEN + 1]; /*!< The URI of this request (1 byte extra for null termination) */ + size_t content_len; /*!< Length of the request body */ + void *aux; /*!< Internally used members */ + + /** + * User context pointer passed during URI registration. + */ + void *user_ctx; + + /** + * Session Context Pointer + * + * A session context. Contexts are maintained across 'sessions' for a + * given open TCP connection. One session could have multiple request + * responses. The web server will ensure that the context persists + * across all these request and responses. + * + * By default, this is NULL. URI Handlers can set this to any meaningful + * value. + * + * If the underlying socket gets closed, and this pointer is non-NULL, + * the web server will free up the context by calling free(), unless + * free_ctx function is set. + */ + void *sess_ctx; + + /** + * Pointer to free context hook + * + * Function to free session context + * + * If the web server's socket closes, it frees up the session context by + * calling free() on the sess_ctx member. If you wish to use a custom + * function for freeing the session context, please specify that here. + */ + httpd_free_sess_ctx_fn_t free_ctx; +} httpd_req_t; + +/** + * @brief Structure for URI handler + */ +typedef struct httpd_uri { + const char *uri; /*!< The URI to handle */ + httpd_method_t method; /*!< Method supported by the URI */ + + /** + * Handler to call for supported request method. This must + * return ESP_OK, or else the underlying socket will be closed. + */ + esp_err_t (*handler)(httpd_req_t *r); + + /** + * Pointer to user context data which will be available to handler + */ + void *user_ctx; +} httpd_uri_t; + +/** + * @brief Registers a URI handler + * + * @note URI handlers can be registered in real time as long as the + * server handle is valid. + * + * Example usage: + * @code{c} + * + * esp_err_t my_uri_handler(httpd_req_t* req) + * { + * // Recv , Process and Send + * .... + * .... + * .... + * + * // Fail condition + * if (....) { + * // Return fail to close session // + * return ESP_FAIL; + * } + * + * // On success + * return ESP_OK; + * } + * + * // URI handler structure + * httpd_uri_t my_uri { + * .uri = "/my_uri/path/xyz", + * .method = HTTPD_GET, + * .handler = my_uri_handler, + * .user_ctx = NULL + * }; + * + * // Register handler + * if (httpd_register_uri_handler(server_handle, &my_uri) != ESP_OK) { + * // If failed to register handler + * .... + * } + * + * @endcode + * + * @param[in] handle handle to HTTPD server instance + * @param[in] uri_handler pointer to handler that needs to be registered + * + * @return + * - ESP_OK : On successfully registering the handler + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler + * - ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and + * method is already registered + */ +esp_err_t httpd_register_uri_handler(httpd_handle_t handle, + const httpd_uri_t *uri_handler); + +/** + * @brief Unregister a URI handler + * + * @param[in] handle handle to HTTPD server instance + * @param[in] uri URI string + * @param[in] method HTTP method + * + * @return + * - ESP_OK : On successfully deregistering the handler + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_NOT_FOUND : Handler with specified URI and method not found + */ +esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle, + const char *uri, httpd_method_t method); + +/** + * @brief Unregister all URI handlers with the specified uri string + * + * @param[in] handle handle to HTTPD server instance + * @param[in] uri uri string specifying all handlers that need + * to be deregisterd + * + * @return + * - ESP_OK : On successfully deregistering all such handlers + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_NOT_FOUND : No handler registered with specified uri string + */ +esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char* uri); + +/** End of URI Handlers + * @} + */ + +/* ************** Group: TX/RX ************** */ +/** @name TX / RX + * Prototype for HTTPDs low-level send/recv functions + * @{ + */ + +/** + * @brief Prototype for HTTPDs low-level send function + * @return + * - Bytes : The number of bytes sent successfully + * - -VE : In case of error + */ +typedef int (*httpd_send_func_t)(int sockfd, const char *buf, size_t buf_len, int flags); + +/** + * @brief Prototype for HTTPDs low-level recv function + * @return + * - Bytes : The number of bytes received successfully + * - -VE : In case of error + */ +typedef int (*httpd_recv_func_t)(int sockfd, char *buf, size_t buf_len, int flags); + +/** End of TX / RX + * @} + */ + +/* ************** Group: Request/Response ************** */ +/** @name Request / Response + * APIs related to the data send/receive by URI handlers. + * These APIs are supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * @{ + */ + +/** + * @brief Override web server's receive function + * + * This function overrides the web server's receive function. This same function is + * used to read and parse HTTP headers as well as body. + * + * @note This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * + * @param[in] r The request being responded to + * @param[in] recv_func The receive function to be set for this request + * + * @return + * - ESP_OK : On successfully registering override + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_set_recv_override(httpd_req_t *r, httpd_recv_func_t recv_func); + +/** + * @brief Override web server's send function + * + * This function overrides the web server's send function. This same function is + * used to send out any response to any HTTP request. + * + * @note This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * + * @param[in] r The request being responded to + * @param[in] send_func The send function to be set for this request + * + * @return + * - ESP_OK : On successfully registering override + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_set_send_override(httpd_req_t *r, httpd_send_func_t send_func); + +/** + * @brief Get the Socket Descriptor from the HTTP request + * + * This API will return the socket descriptor of the session for + * which URI handler was executed on reception of HTTP request. + * This is useful when user wants to call functions that require + * session socket fd, from within a URI handler, ie. : + * httpd_sess_get_ctx(), + * httpd_trigger_sess_close(), + * httpd_sess_update_timestamp(). + * + * @note This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * + * @param[in] r The request whose socket descriptor should be found + * + * @return + * - Socket descriptor : The socket descriptor for this request + * - -1 : Invalid/NULL request pointer + */ +int httpd_req_to_sockfd(httpd_req_t *r); + +/** + * @brief API to read content data from the HTTP request + * + * This API will read HTTP content data from the HTTP request into + * provided buffer. Use content_len provided in httpd_req_t structure + * to know the length of data to be fetched. If content_len is too + * large for the buffer then user may have to make multiple calls to + * this function, each time fetching 'buf_len' number of bytes, + * while the pointer to content data is incremented internally by + * the same number. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - If an error is returned, the URI handler must further return an error. + * This will ensure that the erroneous socket is closed and cleaned up by + * the web server. + * - Presently Chunked Encoding is not supported + * + * @param[in] r The request being responded to + * @param[in] buf Pointer to a buffer that the data will be read into + * @param[in] buf_len Length of the buffer + * + * @return + * - Bytes : Number of bytes read into the buffer successfully + * - Zero : When no more data is left for read + * - -1 : On raw recv error / Null arguments / Request pointer is invalid + */ +int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len); + +/** + * @brief Search for a field in request headers and + * return the string length of it's value + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Once httpd_resp_send() API is called all request headers + * are purged, so request headers need be copied into separate + * buffers if they are required later. + * + * @param[in] r The request being responded to + * @param[in] field The header field to be searched in the request + * + * @return + * - Length : If field is found in the request URL + * - Zero : Field not found / Invalid request / Null arguments + */ +size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field); + +/** + * @brief Get the value string of a field from the request headers + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Once httpd_resp_send() API is called all request headers + * are purged, so request headers need be copied into separate + * buffers if they are required later. + * - If output size is greater than input, then the value is truncated, + * accompanied by truncation error as return value. + * - Use httpd_req_get_hdr_value_len() to know the right buffer length + * + * @param[in] r The request being responded to + * @param[in] field The field to be searched in the header + * @param[out] val Pointer to the buffer into which the value will be copied if the field is found + * @param[in] val_size Size of the user buffer "val" + * + * @return + * - ESP_OK : Field found in the request header and value string copied + * - ESP_ERR_NOT_FOUND : Key not found + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer + * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated + */ +esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size); + +/** + * @brief Get Query string length from the request URL + * + * @note This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid + * + * @param[in] r The request being responded to + * + * @return + * - Length : Query is found in the request URL + * - Zero : Query not found / Null arguments / Invalid request + */ +size_t httpd_req_get_url_query_len(httpd_req_t *r); + +/** + * @brief Get Query string from the request URL + * + * @note + * - Presently, the user can fetch the full URL query string, but decoding + * will have to be performed by the user. Request headers can be read using + * httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type: + * application/x-www-form-urlencoded) and then the appropriate decoding + * algorithm needs to be applied. + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid + * - If output size is greater than input, then the value is truncated, + * accompanied by truncation error as return value + * - Use httpd_req_get_url_query_len() to know the right buffer length + * + * @param[in] r The request being responded to + * @param[out] buf Pointer to the buffer into which the query string will be copied (if found) + * @param[in] buf_len Length of output buffer + * + * @return + * - ESP_OK : Query is found in the request URL and copied to buffer + * - ESP_ERR_NOT_FOUND : Query not found + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer + * - ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated + */ +esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len); + +/** + * @brief Helper function to get a URL query tag from a query + * string of the type param1=val1¶m2=val2 + * + * @note + * - The components of URL query string (keys and values) are not URLdecoded. + * The user must check for 'Content-Type' field in the request headers and + * then depending upon the specified encoding (URLencoded or otherwise) apply + * the appropriate decoding algorithm. + * - If actual value size is greater than val_size, then the value is truncated, + * accompanied by truncation error as return value. + * + * @param[in] qry Pointer to query string + * @param[in] key The key to be searched in the query string + * @param[out] val Pointer to the buffer into which the value will be copied if the key is found + * @param[in] val_size Size of the user buffer "val" + * + * @return + * - ESP_OK : Key is found in the URL query string and copied to buffer + * - ESP_ERR_NOT_FOUND : Key not found + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated + */ +esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size); + +/** + * @brief API to send a complete HTTP response. + * + * This API will send the data as an HTTP response to the request. + * This assumes that you have the entire response ready in a single + * buffer. If you wish to send response in incremental chunks use + * httpd_resp_send_chunk() instead. + * + * If no status code and content-type were set, by default this + * will send 200 OK status code and content type as text/html. + * You may call the following functions before this API to configure + * the response headers : + * httpd_resp_set_status() - for setting the HTTP status string, + * httpd_resp_set_type() - for setting the Content Type, + * httpd_resp_set_hdr() - for appending any additional field + * value entries in the response header + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Once this API is called, the request has been responded to. + * - No additional data can then be sent for the request. + * - Once this API is called, all request headers are purged, so + * request headers need be copied into separate buffers if + * they are required later. + * + * @param[in] r The request being responded to + * @param[in] buf Buffer from where the content is to be fetched + * @param[in] buf_len Length of the buffer + * + * @return + * - ESP_OK : On successfully sending the response packet + * - ESP_ERR_INVALID_ARG : Null request pointer + * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer + * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request + */ +esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, size_t buf_len); + +/** + * @brief API to send one HTTP chunk + * + * This API will send the data as an HTTP response to the + * request. This API will use chunked-encoding and send the response + * in the form of chunks. If you have the entire response contained in + * a single buffer, please use httpd_resp_send() instead. + * + * If no status code and content-type were set, by default this will + * send 200 OK status code and content type as text/html. You may + * call the following functions before this API to configure the + * response headers + * httpd_resp_set_status() - for setting the HTTP status string, + * httpd_resp_set_type() - for setting the Content Type, + * httpd_resp_set_hdr() - for appending any additional field + * value entries in the response header + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - When you are finished sending all your chunks, you must call + * this function with buf_len as 0. + * - Once this API is called, all request headers are purged, so + * request headers need be copied into separate buffers if they + * are required later. + * + * @param[in] r The request being responded to + * @param[in] buf Pointer to a buffer that stores the data + * @param[in] buf_len Length of the data from the buffer that should be sent out + * + * @return + * - ESP_OK : On successfully sending the response packet chunk + * - ESP_ERR_INVALID_ARG : Null request pointer + * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer + * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, size_t buf_len); + +/* Some commonly used status codes */ +#define HTTPD_200 "200 OK" /*!< HTTP Response 200 */ +#define HTTPD_204 "204 No Content" /*!< HTTP Response 204 */ +#define HTTPD_207 "207 Multi-Status" /*!< HTTP Response 207 */ +#define HTTPD_400 "400 Bad Request" /*!< HTTP Response 400 */ +#define HTTPD_404 "404 Not Found" /*!< HTTP Response 404 */ +#define HTTPD_500 "500 Internal Server Error" /*!< HTTP Response 500 */ + +/** + * @brief API to set the HTTP status code + * + * This API sets the status of the HTTP response to the value specified. + * By default, the '200 OK' response is sent as the response. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - This API only sets the status to this value. The status isn't + * sent out until any of the send APIs is executed. + * - Make sure that the lifetime of the status string is valid till + * send function is called. + * + * @param[in] r The request being responded to + * @param[in] status The HTTP status code of this response + * + * @return + * - ESP_OK : On success + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status); + +/* Some commonly used content types */ +#define HTTPD_TYPE_JSON "application/json" /*!< HTTP Content type JSON */ +#define HTTPD_TYPE_TEXT "text/html" /*!< HTTP Content type text/HTML */ +#define HTTPD_TYPE_OCTET "application/octet-stream" /*!< HTTP Content type octext-stream */ + +/** + * @brief API to set the HTTP content type + * + * This API sets the 'Content Type' field of the response. + * The default content type is 'text/html'. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - This API only sets the content type to this value. The type + * isn't sent out until any of the send APIs is executed. + * - Make sure that the lifetime of the type string is valid till + * send function is called. + * + * @param[in] r The request being responded to + * @param[in] type The Content Type of the response + * + * @return + * - ESP_OK : On success + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type); + +/** + * @brief API to append any additional headers + * + * This API sets any additional header fields that need to be sent in the response. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - The header isn't sent out until any of the send APIs is executed. + * - The maximum allowed number of additional headers is limited to + * value of max_resp_headers in config structure. + * - Make sure that the lifetime of the field value strings are valid till + * send function is called. + * + * @param[in] r The request being responded to + * @param[in] field The field name of the HTTP header + * @param[in] value The value of this HTTP header + * + * @return + * - ESP_OK : On successfully appending new header + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value); + +/** + * @brief Helper function for HTTP 404 + * + * Send HTTP 404 message. If you wish to send additional data in the body of the + * response, please use the lower-level functions directly. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Once this API is called, all request headers are purged, so + * request headers need be copied into separate buffers if + * they are required later. + * + * @param[in] r The request being responded to + * + * @return + * - ESP_OK : On successfully sending the response packet + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_resp_send_404(httpd_req_t *r); + +/** + * @brief Raw HTTP send + * + * Call this API if you wish to construct your custom response packet. + * When using this, all essential header, eg. HTTP version, Status Code, + * Content Type and Length, Encoding, etc. will have to be constructed + * manually, and HTTP delimeters (CRLF) will need to be placed correctly + * for separating sub-sections of the HTTP response packet. + * + * If the send override function is set, this API will end up + * calling that function eventually to send data out. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Unless the response has the correct HTTP structure (which the + * user must now ensure) it is not guaranteed that it will be + * recognized by the client. For most cases, you wouldn't have + * to call this API, but you would rather use either of : + * httpd_resp_send(), + * httpd_resp_send_chunk() + * + * @param[in] r The request being responded to + * @param[in] buf Buffer from where the fully constructed packet is to be read + * @param[in] buf_len Length of the buffer + * + * @return + * - Bytes : Number of bytes that were sent successfully + * - -1 : Error in raw send / Invalid request / Null arguments + */ +int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len); + +/** End of Request / Response + * @} + */ + +/* ************** Group: Session ************** */ +/** @name Session + * Functions for controlling sessions and accessing context data + * @{ + */ + +/** + * @brief Get session context from socket descriptor + * + * Typically if a session context is created, it is available to URI handlers + * through the httpd_req_t structure. But, there are cases where the web + * server's send/receive functions may require the context (for example, for + * accessing keying information etc). Since the send/receive function only have + * the socket descriptor at their disposal, this API provides them with a way to + * retrieve the session context. + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in] sockfd The socket descriptor for which the context should be extracted. + * + * @return + * - void* : Pointer to the context associated with this session + * - NULL : Empty context / Invalid handle / Invalid socket fd + */ +void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd); + +/** + * @brief Trigger an httpd session close externally + * + * @note Calling this API is only required in special circumstances wherein + * some application requires to close an httpd client session asynchronously. + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in] sockfd The socket descriptor of the session to be closed + * + * @return + * - ESP_OK : On successfully initiating closure + * - ESP_FAIL : Failure to queue work + * - ESP_ERR_NOT_FOUND : Socket fd not found + * - ESP_ERR_INVALID_ARG : Null arguments + */ +esp_err_t httpd_trigger_sess_close(httpd_handle_t handle, int sockfd); + +/** + * @brief Update timestamp for a given socket + * + * Timestamps are internally associated with each session to monitor + * how recently a session exchanged traffic. When LRU purge is enabled, + * if a client is requesting for connection but maximum number of + * sockets/sessions is reached, then the session having the earliest + * timestamp is closed automatically. + * + * Updating the timestamp manually prevents the socket from being purged + * due to the Least Recently Used (LRU) logic, even though it might not + * have received traffic for some time. This is useful when all open + * sockets/session are frequently exchanging traffic but the user specifically + * wants one of the sessions to be kept open, irrespective of when it last + * exchanged a packet. + * + * @note Calling this API is only necessary if the LRU Purge Enable option + * is enabled. + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in] sockfd The socket descriptor of the session for which timestamp + * is to be updated + * + * @return + * - ESP_OK : Socket found and timestamp updated + * - ESP_ERR_NOT_FOUND : Socket not found + * - ESP_ERR_INVALID_ARG : Null arguments + */ +esp_err_t httpd_sess_update_timestamp(httpd_handle_t handle, int sockfd); + +/** End of Session + * @} + */ + +/* ************** Group: Work Queue ************** */ +/** @name Work Queue + * APIs related to the HTTPD Work Queue + * @{ + */ + +/** + * @brief Prototype of the HTTPD work function + * Please refer to httpd_queue_work() for more details. + * @param[in] arg The arguments for this work function + */ +typedef void (*httpd_work_fn_t)(void *arg); + +/** + * @brief Queue execution of a function in HTTPD's context + * + * This API queues a work function for asynchronous execution + * + * @note Some protocols require that the web server generate some asynchronous data + * and send it to the persistently opened connection. This facility is for use + * by such protocols. + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in] work Pointer to the function to be executed in the HTTPD's context + * @param[in] arg Pointer to the arguments that should be passed to this function + * + * @return + * - ESP_OK : On successfully queueing the work + * - ESP_FAIL : Failure in ctrl socket + * - ESP_ERR_INVALID_ARG : Null arguments + */ +esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg); + +/** End of Group Work Queue + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! _HTTP_SERVER_H_ */ diff --git a/tools/sdk/include/lwip/arch/sys_arch.h b/tools/sdk/include/lwip/arch/sys_arch.h index bb7ea18a..b13d7d1f 100644 --- a/tools/sdk/include/lwip/arch/sys_arch.h +++ b/tools/sdk/include/lwip/arch/sys_arch.h @@ -1,52 +1,52 @@ -/* - * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT - * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING - * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY - * OF SUCH DAMAGE. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Adam Dunkels - * - */ - -#ifndef __SYS_ARCH_H__ -#define __SYS_ARCH_H__ - -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -#include "freertos/queue.h" -#include "freertos/semphr.h" +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef __SYS_ARCH_H__ +#define __SYS_ARCH_H__ + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/semphr.h" #include "arch/vfs_lwip.h" - -#ifdef __cplusplus -extern "C" { -#endif - - -typedef xSemaphoreHandle sys_sem_t; -typedef xSemaphoreHandle sys_mutex_t; -typedef xTaskHandle sys_thread_t; + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef xSemaphoreHandle sys_sem_t; +typedef xSemaphoreHandle sys_mutex_t; +typedef xTaskHandle sys_thread_t; typedef struct sys_mbox_s { xQueueHandle os_mbox; @@ -54,28 +54,28 @@ typedef struct sys_mbox_s { uint8_t alive; }* sys_mbox_t; - -#define LWIP_COMPAT_MUTEX 0 - -#if !LWIP_COMPAT_MUTEX -#define sys_mutex_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) -#define sys_mutex_set_invalid( x ) ( ( *x ) = NULL ) -#endif - -#define sys_mbox_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) -#define sys_mbox_set_invalid( x ) ( ( *x ) = NULL ) -#define sys_sem_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) -#define sys_sem_set_invalid( x ) ( ( *x ) = NULL ) - +#define LWIP_COMPAT_MUTEX 0 + +#if !LWIP_COMPAT_MUTEX +#define sys_mutex_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define sys_mutex_set_invalid( x ) ( ( *x ) = NULL ) +#endif + +#define sys_mbox_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define sys_mbox_set_invalid( x ) ( ( *x ) = NULL ) + +#define sys_sem_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define sys_sem_set_invalid( x ) ( ( *x ) = NULL ) + void sys_delay_ms(uint32_t ms); sys_sem_t* sys_thread_sem_init(void); void sys_thread_sem_deinit(void); -sys_sem_t* sys_thread_sem_get(void); - -#ifdef __cplusplus -} -#endif +sys_sem_t* sys_thread_sem_get(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __SYS_ARCH_H__ */ -#endif /* __SYS_ARCH_H__ */ - diff --git a/tools/sdk/include/lwip/arpa/inet.h b/tools/sdk/include/lwip/arpa/inet.h index 94c6c17e..90428f68 100644 --- a/tools/sdk/include/lwip/arpa/inet.h +++ b/tools/sdk/include/lwip/arpa/inet.h @@ -15,6 +15,6 @@ #ifndef INET_H_ #define INET_H_ -#include "lwip/inet.h" +#include "../../../lwip/src/include/lwip/inet.h" #endif /* INET_H_ */ diff --git a/tools/sdk/include/lwip/cc.h b/tools/sdk/include/lwip/cc.h new file mode 100644 index 00000000..cba0b365 --- /dev/null +++ b/tools/sdk/include/lwip/cc.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __ARCH_CC_H__ +#define __ARCH_CC_H__ + +#include +#include +#include +#include + +#include "arch/sys_arch.h" + +#define BYTE_ORDER LITTLE_ENDIAN + +typedef uint8_t u8_t; +typedef int8_t s8_t; +typedef uint16_t u16_t; +typedef int16_t s16_t; +typedef uint32_t u32_t; +typedef int32_t s32_t; + +typedef unsigned long mem_ptr_t; +typedef int sys_prot_t; + +#define S16_F "d" +#define U16_F "d" +#define X16_F "x" + +#define S32_F "d" +#define U32_F "d" +#define X32_F "x" + +#define PACK_STRUCT_FIELD(x) x +#define PACK_STRUCT_STRUCT __attribute__((packed)) +#define PACK_STRUCT_BEGIN +#define PACK_STRUCT_END + +#include + +#define LWIP_PLATFORM_DIAG(x) do {printf x;} while(0) +// __assert_func is the assertion failure handler from newlib, defined in assert.h +#define LWIP_PLATFORM_ASSERT(message) __assert_func(__FILE__, __LINE__, __ASSERT_FUNC, message) + +#ifdef NDEBUG +#define LWIP_NOASSERT +#else // Assertions enabled + +// If assertions are on, the default LWIP_ERROR handler behaviour is to +// abort w/ an assertion failure. Don't do this, instead just print the error (if LWIP_DEBUG is set) +// and run the handler (same as the LWIP_ERROR behaviour if LWIP_NOASSERT is set). +#ifdef LWIP_DEBUG +#define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ + puts(message); handler;}} while(0) +#else +// If LWIP_DEBUG is not set, return the error silently (default LWIP behaviour, also.) +#define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ + handler;}} while(0) +#endif // LWIP_DEBUG + +#endif /* NDEBUG */ + + +#endif /* __ARCH_CC_H__ */ diff --git a/tools/sdk/include/lwip/lwip/lwip_debug.h b/tools/sdk/include/lwip/debug/lwip_debug.h similarity index 100% rename from tools/sdk/include/lwip/lwip/lwip_debug.h rename to tools/sdk/include/lwip/debug/lwip_debug.h diff --git a/tools/sdk/include/lwip/apps/dhcpserver.h b/tools/sdk/include/lwip/dhcpserver/dhcpserver.h similarity index 100% rename from tools/sdk/include/lwip/apps/dhcpserver.h rename to tools/sdk/include/lwip/dhcpserver/dhcpserver.h diff --git a/tools/sdk/include/lwip/apps/dhcpserver_options.h b/tools/sdk/include/lwip/dhcpserver/dhcpserver_options.h similarity index 100% rename from tools/sdk/include/lwip/apps/dhcpserver_options.h rename to tools/sdk/include/lwip/dhcpserver/dhcpserver_options.h diff --git a/tools/sdk/include/lwip/lwip/api.h b/tools/sdk/include/lwip/lwip/api.h index 5b6a21ec..a4fed9bb 100644 --- a/tools/sdk/include/lwip/lwip/api.h +++ b/tools/sdk/include/lwip/lwip/api.h @@ -1,3 +1,8 @@ +/** + * @file + * netconn API (to be used from non-TCPIP threads) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,8 +43,7 @@ /* Note: Netconn API is always available when sockets are enabled - * sockets are implemented on top of them */ -#include /* for size_t */ - +#include "lwip/arch.h" #include "lwip/netbuf.h" #include "lwip/sys.h" #include "lwip/ip_addr.h" @@ -65,9 +69,11 @@ extern "C" { #define NETCONN_FLAG_NON_BLOCKING 0x02 /** Was the last connect action a non-blocking one? */ #define NETCONN_FLAG_IN_NONBLOCKING_CONNECT 0x04 +#if ESP_AUTO_RECV /** If this is set, a TCP netconn must call netconn_recved() to update the TCP receive window (done automatically if not set). */ #define NETCONN_FLAG_NO_AUTO_RECVED 0x08 +#endif /** If a nonblocking write has been rejected before, poll_tcp needs to check if the netconn is writable again */ #define NETCONN_FLAG_CHECK_WRITESPACE 0x10 @@ -79,7 +85,7 @@ extern "C" { #endif /* LWIP_IPV6 */ - /* Helpers to process several netconn_types by the same code */ +/* Helpers to process several netconn_types by the same code */ #define NETCONNTYPE_GROUP(t) ((t)&0xF0) #define NETCONNTYPE_DATAGRAM(t) ((t)&0xE0) #if LWIP_IPV6 @@ -88,32 +94,42 @@ extern "C" { #define NETCONNTYPE_ISUDPLITE(t) (((t)&0xF3) == NETCONN_UDPLITE) #define NETCONNTYPE_ISUDPNOCHKSUM(t) (((t)&0xF3) == NETCONN_UDPNOCHKSUM) #else /* LWIP_IPV6 */ +#define NETCONNTYPE_ISIPV6(t) (0) #define NETCONNTYPE_ISUDPLITE(t) ((t) == NETCONN_UDPLITE) #define NETCONNTYPE_ISUDPNOCHKSUM(t) ((t) == NETCONN_UDPNOCHKSUM) #endif /* LWIP_IPV6 */ -/** Protocol family and type of the netconn */ +/** @ingroup netconn_common + * Protocol family and type of the netconn + */ enum netconn_type { NETCONN_INVALID = 0, - /* NETCONN_TCP Group */ + /** TCP IPv4 */ NETCONN_TCP = 0x10, #if LWIP_IPV6 + /** TCP IPv6 */ NETCONN_TCP_IPV6 = NETCONN_TCP | NETCONN_TYPE_IPV6 /* 0x18 */, #endif /* LWIP_IPV6 */ - /* NETCONN_UDP Group */ + /** UDP IPv4 */ NETCONN_UDP = 0x20, + /** UDP IPv4 lite */ NETCONN_UDPLITE = 0x21, + /** UDP IPv4 no checksum */ NETCONN_UDPNOCHKSUM = 0x22, #if LWIP_IPV6 + /** UDP IPv6 (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ NETCONN_UDP_IPV6 = NETCONN_UDP | NETCONN_TYPE_IPV6 /* 0x28 */, + /** UDP IPv6 lite (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ NETCONN_UDPLITE_IPV6 = NETCONN_UDPLITE | NETCONN_TYPE_IPV6 /* 0x29 */, + /** UDP IPv6 no checksum (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ NETCONN_UDPNOCHKSUM_IPV6 = NETCONN_UDPNOCHKSUM | NETCONN_TYPE_IPV6 /* 0x2a */, #endif /* LWIP_IPV6 */ - /* NETCONN_RAW Group */ + /** Raw connection IPv4 */ NETCONN_RAW = 0x40 #if LWIP_IPV6 + /** Raw connection IPv6 (dual-stack by default, unless you call @ref netconn_set_ipv6only) */ , NETCONN_RAW_IPV6 = NETCONN_RAW | NETCONN_TYPE_IPV6 /* 0x48 */ #endif /* LWIP_IPV6 */ }; @@ -128,7 +144,32 @@ enum netconn_state { NETCONN_CLOSE }; -/** Use to inform the callback function about changes */ +/** Used to inform the callback function about changes + * + * Event explanation: + * + * In the netconn implementation, there are three ways to block a client: + * + * - accept mbox (sys_arch_mbox_fetch(&conn->acceptmbox, &accept_ptr, 0); in netconn_accept()) + * - receive mbox (sys_arch_mbox_fetch(&conn->recvmbox, &buf, 0); in netconn_recv_data()) + * - send queue is full (sys_arch_sem_wait(LWIP_API_MSG_SEM(msg), 0); in lwip_netconn_do_write()) + * + * The events have to be seen as events signaling the state of these mboxes/semaphores. For non-blocking + * connections, you need to know in advance whether a call to a netconn function call would block or not, + * and these events tell you about that. + * + * RCVPLUS events say: Safe to perform a potentially blocking call call once more. + * They are counted in sockets - three RCVPLUS events for accept mbox means you are safe + * to call netconn_accept 3 times without being blocked. + * Same thing for receive mbox. + * + * RCVMINUS events say: Your call to to a possibly blocking function is "acknowledged". + * Socket implementation decrements the counter. + * + * For TX, there is no need to count, its merely a flag. SENDPLUS means you may send something. + * SENDPLUS occurs when enough data was delivered to peer so netconn_send() can be called again. + * A SENDMINUS event occurs when the next call to a netconn_send() would be blocking. + */ enum netconn_evt { NETCONN_EVT_RCVPLUS, NETCONN_EVT_RCVMINUS, @@ -160,7 +201,7 @@ struct tcp_pcb; struct udp_pcb; struct raw_pcb; struct netconn; -struct api_msg_msg; +struct api_msg; /** A callback prototype to inform about events for a netconn */ typedef void (* netconn_callback)(struct netconn *, enum netconn_evt, u16_t len); @@ -180,13 +221,10 @@ struct netconn { } pcb; /** the last error this netconn had */ err_t last_err; - #if !LWIP_NETCONN_SEM_PER_THREAD /** sem that is used to synchronously execute functions in the core context */ sys_sem_t op_completed; - #endif - /** mbox where received packets are stored until they are fetched by the netconn application thread (can grow quite big) */ sys_mbox_t recvmbox; @@ -231,7 +269,7 @@ struct netconn { /** TCP: when data passed to netconn_write doesn't fit into the send buffer, this temporarily stores the message. Also used during connect and close. */ - struct api_msg_msg *current_msg; + struct api_msg *current_msg; #endif /* LWIP_TCP */ /** A callback function that is informed about events for this netconn */ netconn_callback callback; @@ -253,6 +291,10 @@ struct netconn { }} while(0); /* Network connection functions: */ + +/** @ingroup netconn_common + * Create new netconn connection + * @param t @ref netconn_type */ #define netconn_new(t) netconn_new_with_proto_and_callback(t, 0, NULL) #define netconn_new_with_callback(t, c) netconn_new_with_proto_and_callback(t, 0, c) struct netconn *netconn_new_with_proto_and_callback(enum netconn_type t, u8_t proto, @@ -263,23 +305,29 @@ err_t netconn_delete(struct netconn *conn); err_t netconn_getaddr(struct netconn *conn, ip_addr_t *addr, u16_t *port, u8_t local); +/** @ingroup netconn_common */ #define netconn_peer(c,i,p) netconn_getaddr(c,i,p,0) +/** @ingroup netconn_common */ #define netconn_addr(c,i,p) netconn_getaddr(c,i,p,1) err_t netconn_bind(struct netconn *conn, const ip_addr_t *addr, u16_t port); err_t netconn_connect(struct netconn *conn, const ip_addr_t *addr, u16_t port); err_t netconn_disconnect (struct netconn *conn); err_t netconn_listen_with_backlog(struct netconn *conn, u8_t backlog); +/** @ingroup netconn_tcp */ #define netconn_listen(conn) netconn_listen_with_backlog(conn, TCP_DEFAULT_LISTEN_BACKLOG) err_t netconn_accept(struct netconn *conn, struct netconn **new_conn); err_t netconn_recv(struct netconn *conn, struct netbuf **new_buf); err_t netconn_recv_tcp_pbuf(struct netconn *conn, struct pbuf **new_buf); +#if ESP_AUTO_RECV void netconn_recved(struct netconn *conn, u32_t length); +#endif err_t netconn_sendto(struct netconn *conn, struct netbuf *buf, const ip_addr_t *addr, u16_t port); err_t netconn_send(struct netconn *conn, struct netbuf *buf); err_t netconn_write_partly(struct netconn *conn, const void *dataptr, size_t size, u8_t apiflags, size_t *bytes_written); +/** @ingroup netconn_tcp */ #define netconn_write(conn, dataptr, size, apiflags) \ netconn_write_partly(conn, dataptr, size, apiflags, NULL) err_t netconn_close(struct netconn *conn); @@ -310,6 +358,7 @@ err_t netconn_gethostbyname(const char *name, ip_addr_t *addr); /** Get the blocking status of netconn calls (@todo: write/send is missing) */ #define netconn_is_nonblocking(conn) (((conn)->flags & NETCONN_FLAG_NON_BLOCKING) != 0) +#if ESP_AUTO_RECV /** TCP: Set the no-auto-recved status of netconn calls (see NETCONN_FLAG_NO_AUTO_RECVED) */ #define netconn_set_noautorecved(conn, val) do { if(val) { \ (conn)->flags |= NETCONN_FLAG_NO_AUTO_RECVED; \ @@ -317,14 +366,19 @@ err_t netconn_gethostbyname(const char *name, ip_addr_t *addr); (conn)->flags &= ~ NETCONN_FLAG_NO_AUTO_RECVED; }} while(0) /** TCP: Get the no-auto-recved status of netconn calls (see NETCONN_FLAG_NO_AUTO_RECVED) */ #define netconn_get_noautorecved(conn) (((conn)->flags & NETCONN_FLAG_NO_AUTO_RECVED) != 0) +#endif #if LWIP_IPV6 -/** TCP: Set the IPv6 ONLY status of netconn calls (see NETCONN_FLAG_IPV6_V6ONLY) */ +/** @ingroup netconn_common + * TCP: Set the IPv6 ONLY status of netconn calls (see NETCONN_FLAG_IPV6_V6ONLY) + */ #define netconn_set_ipv6only(conn, val) do { if(val) { \ (conn)->flags |= NETCONN_FLAG_IPV6_V6ONLY; \ } else { \ (conn)->flags &= ~ NETCONN_FLAG_IPV6_V6ONLY; }} while(0) -/** TCP: Get the IPv6 ONLY status of netconn calls (see NETCONN_FLAG_IPV6_V6ONLY) */ +/** @ingroup netconn_common + * TCP: Get the IPv6 ONLY status of netconn calls (see NETCONN_FLAG_IPV6_V6ONLY) + */ #define netconn_get_ipv6only(conn) (((conn)->flags & NETCONN_FLAG_IPV6_V6ONLY) != 0) #endif /* LWIP_IPV6 */ diff --git a/tools/sdk/include/lwip/lwip/apps/FILES b/tools/sdk/include/lwip/lwip/apps/FILES new file mode 100644 index 00000000..adfc0f33 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/FILES @@ -0,0 +1,2 @@ +This directory contains application headers. +Every application shall provide one api file APP.h and optionally one options file APP_opts.h diff --git a/tools/sdk/include/lwip/lwip/apps/fs.h b/tools/sdk/include/lwip/lwip/apps/fs.h new file mode 100644 index 00000000..bb176fa0 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/fs.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_APPS_FS_H +#define LWIP_HDR_APPS_FS_H + +#include "httpd_opts.h" +#include "lwip/err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define FS_READ_EOF -1 +#define FS_READ_DELAYED -2 + +#if HTTPD_PRECALCULATED_CHECKSUM +struct fsdata_chksum { + u32_t offset; + u16_t chksum; + u16_t len; +}; +#endif /* HTTPD_PRECALCULATED_CHECKSUM */ + +#define FS_FILE_FLAGS_HEADER_INCLUDED 0x01 +#define FS_FILE_FLAGS_HEADER_PERSISTENT 0x02 + +struct fs_file { + const char *data; + int len; + int index; + void *pextension; +#if HTTPD_PRECALCULATED_CHECKSUM + const struct fsdata_chksum *chksum; + u16_t chksum_count; +#endif /* HTTPD_PRECALCULATED_CHECKSUM */ + u8_t flags; +#if LWIP_HTTPD_CUSTOM_FILES + u8_t is_custom_file; +#endif /* LWIP_HTTPD_CUSTOM_FILES */ +#if LWIP_HTTPD_FILE_STATE + void *state; +#endif /* LWIP_HTTPD_FILE_STATE */ +}; + +#if LWIP_HTTPD_FS_ASYNC_READ +typedef void (*fs_wait_cb)(void *arg); +#endif /* LWIP_HTTPD_FS_ASYNC_READ */ + +err_t fs_open(struct fs_file *file, const char *name); +void fs_close(struct fs_file *file); +#if LWIP_HTTPD_DYNAMIC_FILE_READ +#if LWIP_HTTPD_FS_ASYNC_READ +int fs_read_async(struct fs_file *file, char *buffer, int count, fs_wait_cb callback_fn, void *callback_arg); +#else /* LWIP_HTTPD_FS_ASYNC_READ */ +int fs_read(struct fs_file *file, char *buffer, int count); +#endif /* LWIP_HTTPD_FS_ASYNC_READ */ +#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ +#if LWIP_HTTPD_FS_ASYNC_READ +int fs_is_file_ready(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg); +#endif /* LWIP_HTTPD_FS_ASYNC_READ */ +int fs_bytes_left(struct fs_file *file); + +#if LWIP_HTTPD_FILE_STATE +/** This user-defined function is called when a file is opened. */ +void *fs_state_init(struct fs_file *file, const char *name); +/** This user-defined function is called when a file is closed. */ +void fs_state_free(struct fs_file *file, void *state); +#endif /* #if LWIP_HTTPD_FILE_STATE */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_FS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/httpd.h b/tools/sdk/include/lwip/lwip/apps/httpd.h new file mode 100644 index 00000000..40f1811e --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/httpd.h @@ -0,0 +1,236 @@ +/** + * @file + * HTTP server + */ + +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * This version of the file has been modified by Texas Instruments to offer + * simple server-side-include (SSI) and Common Gateway Interface (CGI) + * capability. + */ + +#ifndef LWIP_HDR_APPS_HTTPD_H +#define LWIP_HDR_APPS_HTTPD_H + +#include "httpd_opts.h" +#include "lwip/err.h" +#include "lwip/pbuf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_HTTPD_CGI + +/* + * Function pointer for a CGI script handler. + * + * This function is called each time the HTTPD server is asked for a file + * whose name was previously registered as a CGI function using a call to + * http_set_cgi_handler. The iIndex parameter provides the index of the + * CGI within the ppcURLs array passed to http_set_cgi_handler. Parameters + * pcParam and pcValue provide access to the parameters provided along with + * the URI. iNumParams provides a count of the entries in the pcParam and + * pcValue arrays. Each entry in the pcParam array contains the name of a + * parameter with the corresponding entry in the pcValue array containing the + * value for that parameter. Note that pcParam may contain multiple elements + * with the same name if, for example, a multi-selection list control is used + * in the form generating the data. + * + * The function should return a pointer to a character string which is the + * path and filename of the response that is to be sent to the connected + * browser, for example "/thanks.htm" or "/response/error.ssi". + * + * The maximum number of parameters that will be passed to this function via + * iNumParams is defined by LWIP_HTTPD_MAX_CGI_PARAMETERS. Any parameters in the incoming + * HTTP request above this number will be discarded. + * + * Requests intended for use by this CGI mechanism must be sent using the GET + * method (which encodes all parameters within the URI rather than in a block + * later in the request). Attempts to use the POST method will result in the + * request being ignored. + * + */ +typedef const char *(*tCGIHandler)(int iIndex, int iNumParams, char *pcParam[], + char *pcValue[]); + +/* + * Structure defining the base filename (URL) of a CGI and the associated + * function which is to be called when that URL is requested. + */ +typedef struct +{ + const char *pcCGIName; + tCGIHandler pfnCGIHandler; +} tCGI; + +void http_set_cgi_handlers(const tCGI *pCGIs, int iNumHandlers); + +#endif /* LWIP_HTTPD_CGI */ + +#if LWIP_HTTPD_CGI || LWIP_HTTPD_CGI_SSI + +#if LWIP_HTTPD_CGI_SSI +/** Define this generic CGI handler in your application. + * It is called once for every URI with parameters. + * The parameters can be stored to + */ +extern void httpd_cgi_handler(const char* uri, int iNumParams, char **pcParam, char **pcValue +#if defined(LWIP_HTTPD_FILE_STATE) && LWIP_HTTPD_FILE_STATE + , void *connection_state +#endif /* LWIP_HTTPD_FILE_STATE */ + ); +#endif /* LWIP_HTTPD_CGI_SSI */ + +#endif /* LWIP_HTTPD_CGI || LWIP_HTTPD_CGI_SSI */ + +#if LWIP_HTTPD_SSI + +/* + * Function pointer for the SSI tag handler callback. + * + * This function will be called each time the HTTPD server detects a tag of the + * form in a .shtml, .ssi or .shtm file where "name" appears as + * one of the tags supplied to http_set_ssi_handler in the ppcTags array. The + * returned insert string, which will be appended after the the string + * "" in file sent back to the client,should be written to pointer + * pcInsert. iInsertLen contains the size of the buffer pointed to by + * pcInsert. The iIndex parameter provides the zero-based index of the tag as + * found in the ppcTags array and identifies the tag that is to be processed. + * + * The handler returns the number of characters written to pcInsert excluding + * any terminating NULL or a negative number to indicate a failure (tag not + * recognized, for example). + * + * Note that the behavior of this SSI mechanism is somewhat different from the + * "normal" SSI processing as found in, for example, the Apache web server. In + * this case, the inserted text is appended following the SSI tag rather than + * replacing the tag entirely. This allows for an implementation that does not + * require significant additional buffering of output data yet which will still + * offer usable SSI functionality. One downside to this approach is when + * attempting to use SSI within JavaScript. The SSI tag is structured to + * resemble an HTML comment but this syntax does not constitute a comment + * within JavaScript and, hence, leaving the tag in place will result in + * problems in these cases. To work around this, any SSI tag which needs to + * output JavaScript code must do so in an encapsulated way, sending the whole + * HTML section as a single include. + */ +typedef u16_t (*tSSIHandler)( +#if LWIP_HTTPD_SSI_RAW + const char* ssi_tag_name, +#else /* LWIP_HTTPD_SSI_RAW */ + int iIndex, +#endif /* LWIP_HTTPD_SSI_RAW */ + char *pcInsert, int iInsertLen +#if LWIP_HTTPD_SSI_MULTIPART + , u16_t current_tag_part, u16_t *next_tag_part +#endif /* LWIP_HTTPD_SSI_MULTIPART */ +#if defined(LWIP_HTTPD_FILE_STATE) && LWIP_HTTPD_FILE_STATE + , void *connection_state +#endif /* LWIP_HTTPD_FILE_STATE */ + ); + +/** Set the SSI handler function + * (if LWIP_HTTPD_SSI_RAW==1, only the first argument is used) + */ +void http_set_ssi_handler(tSSIHandler pfnSSIHandler, + const char **ppcTags, int iNumTags); + +/** For LWIP_HTTPD_SSI_RAW==1, return this to indicate the tag is unknown. + * In this case, the webserver writes a warning into the page. + * You can also just return 0 to write nothing for unknown tags. + */ +#define HTTPD_SSI_TAG_UNKNOWN 0xFFFF + +#endif /* LWIP_HTTPD_SSI */ + +#if LWIP_HTTPD_SUPPORT_POST + +/* These functions must be implemented by the application */ + +/** Called when a POST request has been received. The application can decide + * whether to accept it or not. + * + * @param connection Unique connection identifier, valid until httpd_post_end + * is called. + * @param uri The HTTP header URI receiving the POST request. + * @param http_request The raw HTTP request (the first packet, normally). + * @param http_request_len Size of 'http_request'. + * @param content_len Content-Length from HTTP header. + * @param response_uri Filename of response file, to be filled when denying the + * request + * @param response_uri_len Size of the 'response_uri' buffer. + * @param post_auto_wnd Set this to 0 to let the callback code handle window + * updates by calling 'httpd_post_data_recved' (to throttle rx speed) + * default is 1 (httpd handles window updates automatically) + * @return ERR_OK: Accept the POST request, data may be passed in + * another err_t: Deny the POST request, send back 'bad request'. + */ +err_t httpd_post_begin(void *connection, const char *uri, const char *http_request, + u16_t http_request_len, int content_len, char *response_uri, + u16_t response_uri_len, u8_t *post_auto_wnd); + +/** Called for each pbuf of data that has been received for a POST. + * ATTENTION: The application is responsible for freeing the pbufs passed in! + * + * @param connection Unique connection identifier. + * @param p Received data. + * @return ERR_OK: Data accepted. + * another err_t: Data denied, http_post_get_response_uri will be called. + */ +err_t httpd_post_receive_data(void *connection, struct pbuf *p); + +/** Called when all data is received or when the connection is closed. + * The application must return the filename/URI of a file to send in response + * to this POST request. If the response_uri buffer is untouched, a 404 + * response is returned. + * + * @param connection Unique connection identifier. + * @param response_uri Filename of response file, to be filled when denying the request + * @param response_uri_len Size of the 'response_uri' buffer. + */ +void httpd_post_finished(void *connection, char *response_uri, u16_t response_uri_len); + +#if LWIP_HTTPD_POST_MANUAL_WND +void httpd_post_data_recved(void *connection, u16_t recved_len); +#endif /* LWIP_HTTPD_POST_MANUAL_WND */ + +#endif /* LWIP_HTTPD_SUPPORT_POST */ + +void httpd_init(void); + + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HTTPD_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/httpd_opts.h b/tools/sdk/include/lwip/lwip/apps/httpd_opts.h new file mode 100644 index 00000000..340db15f --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/httpd_opts.h @@ -0,0 +1,323 @@ +/** + * @file + * HTTP server options list + */ + +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * This version of the file has been modified by Texas Instruments to offer + * simple server-side-include (SSI) and Common Gateway Interface (CGI) + * capability. + */ + +#ifndef LWIP_HDR_APPS_HTTPD_OPTS_H +#define LWIP_HDR_APPS_HTTPD_OPTS_H + +#include "lwip/opt.h" + +/** + * @defgroup httpd_opts Options + * @ingroup httpd + * @{ + */ + +/** Set this to 1 to support CGI (old style) */ +#if !defined LWIP_HTTPD_CGI || defined __DOXYGEN__ +#define LWIP_HTTPD_CGI 0 +#endif + +/** Set this to 1 to support CGI (new style) */ +#if !defined LWIP_HTTPD_CGI_SSI || defined __DOXYGEN__ +#define LWIP_HTTPD_CGI_SSI 0 +#endif + +/** Set this to 1 to support SSI (Server-Side-Includes) */ +#if !defined LWIP_HTTPD_SSI || defined __DOXYGEN__ +#define LWIP_HTTPD_SSI 0 +#endif + +/** Set this to 1 to implement an SSI tag handler callback that gets a const char* + * to the tag (instead of an index into a pre-registered array of known tags) */ +#if !defined LWIP_HTTPD_SSI_RAW || defined __DOXYGEN__ +#define LWIP_HTTPD_SSI_RAW 0 +#endif + +/** Set this to 1 to support HTTP POST */ +#if !defined LWIP_HTTPD_SUPPORT_POST || defined __DOXYGEN__ +#define LWIP_HTTPD_SUPPORT_POST 0 +#endif + +/* The maximum number of parameters that the CGI handler can be sent. */ +#if !defined LWIP_HTTPD_MAX_CGI_PARAMETERS || defined __DOXYGEN__ +#define LWIP_HTTPD_MAX_CGI_PARAMETERS 16 +#endif + +/** LWIP_HTTPD_SSI_MULTIPART==1: SSI handler function is called with 2 more + * arguments indicating a counter for insert string that are too long to be + * inserted at once: the SSI handler function must then set 'next_tag_part' + * which will be passed back to it in the next call. */ +#if !defined LWIP_HTTPD_SSI_MULTIPART || defined __DOXYGEN__ +#define LWIP_HTTPD_SSI_MULTIPART 0 +#endif + +/* The maximum length of the string comprising the tag name */ +#if !defined LWIP_HTTPD_MAX_TAG_NAME_LEN || defined __DOXYGEN__ +#define LWIP_HTTPD_MAX_TAG_NAME_LEN 8 +#endif + +/* The maximum length of string that can be returned to replace any given tag */ +#if !defined LWIP_HTTPD_MAX_TAG_INSERT_LEN || defined __DOXYGEN__ +#define LWIP_HTTPD_MAX_TAG_INSERT_LEN 192 +#endif + +#if !defined LWIP_HTTPD_POST_MANUAL_WND || defined __DOXYGEN__ +#define LWIP_HTTPD_POST_MANUAL_WND 0 +#endif + +/** This string is passed in the HTTP header as "Server: " */ +#if !defined HTTPD_SERVER_AGENT || defined __DOXYGEN__ +#define HTTPD_SERVER_AGENT "lwIP/" LWIP_VERSION_STRING " (http://savannah.nongnu.org/projects/lwip)" +#endif + +/** Set this to 1 if you want to include code that creates HTTP headers + * at runtime. Default is off: HTTP headers are then created statically + * by the makefsdata tool. Static headers mean smaller code size, but + * the (readonly) fsdata will grow a bit as every file includes the HTTP + * header. */ +#if !defined LWIP_HTTPD_DYNAMIC_HEADERS || defined __DOXYGEN__ +#define LWIP_HTTPD_DYNAMIC_HEADERS 0 +#endif + +#if !defined HTTPD_DEBUG || defined __DOXYGEN__ +#define HTTPD_DEBUG LWIP_DBG_OFF +#endif + +/** Set this to 1 to use a memp pool for allocating + * struct http_state instead of the heap. + */ +#if !defined HTTPD_USE_MEM_POOL || defined __DOXYGEN__ +#define HTTPD_USE_MEM_POOL 0 +#endif + +/** The server port for HTTPD to use */ +#if !defined HTTPD_SERVER_PORT || defined __DOXYGEN__ +#define HTTPD_SERVER_PORT 80 +#endif + +/** Maximum retries before the connection is aborted/closed. + * - number of times pcb->poll is called -> default is 4*500ms = 2s; + * - reset when pcb->sent is called + */ +#if !defined HTTPD_MAX_RETRIES || defined __DOXYGEN__ +#define HTTPD_MAX_RETRIES 4 +#endif + +/** The poll delay is X*500ms */ +#if !defined HTTPD_POLL_INTERVAL || defined __DOXYGEN__ +#define HTTPD_POLL_INTERVAL 4 +#endif + +/** Priority for tcp pcbs created by HTTPD (very low by default). + * Lower priorities get killed first when running out of memory. + */ +#if !defined HTTPD_TCP_PRIO || defined __DOXYGEN__ +#define HTTPD_TCP_PRIO TCP_PRIO_MIN +#endif + +/** Set this to 1 to enable timing each file sent */ +#if !defined LWIP_HTTPD_TIMING || defined __DOXYGEN__ +#define LWIP_HTTPD_TIMING 0 +#endif +/** Set this to 1 to enable timing each file sent */ +#if !defined HTTPD_DEBUG_TIMING || defined __DOXYGEN__ +#define HTTPD_DEBUG_TIMING LWIP_DBG_OFF +#endif + +/** Set this to one to show error pages when parsing a request fails instead + of simply closing the connection. */ +#if !defined LWIP_HTTPD_SUPPORT_EXTSTATUS || defined __DOXYGEN__ +#define LWIP_HTTPD_SUPPORT_EXTSTATUS 0 +#endif + +/** Set this to 0 to drop support for HTTP/0.9 clients (to save some bytes) */ +#if !defined LWIP_HTTPD_SUPPORT_V09 || defined __DOXYGEN__ +#define LWIP_HTTPD_SUPPORT_V09 1 +#endif + +/** Set this to 1 to enable HTTP/1.1 persistent connections. + * ATTENTION: If the generated file system includes HTTP headers, these must + * include the "Connection: keep-alive" header (pass argument "-11" to makefsdata). + */ +#if !defined LWIP_HTTPD_SUPPORT_11_KEEPALIVE || defined __DOXYGEN__ +#define LWIP_HTTPD_SUPPORT_11_KEEPALIVE 0 +#endif + +/** Set this to 1 to support HTTP request coming in in multiple packets/pbufs */ +#if !defined LWIP_HTTPD_SUPPORT_REQUESTLIST || defined __DOXYGEN__ +#define LWIP_HTTPD_SUPPORT_REQUESTLIST 1 +#endif + +#if LWIP_HTTPD_SUPPORT_REQUESTLIST +/** Number of rx pbufs to enqueue to parse an incoming request (up to the first + newline) */ +#if !defined LWIP_HTTPD_REQ_QUEUELEN || defined __DOXYGEN__ +#define LWIP_HTTPD_REQ_QUEUELEN 5 +#endif + +/** Number of (TCP payload-) bytes (in pbufs) to enqueue to parse and incoming + request (up to the first double-newline) */ +#if !defined LWIP_HTTPD_REQ_BUFSIZE || defined __DOXYGEN__ +#define LWIP_HTTPD_REQ_BUFSIZE LWIP_HTTPD_MAX_REQ_LENGTH +#endif + +/** Defines the maximum length of a HTTP request line (up to the first CRLF, + copied from pbuf into this a global buffer when pbuf- or packet-queues + are received - otherwise the input pbuf is used directly) */ +#if !defined LWIP_HTTPD_MAX_REQ_LENGTH || defined __DOXYGEN__ +#define LWIP_HTTPD_MAX_REQ_LENGTH LWIP_MIN(1023, (LWIP_HTTPD_REQ_QUEUELEN * PBUF_POOL_BUFSIZE)) +#endif +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + +/** This is the size of a static buffer used when URIs end with '/'. + * In this buffer, the directory requested is concatenated with all the + * configured default file names. + * Set to 0 to disable checking default filenames on non-root directories. + */ +#if !defined LWIP_HTTPD_MAX_REQUEST_URI_LEN || defined __DOXYGEN__ +#define LWIP_HTTPD_MAX_REQUEST_URI_LEN 63 +#endif + +/** Maximum length of the filename to send as response to a POST request, + * filled in by the application when a POST is finished. + */ +#if !defined LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN || defined __DOXYGEN__ +#define LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN 63 +#endif + +/** Set this to 0 to not send the SSI tag (default is on, so the tag will + * be sent in the HTML page */ +#if !defined LWIP_HTTPD_SSI_INCLUDE_TAG || defined __DOXYGEN__ +#define LWIP_HTTPD_SSI_INCLUDE_TAG 1 +#endif + +/** Set this to 1 to call tcp_abort when tcp_close fails with memory error. + * This can be used to prevent consuming all memory in situations where the + * HTTP server has low priority compared to other communication. */ +#if !defined LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR || defined __DOXYGEN__ +#define LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR 0 +#endif + +/** Set this to 1 to kill the oldest connection when running out of + * memory for 'struct http_state' or 'struct http_ssi_state'. + * ATTENTION: This puts all connections on a linked list, so may be kind of slow. + */ +#if !defined LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED || defined __DOXYGEN__ +#define LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED 0 +#endif + +/** Set this to 1 to send URIs without extension without headers + * (who uses this at all??) */ +#if !defined LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI || defined __DOXYGEN__ +#define LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI 0 +#endif + +/** Default: Tags are sent from struct http_state and are therefore volatile */ +#if !defined HTTP_IS_TAG_VOLATILE || defined __DOXYGEN__ +#define HTTP_IS_TAG_VOLATILE(ptr) TCP_WRITE_FLAG_COPY +#endif + +/* By default, the httpd is limited to send 2*pcb->mss to keep resource usage low + when http is not an important protocol in the device. */ +#if !defined HTTPD_LIMIT_SENDING_TO_2MSS || defined __DOXYGEN__ +#define HTTPD_LIMIT_SENDING_TO_2MSS 1 +#endif + +/* Define this to a function that returns the maximum amount of data to enqueue. + The function have this signature: u16_t fn(struct tcp_pcb* pcb); */ +#if !defined HTTPD_MAX_WRITE_LEN || defined __DOXYGEN__ +#if HTTPD_LIMIT_SENDING_TO_2MSS +#define HTTPD_MAX_WRITE_LEN(pcb) (2 * tcp_mss(pcb)) +#endif +#endif + +/*------------------- FS OPTIONS -------------------*/ + +/** Set this to 1 and provide the functions: + * - "int fs_open_custom(struct fs_file *file, const char *name)" + * Called first for every opened file to allow opening files + * that are not included in fsdata(_custom).c + * - "void fs_close_custom(struct fs_file *file)" + * Called to free resources allocated by fs_open_custom(). + */ +#if !defined LWIP_HTTPD_CUSTOM_FILES || defined __DOXYGEN__ +#define LWIP_HTTPD_CUSTOM_FILES 0 +#endif + +/** Set this to 1 to support fs_read() to dynamically read file data. + * Without this (default=off), only one-block files are supported, + * and the contents must be ready after fs_open(). + */ +#if !defined LWIP_HTTPD_DYNAMIC_FILE_READ || defined __DOXYGEN__ +#define LWIP_HTTPD_DYNAMIC_FILE_READ 0 +#endif + +/** Set this to 1 to include an application state argument per file + * that is opened. This allows to keep a state per connection/file. + */ +#if !defined LWIP_HTTPD_FILE_STATE || defined __DOXYGEN__ +#define LWIP_HTTPD_FILE_STATE 0 +#endif + +/** HTTPD_PRECALCULATED_CHECKSUM==1: include precompiled checksums for + * predefined (MSS-sized) chunks of the files to prevent having to calculate + * the checksums at runtime. */ +#if !defined HTTPD_PRECALCULATED_CHECKSUM || defined __DOXYGEN__ +#define HTTPD_PRECALCULATED_CHECKSUM 0 +#endif + +/** LWIP_HTTPD_FS_ASYNC_READ==1: support asynchronous read operations + * (fs_read_async returns FS_READ_DELAYED and calls a callback when finished). + */ +#if !defined LWIP_HTTPD_FS_ASYNC_READ || defined __DOXYGEN__ +#define LWIP_HTTPD_FS_ASYNC_READ 0 +#endif + +/** Set this to 1 to include "fsdata_custom.c" instead of "fsdata.c" for the + * file system (to prevent changing the file included in CVS) */ +#if !defined HTTPD_USE_CUSTOM_FSDATA || defined __DOXYGEN__ +#define HTTPD_USE_CUSTOM_FSDATA 0 +#endif + +/** + * @} + */ + +#endif /* LWIP_HDR_APPS_HTTPD_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/lwiperf.h b/tools/sdk/include/lwip/lwip/apps/lwiperf.h new file mode 100644 index 00000000..7dbebb08 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/lwiperf.h @@ -0,0 +1,84 @@ +/** + * @file + * lwIP iPerf server implementation + */ + +/* + * Copyright (c) 2014 Simon Goldschmidt + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Simon Goldschmidt + * + */ +#ifndef LWIP_HDR_APPS_LWIPERF_H +#define LWIP_HDR_APPS_LWIPERF_H + +#include "lwip/opt.h" +#include "lwip/ip_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define LWIPERF_TCP_PORT_DEFAULT 5001 + +/** lwIPerf test results */ +enum lwiperf_report_type +{ + /** The server side test is done */ + LWIPERF_TCP_DONE_SERVER, + /** The client side test is done */ + LWIPERF_TCP_DONE_CLIENT, + /** Local error lead to test abort */ + LWIPERF_TCP_ABORTED_LOCAL, + /** Data check error lead to test abort */ + LWIPERF_TCP_ABORTED_LOCAL_DATAERROR, + /** Transmit error lead to test abort */ + LWIPERF_TCP_ABORTED_LOCAL_TXERROR, + /** Remote side aborted the test */ + LWIPERF_TCP_ABORTED_REMOTE +}; + +/** Prototype of a report function that is called when a session is finished. + This report function can show the test results. + @param report_type contains the test result */ +typedef void (*lwiperf_report_fn)(void *arg, enum lwiperf_report_type report_type, + const ip_addr_t* local_addr, u16_t local_port, const ip_addr_t* remote_addr, u16_t remote_port, + u32_t bytes_transferred, u32_t ms_duration, u32_t bandwidth_kbitpsec); + + +void* lwiperf_start_tcp_server(const ip_addr_t* local_addr, u16_t local_port, + lwiperf_report_fn report_fn, void* report_arg); +void* lwiperf_start_tcp_server_default(lwiperf_report_fn report_fn, void* report_arg); +void lwiperf_abort(void* lwiperf_session); + + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_LWIPERF_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/mdns.h b/tools/sdk/include/lwip/lwip/apps/mdns.h new file mode 100644 index 00000000..d0368161 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/mdns.h @@ -0,0 +1,69 @@ +/** + * @file + * MDNS responder + */ + + /* + * Copyright (c) 2015 Verisure Innovation AB + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Erik Ekman + * + */ +#ifndef LWIP_HDR_MDNS_H +#define LWIP_HDR_MDNS_H + +#include "lwip/apps/mdns_opts.h" +#include "lwip/netif.h" + +#if LWIP_MDNS_RESPONDER + +enum mdns_sd_proto { + DNSSD_PROTO_UDP = 0, + DNSSD_PROTO_TCP = 1 +}; + +#define MDNS_LABEL_MAXLEN 63 + +struct mdns_host; +struct mdns_service; + +/** Callback function to add text to a reply, called when generating the reply */ +typedef void (*service_get_txt_fn_t)(struct mdns_service *service, void *txt_userdata); + +void mdns_resp_init(void); + +err_t mdns_resp_add_netif(struct netif *netif, const char *hostname, u32_t dns_ttl); +err_t mdns_resp_remove_netif(struct netif *netif); + +err_t mdns_resp_add_service(struct netif *netif, const char *name, const char *service, enum mdns_sd_proto proto, u16_t port, u32_t dns_ttl, service_get_txt_fn_t txt_fn, void *txt_userdata); +err_t mdns_resp_add_service_txtitem(struct mdns_service *service, const char *txt, u8_t txt_len); +void mdns_resp_netif_settings_changed(struct netif *netif); + +#endif /* LWIP_MDNS_RESPONDER */ + +#endif /* LWIP_HDR_MDNS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/mdns_opts.h b/tools/sdk/include/lwip/lwip/apps/mdns_opts.h new file mode 100644 index 00000000..bf186bcc --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/mdns_opts.h @@ -0,0 +1,74 @@ +/** + * @file + * MDNS responder + */ + + /* + * Copyright (c) 2015 Verisure Innovation AB + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Erik Ekman + * + */ + +#ifndef LWIP_HDR_APPS_MDNS_OPTS_H +#define LWIP_HDR_APPS_MDNS_OPTS_H + +#include "lwip/opt.h" + +/** + * @defgroup mdns_opts Options + * @ingroup mdns + * @{ + */ + +/** + * LWIP_MDNS_RESPONDER==1: Turn on multicast DNS module. UDP must be available for MDNS + * transport. IGMP is needed for IPv4 multicast. + */ +#ifndef LWIP_MDNS_RESPONDER +#define LWIP_MDNS_RESPONDER 0 +#endif /* LWIP_MDNS_RESPONDER */ + +/** The maximum number of services per netif */ +#ifndef MDNS_MAX_SERVICES +#define MDNS_MAX_SERVICES 1 +#endif + +/** + * MDNS_DEBUG: Enable debugging for multicast DNS. + */ +#ifndef MDNS_DEBUG +#define MDNS_DEBUG LWIP_DBG_OFF +#endif + +/** + * @} + */ + +#endif /* LWIP_HDR_APPS_MDNS_OPTS_H */ + diff --git a/tools/sdk/include/lwip/lwip/apps/mdns_priv.h b/tools/sdk/include/lwip/lwip/apps/mdns_priv.h new file mode 100644 index 00000000..8ee6db86 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/mdns_priv.h @@ -0,0 +1,66 @@ +/** + * @file + * MDNS responder private definitions + */ + + /* + * Copyright (c) 2015 Verisure Innovation AB + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Erik Ekman + * + */ +#ifndef LWIP_HDR_MDNS_PRIV_H +#define LWIP_HDR_MDNS_PRIV_H + +#include "lwip/apps/mdns_opts.h" +#include "lwip/pbuf.h" + +#if LWIP_MDNS_RESPONDER + +/* Domain struct and methods - visible for unit tests */ + +#define MDNS_DOMAIN_MAXLEN 256 +#define MDNS_READNAME_ERROR 0xFFFF + +struct mdns_domain { + /* Encoded domain name */ + u8_t name[MDNS_DOMAIN_MAXLEN]; + /* Total length of domain name, including zero */ + u16_t length; + /* Set if compression of this domain is not allowed */ + u8_t skip_compression; +}; + +err_t mdns_domain_add_label(struct mdns_domain *domain, const char *label, u8_t len); +u16_t mdns_readname(struct pbuf *p, u16_t offset, struct mdns_domain *domain); +int mdns_domain_eq(struct mdns_domain *a, struct mdns_domain *b); +u16_t mdns_compress_domain(struct pbuf *pbuf, u16_t *offset, struct mdns_domain *domain); + +#endif /* LWIP_MDNS_RESPONDER */ + +#endif /* LWIP_HDR_MDNS_PRIV_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/mqtt.h b/tools/sdk/include/lwip/lwip/apps/mqtt.h new file mode 100644 index 00000000..34b230b8 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/mqtt.h @@ -0,0 +1,244 @@ +/** + * @file + * MQTT client + */ + +/* + * Copyright (c) 2016 Erik Andersson + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Erik Andersson + * + */ +#ifndef LWIP_HDR_APPS_MQTT_CLIENT_H +#define LWIP_HDR_APPS_MQTT_CLIENT_H + +#include "lwip/apps/mqtt_opts.h" +#include "lwip/err.h" +#include "lwip/ip_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct mqtt_client_t mqtt_client_t; + +/** @ingroup mqtt + * Default MQTT port */ +#define MQTT_PORT 1883 + +/*---------------------------------------------------------------------------------------------- */ +/* Connection with server */ + +/** + * @ingroup mqtt + * Client information and connection parameters */ +struct mqtt_connect_client_info_t { + /** Client identifier, must be set by caller */ + const char *client_id; + /** User name and password, set to NULL if not used */ + const char* client_user; + const char* client_pass; + /** keep alive time in seconds, 0 to disable keep alive functionality*/ + u16_t keep_alive; + /** will topic, set to NULL if will is not to be used, + will_msg, will_qos and will retain are then ignored */ + const char* will_topic; + const char* will_msg; + u8_t will_qos; + u8_t will_retain; +}; + +/** + * @ingroup mqtt + * Connection status codes */ +typedef enum +{ + MQTT_CONNECT_ACCEPTED = 0, + MQTT_CONNECT_REFUSED_PROTOCOL_VERSION = 1, + MQTT_CONNECT_REFUSED_IDENTIFIER = 2, + MQTT_CONNECT_REFUSED_SERVER = 3, + MQTT_CONNECT_REFUSED_USERNAME_PASS = 4, + MQTT_CONNECT_REFUSED_NOT_AUTHORIZED_ = 5, + MQTT_CONNECT_DISCONNECTED = 256, + MQTT_CONNECT_TIMEOUT = 257 +} mqtt_connection_status_t; + +/** + * @ingroup mqtt + * Function prototype for mqtt connection status callback. Called when + * client has connected to the server after initiating a mqtt connection attempt by + * calling mqtt_connect() or when connection is closed by server or an error + * + * @param client MQTT client itself + * @param arg Additional argument to pass to the callback function + * @param status Connect result code or disconnection notification @see mqtt_connection_status_t + * + */ +typedef void (*mqtt_connection_cb_t)(mqtt_client_t *client, void *arg, mqtt_connection_status_t status); + + +/** + * @ingroup mqtt + * Data callback flags */ +enum { + /** Flag set when last fragment of data arrives in data callback */ + MQTT_DATA_FLAG_LAST = 1 +}; + +/** + * @ingroup mqtt + * Function prototype for MQTT incoming publish data callback function. Called when data + * arrives to a subscribed topic @see mqtt_subscribe + * + * @param arg Additional argument to pass to the callback function + * @param data User data, pointed object, data may not be referenced after callback return, + NULL is passed when all publish data are delivered + * @param len Length of publish data fragment + * @param flags MQTT_DATA_FLAG_LAST set when this call contains the last part of data from publish message + * + */ +typedef void (*mqtt_incoming_data_cb_t)(void *arg, const u8_t *data, u16_t len, u8_t flags); + + +/** + * @ingroup mqtt + * Function prototype for MQTT incoming publish function. Called when an incoming publish + * arrives to a subscribed topic @see mqtt_subscribe + * + * @param arg Additional argument to pass to the callback function + * @param topic Zero terminated Topic text string, topic may not be referenced after callback return + * @param tot_len Total length of publish data, if set to 0 (no publish payload) data callback will not be invoked + */ +typedef void (*mqtt_incoming_publish_cb_t)(void *arg, const char *topic, u32_t tot_len); + + +/** + * @ingroup mqtt + * Function prototype for mqtt request callback. Called when a subscribe, unsubscribe + * or publish request has completed + * @param arg Pointer to user data supplied when invoking request + * @param err ERR_OK on success + * ERR_TIMEOUT if no response was received within timeout, + * ERR_ABRT if (un)subscribe was denied + */ +typedef void (*mqtt_request_cb_t)(void *arg, err_t err); + + +/** + * Pending request item, binds application callback to pending server requests + */ +struct mqtt_request_t +{ + /** Next item in list, NULL means this is the last in chain, + next pointing at itself means request is unallocated */ + struct mqtt_request_t *next; + /** Callback to upper layer */ + mqtt_request_cb_t cb; + void *arg; + /** MQTT packet identifier */ + u16_t pkt_id; + /** Expire time relative to element before this */ + u16_t timeout_diff; +}; + +/** Ring buffer */ +struct mqtt_ringbuf_t { + u16_t put; + u16_t get; + u8_t buf[MQTT_OUTPUT_RINGBUF_SIZE]; +}; + +/** MQTT client */ +struct mqtt_client_t +{ + /** Timers and timeouts */ + u16_t cyclic_tick; + u16_t keep_alive; + u16_t server_watchdog; + /** Packet identifier generator*/ + u16_t pkt_id_seq; + /** Packet identifier of pending incoming publish */ + u16_t inpub_pkt_id; + /** Connection state */ + u8_t conn_state; + struct tcp_pcb *conn; + /** Connection callback */ + void *connect_arg; + mqtt_connection_cb_t connect_cb; + /** Pending requests to server */ + struct mqtt_request_t *pend_req_queue; + struct mqtt_request_t req_list[MQTT_REQ_MAX_IN_FLIGHT]; + void *inpub_arg; + /** Incoming data callback */ + mqtt_incoming_data_cb_t data_cb; + mqtt_incoming_publish_cb_t pub_cb; + /** Input */ + u32_t msg_idx; + u8_t rx_buffer[MQTT_VAR_HEADER_BUFFER_LEN]; + /** Output ring-buffer */ + struct mqtt_ringbuf_t output; +}; + + +/** Connect to server */ +err_t mqtt_client_connect(mqtt_client_t *client, const ip_addr_t *ipaddr, u16_t port, mqtt_connection_cb_t cb, void *arg, + const struct mqtt_connect_client_info_t *client_info); + +/** Disconnect from server */ +void mqtt_disconnect(mqtt_client_t *client); + +/** Create new client */ +mqtt_client_t *mqtt_client_new(void); + +/** Check connection status */ +u8_t mqtt_client_is_connected(mqtt_client_t *client); + +/** Set callback to call for incoming publish */ +void mqtt_set_inpub_callback(mqtt_client_t *client, mqtt_incoming_publish_cb_t, + mqtt_incoming_data_cb_t data_cb, void *arg); + +/** Common function for subscribe and unsubscribe */ +err_t mqtt_sub_unsub(mqtt_client_t *client, const char *topic, u8_t qos, mqtt_request_cb_t cb, void *arg, u8_t sub); + +/** @ingroup mqtt + *Subscribe to topic */ +#define mqtt_subscribe(client, topic, qos, cb, arg) mqtt_sub_unsub(client, topic, qos, cb, arg, 1) +/** @ingroup mqtt + * Unsubscribe to topic */ +#define mqtt_unsubscribe(client, topic, cb, arg) mqtt_sub_unsub(client, topic, 0, cb, arg, 0) + + +/** Publish data to topic */ +err_t mqtt_publish(mqtt_client_t *client, const char *topic, const void *payload, u16_t payload_length, u8_t qos, u8_t retain, + mqtt_request_cb_t cb, void *arg); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_MQTT_CLIENT_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/mqtt_opts.h b/tools/sdk/include/lwip/lwip/apps/mqtt_opts.h new file mode 100644 index 00000000..ffefacd2 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/mqtt_opts.h @@ -0,0 +1,103 @@ +/** + * @file + * MQTT client options + */ + +/* + * Copyright (c) 2016 Erik Andersson + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Erik Andersson + * + */ +#ifndef LWIP_HDR_APPS_MQTT_OPTS_H +#define LWIP_HDR_APPS_MQTT_OPTS_H + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup mqtt_opts Options + * @ingroup mqtt + * @{ + */ + +/** + * Output ring-buffer size, must be able to fit largest outgoing publish message topic+payloads + */ +#ifndef MQTT_OUTPUT_RINGBUF_SIZE +#define MQTT_OUTPUT_RINGBUF_SIZE 256 +#endif + +/** + * Number of bytes in receive buffer, must be at least the size of the longest incoming topic + 8 + * If one wants to avoid fragmented incoming publish, set length to max incoming topic length + max payload length + 8 + */ +#ifndef MQTT_VAR_HEADER_BUFFER_LEN +#define MQTT_VAR_HEADER_BUFFER_LEN 128 +#endif + +/** + * Maximum number of pending subscribe, unsubscribe and publish requests to server . + */ +#ifndef MQTT_REQ_MAX_IN_FLIGHT +#define MQTT_REQ_MAX_IN_FLIGHT 4 +#endif + +/** + * Seconds between each cyclic timer call. + */ +#ifndef MQTT_CYCLIC_TIMER_INTERVAL +#define MQTT_CYCLIC_TIMER_INTERVAL 5 +#endif + +/** + * Publish, subscribe and unsubscribe request timeout in seconds. + */ +#ifndef MQTT_REQ_TIMEOUT +#define MQTT_REQ_TIMEOUT 30 +#endif + +/** + * Seconds for MQTT connect response timeout after sending connect request + */ +#ifndef MQTT_CONNECT_TIMOUT +#define MQTT_CONNECT_TIMOUT 100 +#endif + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_MQTT_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/netbiosns.h b/tools/sdk/include/lwip/lwip/apps/netbiosns.h new file mode 100644 index 00000000..c9f68d8d --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/netbiosns.h @@ -0,0 +1,43 @@ +/** + * @file + * NETBIOS name service responder + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ +#ifndef LWIP_HDR_APPS_NETBIOS_H +#define LWIP_HDR_APPS_NETBIOS_H + +#include "lwip/apps/netbiosns_opts.h" + +void netbiosns_init(void); +#ifndef NETBIOS_LWIP_NAME +void netbiosns_set_name(const char* hostname); +#endif +void netbiosns_stop(void); + +#endif /* LWIP_HDR_APPS_NETBIOS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/netbiosns_opts.h b/tools/sdk/include/lwip/lwip/apps/netbiosns_opts.h new file mode 100644 index 00000000..0909ef7b --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/netbiosns_opts.h @@ -0,0 +1,59 @@ +/** + * @file + * NETBIOS name service responder options + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ +#ifndef LWIP_HDR_APPS_NETBIOS_OPTS_H +#define LWIP_HDR_APPS_NETBIOS_OPTS_H + +#include "lwip/opt.h" + +/** + * @defgroup netbiosns_opts Options + * @ingroup netbiosns + * @{ + */ + +/** NetBIOS name of lwip device + * This must be uppercase until NETBIOS_STRCMP() is defined to a string + * comparision function that is case insensitive. + * If you want to use the netif's hostname, use this (with LWIP_NETIF_HOSTNAME): + * (ip_current_netif() != NULL ? ip_current_netif()->hostname != NULL ? ip_current_netif()->hostname : "" : "") + * + * If this is not defined, netbiosns_set_name() can be called at runtime to change the name. + */ +#ifdef __DOXYGEN__ +#define NETBIOS_LWIP_NAME "NETBIOSLWIPDEV" +#endif + +/** + * @} + */ + +#endif /* LWIP_HDR_APPS_NETBIOS_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp.h b/tools/sdk/include/lwip/lwip/apps/snmp.h new file mode 100644 index 00000000..10e8ff43 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp.h @@ -0,0 +1,128 @@ +/** + * @file + * SNMP server main API - start and basic configuration + */ + +/* + * Copyright (c) 2001, 2002 Leon Woestenberg + * Copyright (c) 2001, 2002 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Leon Woestenberg + * Martin Hentschel + * + */ +#ifndef LWIP_HDR_APPS_SNMP_H +#define LWIP_HDR_APPS_SNMP_H + +#include "lwip/apps/snmp_opts.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/err.h" +#include "lwip/apps/snmp_core.h" + +/** SNMP variable binding descriptor (publically needed for traps) */ +struct snmp_varbind +{ + /** pointer to next varbind, NULL for last in list */ + struct snmp_varbind *next; + /** pointer to previous varbind, NULL for first in list */ + struct snmp_varbind *prev; + + /** object identifier */ + struct snmp_obj_id oid; + + /** value ASN1 type */ + u8_t type; + /** object value length */ + u16_t value_len; + /** object value */ + void *value; +}; + +/** + * @ingroup snmp_core + * Agent setup, start listening to port 161. + */ +void snmp_init(void); +void snmp_set_mibs(const struct snmp_mib **mibs, u8_t num_mibs); + +void snmp_set_device_enterprise_oid(const struct snmp_obj_id* device_enterprise_oid); +const struct snmp_obj_id* snmp_get_device_enterprise_oid(void); + +void snmp_trap_dst_enable(u8_t dst_idx, u8_t enable); +void snmp_trap_dst_ip_set(u8_t dst_idx, const ip_addr_t *dst); + +/** Generic trap: cold start */ +#define SNMP_GENTRAP_COLDSTART 0 +/** Generic trap: warm start */ +#define SNMP_GENTRAP_WARMSTART 1 +/** Generic trap: link down */ +#define SNMP_GENTRAP_LINKDOWN 2 +/** Generic trap: link up */ +#define SNMP_GENTRAP_LINKUP 3 +/** Generic trap: authentication failure */ +#define SNMP_GENTRAP_AUTH_FAILURE 4 +/** Generic trap: EGP neighbor lost */ +#define SNMP_GENTRAP_EGP_NEIGHBOR_LOSS 5 +/** Generic trap: enterprise specific */ +#define SNMP_GENTRAP_ENTERPRISE_SPECIFIC 6 + +err_t snmp_send_trap_generic(s32_t generic_trap); +err_t snmp_send_trap_specific(s32_t specific_trap, struct snmp_varbind *varbinds); +err_t snmp_send_trap(const struct snmp_obj_id* oid, s32_t generic_trap, s32_t specific_trap, struct snmp_varbind *varbinds); + +#define SNMP_AUTH_TRAPS_DISABLED 0 +#define SNMP_AUTH_TRAPS_ENABLED 1 +void snmp_set_auth_traps_enabled(u8_t enable); +u8_t snmp_get_auth_traps_enabled(void); + +const char * snmp_get_community(void); +const char * snmp_get_community_write(void); +const char * snmp_get_community_trap(void); +void snmp_set_community(const char * const community); +void snmp_set_community_write(const char * const community); +void snmp_set_community_trap(const char * const community); + +void snmp_coldstart_trap(void); +void snmp_authfail_trap(void); + +typedef void (*snmp_write_callback_fct)(const u32_t* oid, u8_t oid_len, void* callback_arg); +void snmp_set_write_callback(snmp_write_callback_fct write_callback, void* callback_arg); + +#endif /* LWIP_SNMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_SNMP_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_core.h b/tools/sdk/include/lwip/lwip/apps/snmp_core.h new file mode 100644 index 00000000..e781c532 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_core.h @@ -0,0 +1,364 @@ +/** + * @file + * SNMP core API for implementing MIBs + */ + +/* + * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Christiaan Simons + * Martin Hentschel + */ + +#ifndef LWIP_HDR_APPS_SNMP_CORE_H +#define LWIP_HDR_APPS_SNMP_CORE_H + +#include "lwip/apps/snmp_opts.h" + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/ip_addr.h" +#include "lwip/err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* basic ASN1 defines */ +#define SNMP_ASN1_CLASS_UNIVERSAL 0x00 +#define SNMP_ASN1_CLASS_APPLICATION 0x40 +#define SNMP_ASN1_CLASS_CONTEXT 0x80 +#define SNMP_ASN1_CLASS_PRIVATE 0xC0 + +#define SNMP_ASN1_CONTENTTYPE_PRIMITIVE 0x00 +#define SNMP_ASN1_CONTENTTYPE_CONSTRUCTED 0x20 + +/* universal tags (from ASN.1 spec.) */ +#define SNMP_ASN1_UNIVERSAL_END_OF_CONTENT 0 +#define SNMP_ASN1_UNIVERSAL_INTEGER 2 +#define SNMP_ASN1_UNIVERSAL_OCTET_STRING 4 +#define SNMP_ASN1_UNIVERSAL_NULL 5 +#define SNMP_ASN1_UNIVERSAL_OBJECT_ID 6 +#define SNMP_ASN1_UNIVERSAL_SEQUENCE_OF 16 + +/* application specific (SNMP) tags (from SNMPv2-SMI) */ +#define SNMP_ASN1_APPLICATION_IPADDR 0 /* [APPLICATION 0] IMPLICIT OCTET STRING (SIZE (4)) */ +#define SNMP_ASN1_APPLICATION_COUNTER 1 /* [APPLICATION 1] IMPLICIT INTEGER (0..4294967295) => u32_t */ +#define SNMP_ASN1_APPLICATION_GAUGE 2 /* [APPLICATION 2] IMPLICIT INTEGER (0..4294967295) => u32_t */ +#define SNMP_ASN1_APPLICATION_TIMETICKS 3 /* [APPLICATION 3] IMPLICIT INTEGER (0..4294967295) => u32_t */ +#define SNMP_ASN1_APPLICATION_OPAQUE 4 /* [APPLICATION 4] IMPLICIT OCTET STRING */ +#define SNMP_ASN1_APPLICATION_COUNTER64 6 /* [APPLICATION 6] IMPLICIT INTEGER (0..18446744073709551615) */ + +/* context specific (SNMP) tags (from RFC 1905) */ +#define SNMP_ASN1_CONTEXT_VARBIND_NO_SUCH_INSTANCE 1 + +/* full ASN1 type defines */ +#define SNMP_ASN1_TYPE_END_OF_CONTENT (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_UNIVERSAL_END_OF_CONTENT) +#define SNMP_ASN1_TYPE_INTEGER (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_UNIVERSAL_INTEGER) +#define SNMP_ASN1_TYPE_OCTET_STRING (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_UNIVERSAL_OCTET_STRING) +#define SNMP_ASN1_TYPE_NULL (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_UNIVERSAL_NULL) +#define SNMP_ASN1_TYPE_OBJECT_ID (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_UNIVERSAL_OBJECT_ID) +#define SNMP_ASN1_TYPE_SEQUENCE (SNMP_ASN1_CLASS_UNIVERSAL | SNMP_ASN1_CONTENTTYPE_CONSTRUCTED | SNMP_ASN1_UNIVERSAL_SEQUENCE_OF) +#define SNMP_ASN1_TYPE_IPADDR (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_IPADDR) +#define SNMP_ASN1_TYPE_IPADDRESS SNMP_ASN1_TYPE_IPADDR +#define SNMP_ASN1_TYPE_COUNTER (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_COUNTER) +#define SNMP_ASN1_TYPE_COUNTER32 SNMP_ASN1_TYPE_COUNTER +#define SNMP_ASN1_TYPE_GAUGE (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_GAUGE) +#define SNMP_ASN1_TYPE_GAUGE32 SNMP_ASN1_TYPE_GAUGE +#define SNMP_ASN1_TYPE_UNSIGNED32 SNMP_ASN1_TYPE_GAUGE +#define SNMP_ASN1_TYPE_TIMETICKS (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_TIMETICKS) +#define SNMP_ASN1_TYPE_OPAQUE (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_OPAQUE) +#define SNMP_ASN1_TYPE_COUNTER64 (SNMP_ASN1_CLASS_APPLICATION | SNMP_ASN1_CONTENTTYPE_PRIMITIVE | SNMP_ASN1_APPLICATION_COUNTER64) + +#define SNMP_VARBIND_EXCEPTION_OFFSET 0xF0 +#define SNMP_VARBIND_EXCEPTION_MASK 0x0F + +/** error codes predefined by SNMP prot. */ +typedef enum { + SNMP_ERR_NOERROR = 0, +/* +outdated v1 error codes. do not use anmore! +#define SNMP_ERR_NOSUCHNAME 2 use SNMP_ERR_NOSUCHINSTANCE instead +#define SNMP_ERR_BADVALUE 3 use SNMP_ERR_WRONGTYPE,SNMP_ERR_WRONGLENGTH,SNMP_ERR_WRONGENCODING or SNMP_ERR_WRONGVALUE instead +#define SNMP_ERR_READONLY 4 use SNMP_ERR_NOTWRITABLE instead +*/ + SNMP_ERR_GENERROR = 5, + SNMP_ERR_NOACCESS = 6, + SNMP_ERR_WRONGTYPE = 7, + SNMP_ERR_WRONGLENGTH = 8, + SNMP_ERR_WRONGENCODING = 9, + SNMP_ERR_WRONGVALUE = 10, + SNMP_ERR_NOCREATION = 11, + SNMP_ERR_INCONSISTENTVALUE = 12, + SNMP_ERR_RESOURCEUNAVAILABLE = 13, + SNMP_ERR_COMMITFAILED = 14, + SNMP_ERR_UNDOFAILED = 15, + SNMP_ERR_NOTWRITABLE = 17, + SNMP_ERR_INCONSISTENTNAME = 18, + + SNMP_ERR_NOSUCHINSTANCE = SNMP_VARBIND_EXCEPTION_OFFSET + SNMP_ASN1_CONTEXT_VARBIND_NO_SUCH_INSTANCE +} snmp_err_t; + +/** internal object identifier representation */ +struct snmp_obj_id +{ + u8_t len; + u32_t id[SNMP_MAX_OBJ_ID_LEN]; +}; + +struct snmp_obj_id_const_ref +{ + u8_t len; + const u32_t* id; +}; + +extern const struct snmp_obj_id_const_ref snmp_zero_dot_zero; /* administrative identifier from SNMPv2-SMI */ + +/** SNMP variant value, used as reference in struct snmp_node_instance and table implementation */ +union snmp_variant_value +{ + void* ptr; + const void* const_ptr; + u32_t u32; + s32_t s32; +}; + + +/** +SNMP MIB node types + tree node is the only node the stack can process in order to walk the tree, + all other nodes are assumed to be leaf nodes. + This cannot be an enum because users may want to define their own node types. +*/ +#define SNMP_NODE_TREE 0x00 +/* predefined leaf node types */ +#define SNMP_NODE_SCALAR 0x01 +#define SNMP_NODE_SCALAR_ARRAY 0x02 +#define SNMP_NODE_TABLE 0x03 +#define SNMP_NODE_THREADSYNC 0x04 + +/** node "base class" layout, the mandatory fields for a node */ +struct snmp_node +{ + /** one out of SNMP_NODE_TREE or any leaf node type (like SNMP_NODE_SCALAR) */ + u8_t node_type; + /** the number assigned to this node which used as part of the full OID */ + u32_t oid; +}; + +/** SNMP node instance access types */ +typedef enum { + SNMP_NODE_INSTANCE_ACCESS_READ = 1, + SNMP_NODE_INSTANCE_ACCESS_WRITE = 2, + SNMP_NODE_INSTANCE_READ_ONLY = SNMP_NODE_INSTANCE_ACCESS_READ, + SNMP_NODE_INSTANCE_READ_WRITE = (SNMP_NODE_INSTANCE_ACCESS_READ | SNMP_NODE_INSTANCE_ACCESS_WRITE), + SNMP_NODE_INSTANCE_WRITE_ONLY = SNMP_NODE_INSTANCE_ACCESS_WRITE, + SNMP_NODE_INSTANCE_NOT_ACCESSIBLE = 0 +} snmp_access_t; + +struct snmp_node_instance; + +typedef s16_t (*node_instance_get_value_method)(struct snmp_node_instance*, void*); +typedef snmp_err_t (*node_instance_set_test_method)(struct snmp_node_instance*, u16_t, void*); +typedef snmp_err_t (*node_instance_set_value_method)(struct snmp_node_instance*, u16_t, void*); +typedef void (*node_instance_release_method)(struct snmp_node_instance*); + +#define SNMP_GET_VALUE_RAW_DATA 0x8000 + +/** SNMP node instance */ +struct snmp_node_instance +{ + /** prefilled with the node, get_instance() is called on; may be changed by user to any value to pass an arbitrary node between calls to get_instance() and get_value/test_value/set_value */ + const struct snmp_node* node; + /** prefilled with the instance id requested; for get_instance() this is the exact oid requested; for get_next_instance() this is the relative starting point, stack expects relative oid of next node here */ + struct snmp_obj_id instance_oid; + + /** ASN type for this object (see snmp_asn1.h for definitions) */ + u8_t asn1_type; + /** one out of instance access types defined above (SNMP_NODE_INSTANCE_READ_ONLY,...) */ + snmp_access_t access; + + /** returns object value for the given object identifier. Return values <0 to indicate an error */ + node_instance_get_value_method get_value; + /** tests length and/or range BEFORE setting */ + node_instance_set_test_method set_test; + /** sets object value, only called when set_test() was successful */ + node_instance_set_value_method set_value; + /** called in any case when the instance is not required anymore by stack (useful for freeing memory allocated in get_instance/get_next_instance methods) */ + node_instance_release_method release_instance; + + /** reference to pass arbitrary value between calls to get_instance() and get_value/test_value/set_value */ + union snmp_variant_value reference; + /** see reference (if reference is a pointer, the length of underlying data may be stored here or anything else) */ + u32_t reference_len; +}; + + +/** SNMP tree node */ +struct snmp_tree_node +{ + /** inherited "base class" members */ + struct snmp_node node; + u16_t subnode_count; + const struct snmp_node* const *subnodes; +}; + +#define SNMP_CREATE_TREE_NODE(oid, subnodes) \ + {{ SNMP_NODE_TREE, (oid) }, \ + (u16_t)LWIP_ARRAYSIZE(subnodes), (subnodes) } + +#define SNMP_CREATE_EMPTY_TREE_NODE(oid) \ + {{ SNMP_NODE_TREE, (oid) }, \ + 0, NULL } + +/** SNMP leaf node */ +struct snmp_leaf_node +{ + /** inherited "base class" members */ + struct snmp_node node; + snmp_err_t (*get_instance)(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + snmp_err_t (*get_next_instance)(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +}; + +/** represents a single mib with its base oid and root node */ +struct snmp_mib +{ + const u32_t *base_oid; + u8_t base_oid_len; + const struct snmp_node *root_node; +}; + +#define SNMP_MIB_CREATE(oid_list, root_node) { (oid_list), (u8_t)LWIP_ARRAYSIZE(oid_list), root_node } + +/** OID range structure */ +struct snmp_oid_range +{ + u32_t min; + u32_t max; +}; + +/** checks if incoming OID length and values are in allowed ranges */ +u8_t snmp_oid_in_range(const u32_t *oid_in, u8_t oid_len, const struct snmp_oid_range *oid_ranges, u8_t oid_ranges_len); + +typedef enum { + SNMP_NEXT_OID_STATUS_SUCCESS, + SNMP_NEXT_OID_STATUS_NO_MATCH, + SNMP_NEXT_OID_STATUS_BUF_TO_SMALL +} snmp_next_oid_status_t; + +/** state for next_oid_init / next_oid_check functions */ +struct snmp_next_oid_state +{ + const u32_t* start_oid; + u8_t start_oid_len; + + u32_t* next_oid; + u8_t next_oid_len; + u8_t next_oid_max_len; + + snmp_next_oid_status_t status; + void* reference; +}; + +void snmp_next_oid_init(struct snmp_next_oid_state *state, + const u32_t *start_oid, u8_t start_oid_len, + u32_t *next_oid_buf, u8_t next_oid_max_len); +u8_t snmp_next_oid_precheck(struct snmp_next_oid_state *state, const u32_t *oid, const u8_t oid_len); +u8_t snmp_next_oid_check(struct snmp_next_oid_state *state, const u32_t *oid, const u8_t oid_len, void* reference); + +void snmp_oid_assign(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len); +void snmp_oid_combine(struct snmp_obj_id* target, const u32_t *oid1, u8_t oid1_len, const u32_t *oid2, u8_t oid2_len); +void snmp_oid_prefix(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len); +void snmp_oid_append(struct snmp_obj_id* target, const u32_t *oid, u8_t oid_len); +u8_t snmp_oid_equal(const u32_t *oid1, u8_t oid1_len, const u32_t *oid2, u8_t oid2_len); +s8_t snmp_oid_compare(const u32_t *oid1, u8_t oid1_len, const u32_t *oid2, u8_t oid2_len); + +#if LWIP_IPV4 +u8_t snmp_oid_to_ip4(const u32_t *oid, ip4_addr_t *ip); +void snmp_ip4_to_oid(const ip4_addr_t *ip, u32_t *oid); +#endif /* LWIP_IPV4 */ +#if LWIP_IPV6 +u8_t snmp_oid_to_ip6(const u32_t *oid, ip6_addr_t *ip); +void snmp_ip6_to_oid(const ip6_addr_t *ip, u32_t *oid); +#endif /* LWIP_IPV6 */ +#if LWIP_IPV4 || LWIP_IPV6 +u8_t snmp_ip_to_oid(const ip_addr_t *ip, u32_t *oid); +u8_t snmp_ip_port_to_oid(const ip_addr_t *ip, u16_t port, u32_t *oid); + +u8_t snmp_oid_to_ip(const u32_t *oid, u8_t oid_len, ip_addr_t *ip); +u8_t snmp_oid_to_ip_port(const u32_t *oid, u8_t oid_len, ip_addr_t *ip, u16_t *port); +#endif /* LWIP_IPV4 || LWIP_IPV6 */ + +struct netif; +u8_t netif_to_num(const struct netif *netif); + +snmp_err_t snmp_set_test_ok(struct snmp_node_instance* instance, u16_t value_len, void* value); /* generic function which can be used if test is always successful */ + +err_t snmp_decode_bits(const u8_t *buf, u32_t buf_len, u32_t *bit_value); +err_t snmp_decode_truthvalue(const s32_t *asn1_value, u8_t *bool_value); +u8_t snmp_encode_bits(u8_t *buf, u32_t buf_len, u32_t bit_value, u8_t bit_count); +u8_t snmp_encode_truthvalue(s32_t *asn1_value, u32_t bool_value); + +struct snmp_statistics +{ + u32_t inpkts; + u32_t outpkts; + u32_t inbadversions; + u32_t inbadcommunitynames; + u32_t inbadcommunityuses; + u32_t inasnparseerrs; + u32_t intoobigs; + u32_t innosuchnames; + u32_t inbadvalues; + u32_t inreadonlys; + u32_t ingenerrs; + u32_t intotalreqvars; + u32_t intotalsetvars; + u32_t ingetrequests; + u32_t ingetnexts; + u32_t insetrequests; + u32_t ingetresponses; + u32_t intraps; + u32_t outtoobigs; + u32_t outnosuchnames; + u32_t outbadvalues; + u32_t outgenerrs; + u32_t outgetrequests; + u32_t outgetnexts; + u32_t outsetrequests; + u32_t outgetresponses; + u32_t outtraps; +}; + +extern struct snmp_statistics snmp_stats; + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_SNMP */ + +#endif /* LWIP_HDR_APPS_SNMP_CORE_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_mib2.h b/tools/sdk/include/lwip/lwip/apps/snmp_mib2.h new file mode 100644 index 00000000..2f4a6893 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_mib2.h @@ -0,0 +1,78 @@ +/** + * @file + * SNMP MIB2 API + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Dirk Ziegelmeier + * + */ +#ifndef LWIP_HDR_APPS_SNMP_MIB2_H +#define LWIP_HDR_APPS_SNMP_MIB2_H + +#include "lwip/apps/snmp_opts.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ +#if SNMP_LWIP_MIB2 + +#include "lwip/apps/snmp_core.h" + +extern const struct snmp_mib mib2; + +#if SNMP_USE_NETCONN +#include "lwip/apps/snmp_threadsync.h" +void snmp_mib2_lwip_synchronizer(snmp_threadsync_called_fn fn, void* arg); +extern struct snmp_threadsync_instance snmp_mib2_lwip_locks; +#endif + +#ifndef SNMP_SYSSERVICES +#define SNMP_SYSSERVICES ((1 << 6) | (1 << 3) | ((IP_FORWARD) << 2)) +#endif + +void snmp_mib2_set_sysdescr(const u8_t* str, const u16_t* len); /* read-only be defintion */ +void snmp_mib2_set_syscontact(u8_t *ocstr, u16_t *ocstrlen, u16_t bufsize); +void snmp_mib2_set_syscontact_readonly(const u8_t *ocstr, const u16_t *ocstrlen); +void snmp_mib2_set_sysname(u8_t *ocstr, u16_t *ocstrlen, u16_t bufsize); +void snmp_mib2_set_sysname_readonly(const u8_t *ocstr, const u16_t *ocstrlen); +void snmp_mib2_set_syslocation(u8_t *ocstr, u16_t *ocstrlen, u16_t bufsize); +void snmp_mib2_set_syslocation_readonly(const u8_t *ocstr, const u16_t *ocstrlen); + +#endif /* SNMP_LWIP_MIB2 */ +#endif /* LWIP_SNMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_SNMP_MIB2_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_opts.h b/tools/sdk/include/lwip/lwip/apps/snmp_opts.h new file mode 100644 index 00000000..6c9ba7be --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_opts.h @@ -0,0 +1,293 @@ +/** + * @file + * SNMP server options list + */ + +/* + * Copyright (c) 2015 Dirk Ziegelmeier + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Dirk Ziegelmeier + * + */ +#ifndef LWIP_HDR_SNMP_OPTS_H +#define LWIP_HDR_SNMP_OPTS_H + +#include "lwip/opt.h" + +/** + * @defgroup snmp_opts Options + * @ingroup snmp + * @{ + */ + +/** + * LWIP_SNMP==1: This enables the lwIP SNMP agent. UDP must be available + * for SNMP transport. + * If you want to use your own SNMP agent, leave this disabled. + * To integrate MIB2 of an external agent, you need to enable + * LWIP_MIB2_CALLBACKS and MIB2_STATS. This will give you the callbacks + * and statistics counters you need to get MIB2 working. + */ +#if !defined LWIP_SNMP || defined __DOXYGEN__ +#define LWIP_SNMP 0 +#endif + +/** + * SNMP_USE_NETCONN: Use netconn API instead of raw API. + * Makes SNMP agent run in a worker thread, so blocking operations + * can be done in MIB calls. + */ +#if !defined SNMP_USE_NETCONN || defined __DOXYGEN__ +#define SNMP_USE_NETCONN 0 +#endif + +/** + * SNMP_USE_RAW: Use raw API. + * SNMP agent does not run in a worker thread, so blocking operations + * should not be done in MIB calls. + */ +#if !defined SNMP_USE_RAW || defined __DOXYGEN__ +#define SNMP_USE_RAW 1 +#endif + +#if SNMP_USE_NETCONN && SNMP_USE_RAW +#error SNMP stack can use only one of the APIs {raw, netconn} +#endif + +#if LWIP_SNMP && !SNMP_USE_NETCONN && !SNMP_USE_RAW +#error SNMP stack needs a receive API and UDP {raw, netconn} +#endif + +#if SNMP_USE_NETCONN +/** + * SNMP_STACK_SIZE: Stack size of SNMP netconn worker thread + */ +#if !defined SNMP_STACK_SIZE || defined __DOXYGEN__ +#define SNMP_STACK_SIZE DEFAULT_THREAD_STACKSIZE +#endif + +/** + * SNMP_THREAD_PRIO: SNMP netconn worker thread priority + */ +#if !defined SNMP_THREAD_PRIO || defined __DOXYGEN__ +#define SNMP_THREAD_PRIO DEFAULT_THREAD_PRIO +#endif +#endif /* SNMP_USE_NETCONN */ + +/** + * SNMP_TRAP_DESTINATIONS: Number of trap destinations. At least one trap + * destination is required + */ +#if !defined SNMP_TRAP_DESTINATIONS || defined __DOXYGEN__ +#define SNMP_TRAP_DESTINATIONS 1 +#endif + +/** + * Only allow SNMP write actions that are 'safe' (e.g. disabling netifs is not + * a safe action and disabled when SNMP_SAFE_REQUESTS = 1). + * Unsafe requests are disabled by default! + */ +#if !defined SNMP_SAFE_REQUESTS || defined __DOXYGEN__ +#define SNMP_SAFE_REQUESTS 1 +#endif + +/** + * The maximum length of strings used. + */ +#if !defined SNMP_MAX_OCTET_STRING_LEN || defined __DOXYGEN__ +#define SNMP_MAX_OCTET_STRING_LEN 127 +#endif + +/** + * The maximum number of Sub ID's inside an object identifier. + * Indirectly this also limits the maximum depth of SNMP tree. + */ +#if !defined SNMP_MAX_OBJ_ID_LEN || defined __DOXYGEN__ +#define SNMP_MAX_OBJ_ID_LEN 50 +#endif + +#if !defined SNMP_MAX_VALUE_SIZE || defined __DOXYGEN__ +/** + * The maximum size of a value. + */ +#define SNMP_MIN_VALUE_SIZE (2 * sizeof(u32_t*)) /* size required to store the basic types (8 bytes for counter64) */ +/** + * The minimum size of a value. + */ +#define SNMP_MAX_VALUE_SIZE LWIP_MAX(LWIP_MAX((SNMP_MAX_OCTET_STRING_LEN), sizeof(u32_t)*(SNMP_MAX_OBJ_ID_LEN)), SNMP_MIN_VALUE_SIZE) +#endif + +/** + * The snmp read-access community. Used for write-access and traps, too + * unless SNMP_COMMUNITY_WRITE or SNMP_COMMUNITY_TRAP are enabled, respectively. + */ +#if !defined SNMP_COMMUNITY || defined __DOXYGEN__ +#define SNMP_COMMUNITY "public" +#endif + +/** + * The snmp write-access community. + * Set this community to "" in order to disallow any write access. + */ +#if !defined SNMP_COMMUNITY_WRITE || defined __DOXYGEN__ +#define SNMP_COMMUNITY_WRITE "private" +#endif + +/** + * The snmp community used for sending traps. + */ +#if !defined SNMP_COMMUNITY_TRAP || defined __DOXYGEN__ +#define SNMP_COMMUNITY_TRAP "public" +#endif + +/** + * The maximum length of community string. + * If community names shall be adjusted at runtime via snmp_set_community() calls, + * enter here the possible maximum length (+1 for terminating null character). + */ +#if !defined SNMP_MAX_COMMUNITY_STR_LEN || defined __DOXYGEN__ +#define SNMP_MAX_COMMUNITY_STR_LEN LWIP_MAX(LWIP_MAX(sizeof(SNMP_COMMUNITY), sizeof(SNMP_COMMUNITY_WRITE)), sizeof(SNMP_COMMUNITY_TRAP)) +#endif + +/** + * The OID identifiying the device. This may be the enterprise OID itself or any OID located below it in tree. + */ +#if !defined SNMP_DEVICE_ENTERPRISE_OID || defined __DOXYGEN__ +#define SNMP_LWIP_ENTERPRISE_OID 26381 +/** + * IANA assigned enterprise ID for lwIP is 26381 + * @see http://www.iana.org/assignments/enterprise-numbers + * + * @note this enterprise ID is assigned to the lwIP project, + * all object identifiers living under this ID are assigned + * by the lwIP maintainers! + * @note don't change this define, use snmp_set_device_enterprise_oid() + * + * If you need to create your own private MIB you'll need + * to apply for your own enterprise ID with IANA: + * http://www.iana.org/numbers.html + */ +#define SNMP_DEVICE_ENTERPRISE_OID {1, 3, 6, 1, 4, 1, SNMP_LWIP_ENTERPRISE_OID} +/** + * Length of SNMP_DEVICE_ENTERPRISE_OID + */ +#define SNMP_DEVICE_ENTERPRISE_OID_LEN 7 +#endif + +/** + * SNMP_DEBUG: Enable debugging for SNMP messages. + */ +#if !defined SNMP_DEBUG || defined __DOXYGEN__ +#define SNMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * SNMP_MIB_DEBUG: Enable debugging for SNMP MIBs. + */ +#if !defined SNMP_MIB_DEBUG || defined __DOXYGEN__ +#define SNMP_MIB_DEBUG LWIP_DBG_OFF +#endif + +/** + * Indicates if the MIB2 implementation of LWIP SNMP stack is used. + */ +#if !defined SNMP_LWIP_MIB2 || defined __DOXYGEN__ +#define SNMP_LWIP_MIB2 LWIP_SNMP +#endif + +/** + * Value return for sysDesc field of MIB2. + */ +#if !defined SNMP_LWIP_MIB2_SYSDESC || defined __DOXYGEN__ +#define SNMP_LWIP_MIB2_SYSDESC "lwIP" +#endif + +/** + * Value return for sysName field of MIB2. + * To make sysName field settable, call snmp_mib2_set_sysname() to provide the necessary buffers. + */ +#if !defined SNMP_LWIP_MIB2_SYSNAME || defined __DOXYGEN__ +#define SNMP_LWIP_MIB2_SYSNAME "FQDN-unk" +#endif + +/** + * Value return for sysContact field of MIB2. + * To make sysContact field settable, call snmp_mib2_set_syscontact() to provide the necessary buffers. + */ +#if !defined SNMP_LWIP_MIB2_SYSCONTACT || defined __DOXYGEN__ +#define SNMP_LWIP_MIB2_SYSCONTACT "" +#endif + +/** + * Value return for sysLocation field of MIB2. + * To make sysLocation field settable, call snmp_mib2_set_syslocation() to provide the necessary buffers. + */ +#if !defined SNMP_LWIP_MIB2_SYSLOCATION || defined __DOXYGEN__ +#define SNMP_LWIP_MIB2_SYSLOCATION "" +#endif + +/** + * This value is used to limit the repetitions processed in GetBulk requests (value == 0 means no limitation). + * This may be useful to limit the load for a single request. + * According to SNMP RFC 1905 it is allowed to not return all requested variables from a GetBulk request if system load would be too high. + * so the effect is that the client will do more requests to gather all data. + * For the stack this could be useful in case that SNMP processing is done in TCP/IP thread. In this situation a request with many + * repetitions could block the thread for a longer time. Setting limit here will keep the stack more responsive. + */ +#if !defined SNMP_LWIP_GETBULK_MAX_REPETITIONS || defined __DOXYGEN__ +#define SNMP_LWIP_GETBULK_MAX_REPETITIONS 0 +#endif + +/** + * @} + */ + +/* + ------------------------------------ + ---------- SNMPv3 options ---------- + ------------------------------------ +*/ + +/** + * LWIP_SNMP_V3==1: This enables EXPERIMENTAL SNMPv3 support. LWIP_SNMP must + * also be enabled. + * THIS IS UNDER DEVELOPMENT AND SHOULD NOT BE ENABLED IN PRODUCTS. + */ +#ifndef LWIP_SNMP_V3 +#define LWIP_SNMP_V3 0 +#endif + +#ifndef LWIP_SNMP_V3_CRYPTO +#define LWIP_SNMP_V3_CRYPTO LWIP_SNMP_V3 +#endif + +#ifndef LWIP_SNMP_V3_MBEDTLS +#define LWIP_SNMP_V3_MBEDTLS LWIP_SNMP_V3 +#endif + +#endif /* LWIP_HDR_SNMP_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_scalar.h b/tools/sdk/include/lwip/lwip/apps/snmp_scalar.h new file mode 100644 index 00000000..40a060c6 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_scalar.h @@ -0,0 +1,113 @@ +/** + * @file + * SNMP server MIB API to implement scalar nodes + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +#ifndef LWIP_HDR_APPS_SNMP_SCALAR_H +#define LWIP_HDR_APPS_SNMP_SCALAR_H + +#include "lwip/apps/snmp_opts.h" +#include "lwip/apps/snmp_core.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +/** basic scalar node */ +struct snmp_scalar_node +{ + /** inherited "base class" members */ + struct snmp_leaf_node node; + u8_t asn1_type; + snmp_access_t access; + node_instance_get_value_method get_value; + node_instance_set_test_method set_test; + node_instance_set_value_method set_value; +}; + + +snmp_err_t snmp_scalar_get_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +snmp_err_t snmp_scalar_get_next_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + +#define SNMP_SCALAR_CREATE_NODE(oid, access, asn1_type, get_value_method, set_test_method, set_value_method) \ + {{{ SNMP_NODE_SCALAR, (oid) }, \ + snmp_scalar_get_instance, \ + snmp_scalar_get_next_instance }, \ + (asn1_type), (access), (get_value_method), (set_test_method), (set_value_method) } + +#define SNMP_SCALAR_CREATE_NODE_READONLY(oid, asn1_type, get_value_method) SNMP_SCALAR_CREATE_NODE(oid, SNMP_NODE_INSTANCE_READ_ONLY, asn1_type, get_value_method, NULL, NULL) + +/** scalar array node - a tree node which contains scalars only as children */ +struct snmp_scalar_array_node_def +{ + u32_t oid; + u8_t asn1_type; + snmp_access_t access; +}; + +typedef s16_t (*snmp_scalar_array_get_value_method)(const struct snmp_scalar_array_node_def*, void*); +typedef snmp_err_t (*snmp_scalar_array_set_test_method)(const struct snmp_scalar_array_node_def*, u16_t, void*); +typedef snmp_err_t (*snmp_scalar_array_set_value_method)(const struct snmp_scalar_array_node_def*, u16_t, void*); + +/** basic scalar array node */ +struct snmp_scalar_array_node +{ + /** inherited "base class" members */ + struct snmp_leaf_node node; + u16_t array_node_count; + const struct snmp_scalar_array_node_def* array_nodes; + snmp_scalar_array_get_value_method get_value; + snmp_scalar_array_set_test_method set_test; + snmp_scalar_array_set_value_method set_value; +}; + +snmp_err_t snmp_scalar_array_get_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +snmp_err_t snmp_scalar_array_get_next_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + +#define SNMP_SCALAR_CREATE_ARRAY_NODE(oid, array_nodes, get_value_method, set_test_method, set_value_method) \ + {{{ SNMP_NODE_SCALAR_ARRAY, (oid) }, \ + snmp_scalar_array_get_instance, \ + snmp_scalar_array_get_next_instance }, \ + (u16_t)LWIP_ARRAYSIZE(array_nodes), (array_nodes), (get_value_method), (set_test_method), (set_value_method) } + +#endif /* LWIP_SNMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_SNMP_SCALAR_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_table.h b/tools/sdk/include/lwip/lwip/apps/snmp_table.h new file mode 100644 index 00000000..4988b51c --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_table.h @@ -0,0 +1,134 @@ +/** + * @file + * SNMP server MIB API to implement table nodes + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Martin Hentschel + * + */ + +#ifndef LWIP_HDR_APPS_SNMP_TABLE_H +#define LWIP_HDR_APPS_SNMP_TABLE_H + +#include "lwip/apps/snmp_opts.h" +#include "lwip/apps/snmp_core.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +/** default (customizable) read/write table */ +struct snmp_table_col_def +{ + u32_t index; + u8_t asn1_type; + snmp_access_t access; +}; + +/** table node */ +struct snmp_table_node +{ + /** inherited "base class" members */ + struct snmp_leaf_node node; + u16_t column_count; + const struct snmp_table_col_def* columns; + snmp_err_t (*get_cell_instance)(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, struct snmp_node_instance* cell_instance); + snmp_err_t (*get_next_cell_instance)(const u32_t* column, struct snmp_obj_id* row_oid, struct snmp_node_instance* cell_instance); + /** returns object value for the given object identifier */ + node_instance_get_value_method get_value; + /** tests length and/or range BEFORE setting */ + node_instance_set_test_method set_test; + /** sets object value, only called when set_test() was successful */ + node_instance_set_value_method set_value; +}; + +snmp_err_t snmp_table_get_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +snmp_err_t snmp_table_get_next_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + +#define SNMP_TABLE_CREATE(oid, columns, get_cell_instance_method, get_next_cell_instance_method, get_value_method, set_test_method, set_value_method) \ + {{{ SNMP_NODE_TABLE, (oid) }, \ + snmp_table_get_instance, \ + snmp_table_get_next_instance }, \ + (u16_t)LWIP_ARRAYSIZE(columns), (columns), \ + (get_cell_instance_method), (get_next_cell_instance_method), \ + (get_value_method), (set_test_method), (set_value_method)} + +#define SNMP_TABLE_GET_COLUMN_FROM_OID(oid) ((oid)[1]) /* first array value is (fixed) row entry (fixed to 1) and 2nd value is column, follow3ed by instance */ + + +/** simple read-only table */ +typedef enum { + SNMP_VARIANT_VALUE_TYPE_U32, + SNMP_VARIANT_VALUE_TYPE_S32, + SNMP_VARIANT_VALUE_TYPE_PTR, + SNMP_VARIANT_VALUE_TYPE_CONST_PTR +} snmp_table_column_data_type_t; + +struct snmp_table_simple_col_def +{ + u32_t index; + u8_t asn1_type; + snmp_table_column_data_type_t data_type; /* depending of what union member is used to store the value*/ +}; + +/** simple read-only table node */ +struct snmp_table_simple_node +{ + /* inherited "base class" members */ + struct snmp_leaf_node node; + u16_t column_count; + const struct snmp_table_simple_col_def* columns; + snmp_err_t (*get_cell_value)(const u32_t* column, const u32_t* row_oid, u8_t row_oid_len, union snmp_variant_value* value, u32_t* value_len); + snmp_err_t (*get_next_cell_instance_and_value)(const u32_t* column, struct snmp_obj_id* row_oid, union snmp_variant_value* value, u32_t* value_len); +}; + +snmp_err_t snmp_table_simple_get_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +snmp_err_t snmp_table_simple_get_next_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + +#define SNMP_TABLE_CREATE_SIMPLE(oid, columns, get_cell_value_method, get_next_cell_instance_and_value_method) \ + {{{ SNMP_NODE_TABLE, (oid) }, \ + snmp_table_simple_get_instance, \ + snmp_table_simple_get_next_instance }, \ + (u16_t)LWIP_ARRAYSIZE(columns), (columns), (get_cell_value_method), (get_next_cell_instance_and_value_method) } + +s16_t snmp_table_extract_value_from_s32ref(struct snmp_node_instance* instance, void* value); +s16_t snmp_table_extract_value_from_u32ref(struct snmp_node_instance* instance, void* value); +s16_t snmp_table_extract_value_from_refconstptr(struct snmp_node_instance* instance, void* value); + +#endif /* LWIP_SNMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_SNMP_TABLE_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmp_threadsync.h b/tools/sdk/include/lwip/lwip/apps/snmp_threadsync.h new file mode 100644 index 00000000..a25dbf2d --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmp_threadsync.h @@ -0,0 +1,114 @@ +/** + * @file + * SNMP server MIB API to implement thread synchronization + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Dirk Ziegelmeier + * + */ + +#ifndef LWIP_HDR_APPS_SNMP_THREADSYNC_H +#define LWIP_HDR_APPS_SNMP_THREADSYNC_H + +#include "lwip/apps/snmp_opts.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/apps/snmp_core.h" +#include "lwip/sys.h" + +typedef void (*snmp_threadsync_called_fn)(void* arg); +typedef void (*snmp_threadsync_synchronizer_fn)(snmp_threadsync_called_fn fn, void* arg); + + +/** Thread sync runtime data. For internal usage only. */ +struct threadsync_data +{ + union { + snmp_err_t err; + s16_t s16; + } retval; + union { + const u32_t *root_oid; + void *value; + } arg1; + union { + u8_t root_oid_len; + u16_t len; + } arg2; + const struct snmp_threadsync_node *threadsync_node; + struct snmp_node_instance proxy_instance; +}; + +/** Thread sync instance. Needed EXCATLY once for every thread to be synced into. */ +struct snmp_threadsync_instance +{ + sys_sem_t sem; + sys_mutex_t sem_usage_mutex; + snmp_threadsync_synchronizer_fn sync_fn; + struct threadsync_data data; +}; + +/** SNMP thread sync proxy leaf node */ +struct snmp_threadsync_node +{ + /* inherited "base class" members */ + struct snmp_leaf_node node; + + const struct snmp_leaf_node *target; + struct snmp_threadsync_instance *instance; +}; + +snmp_err_t snmp_threadsync_get_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); +snmp_err_t snmp_threadsync_get_next_instance(const u32_t *root_oid, u8_t root_oid_len, struct snmp_node_instance* instance); + +/** Create thread sync proxy node */ +#define SNMP_CREATE_THREAD_SYNC_NODE(oid, target_leaf_node, threadsync_instance) \ + {{{ SNMP_NODE_THREADSYNC, (oid) }, \ + snmp_threadsync_get_instance, \ + snmp_threadsync_get_next_instance }, \ + (target_leaf_node), \ + (threadsync_instance) } + +/** Create thread sync instance data */ +void snmp_threadsync_init(struct snmp_threadsync_instance *instance, snmp_threadsync_synchronizer_fn sync_fn); + +#endif /* LWIP_SNMP */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_SNMP_THREADSYNC_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/snmpv3.h b/tools/sdk/include/lwip/lwip/apps/snmpv3.h new file mode 100644 index 00000000..c99fed4e --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/snmpv3.h @@ -0,0 +1,90 @@ +/** + * @file + * Additional SNMPv3 functionality RFC3414 and RFC3826. + */ + +/* + * Copyright (c) 2016 Elias Oenal. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Elias Oenal + */ + +#ifndef LWIP_HDR_APPS_SNMP_V3_H +#define LWIP_HDR_APPS_SNMP_V3_H + +#include "lwip/apps/snmp_opts.h" +#include "lwip/err.h" + +#if LWIP_SNMP && LWIP_SNMP_V3 + +#define SNMP_V3_AUTH_ALGO_INVAL 0 +#define SNMP_V3_AUTH_ALGO_MD5 1 +#define SNMP_V3_AUTH_ALGO_SHA 2 + +#define SNMP_V3_PRIV_ALGO_INVAL 0 +#define SNMP_V3_PRIV_ALGO_DES 1 +#define SNMP_V3_PRIV_ALGO_AES 2 + +#define SNMP_V3_PRIV_MODE_DECRYPT 0 +#define SNMP_V3_PRIV_MODE_ENCRYPT 1 + +/* + * The following callback functions must be implemented by the application. + * There is a dummy implementation in snmpv3_dummy.c. + */ + +void snmpv3_get_engine_id(const char **id, u8_t *len); +err_t snmpv3_set_engine_id(const char* id, u8_t len); + +u32_t snmpv3_get_engine_boots(void); +void snmpv3_set_engine_boots(u32_t boots); + +u32_t snmpv3_get_engine_time(void); +void snmpv3_reset_engine_time(void); + +err_t snmpv3_get_user(const char* username, u8_t *auth_algo, u8_t *auth_key, u8_t *priv_algo, u8_t *priv_key); + +/* The following functions are provided by the SNMPv3 agent */ + +void snmpv3_engine_id_changed(void); + +void snmpv3_password_to_key_md5( + const u8_t *password, /* IN */ + u8_t passwordlen, /* IN */ + const u8_t *engineID, /* IN - pointer to snmpEngineID */ + u8_t engineLength, /* IN - length of snmpEngineID */ + u8_t *key); /* OUT - pointer to caller 16-octet buffer */ + +void snmpv3_password_to_key_sha( + const u8_t *password, /* IN */ + u8_t passwordlen, /* IN */ + const u8_t *engineID, /* IN - pointer to snmpEngineID */ + u8_t engineLength, /* IN - length of snmpEngineID */ + u8_t *key); /* OUT - pointer to caller 20-octet buffer */ + +#endif + +#endif /* LWIP_HDR_APPS_SNMP_V3_H */ diff --git a/tools/sdk/include/lwip/apps/sntp/sntp.h b/tools/sdk/include/lwip/lwip/apps/sntp.h similarity index 95% rename from tools/sdk/include/lwip/apps/sntp/sntp.h rename to tools/sdk/include/lwip/lwip/apps/sntp.h index b0086936..40df9cc5 100644 --- a/tools/sdk/include/lwip/apps/sntp/sntp.h +++ b/tools/sdk/include/lwip/lwip/apps/sntp.h @@ -1,3 +1,8 @@ +/** + * @file + * SNTP client API + */ + /* * Copyright (c) 2007-2009 Frédéric Bernon, Simon Goldschmidt * All rights reserved. @@ -32,7 +37,7 @@ #ifndef LWIP_HDR_APPS_SNTP_H #define LWIP_HDR_APPS_SNTP_H -#include "apps/sntp/sntp_opts.h" +#include "lwip/apps/sntp_opts.h" #include "lwip/ip_addr.h" #ifdef __cplusplus @@ -51,7 +56,7 @@ void sntp_stop(void); u8_t sntp_enabled(void); void sntp_setserver(u8_t idx, const ip_addr_t *addr); -ip_addr_t sntp_getserver(u8_t idx); +const ip_addr_t* sntp_getserver(u8_t idx); #if SNTP_SERVER_DNS void sntp_setservername(u8_t idx, char *server); diff --git a/tools/sdk/include/lwip/apps/sntp/sntp_opts.h b/tools/sdk/include/lwip/lwip/apps/sntp_opts.h similarity index 80% rename from tools/sdk/include/lwip/apps/sntp/sntp_opts.h rename to tools/sdk/include/lwip/lwip/apps/sntp_opts.h index c8a39649..dee0f0a4 100644 --- a/tools/sdk/include/lwip/apps/sntp/sntp_opts.h +++ b/tools/sdk/include/lwip/lwip/apps/sntp_opts.h @@ -1,3 +1,8 @@ +/** + * @file + * SNTP client options list + */ + /* * Copyright (c) 2007-2009 Frédéric Bernon, Simon Goldschmidt * All rights reserved. @@ -34,48 +39,53 @@ #include "lwip/opt.h" +/** + * @defgroup sntp_opts Options + * @ingroup sntp + * @{ + */ + /** SNTP macro to change system time in seconds * Define SNTP_SET_SYSTEM_TIME_US(sec, us) to set the time in microseconds instead of this one * if you need the additional precision. */ -#ifndef SNTP_SET_SYSTEM_TIME +#if !defined SNTP_SET_SYSTEM_TIME || defined __DOXYGEN__ #define SNTP_SET_SYSTEM_TIME(sec) LWIP_UNUSED_ARG(sec) #endif /** The maximum number of SNTP servers that can be set */ -#ifndef SNTP_MAX_SERVERS +#if !defined SNTP_MAX_SERVERS || defined __DOXYGEN__ #define SNTP_MAX_SERVERS LWIP_DHCP_MAX_NTP_SERVERS #endif /** Set this to 1 to implement the callback function called by dhcp when * NTP servers are received. */ -#ifndef SNTP_GET_SERVERS_FROM_DHCP +#if !defined SNTP_GET_SERVERS_FROM_DHCP || defined __DOXYGEN__ #define SNTP_GET_SERVERS_FROM_DHCP LWIP_DHCP_GET_NTP_SRV #endif -/* Set this to 1 to support DNS names (or IP address strings) to set sntp servers */ -#ifndef SNTP_SERVER_DNS +/** Set this to 1 to support DNS names (or IP address strings) to set sntp servers + * One server address/name can be defined as default if SNTP_SERVER_DNS == 1: + * \#define SNTP_SERVER_ADDRESS "pool.ntp.org" + */ +#if !defined SNTP_SERVER_DNS || defined __DOXYGEN__ #define SNTP_SERVER_DNS 1 #endif -/** One server address/name can be defined as default if SNTP_SERVER_DNS == 1: - * #define SNTP_SERVER_ADDRESS "pool.ntp.org" - */ - /** * SNTP_DEBUG: Enable debugging for SNTP. */ -#ifndef SNTP_DEBUG +#if !defined SNTP_DEBUG || defined __DOXYGEN__ #define SNTP_DEBUG LWIP_DBG_OFF #endif /** SNTP server port */ -#ifndef SNTP_PORT +#if !defined SNTP_PORT || defined __DOXYGEN__ #define SNTP_PORT 123 #endif /** Set this to 1 to allow config of SNTP server(s) by DNS name */ -#ifndef SNTP_SERVER_DNS +#if !defined SNTP_SERVER_DNS || defined __DOXYGEN__ #define SNTP_SERVER_DNS 0 #endif @@ -93,7 +103,7 @@ * currently a cozy number like one second. This check avoids using a * server whose synchronization source has expired for a very long time. */ -#ifndef SNTP_CHECK_RESPONSE +#if !defined SNTP_CHECK_RESPONSE || defined __DOXYGEN__ #define SNTP_CHECK_RESPONSE 0 #endif @@ -103,14 +113,14 @@ * which must return the delay in milliseconds as u32_t. * Turned off by default. */ -#ifndef SNTP_STARTUP_DELAY +#if !defined SNTP_STARTUP_DELAY || defined __DOXYGEN__ #define SNTP_STARTUP_DELAY 0 #endif /** If you want the startup delay to be a function, define this * to a function (including the brackets) and define SNTP_STARTUP_DELAY to 1. */ -#ifndef SNTP_STARTUP_DELAY_FUNC +#if !defined SNTP_STARTUP_DELAY_FUNC || defined __DOXYGEN__ #define SNTP_STARTUP_DELAY_FUNC SNTP_STARTUP_DELAY #endif @@ -118,21 +128,21 @@ * Also used as retry timeout - this shouldn't be too low. * Default is 3 seconds. */ -#ifndef SNTP_RECV_TIMEOUT +#if !defined SNTP_RECV_TIMEOUT || defined __DOXYGEN__ #define SNTP_RECV_TIMEOUT 3000 #endif /** SNTP update delay - in milliseconds * Default is 1 hour. Must not be beolw 15 seconds by specification (i.e. 15000) */ -#ifndef SNTP_UPDATE_DELAY +#if !defined SNTP_UPDATE_DELAY || defined __DOXYGEN__ #define SNTP_UPDATE_DELAY 3600000 #endif /** SNTP macro to get system time, used with SNTP_CHECK_RESPONSE >= 2 * to send in request and compare in response. */ -#ifndef SNTP_GET_SYSTEM_TIME +#if !defined SNTP_GET_SYSTEM_TIME || defined __DOXYGEN__ #define SNTP_GET_SYSTEM_TIME(sec, us) do { (sec) = 0; (us) = 0; } while(0) #endif @@ -140,20 +150,24 @@ * received is invalid. * This is doubled with each retry until SNTP_RETRY_TIMEOUT_MAX is reached. */ -#ifndef SNTP_RETRY_TIMEOUT +#if !defined SNTP_RETRY_TIMEOUT || defined __DOXYGEN__ #define SNTP_RETRY_TIMEOUT SNTP_RECV_TIMEOUT #endif /** Maximum retry timeout (in milliseconds). */ -#ifndef SNTP_RETRY_TIMEOUT_MAX +#if !defined SNTP_RETRY_TIMEOUT_MAX || defined __DOXYGEN__ #define SNTP_RETRY_TIMEOUT_MAX (SNTP_RETRY_TIMEOUT * 10) #endif /** Increase retry timeout with every retry sent * Default is on to conform to RFC. */ -#ifndef SNTP_RETRY_TIMEOUT_EXP +#if !defined SNTP_RETRY_TIMEOUT_EXP || defined __DOXYGEN__ #define SNTP_RETRY_TIMEOUT_EXP 1 #endif +/** + * @} + */ + #endif /* LWIP_HDR_APPS_SNTP_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/tftp_opts.h b/tools/sdk/include/lwip/lwip/apps/tftp_opts.h new file mode 100644 index 00000000..6968a803 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/tftp_opts.h @@ -0,0 +1,105 @@ +/****************************************************************//** + * + * @file tftp_opts.h + * + * @author Logan Gunthorpe + * + * @brief Trivial File Transfer Protocol (RFC 1350) implementation options + * + * Copyright (c) Deltatee Enterprises Ltd. 2013 + * All rights reserved. + * + ********************************************************************/ + +/* + * Redistribution and use in source and binary forms, with or without + * modification,are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Author: Logan Gunthorpe + * + */ + +#ifndef LWIP_HDR_APPS_TFTP_OPTS_H +#define LWIP_HDR_APPS_TFTP_OPTS_H + +#include "lwip/opt.h" + +/** + * @defgroup tftp_opts Options + * @ingroup tftp + * @{ + */ + +/** + * Enable TFTP debug messages + */ +#if !defined TFTP_DEBUG || defined __DOXYGEN__ +#define TFTP_DEBUG LWIP_DBG_ON +#endif + +/** + * TFTP server port + */ +#if !defined TFTP_PORT || defined __DOXYGEN__ +#define TFTP_PORT 69 +#endif + +/** + * TFTP timeout + */ +#if !defined TFTP_TIMEOUT_MSECS || defined __DOXYGEN__ +#define TFTP_TIMEOUT_MSECS 10000 +#endif + +/** + * Max. number of retries when a file is read from server + */ +#if !defined TFTP_MAX_RETRIES || defined __DOXYGEN__ +#define TFTP_MAX_RETRIES 5 +#endif + +/** + * TFTP timer cyclic interval + */ +#if !defined TFTP_TIMER_MSECS || defined __DOXYGEN__ +#define TFTP_TIMER_MSECS 50 +#endif + +/** + * Max. length of TFTP filename + */ +#if !defined TFTP_MAX_FILENAME_LEN || defined __DOXYGEN__ +#define TFTP_MAX_FILENAME_LEN 20 +#endif + +/** + * Max. length of TFTP mode + */ +#if !defined TFTP_MAX_MODE_LEN || defined __DOXYGEN__ +#define TFTP_MAX_MODE_LEN 7 +#endif + +/** + * @} + */ + +#endif /* LWIP_HDR_APPS_TFTP_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/apps/tftp_server.h b/tools/sdk/include/lwip/lwip/apps/tftp_server.h new file mode 100644 index 00000000..3fbe701e --- /dev/null +++ b/tools/sdk/include/lwip/lwip/apps/tftp_server.h @@ -0,0 +1,94 @@ +/****************************************************************//** + * + * @file tftp_server.h + * + * @author Logan Gunthorpe + * + * @brief Trivial File Transfer Protocol (RFC 1350) + * + * Copyright (c) Deltatee Enterprises Ltd. 2013 + * All rights reserved. + * + ********************************************************************/ + +/* + * Redistribution and use in source and binary forms, with or without + * modification,are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Author: Logan Gunthorpe + * + */ + +#ifndef LWIP_HDR_APPS_TFTP_SERVER_H +#define LWIP_HDR_APPS_TFTP_SERVER_H + +#include "lwip/apps/tftp_opts.h" +#include "lwip/err.h" +#include "lwip/pbuf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @ingroup tftp + * TFTP context containing callback functions for TFTP transfers + */ +struct tftp_context { + /** + * Open file for read/write. + * @param fname Filename + * @param mode Mode string from TFTP RFC 1350 (netascii, octet, mail) + * @param write Flag indicating read (0) or write (!= 0) access + * @returns File handle supplied to other functions + */ + void* (*open)(const char* fname, const char* mode, u8_t write); + /** + * Close file handle + * @param handle File handle returned by open() + */ + void (*close)(void* handle); + /** + * Read from file + * @param handle File handle returned by open() + * @param buf Target buffer to copy read data to + * @param bytes Number of bytes to copy to buf + * @returns >= 0: Success; < 0: Error + */ + int (*read)(void* handle, void* buf, int bytes); + /** + * Write to file + * @param handle File handle returned by open() + * @param pbuf PBUF adjusted such that payload pointer points + * to the beginning of write data. In other words, + * TFTP headers are stripped off. + * @returns >= 0: Success; < 0: Error + */ + int (*write)(void* handle, struct pbuf* p); +}; + +err_t tftp_init(const struct tftp_context* ctx); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_APPS_TFTP_SERVER_H */ diff --git a/tools/sdk/include/lwip/lwip/arch.h b/tools/sdk/include/lwip/lwip/arch.h index 7b99c260..31d92ca3 100644 --- a/tools/sdk/include/lwip/lwip/arch.h +++ b/tools/sdk/include/lwip/lwip/arch.h @@ -1,3 +1,8 @@ +/** + * @file + * Support for different processor and compiler architectures + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -42,189 +47,269 @@ #include "arch/cc.h" -/** Temporary: define format string for size_t if not defined in cc.h */ -#ifndef SZT_F -#define SZT_F U32_F -#endif /* SZT_F */ -/** Temporary upgrade helper: define format string for u8_t as hex if not - defined in cc.h */ +/** + * @defgroup compiler_abstraction Compiler/platform abstraction + * @ingroup sys_layer + * All defines related to this section must not be placed in lwipopts.h, + * but in arch/cc.h! + * These options cannot be \#defined in lwipopts.h since they are not options + * of lwIP itself, but options of the lwIP port to your system. + * @{ + */ + +/** Define the byte order of the system. + * Needed for conversion of network data to host byte order. + * Allowed values: LITTLE_ENDIAN and BIG_ENDIAN + */ +#ifndef BYTE_ORDER +#define BYTE_ORDER LITTLE_ENDIAN +#endif + +/** Define random number generator function of your system */ +#ifdef __DOXYGEN__ +#define LWIP_RAND() ((u32_t)rand()) +#endif + +/** Platform specific diagnostic output.\n + * Note the default implementation pulls in printf, which may + * in turn pull in a lot of standard libary code. In resource-constrained + * systems, this should be defined to something less resource-consuming. + */ +#ifndef LWIP_PLATFORM_DIAG +#define LWIP_PLATFORM_DIAG(x) do {printf x;} while(0) +#include +#include +#endif + +/** Platform specific assertion handling.\n + * Note the default implementation pulls in printf, fflush and abort, which may + * in turn pull in a lot of standard libary code. In resource-constrained + * systems, this should be defined to something less resource-consuming. + */ +#ifndef LWIP_PLATFORM_ASSERT +#define LWIP_PLATFORM_ASSERT(x) do {printf("Assertion \"%s\" failed at line %d in %s\n", \ + x, __LINE__, __FILE__); fflush(NULL); abort();} while(0) +#include +#include +#endif + +/** Define this to 1 in arch/cc.h of your port if you do not want to + * include stddef.h header to get size_t. You need to typedef size_t + * by yourself in this case. + */ +#ifndef LWIP_NO_STDDEF_H +#define LWIP_NO_STDDEF_H 0 +#endif + +#if !LWIP_NO_STDDEF_H +#include /* for size_t */ +#endif + +/** Define this to 1 in arch/cc.h of your port if your compiler does not provide + * the stdint.h header. You need to typedef the generic types listed in + * lwip/arch.h yourself in this case (u8_t, u16_t...). + */ +#ifndef LWIP_NO_STDINT_H +#define LWIP_NO_STDINT_H 0 +#endif + +/* Define generic types used in lwIP */ +#if !LWIP_NO_STDINT_H +#include +typedef uint8_t u8_t; +typedef int8_t s8_t; +typedef uint16_t u16_t; +typedef int16_t s16_t; +typedef uint32_t u32_t; +typedef int32_t s32_t; +#endif + +/** Define this to 1 in arch/cc.h of your port if your compiler does not provide + * the inttypes.h header. You need to define the format strings listed in + * lwip/arch.h yourself in this case (X8_F, U16_F...). + */ +#ifndef LWIP_NO_INTTYPES_H +#define LWIP_NO_INTTYPES_H 0 +#endif + +/* Define (sn)printf formatters for these lwIP types */ +#if !LWIP_NO_INTTYPES_H +#include #ifndef X8_F -#define X8_F "02x" -#endif /* X8_F */ +#define X8_F "02" PRIx8 +#endif +#ifndef U16_F +#define U16_F PRIu16 +#endif +#ifndef S16_F +#define S16_F PRId16 +#endif +#ifndef X16_F +#define X16_F PRIx16 +#endif +#ifndef U32_F +#define U32_F PRIu32 +#endif +#ifndef S32_F +#define S32_F PRId32 +#endif +#ifndef X32_F +#define X32_F PRIx32 +#endif +#ifndef SZT_F +#define SZT_F PRIuPTR +#endif +#endif + +/** Define this to 1 in arch/cc.h of your port if your compiler does not provide + * the limits.h header. You need to define the type limits yourself in this case + * (e.g. INT_MAX). + */ +#ifndef LWIP_NO_LIMITS_H +#define LWIP_NO_LIMITS_H 0 +#endif + +/* Include limits.h? */ +#if !LWIP_NO_LIMITS_H +#include +#endif + +/** C++ const_cast(val) equivalent to remove constness from a value (GCC -Wcast-qual) */ +#ifndef LWIP_CONST_CAST +#define LWIP_CONST_CAST(target_type, val) ((target_type)((ptrdiff_t)val)) +#endif + +/** Get rid of alignment cast warnings (GCC -Wcast-align) */ +#ifndef LWIP_ALIGNMENT_CAST +#define LWIP_ALIGNMENT_CAST(target_type, val) LWIP_CONST_CAST(target_type, val) +#endif + +/** Get rid of warnings related to pointer-to-numeric and vice-versa casts, + * e.g. "conversion from 'u8_t' to 'void *' of greater size" + */ +#ifndef LWIP_PTR_NUMERIC_CAST +#define LWIP_PTR_NUMERIC_CAST(target_type, val) LWIP_CONST_CAST(target_type, val) +#endif + +/** Allocates a memory buffer of specified size that is of sufficient size to align + * its start address using LWIP_MEM_ALIGN. + * You can declare your own version here e.g. to enforce alignment without adding + * trailing padding bytes (see LWIP_MEM_ALIGN_BUFFER) or your own section placement + * requirements.\n + * e.g. if you use gcc and need 32 bit alignment:\n + * \#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) u8_t variable_name[size] \_\_attribute\_\_((aligned(4)))\n + * or more portable:\n + * \#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) u32_t variable_name[(size + sizeof(u32_t) - 1) / sizeof(u32_t)] + */ +#ifndef LWIP_DECLARE_MEMORY_ALIGNED +#define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size) u8_t variable_name[LWIP_MEM_ALIGN_BUFFER(size)] +#endif + +/** Calculate memory size for an aligned buffer - returns the next highest + * multiple of MEM_ALIGNMENT (e.g. LWIP_MEM_ALIGN_SIZE(3) and + * LWIP_MEM_ALIGN_SIZE(4) will both yield 4 for MEM_ALIGNMENT == 4). + */ +#ifndef LWIP_MEM_ALIGN_SIZE +#define LWIP_MEM_ALIGN_SIZE(size) (((size) + MEM_ALIGNMENT - 1U) & ~(MEM_ALIGNMENT-1U)) +#endif + +/** Calculate safe memory size for an aligned buffer when using an unaligned + * type as storage. This includes a safety-margin on (MEM_ALIGNMENT - 1) at the + * start (e.g. if buffer is u8_t[] and actual data will be u32_t*) + */ +#ifndef LWIP_MEM_ALIGN_BUFFER +#define LWIP_MEM_ALIGN_BUFFER(size) (((size) + MEM_ALIGNMENT - 1U)) +#endif + +/** Align a memory pointer to the alignment defined by MEM_ALIGNMENT + * so that ADDR % MEM_ALIGNMENT == 0 + */ +#ifndef LWIP_MEM_ALIGN +#define LWIP_MEM_ALIGN(addr) ((void *)(((mem_ptr_t)(addr) + MEM_ALIGNMENT - 1) & ~(mem_ptr_t)(MEM_ALIGNMENT-1))) +#endif #ifdef __cplusplus extern "C" { #endif +/** Packed structs support. + * Placed BEFORE declaration of a packed struct.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_BEGIN #define PACK_STRUCT_BEGIN #endif /* PACK_STRUCT_BEGIN */ +/** Packed structs support. + * Placed AFTER declaration of a packed struct.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_END #define PACK_STRUCT_END #endif /* PACK_STRUCT_END */ +/** Packed structs support. + * Placed between end of declaration of a packed struct and trailing semicolon.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_STRUCT +#if defined(__GNUC__) || defined(__clang__) +#define PACK_STRUCT_STRUCT __attribute__((packed)) +#else #define PACK_STRUCT_STRUCT +#endif #endif /* PACK_STRUCT_STRUCT */ +/** Packed structs support. + * Wraps u32_t and u16_t members.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_FIELD #define PACK_STRUCT_FIELD(x) x #endif /* PACK_STRUCT_FIELD */ -/* Used for struct fields of u8_t, - * where some compilers warn that packing is not necessary */ +/** Packed structs support. + * Wraps u8_t members, where some compilers warn that packing is not necessary.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_FLD_8 #define PACK_STRUCT_FLD_8(x) PACK_STRUCT_FIELD(x) #endif /* PACK_STRUCT_FLD_8 */ -/* Used for struct fields of that are packed structs themself, - * where some compilers warn that packing is not necessary */ +/** Packed structs support. + * Wraps members that are packed structs themselves, where some compilers warn that packing is not necessary.\n + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ #ifndef PACK_STRUCT_FLD_S #define PACK_STRUCT_FLD_S(x) PACK_STRUCT_FIELD(x) #endif /* PACK_STRUCT_FLD_S */ +/** Packed structs support using \#include files before and after struct to be packed.\n + * The file included BEFORE the struct is "arch/bpstruct.h".\n + * The file included AFTER the struct is "arch/epstruct.h".\n + * This can be used to implement struct packing on MS Visual C compilers, see + * the Win32 port in the lwIP contrib repository for reference. + * For examples of packed struct declarations, see include/lwip/prot/ subfolder.\n + * A port to GCC/clang is included in lwIP, if you use these compilers there is nothing to do here. + */ +#ifdef __DOXYGEN__ +#define PACK_STRUCT_USE_INCLUDES +#endif +/** Eliminates compiler warning about unused arguments (GCC -Wextra -Wunused). */ #ifndef LWIP_UNUSED_ARG #define LWIP_UNUSED_ARG(x) (void)x #endif /* LWIP_UNUSED_ARG */ - -#ifdef LWIP_PROVIDE_ERRNO - -#define EPERM 1 /* Operation not permitted */ -#define ENOENT 2 /* No such file or directory */ -#define ESRCH 3 /* No such process */ -#define EINTR 4 /* Interrupted system call */ -#define EIO 5 /* I/O error */ -#define ENXIO 6 /* No such device or address */ -#define E2BIG 7 /* Arg list too long */ -#define ENOEXEC 8 /* Exec format error */ -#define EBADF 9 /* Bad file number */ -#define ECHILD 10 /* No child processes */ -#define EAGAIN 11 /* Try again */ -#define ENOMEM 12 /* Out of memory */ -#define EACCES 13 /* Permission denied */ -#define EFAULT 14 /* Bad address */ -#define ENOTBLK 15 /* Block device required */ -#define EBUSY 16 /* Device or resource busy */ -#define EEXIST 17 /* File exists */ -#define EXDEV 18 /* Cross-device link */ -#define ENODEV 19 /* No such device */ -#define ENOTDIR 20 /* Not a directory */ -#define EISDIR 21 /* Is a directory */ -#define EINVAL 22 /* Invalid argument */ -#define ENFILE 23 /* File table overflow */ -#define EMFILE 24 /* Too many open files */ -#define ENOTTY 25 /* Not a typewriter */ -#define ETXTBSY 26 /* Text file busy */ -#define EFBIG 27 /* File too large */ -#define ENOSPC 28 /* No space left on device */ -#define ESPIPE 29 /* Illegal seek */ -#define EROFS 30 /* Read-only file system */ -#define EMLINK 31 /* Too many links */ -#define EPIPE 32 /* Broken pipe */ -#define EDOM 33 /* Math argument out of domain of func */ -#define ERANGE 34 /* Math result not representable */ -#define EDEADLK 35 /* Resource deadlock would occur */ -#define ENAMETOOLONG 36 /* File name too long */ -#define ENOLCK 37 /* No record locks available */ -#define ENOSYS 38 /* Function not implemented */ -#define ENOTEMPTY 39 /* Directory not empty */ -#define ELOOP 40 /* Too many symbolic links encountered */ -#define EWOULDBLOCK EAGAIN /* Operation would block */ -#define ENOMSG 42 /* No message of desired type */ -#define EIDRM 43 /* Identifier removed */ -#define ECHRNG 44 /* Channel number out of range */ -#define EL2NSYNC 45 /* Level 2 not synchronized */ -#define EL3HLT 46 /* Level 3 halted */ -#define EL3RST 47 /* Level 3 reset */ -#define ELNRNG 48 /* Link number out of range */ -#define EUNATCH 49 /* Protocol driver not attached */ -#define ENOCSI 50 /* No CSI structure available */ -#define EL2HLT 51 /* Level 2 halted */ -#define EBADE 52 /* Invalid exchange */ -#define EBADR 53 /* Invalid request descriptor */ -#define EXFULL 54 /* Exchange full */ -#define ENOANO 55 /* No anode */ -#define EBADRQC 56 /* Invalid request code */ -#define EBADSLT 57 /* Invalid slot */ - -#define EDEADLOCK EDEADLK - -#define EBFONT 59 /* Bad font file format */ -#define ENOSTR 60 /* Device not a stream */ -#define ENODATA 61 /* No data available */ -#define ETIME 62 /* Timer expired */ -#define ENOSR 63 /* Out of streams resources */ -#define ENONET 64 /* Machine is not on the network */ -#define ENOPKG 65 /* Package not installed */ -#define EREMOTE 66 /* Object is remote */ -#define ENOLINK 67 /* Link has been severed */ -#define EADV 68 /* Advertise error */ -#define ESRMNT 69 /* Srmount error */ -#define ECOMM 70 /* Communication error on send */ -#define EPROTO 71 /* Protocol error */ -#define EMULTIHOP 72 /* Multihop attempted */ -#define EDOTDOT 73 /* RFS specific error */ -#define EBADMSG 74 /* Not a data message */ -#define EOVERFLOW 75 /* Value too large for defined data type */ -#define ENOTUNIQ 76 /* Name not unique on network */ -#define EBADFD 77 /* File descriptor in bad state */ -#define EREMCHG 78 /* Remote address changed */ -#define ELIBACC 79 /* Can not access a needed shared library */ -#define ELIBBAD 80 /* Accessing a corrupted shared library */ -#define ELIBSCN 81 /* .lib section in a.out corrupted */ -#define ELIBMAX 82 /* Attempting to link in too many shared libraries */ -#define ELIBEXEC 83 /* Cannot exec a shared library directly */ -#define EILSEQ 84 /* Illegal byte sequence */ -#define ERESTART 85 /* Interrupted system call should be restarted */ -#define ESTRPIPE 86 /* Streams pipe error */ -#define EUSERS 87 /* Too many users */ -#define ENOTSOCK 88 /* Socket operation on non-socket */ -#define EDESTADDRREQ 89 /* Destination address required */ -#define EMSGSIZE 90 /* Message too long */ -#define EPROTOTYPE 91 /* Protocol wrong type for socket */ -#define ENOPROTOOPT 92 /* Protocol not available */ -#define EPROTONOSUPPORT 93 /* Protocol not supported */ -#define ESOCKTNOSUPPORT 94 /* Socket type not supported */ -#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ -#define EPFNOSUPPORT 96 /* Protocol family not supported */ -#define EAFNOSUPPORT 97 /* Address family not supported by protocol */ -#define EADDRINUSE 98 /* Address already in use */ -#define EADDRNOTAVAIL 99 /* Cannot assign requested address */ -#define ENETDOWN 100 /* Network is down */ -#define ENETUNREACH 101 /* Network is unreachable */ -#define ENETRESET 102 /* Network dropped connection because of reset */ -#define ECONNABORTED 103 /* Software caused connection abort */ -#define ECONNRESET 104 /* Connection reset by peer */ -#define ENOBUFS 105 /* No buffer space available */ -#define EISCONN 106 /* Transport endpoint is already connected */ -#define ENOTCONN 107 /* Transport endpoint is not connected */ -#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ -#define ETOOMANYREFS 109 /* Too many references: cannot splice */ -#define ETIMEDOUT 110 /* Connection timed out */ -#define ECONNREFUSED 111 /* Connection refused */ -#define EHOSTDOWN 112 /* Host is down */ -#define EHOSTUNREACH 113 /* No route to host */ -#define EALREADY 114 /* Operation already in progress */ -#define EINPROGRESS 115 /* Operation now in progress */ -#define ESTALE 116 /* Stale NFS file handle */ -#define EUCLEAN 117 /* Structure needs cleaning */ -#define ENOTNAM 118 /* Not a XENIX named type file */ -#define ENAVAIL 119 /* No XENIX semaphores available */ -#define EISNAM 120 /* Is a named type file */ -#define EREMOTEIO 121 /* Remote I/O error */ -#define EDQUOT 122 /* Quota exceeded */ - -#define ENOMEDIUM 123 /* No medium found */ -#define EMEDIUMTYPE 124 /* Wrong medium type */ - -#ifndef errno -extern int errno; -#endif - -#endif /* LWIP_PROVIDE_ERRNO */ +/** + * @} + */ #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/autoip.h b/tools/sdk/include/lwip/lwip/autoip.h index 16eac510..82a69b46 100644 --- a/tools/sdk/include/lwip/lwip/autoip.h +++ b/tools/sdk/include/lwip/lwip/autoip.h @@ -36,9 +36,6 @@ * This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform * with RFC 3927. * - * - * Please coordinate changes and requests with Dominik Spies - * */ #ifndef LWIP_HDR_AUTOIP_H @@ -50,16 +47,17 @@ #include "lwip/netif.h" /* #include "lwip/udp.h" */ -#include "netif/etharp.h" +#include "lwip/etharp.h" #ifdef __cplusplus extern "C" { #endif -/* AutoIP Timing */ +/** AutoIP Timing */ #define AUTOIP_TMR_INTERVAL 100 #define AUTOIP_TICKS_PER_SECOND (1000 / AUTOIP_TMR_INTERVAL) +#if ESP_LWIP /* RFC 3927 Constants */ #define PROBE_WAIT 1 /* second (initial random delay) */ #define PROBE_MIN 1 /* second (minimum delay till repeated probe) */ @@ -77,43 +75,40 @@ extern "C" { #define AUTOIP_STATE_PROBING 1 #define AUTOIP_STATE_ANNOUNCING 2 #define AUTOIP_STATE_BOUND 3 +#endif +/** AutoIP state information per netif */ struct autoip { - ip4_addr_t llipaddr; /* the currently selected, probed, announced or used LL IP-Address */ - u8_t state; /* current AutoIP state machine state */ - u8_t sent_num; /* sent number of probes or announces, dependent on state */ - u16_t ttw; /* ticks to wait, tick is AUTOIP_TMR_INTERVAL long */ - u8_t lastconflict; /* ticks until a conflict can be solved by defending */ - u8_t tried_llipaddr; /* total number of probed/used Link Local IP-Addresses */ + /** the currently selected, probed, announced or used LL IP-Address */ + ip4_addr_t llipaddr; + /** current AutoIP state machine state */ + u8_t state; + /** sent number of probes or announces, dependent on state */ + u8_t sent_num; + /** ticks to wait, tick is AUTOIP_TMR_INTERVAL long */ + u16_t ttw; + /** ticks until a conflict can be solved by defending */ + u8_t lastconflict; + /** total number of probed/used Link Local IP-Addresses */ + u8_t tried_llipaddr; }; -#define autoip_init() /* Compatibility define, no init needed. */ - -/** Set a struct autoip allocated by the application to work with */ void autoip_set_struct(struct netif *netif, struct autoip *autoip); - /** Remove a struct autoip previously set to the netif using autoip_set_struct() */ #define autoip_remove_struct(netif) do { (netif)->autoip = NULL; } while (0) - -/** Start AutoIP client */ err_t autoip_start(struct netif *netif); - -/** Stop AutoIP client */ err_t autoip_stop(struct netif *netif); - -/** Handles every incoming ARP Packet, called by etharp_arp_input */ void autoip_arp_reply(struct netif *netif, struct etharp_hdr *hdr); - -/** Has to be called in loop every AUTOIP_TMR_INTERVAL milliseconds */ void autoip_tmr(void); - -/** Handle a possible change in the network configuration */ void autoip_network_changed(struct netif *netif); +u8_t autoip_supplied_address(const struct netif *netif); -/** check if AutoIP supplied netif->ip_addr */ -u8_t autoip_supplied_address(struct netif *netif); +/* for lwIP internal use by ip4.c */ +u8_t autoip_accept_packet(struct netif *netif, const ip4_addr_t *addr); + +#define netif_autoip_data(netif) ((struct autoip*)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_AUTOIP)) #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/debug.h b/tools/sdk/include/lwip/lwip/debug.h index 973a633d..a142f1cf 100644 --- a/tools/sdk/include/lwip/lwip/debug.h +++ b/tools/sdk/include/lwip/lwip/debug.h @@ -1,3 +1,8 @@ +/** + * @file + * Debug messages infrastructure + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -35,24 +40,45 @@ #include "lwip/arch.h" #include "lwip/opt.h" -/** lower two bits indicate debug level - * - 0 all - * - 1 warning - * - 2 serious - * - 3 severe +/** + * @defgroup debugging_levels LWIP_DBG_MIN_LEVEL and LWIP_DBG_TYPES_ON values + * @ingroup lwip_opts_debugmsg + * @{ */ -#define LWIP_DBG_LEVEL_ALL 0x00 -#define LWIP_DBG_LEVEL_OFF LWIP_DBG_LEVEL_ALL /* compatibility define only */ -#define LWIP_DBG_LEVEL_WARNING 0x01 /* bad checksums, dropped packets, ... */ -#define LWIP_DBG_LEVEL_SERIOUS 0x02 /* memory allocation failures, ... */ -#define LWIP_DBG_LEVEL_SEVERE 0x03 -#define LWIP_DBG_MASK_LEVEL 0x03 +/** @name Debug level (LWIP_DBG_MIN_LEVEL) + * @{ + */ +/** Debug level: ALL messages*/ +#define LWIP_DBG_LEVEL_ALL 0x00 +/** Debug level: Warnings. bad checksums, dropped packets, ... */ +#define LWIP_DBG_LEVEL_WARNING 0x01 +/** Debug level: Serious. memory allocation failures, ... */ +#define LWIP_DBG_LEVEL_SERIOUS 0x02 +/** Debug level: Severe */ +#define LWIP_DBG_LEVEL_SEVERE 0x03 +/** + * @} + */ + +#define LWIP_DBG_MASK_LEVEL 0x03 +/* compatibility define only */ +#define LWIP_DBG_LEVEL_OFF LWIP_DBG_LEVEL_ALL + +/** @name Enable/disable debug messages completely (LWIP_DBG_TYPES_ON) + * @{ + */ /** flag for LWIP_DEBUGF to enable that debug message */ #define LWIP_DBG_ON 0x80U /** flag for LWIP_DEBUGF to disable that debug message */ #define LWIP_DBG_OFF 0x00U +/** + * @} + */ +/** @name Debug message types (LWIP_DBG_TYPES_ON) + * @{ + */ /** flag for LWIP_DEBUGF indicating a tracing message (to follow program flow) */ #define LWIP_DBG_TRACE 0x40U /** flag for LWIP_DEBUGF indicating a state debug message (to follow module states) */ @@ -61,14 +87,34 @@ #define LWIP_DBG_FRESH 0x10U /** flag for LWIP_DEBUGF to halt after printing this debug message */ #define LWIP_DBG_HALT 0x08U +/** + * @} + */ /** - * LWIP_NOASSERT: Disable LWIP_ASSERT checks. - * -- To disable assertions define LWIP_NOASSERT in arch/cc.h. + * @} */ + +/** + * @defgroup lwip_assertions Assertion handling + * @ingroup lwip_opts_debug + * @{ + */ +/** + * LWIP_NOASSERT: Disable LWIP_ASSERT checks: + * To disable assertions define LWIP_NOASSERT in arch/cc.h. + */ +#ifdef __DOXYGEN__ +#define LWIP_NOASSERT +#undef LWIP_NOASSERT +#endif +/** + * @} + */ + #ifndef LWIP_NOASSERT -#define LWIP_ASSERT(message, assertion) do { if(!(assertion)) \ - LWIP_PLATFORM_ASSERT(message); } while(0) +#define LWIP_ASSERT(message, assertion) do { if (!(assertion)) { \ + LWIP_PLATFORM_ASSERT(message); }} while(0) #ifndef LWIP_PLATFORM_ASSERT #error "If you want to use LWIP_ASSERT, LWIP_PLATFORM_ASSERT(message) needs to be defined in your arch/cc.h" #endif @@ -76,7 +122,6 @@ #define LWIP_ASSERT(message, assertion) #endif /* LWIP_NOASSERT */ -/** if "expression" isn't true, then print "message" and execute "handler" expression */ #ifndef LWIP_ERROR #ifndef LWIP_NOASSERT #define LWIP_PLATFORM_ERROR(message) LWIP_PLATFORM_ASSERT(message) @@ -86,17 +131,23 @@ #define LWIP_PLATFORM_ERROR(message) #endif +/* if "expression" isn't true, then print "message" and execute "handler" expression */ #define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ LWIP_PLATFORM_ERROR(message); handler;}} while(0) #endif /* LWIP_ERROR */ +/** Enable debug message printing, but only if debug message type is enabled + * AND is of correct type AND is at least LWIP_DBG_LEVEL. + */ +#ifdef __DOXYGEN__ +#define LWIP_DEBUG +#undef LWIP_DEBUG +#endif + #ifdef LWIP_DEBUG #ifndef LWIP_PLATFORM_DIAG #error "If you want to use LWIP_DEBUG, LWIP_PLATFORM_DIAG(message) needs to be defined in your arch/cc.h" #endif -/** print debug message only if debug message type is enabled... - * AND is of correct type AND is at least LWIP_DBG_LEVEL - */ #define LWIP_DEBUGF(debug, message) do { \ if ( \ ((debug) & LWIP_DBG_ON) && \ @@ -114,4 +165,3 @@ #endif /* LWIP_DEBUG */ #endif /* LWIP_HDR_DEBUG_H */ - diff --git a/tools/sdk/include/lwip/lwip/def.h b/tools/sdk/include/lwip/lwip/def.h index 49571363..82a9d896 100644 --- a/tools/sdk/include/lwip/lwip/def.h +++ b/tools/sdk/include/lwip/lwip/def.h @@ -1,3 +1,8 @@ +/** + * @file + * various utility macros + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -52,43 +57,20 @@ extern "C" { /* Get the number of entries in an array ('x' must NOT be a pointer!) */ #define LWIP_ARRAYSIZE(x) (sizeof(x)/sizeof((x)[0])) +/** Create u32_t value from bytes */ +#define LWIP_MAKEU32(a,b,c,d) (((u32_t)((a) & 0xff) << 24) | \ + ((u32_t)((b) & 0xff) << 16) | \ + ((u32_t)((c) & 0xff) << 8) | \ + (u32_t)((d) & 0xff)) + #ifndef NULL +#ifdef __cplusplus +#define NULL 0 +#else #define NULL ((void *)0) #endif - -/* Endianess-optimized shifting of two u8_t to create one u16_t */ -#if BYTE_ORDER == LITTLE_ENDIAN -#define LWIP_MAKE_U16(a, b) ((a << 8) | b) -#else -#define LWIP_MAKE_U16(a, b) ((b << 8) | a) #endif -#ifndef LWIP_PLATFORM_BYTESWAP -#define LWIP_PLATFORM_BYTESWAP 0 -#endif - -#ifndef LWIP_PREFIX_BYTEORDER_FUNCS -/* workaround for naming collisions on some platforms */ - -#ifdef htons -#undef htons -#endif /* htons */ -#ifdef htonl -#undef htonl -#endif /* htonl */ -#ifdef ntohs -#undef ntohs -#endif /* ntohs */ -#ifdef ntohl -#undef ntohl -#endif /* ntohl */ - -#define htons(x) lwip_htons(x) -#define ntohs(x) lwip_ntohs(x) -#define htonl(x) lwip_htonl(x) -#define ntohl(x) lwip_ntohl(x) -#endif /* LWIP_PREFIX_BYTEORDER_FUNCS */ - #if BYTE_ORDER == BIG_ENDIAN #define lwip_htons(x) (x) #define lwip_ntohs(x) (x) @@ -99,34 +81,61 @@ extern "C" { #define PP_HTONL(x) (x) #define PP_NTOHL(x) (x) #else /* BYTE_ORDER != BIG_ENDIAN */ -#if LWIP_PLATFORM_BYTESWAP -#define lwip_htons(x) LWIP_PLATFORM_HTONS(x) -#define lwip_ntohs(x) LWIP_PLATFORM_HTONS(x) -#define lwip_htonl(x) LWIP_PLATFORM_HTONL(x) -#define lwip_ntohl(x) LWIP_PLATFORM_HTONL(x) -#else /* LWIP_PLATFORM_BYTESWAP */ +#ifndef lwip_htons u16_t lwip_htons(u16_t x); -u16_t lwip_ntohs(u16_t x); +#endif +#define lwip_ntohs(x) lwip_htons(x) + +#ifndef lwip_htonl u32_t lwip_htonl(u32_t x); -u32_t lwip_ntohl(u32_t x); -#endif /* LWIP_PLATFORM_BYTESWAP */ +#endif +#define lwip_ntohl(x) lwip_htonl(x) /* These macros should be calculated by the preprocessor and are used with compile-time constants only (so that there is no little-endian overhead at runtime). */ -#define PP_HTONS(x) ((((x) & 0xff) << 8) | (((x) & 0xff00) >> 8)) +#define PP_HTONS(x) ((((x) & 0x00ffUL) << 8) | (((x) & 0xff00UL) >> 8)) #define PP_NTOHS(x) PP_HTONS(x) -#define PP_HTONL(x) ((((x) & 0xff) << 24) | \ - (((x) & 0xff00) << 8) | \ - (((x) & 0xff0000UL) >> 8) | \ +#define PP_HTONL(x) ((((x) & 0x000000ffUL) << 24) | \ + (((x) & 0x0000ff00UL) << 8) | \ + (((x) & 0x00ff0000UL) >> 8) | \ (((x) & 0xff000000UL) >> 24)) #define PP_NTOHL(x) PP_HTONL(x) - #endif /* BYTE_ORDER == BIG_ENDIAN */ +/* Provide usual function names as macros for users, but this can be turned off */ +#ifndef LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS +#define htons(x) lwip_htons(x) +#define ntohs(x) lwip_ntohs(x) +#define htonl(x) lwip_htonl(x) +#define ntohl(x) lwip_ntohl(x) +#endif + +/* Functions that are not available as standard implementations. + * In cc.h, you can #define these to implementations available on + * your platform to save some code bytes if you use these functions + * in your application, too. + */ + +#ifndef lwip_itoa +/* This can be #defined to itoa() or snprintf(result, bufsize, "%d", number) depending on your platform */ +void lwip_itoa(char* result, size_t bufsize, int number); +#endif +#ifndef lwip_strnicmp +/* This can be #defined to strnicmp() or strncasecmp() depending on your platform */ +int lwip_strnicmp(const char* str1, const char* str2, size_t len); +#endif +#ifndef lwip_stricmp +/* This can be #defined to stricmp() or strcasecmp() depending on your platform */ +int lwip_stricmp(const char* str1, const char* str2); +#endif +#ifndef lwip_strnstr +/* This can be #defined to strnstr() depending on your platform */ +char* lwip_strnstr(const char* buffer, const char* token, size_t n); +#endif + #ifdef __cplusplus } #endif #endif /* LWIP_HDR_DEF_H */ - diff --git a/tools/sdk/include/lwip/lwip/dhcp.h b/tools/sdk/include/lwip/lwip/dhcp.h index f282c8ab..23a36bb0 100644 --- a/tools/sdk/include/lwip/lwip/dhcp.h +++ b/tools/sdk/include/lwip/lwip/dhcp.h @@ -1,3 +1,8 @@ +/** + * @file + * DHCP client API + */ + /* * Copyright (c) 2001-2004 Leon Woestenberg * Copyright (c) 2001-2004 Axon Digital Design B.V., The Netherlands. @@ -45,15 +50,23 @@ extern "C" { #endif /** period (in seconds) of the application calling dhcp_coarse_tmr() */ +#if ESP_DHCP #define DHCP_COARSE_TIMER_SECS 1 +#else +#define DHCP_COARSE_TIMER_SECS 60 +#endif /** period (in milliseconds) of the application calling dhcp_coarse_tmr() */ #define DHCP_COARSE_TIMER_MSECS (DHCP_COARSE_TIMER_SECS * 1000UL) /** period (in milliseconds) of the application calling dhcp_fine_tmr() */ -#define DHCP_FINE_TIMER_MSECS 500 +#define DHCP_FINE_TIMER_MSECS 500 -#define DHCP_CHADDR_LEN 16U -#define DHCP_SNAME_LEN 64U -#define DHCP_FILE_LEN 128U +#define DHCP_BOOT_FILE_LEN 128U + +/* AutoIP cooperation flags (struct dhcp.autoip_coop_state) */ +typedef enum { + DHCP_AUTOIP_COOP_STATE_OFF = 0, + DHCP_AUTOIP_COOP_STATE_ON = 1 +} dhcp_autoip_coop_state_enum_t; struct dhcp { @@ -76,12 +89,12 @@ struct dhcp struct dhcp_msg *msg_out; /* outgoing msg */ u16_t options_out_len; /* outgoing msg options length */ u16_t request_timeout; /* #ticks with period DHCP_FINE_TIMER_SECS for request timeout */ - u32_t t1_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for renewal time */ - u32_t t2_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for rebind time */ - u32_t t1_renew_time; /* #ticks with period DHCP_COARSE_TIMER_SECS until next renew try */ - u32_t t2_rebind_time; /* #ticks with period DHCP_COARSE_TIMER_SECS until next rebind try */ - u32_t lease_used; /* #ticks with period DHCP_COARSE_TIMER_SECS since last received DHCP ack */ - u32_t t0_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for lease time */ + u16_t t1_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for renewal time */ + u16_t t2_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for rebind time */ + u16_t t1_renew_time; /* #ticks with period DHCP_COARSE_TIMER_SECS until next renew try */ + u16_t t2_rebind_time; /* #ticks with period DHCP_COARSE_TIMER_SECS until next rebind try */ + u16_t lease_used; /* #ticks with period DHCP_COARSE_TIMER_SECS since last received DHCP ack */ + u16_t t0_timeout; /* #ticks with period DHCP_COARSE_TIMER_SECS for lease time */ ip_addr_t server_ip_addr; /* dhcp server address that offered this lease (ip_addr_t because passed to UDP) */ ip4_addr_t offered_ip_addr; ip4_addr_t offered_sn_mask; @@ -91,12 +104,12 @@ struct dhcp u32_t offered_t1_renew; /* recommended renew time (usually 50% of lease period) */ u32_t offered_t2_rebind; /* recommended rebind time (usually 87.5 of lease period) */ #if LWIP_DHCP_BOOTP_FILE - ip_addr_t offered_si_addr; - char boot_file_name[DHCP_FILE_LEN]; + ip4_addr_t offered_si_addr; + char boot_file_name[DHCP_BOOT_FILE_LEN]; #endif /* LWIP_DHCP_BOOTPFILE */ /* Espressif add start. */ -#ifdef ESP_LWIP +#ifdef ESP_DHCP void (*cb)(struct netif*); /* callback for dhcp, add a parameter to show dhcp status if needed */ #else void (*cb)(void); /* callback for dhcp, add a parameter to show dhcp status if needed */ @@ -104,200 +117,36 @@ struct dhcp /* Espressif add end. */ }; -/* MUST be compiled with "pack structs" or equivalent! */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -/** minimum set of fields of any DHCP message */ -struct dhcp_msg -{ - PACK_STRUCT_FLD_8(u8_t op); - PACK_STRUCT_FLD_8(u8_t htype); - PACK_STRUCT_FLD_8(u8_t hlen); - PACK_STRUCT_FLD_8(u8_t hops); - PACK_STRUCT_FIELD(u32_t xid); - PACK_STRUCT_FIELD(u16_t secs); - PACK_STRUCT_FIELD(u16_t flags); - PACK_STRUCT_FLD_S(ip4_addr_p_t ciaddr); - PACK_STRUCT_FLD_S(ip4_addr_p_t yiaddr); - PACK_STRUCT_FLD_S(ip4_addr_p_t siaddr); - PACK_STRUCT_FLD_S(ip4_addr_p_t giaddr); - PACK_STRUCT_FLD_8(u8_t chaddr[DHCP_CHADDR_LEN]); - PACK_STRUCT_FLD_8(u8_t sname[DHCP_SNAME_LEN]); - PACK_STRUCT_FLD_8(u8_t file[DHCP_FILE_LEN]); - PACK_STRUCT_FIELD(u32_t cookie); -#define DHCP_MIN_OPTIONS_LEN 68U -/** make sure user does not configure this too small */ -#if ((defined(DHCP_OPTIONS_LEN)) && (DHCP_OPTIONS_LEN < DHCP_MIN_OPTIONS_LEN)) -# undef DHCP_OPTIONS_LEN -#endif -/** allow this to be configured in lwipopts.h, but not too small */ -#if (!defined(DHCP_OPTIONS_LEN)) -/** set this to be sufficient for your options in outgoing DHCP msgs */ -# define DHCP_OPTIONS_LEN DHCP_MIN_OPTIONS_LEN -#endif - PACK_STRUCT_FLD_8(u8_t options[DHCP_OPTIONS_LEN]); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif void dhcp_set_struct(struct netif *netif, struct dhcp *dhcp); /** Remove a struct dhcp previously set to the netif using dhcp_set_struct() */ -#define dhcp_remove_struct(netif) do { (netif)->dhcp = NULL; } while(0) +#define dhcp_remove_struct(netif) netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, NULL) void dhcp_cleanup(struct netif *netif); +err_t dhcp_start(struct netif *netif); +err_t dhcp_renew(struct netif *netif); +err_t dhcp_release(struct netif *netif); +void dhcp_stop(struct netif *netif); +void dhcp_inform(struct netif *netif); +void dhcp_network_changed(struct netif *netif); + /* Espressif add start. */ /** set callback for DHCP */ -#ifdef ESP_LWIP +#ifdef ESP_DHCP void dhcp_set_cb(struct netif *netif, void (*cb)(struct netif*)); #else void dhcp_set_cb(struct netif *netif, void (*cb)(void)); #endif /* Espressif add end. */ -/** start DHCP configuration */ -err_t dhcp_start(struct netif *netif); -/** enforce early lease renewal (not needed normally)*/ -err_t dhcp_renew(struct netif *netif); -/** release the DHCP lease, usually called before dhcp_stop()*/ -err_t dhcp_release(struct netif *netif); -/** stop DHCP configuration */ -void dhcp_stop(struct netif *netif); -/** inform server of our manual IP address */ -void dhcp_inform(struct netif *netif); -/** Handle a possible change in the network configuration */ -void dhcp_network_changed(struct netif *netif); -/** if enabled, check whether the offered IP address is not in use, using ARP */ #if DHCP_DOES_ARP_CHECK void dhcp_arp_reply(struct netif *netif, const ip4_addr_t *addr); #endif - -/** check if DHCP supplied netif->ip_addr */ -u8_t dhcp_supplied_address(struct netif *netif); - -/** to be called every minute */ +u8_t dhcp_supplied_address(const struct netif *netif); +/* to be called every minute */ void dhcp_coarse_tmr(void); -/** to be called every half second */ +/* to be called every half second */ void dhcp_fine_tmr(void); -/** DHCP message item offsets and length */ -#define DHCP_OP_OFS 0 -#define DHCP_HTYPE_OFS 1 -#define DHCP_HLEN_OFS 2 -#define DHCP_HOPS_OFS 3 -#define DHCP_XID_OFS 4 -#define DHCP_SECS_OFS 8 -#define DHCP_FLAGS_OFS 10 -#define DHCP_CIADDR_OFS 12 -#define DHCP_YIADDR_OFS 16 -#define DHCP_SIADDR_OFS 20 -#define DHCP_GIADDR_OFS 24 -#define DHCP_CHADDR_OFS 28 -#define DHCP_SNAME_OFS 44 -#define DHCP_FILE_OFS 108 -#define DHCP_MSG_LEN 236 - -#define DHCP_COOKIE_OFS DHCP_MSG_LEN -#define DHCP_OPTIONS_OFS (DHCP_MSG_LEN + 4) - -#define DHCP_CLIENT_PORT 68 -#define DHCP_SERVER_PORT 67 - -/** DHCP client states */ -#define DHCP_STATE_OFF 0 -#define DHCP_STATE_REQUESTING 1 -#define DHCP_STATE_INIT 2 -#define DHCP_STATE_REBOOTING 3 -#define DHCP_STATE_REBINDING 4 -#define DHCP_STATE_RENEWING 5 -#define DHCP_STATE_SELECTING 6 -#define DHCP_STATE_INFORMING 7 -#define DHCP_STATE_CHECKING 8 -/** not yet implemented #define DHCP_STATE_PERMANENT 9 */ -#define DHCP_STATE_BOUND 10 -/** not yet implemented #define DHCP_STATE_RELEASING 11 */ -#define DHCP_STATE_BACKING_OFF 12 - -/** AUTOIP cooperation flags */ -#define DHCP_AUTOIP_COOP_STATE_OFF 0 -#define DHCP_AUTOIP_COOP_STATE_ON 1 - -#define DHCP_BOOTREQUEST 1 -#define DHCP_BOOTREPLY 2 - -/** DHCP message types */ -#define DHCP_DISCOVER 1 -#define DHCP_OFFER 2 -#define DHCP_REQUEST 3 -#define DHCP_DECLINE 4 -#define DHCP_ACK 5 -#define DHCP_NAK 6 -#define DHCP_RELEASE 7 -#define DHCP_INFORM 8 - -/** DHCP hardware type, currently only ethernet is supported */ -#define DHCP_HTYPE_ETH 1 - -#define DHCP_MAGIC_COOKIE 0x63825363UL - -/* This is a list of options for BOOTP and DHCP, see RFC 2132 for descriptions */ - -/** BootP options */ -#define DHCP_OPTION_PAD 0 -#define DHCP_OPTION_SUBNET_MASK 1 /* RFC 2132 3.3 */ -#define DHCP_OPTION_ROUTER 3 -#define DHCP_OPTION_DNS_SERVER 6 -#define DHCP_OPTION_HOSTNAME 12 -#define DHCP_OPTION_IP_TTL 23 -#define DHCP_OPTION_MTU 26 -#define DHCP_OPTION_BROADCAST 28 -#define DHCP_OPTION_TCP_TTL 37 -#define DHCP_OPTION_NTP 42 -#define DHCP_OPTION_END 255 - -#if ESP_LWIP -/**add options for support more router by liuHan**/ -#define DHCP_OPTION_DOMAIN_NAME 15 -#define DHCP_OPTION_PRD 31 -#define DHCP_OPTION_STATIC_ROUTER 33 -#define DHCP_OPTION_VSN 43 -#define DHCP_OPTION_NB_TINS 44 -#define DHCP_OPTION_NB_TINT 46 -#define DHCP_OPTION_NB_TIS 47 -#define DHCP_OPTION_CLASSLESS_STATIC_ROUTER 121 -#endif - - - -/** DHCP options */ -#define DHCP_OPTION_REQUESTED_IP 50 /* RFC 2132 9.1, requested IP address */ -#define DHCP_OPTION_LEASE_TIME 51 /* RFC 2132 9.2, time in seconds, in 4 bytes */ -#define DHCP_OPTION_OVERLOAD 52 /* RFC2132 9.3, use file and/or sname field for options */ - -#define DHCP_OPTION_MESSAGE_TYPE 53 /* RFC 2132 9.6, important for DHCP */ -#define DHCP_OPTION_MESSAGE_TYPE_LEN 1 - -#define DHCP_OPTION_SERVER_ID 54 /* RFC 2132 9.7, server IP address */ -#define DHCP_OPTION_PARAMETER_REQUEST_LIST 55 /* RFC 2132 9.8, requested option types */ - -#define DHCP_OPTION_MAX_MSG_SIZE 57 /* RFC 2132 9.10, message size accepted >= 576 */ -#define DHCP_OPTION_MAX_MSG_SIZE_LEN 2 - -#define DHCP_OPTION_T1 58 /* T1 renewal time */ -#define DHCP_OPTION_T2 59 /* T2 rebinding time */ -#define DHCP_OPTION_US 60 -#define DHCP_OPTION_CLIENT_ID 61 -#define DHCP_OPTION_TFTP_SERVERNAME 66 -#define DHCP_OPTION_BOOTFILE 67 - -/** possible combinations of overloading the file and sname fields with options */ -#define DHCP_OVERLOAD_NONE 0 -#define DHCP_OVERLOAD_FILE 1 -#define DHCP_OVERLOAD_SNAME 2 -#define DHCP_OVERLOAD_SNAME_FILE 3 - #if LWIP_DHCP_GET_NTP_SRV /** This function must exist, in other to add offered NTP servers to * the NTP (or SNTP) engine. @@ -305,6 +154,8 @@ void dhcp_fine_tmr(void); extern void dhcp_set_ntp_servers(u8_t num_ntp_servers, const ip4_addr_t* ntp_server_addrs); #endif /* LWIP_DHCP_GET_NTP_SRV */ +#define netif_dhcp_data(netif) ((struct dhcp*)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP)) + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/dhcp6.h b/tools/sdk/include/lwip/lwip/dhcp6.h index 345bcf00..455336d3 100644 --- a/tools/sdk/include/lwip/lwip/dhcp6.h +++ b/tools/sdk/include/lwip/lwip/dhcp6.h @@ -50,7 +50,7 @@ struct dhcp6 { - /*TODO: implement DHCP6*/ + /*@todo: implement DHCP6*/ }; #endif /* LWIP_IPV6_DHCP6 */ diff --git a/tools/sdk/include/lwip/lwip/dns.h b/tools/sdk/include/lwip/lwip/dns.h index e0802803..38ea6367 100644 --- a/tools/sdk/include/lwip/lwip/dns.h +++ b/tools/sdk/include/lwip/lwip/dns.h @@ -1,3 +1,8 @@ +/** + * @file + * DNS API + */ + /** * lwip DNS resolver header file. @@ -36,14 +41,10 @@ #include "lwip/opt.h" -#if ESP_DNS -#include "lwip/err.h" -#endif - - #if LWIP_DNS #include "lwip/ip_addr.h" +#include "lwip/err.h" #ifdef __cplusplus extern "C" { @@ -61,7 +62,7 @@ extern "C" { #ifndef LWIP_DNS_ADDRTYPE_DEFAULT #define LWIP_DNS_ADDRTYPE_DEFAULT LWIP_DNS_ADDRTYPE_IPV4_IPV6 #endif -#elif defined(LWIP_IPV4) +#elif LWIP_IPV4 #define LWIP_DNS_ADDRTYPE_DEFAULT LWIP_DNS_ADDRTYPE_IPV4 #else #define LWIP_DNS_ADDRTYPE_DEFAULT LWIP_DNS_ADDRTYPE_IPV6 @@ -76,6 +77,7 @@ struct local_hostlist_entry { ip_addr_t addr; struct local_hostlist_entry *next; }; +#define DNS_LOCAL_HOSTLIST_ELEM(name, addr_init) {name, addr_init, NULL} #if DNS_LOCAL_HOSTLIST_IS_DYNAMIC #ifndef DNS_LOCAL_HOSTLIST_MAX_NAMELEN #define DNS_LOCAL_HOSTLIST_MAX_NAMELEN DNS_MAX_NAME_LENGTH @@ -84,6 +86,13 @@ struct local_hostlist_entry { #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ #endif /* DNS_LOCAL_HOSTLIST */ +#if LWIP_IPV4 +extern const ip_addr_t dns_mquery_v4group; +#endif /* LWIP_IPV4 */ +#if LWIP_IPV6 +extern const ip_addr_t dns_mquery_v6group; +#endif /* LWIP_IPV6 */ + /** Callback which is invoked when a hostname is found. * A function of this type must be implemented by the application using the DNS resolver. * @param name pointer to the name that was looked up. @@ -93,22 +102,32 @@ struct local_hostlist_entry { */ typedef void (*dns_found_callback)(const char *name, const ip_addr_t *ipaddr, void *callback_arg); -void dns_init(void); -void dns_tmr(void); -void dns_setserver(u8_t numdns, const ip_addr_t *dnsserver); -void dns_clear_servers(bool keep_fallback); -ip_addr_t dns_getserver(u8_t numdns); -err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, - dns_found_callback found, void *callback_arg); -err_t dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, - dns_found_callback found, void *callback_arg, - u8_t dns_addrtype); +void dns_init(void); +void dns_tmr(void); +void dns_setserver(u8_t numdns, const ip_addr_t *dnsserver); +#if ESP_DNS +ip_addr_t dns_getserver(u8_t numdns); +#else +const ip_addr_t* dns_getserver(u8_t numdns); +#endif +err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, + dns_found_callback found, void *callback_arg); +err_t dns_gethostbyname_addrtype(const char *hostname, ip_addr_t *addr, + dns_found_callback found, void *callback_arg, + u8_t dns_addrtype); +#if ESP_DNS +void dns_clear_servers(bool keep_fallback); +#endif -#if DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC +#if DNS_LOCAL_HOSTLIST +size_t dns_local_iterate(dns_found_callback iterator_fn, void *iterator_arg); +err_t dns_local_lookup(const char *hostname, ip_addr_t *addr, u8_t dns_addrtype); +#if DNS_LOCAL_HOSTLIST_IS_DYNAMIC int dns_local_removehost(const char *hostname, const ip_addr_t *addr); err_t dns_local_addhost(const char *hostname, const ip_addr_t *addr); -#endif /* DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ +#endif /* DNS_LOCAL_HOSTLIST */ #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/err.h b/tools/sdk/include/lwip/lwip/err.h index a766ee18..84e528d1 100644 --- a/tools/sdk/include/lwip/lwip/err.h +++ b/tools/sdk/include/lwip/lwip/err.h @@ -1,3 +1,7 @@ +/** + * @file + * lwIP Error codes + */ /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -39,6 +43,12 @@ extern "C" { #endif +/** + * @defgroup infrastructure_errors Error codes + * @ingroup infrastructure + * @{ + */ + /** Define LWIP_ERR_T in cc.h if you want to use * a different type for your platform (must be signed). */ #ifdef LWIP_ERR_T @@ -47,40 +57,50 @@ typedef LWIP_ERR_T err_t; typedef s8_t err_t; #endif /* LWIP_ERR_T*/ -/* Definitions for error constants. */ +/** Definitions for error constants. */ +typedef enum { +/** No error, everything OK. */ + ERR_OK = 0, +/** Out of memory error. */ + ERR_MEM = -1, +/** Buffer error. */ + ERR_BUF = -2, +/** Timeout. */ + ERR_TIMEOUT = -3, +/** Routing problem. */ + ERR_RTE = -4, +/** Operation in progress */ + ERR_INPROGRESS = -5, +/** Illegal value. */ + ERR_VAL = -6, +/** Operation would block. */ + ERR_WOULDBLOCK = -7, +/** Address in use. */ + ERR_USE = -8, +/** Already connecting. */ + ERR_ALREADY = -9, +/** Conn already established.*/ + ERR_ISCONN = -10, +/** Not connected. */ + ERR_CONN = -11, +/** Low-level netif error */ + ERR_IF = -12, -#define ERR_OK 0 /* No error, everything OK. */ -#define ERR_MEM -1 /* Out of memory error. */ -#define ERR_BUF -2 /* Buffer error. */ -#define ERR_TIMEOUT -3 /* Timeout. */ -#define ERR_RTE -4 /* Routing problem. */ -#define ERR_INPROGRESS -5 /* Operation in progress */ -#define ERR_VAL -6 /* Illegal value. */ -#define ERR_WOULDBLOCK -7 /* Operation would block. */ -#define ERR_USE -8 /* Address in use. */ +/** Connection aborted. */ + ERR_ABRT = -13, +/** Connection reset. */ + ERR_RST = -14, +/** Connection closed. */ + ERR_CLSD = -15, +/** Illegal argument. */ + ERR_ARG = -16 +} err_enum_t; - -#if ESP_LWIP -#define ERR_ALREADY -9 /* Already connected. */ -#define ERR_ISCONN -10 /* Conn already established.*/ -#define ERR_IS_FATAL(e) ((e) < ERR_ISCONN) -#define ERR_ABRT -11 /* Connection aborted. */ -#define ERR_RST -12 /* Connection reset. */ -#define ERR_CLSD -13 /* Connection closed. */ -#define ERR_CONN -14 /* Not connected. */ -#define ERR_ARG -15 /* Illegal argument. */ -#define ERR_IF -16 /* Low-level netif error */ -#else -#define ERR_ALREADY -9 /* Already connecting. */ -#define ERR_ISCONN -10 /* Conn already established.*/ -#define ERR_CONN -11 /* Not connected. */ -#define ERR_IF -12 /* Low-level netif error */ #define ERR_IS_FATAL(e) ((e) <= ERR_ABRT) -#define ERR_ABRT -13 /* Connection aborted. */ -#define ERR_RST -14 /* Connection reset. */ -#define ERR_CLSD -15 /* Connection closed. */ -#define ERR_ARG -16 /* Illegal argument. */ -#endif + +/** + * @} + */ #ifdef LWIP_DEBUG extern const char *lwip_strerr(err_t err); @@ -88,6 +108,10 @@ extern const char *lwip_strerr(err_t err); #define lwip_strerr(x) "" #endif /* LWIP_DEBUG */ +#if !NO_SYS +int err_to_errno(err_t err); +#endif /* !NO_SYS */ + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/errno.h b/tools/sdk/include/lwip/lwip/errno.h new file mode 100644 index 00000000..641cffb0 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/errno.h @@ -0,0 +1,193 @@ +/** + * @file + * Posix Errno defines + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_ERRNO_H +#define LWIP_HDR_ERRNO_H + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef LWIP_PROVIDE_ERRNO + +#define EPERM 1 /* Operation not permitted */ +#define ENOENT 2 /* No such file or directory */ +#define ESRCH 3 /* No such process */ +#define EINTR 4 /* Interrupted system call */ +#define EIO 5 /* I/O error */ +#define ENXIO 6 /* No such device or address */ +#define E2BIG 7 /* Arg list too long */ +#define ENOEXEC 8 /* Exec format error */ +#define EBADF 9 /* Bad file number */ +#define ECHILD 10 /* No child processes */ +#define EAGAIN 11 /* Try again */ +#define ENOMEM 12 /* Out of memory */ +#define EACCES 13 /* Permission denied */ +#define EFAULT 14 /* Bad address */ +#define ENOTBLK 15 /* Block device required */ +#define EBUSY 16 /* Device or resource busy */ +#define EEXIST 17 /* File exists */ +#define EXDEV 18 /* Cross-device link */ +#define ENODEV 19 /* No such device */ +#define ENOTDIR 20 /* Not a directory */ +#define EISDIR 21 /* Is a directory */ +#define EINVAL 22 /* Invalid argument */ +#define ENFILE 23 /* File table overflow */ +#define EMFILE 24 /* Too many open files */ +#define ENOTTY 25 /* Not a typewriter */ +#define ETXTBSY 26 /* Text file busy */ +#define EFBIG 27 /* File too large */ +#define ENOSPC 28 /* No space left on device */ +#define ESPIPE 29 /* Illegal seek */ +#define EROFS 30 /* Read-only file system */ +#define EMLINK 31 /* Too many links */ +#define EPIPE 32 /* Broken pipe */ +#define EDOM 33 /* Math argument out of domain of func */ +#define ERANGE 34 /* Math result not representable */ +#define EDEADLK 35 /* Resource deadlock would occur */ +#define ENAMETOOLONG 36 /* File name too long */ +#define ENOLCK 37 /* No record locks available */ +#define ENOSYS 38 /* Function not implemented */ +#define ENOTEMPTY 39 /* Directory not empty */ +#define ELOOP 40 /* Too many symbolic links encountered */ +#define EWOULDBLOCK EAGAIN /* Operation would block */ +#define ENOMSG 42 /* No message of desired type */ +#define EIDRM 43 /* Identifier removed */ +#define ECHRNG 44 /* Channel number out of range */ +#define EL2NSYNC 45 /* Level 2 not synchronized */ +#define EL3HLT 46 /* Level 3 halted */ +#define EL3RST 47 /* Level 3 reset */ +#define ELNRNG 48 /* Link number out of range */ +#define EUNATCH 49 /* Protocol driver not attached */ +#define ENOCSI 50 /* No CSI structure available */ +#define EL2HLT 51 /* Level 2 halted */ +#define EBADE 52 /* Invalid exchange */ +#define EBADR 53 /* Invalid request descriptor */ +#define EXFULL 54 /* Exchange full */ +#define ENOANO 55 /* No anode */ +#define EBADRQC 56 /* Invalid request code */ +#define EBADSLT 57 /* Invalid slot */ + +#define EDEADLOCK EDEADLK + +#define EBFONT 59 /* Bad font file format */ +#define ENOSTR 60 /* Device not a stream */ +#define ENODATA 61 /* No data available */ +#define ETIME 62 /* Timer expired */ +#define ENOSR 63 /* Out of streams resources */ +#define ENONET 64 /* Machine is not on the network */ +#define ENOPKG 65 /* Package not installed */ +#define EREMOTE 66 /* Object is remote */ +#define ENOLINK 67 /* Link has been severed */ +#define EADV 68 /* Advertise error */ +#define ESRMNT 69 /* Srmount error */ +#define ECOMM 70 /* Communication error on send */ +#define EPROTO 71 /* Protocol error */ +#define EMULTIHOP 72 /* Multihop attempted */ +#define EDOTDOT 73 /* RFS specific error */ +#define EBADMSG 74 /* Not a data message */ +#define EOVERFLOW 75 /* Value too large for defined data type */ +#define ENOTUNIQ 76 /* Name not unique on network */ +#define EBADFD 77 /* File descriptor in bad state */ +#define EREMCHG 78 /* Remote address changed */ +#define ELIBACC 79 /* Can not access a needed shared library */ +#define ELIBBAD 80 /* Accessing a corrupted shared library */ +#define ELIBSCN 81 /* .lib section in a.out corrupted */ +#define ELIBMAX 82 /* Attempting to link in too many shared libraries */ +#define ELIBEXEC 83 /* Cannot exec a shared library directly */ +#define EILSEQ 84 /* Illegal byte sequence */ +#define ERESTART 85 /* Interrupted system call should be restarted */ +#define ESTRPIPE 86 /* Streams pipe error */ +#define EUSERS 87 /* Too many users */ +#define ENOTSOCK 88 /* Socket operation on non-socket */ +#define EDESTADDRREQ 89 /* Destination address required */ +#define EMSGSIZE 90 /* Message too long */ +#define EPROTOTYPE 91 /* Protocol wrong type for socket */ +#define ENOPROTOOPT 92 /* Protocol not available */ +#define EPROTONOSUPPORT 93 /* Protocol not supported */ +#define ESOCKTNOSUPPORT 94 /* Socket type not supported */ +#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define EPFNOSUPPORT 96 /* Protocol family not supported */ +#define EAFNOSUPPORT 97 /* Address family not supported by protocol */ +#define EADDRINUSE 98 /* Address already in use */ +#define EADDRNOTAVAIL 99 /* Cannot assign requested address */ +#define ENETDOWN 100 /* Network is down */ +#define ENETUNREACH 101 /* Network is unreachable */ +#define ENETRESET 102 /* Network dropped connection because of reset */ +#define ECONNABORTED 103 /* Software caused connection abort */ +#define ECONNRESET 104 /* Connection reset by peer */ +#define ENOBUFS 105 /* No buffer space available */ +#define EISCONN 106 /* Transport endpoint is already connected */ +#define ENOTCONN 107 /* Transport endpoint is not connected */ +#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ +#define ETOOMANYREFS 109 /* Too many references: cannot splice */ +#define ETIMEDOUT 110 /* Connection timed out */ +#define ECONNREFUSED 111 /* Connection refused */ +#define EHOSTDOWN 112 /* Host is down */ +#define EHOSTUNREACH 113 /* No route to host */ +#define EALREADY 114 /* Operation already in progress */ +#define EINPROGRESS 115 /* Operation now in progress */ +#define ESTALE 116 /* Stale NFS file handle */ +#define EUCLEAN 117 /* Structure needs cleaning */ +#define ENOTNAM 118 /* Not a XENIX named type file */ +#define ENAVAIL 119 /* No XENIX semaphores available */ +#define EISNAM 120 /* Is a named type file */ +#define EREMOTEIO 121 /* Remote I/O error */ +#define EDQUOT 122 /* Quota exceeded */ + +#define ENOMEDIUM 123 /* No medium found */ +#define EMEDIUMTYPE 124 /* Wrong medium type */ + +#ifndef errno +extern int errno; +#endif + +#else /* LWIP_PROVIDE_ERRNO */ + +/* Define LWIP_ERRNO_INCLUDE to to include the error defines here */ +#ifdef LWIP_ERRNO_INCLUDE +#include LWIP_ERRNO_INCLUDE +#endif /* LWIP_ERRNO_INCLUDE */ + +#endif /* LWIP_PROVIDE_ERRNO */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_ERRNO_H */ diff --git a/tools/sdk/include/lwip/lwip/etharp.h b/tools/sdk/include/lwip/lwip/etharp.h new file mode 100644 index 00000000..0662f072 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/etharp.h @@ -0,0 +1,116 @@ +/** + * @file + * Ethernet output function - handles OUTGOING ethernet level traffic, implements + * ARP resolving. + * To be used in most low-level netif implementations + */ + +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * Copyright (c) 2003-2004 Leon Woestenberg + * Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef LWIP_HDR_NETIF_ETHARP_H +#define LWIP_HDR_NETIF_ETHARP_H + +#include "lwip/opt.h" + +#if LWIP_ARP || LWIP_ETHERNET /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/ip4_addr.h" +#include "lwip/netif.h" +#include "lwip/ip4.h" +#include "lwip/prot/ethernet.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_IPV4 && LWIP_ARP /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/prot/etharp.h" + +/** 1 seconds period */ +#define ARP_TMR_INTERVAL 1000 + +#if ARP_QUEUEING +/** struct for queueing outgoing packets for unknown address + * defined here to be accessed by memp.h + */ +struct etharp_q_entry { + struct etharp_q_entry *next; + struct pbuf *p; +}; +#endif /* ARP_QUEUEING */ + +#if ESP_GRATUITOUS_ARP +#ifdef CONFIG_GARP_TMR_INTERVAL +#define GARP_TMR_INTERVAL (CONFIG_GARP_TMR_INTERVAL*1000UL) +#else +#define GARP_TMR_INTERVAL 60000 +#endif + +void garp_tmr(void); +#endif + +#define etharp_init() /* Compatibility define, no init needed. */ +void etharp_tmr(void); +s8_t etharp_find_addr(struct netif *netif, const ip4_addr_t *ipaddr, + struct eth_addr **eth_ret, const ip4_addr_t **ip_ret); +u8_t etharp_get_entry(u8_t i, ip4_addr_t **ipaddr, struct netif **netif, struct eth_addr **eth_ret); +err_t etharp_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr); +err_t etharp_query(struct netif *netif, const ip4_addr_t *ipaddr, struct pbuf *q); +err_t etharp_request(struct netif *netif, const ip4_addr_t *ipaddr); +/** For Ethernet network interfaces, we might want to send "gratuitous ARP"; + * this is an ARP packet sent by a node in order to spontaneously cause other + * nodes to update an entry in their ARP cache. + * From RFC 3220 "IP Mobility Support for IPv4" section 4.6. */ +#define etharp_gratuitous(netif) etharp_request((netif), netif_ip4_addr(netif)) +void etharp_cleanup_netif(struct netif *netif); + +#if ETHARP_SUPPORT_STATIC_ENTRIES +err_t etharp_add_static_entry(const ip4_addr_t *ipaddr, struct eth_addr *ethaddr); +err_t etharp_remove_static_entry(const ip4_addr_t *ipaddr); +#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ + +#endif /* LWIP_IPV4 && LWIP_ARP */ + +void etharp_input(struct pbuf *p, struct netif *netif); + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_ARP || LWIP_ETHERNET */ + +#endif /* LWIP_HDR_NETIF_ETHARP_H */ diff --git a/tools/sdk/include/lwip/lwip/icmp.h b/tools/sdk/include/lwip/lwip/icmp.h index af3a4550..f5a31fd4 100644 --- a/tools/sdk/include/lwip/lwip/icmp.h +++ b/tools/sdk/include/lwip/lwip/icmp.h @@ -1,3 +1,8 @@ +/** + * @file + * ICMP API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -36,6 +41,7 @@ #include "lwip/pbuf.h" #include "lwip/ip_addr.h" #include "lwip/netif.h" +#include "lwip/prot/icmp.h" #if LWIP_IPV6 && LWIP_ICMP6 #include "lwip/icmp6.h" @@ -45,63 +51,30 @@ extern "C" { #endif -#define ICMP_ER 0 /* echo reply */ -#define ICMP_DUR 3 /* destination unreachable */ -#define ICMP_SQ 4 /* source quench */ -#define ICMP_RD 5 /* redirect */ -#define ICMP_ECHO 8 /* echo */ -#define ICMP_TE 11 /* time exceeded */ -#define ICMP_PP 12 /* parameter problem */ -#define ICMP_TS 13 /* timestamp */ -#define ICMP_TSR 14 /* timestamp reply */ -#define ICMP_IRQ 15 /* information request */ -#define ICMP_IR 16 /* information reply */ -#define ICMP_AM 17 /* address mask request */ -#define ICMP_AMR 18 /* address mask reply */ - +/** ICMP destination unreachable codes */ enum icmp_dur_type { - ICMP_DUR_NET = 0, /* net unreachable */ - ICMP_DUR_HOST = 1, /* host unreachable */ - ICMP_DUR_PROTO = 2, /* protocol unreachable */ - ICMP_DUR_PORT = 3, /* port unreachable */ - ICMP_DUR_FRAG = 4, /* fragmentation needed and DF set */ - ICMP_DUR_SR = 5 /* source route failed */ + /** net unreachable */ + ICMP_DUR_NET = 0, + /** host unreachable */ + ICMP_DUR_HOST = 1, + /** protocol unreachable */ + ICMP_DUR_PROTO = 2, + /** port unreachable */ + ICMP_DUR_PORT = 3, + /** fragmentation needed and DF set */ + ICMP_DUR_FRAG = 4, + /** source route failed */ + ICMP_DUR_SR = 5 }; +/** ICMP time exceeded codes */ enum icmp_te_type { - ICMP_TE_TTL = 0, /* time to live exceeded in transit */ - ICMP_TE_FRAG = 1 /* fragment reassembly time exceeded */ + /** time to live exceeded in transit */ + ICMP_TE_TTL = 0, + /** fragment reassembly time exceeded */ + ICMP_TE_FRAG = 1 }; -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -/** This is the standard ICMP header only that the u32_t data - * is split to two u16_t like ICMP echo needs it. - * This header is also used for other ICMP types that do not - * use the data part. - */ -PACK_STRUCT_BEGIN -struct icmp_echo_hdr { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u16_t id); - PACK_STRUCT_FIELD(u16_t seqno); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define ICMPH_TYPE(hdr) ((hdr)->type) -#define ICMPH_CODE(hdr) ((hdr)->code) - -/** Combines type and code to an u16_t */ -#define ICMPH_TYPE_SET(hdr, t) ((hdr)->type = (t)) -#define ICMPH_CODE_SET(hdr, c) ((hdr)->code = (c)) - - #if LWIP_IPV4 && LWIP_ICMP /* don't build if not configured for use in lwipopts.h */ void icmp_input(struct pbuf *p, struct netif *inp); diff --git a/tools/sdk/include/lwip/lwip/icmp6.h b/tools/sdk/include/lwip/lwip/icmp6.h index 9d57103f..a29dc8c1 100644 --- a/tools/sdk/include/lwip/lwip/icmp6.h +++ b/tools/sdk/include/lwip/lwip/icmp6.h @@ -45,94 +45,12 @@ #include "lwip/pbuf.h" #include "lwip/ip6_addr.h" #include "lwip/netif.h" - +#include "lwip/prot/icmp6.h" #ifdef __cplusplus extern "C" { #endif -enum icmp6_type { - ICMP6_TYPE_DUR = 1, /* Destination unreachable */ - ICMP6_TYPE_PTB = 2, /* Packet too big */ - ICMP6_TYPE_TE = 3, /* Time exceeded */ - ICMP6_TYPE_PP = 4, /* Parameter problem */ - ICMP6_TYPE_PE1 = 100, /* Private experimentation */ - ICMP6_TYPE_PE2 = 101, /* Private experimentation */ - ICMP6_TYPE_RSV_ERR = 127, /* Reserved for expansion of error messages */ - - ICMP6_TYPE_EREQ = 128, /* Echo request */ - ICMP6_TYPE_EREP = 129, /* Echo reply */ - ICMP6_TYPE_MLQ = 130, /* Multicast listener query */ - ICMP6_TYPE_MLR = 131, /* Multicast listener report */ - ICMP6_TYPE_MLD = 132, /* Multicast listener done */ - ICMP6_TYPE_RS = 133, /* Router solicitation */ - ICMP6_TYPE_RA = 134, /* Router advertisement */ - ICMP6_TYPE_NS = 135, /* Neighbor solicitation */ - ICMP6_TYPE_NA = 136, /* Neighbor advertisement */ - ICMP6_TYPE_RD = 137, /* Redirect */ - ICMP6_TYPE_MRA = 151, /* Multicast router advertisement */ - ICMP6_TYPE_MRS = 152, /* Multicast router solicitation */ - ICMP6_TYPE_MRT = 153, /* Multicast router termination */ - ICMP6_TYPE_PE3 = 200, /* Private experimentation */ - ICMP6_TYPE_PE4 = 201, /* Private experimentation */ - ICMP6_TYPE_RSV_INF = 255 /* Reserved for expansion of informational messages */ -}; - -enum icmp6_dur_code { - ICMP6_DUR_NO_ROUTE = 0, /* No route to destination */ - ICMP6_DUR_PROHIBITED = 1, /* Communication with destination administratively prohibited */ - ICMP6_DUR_SCOPE = 2, /* Beyond scope of source address */ - ICMP6_DUR_ADDRESS = 3, /* Address unreachable */ - ICMP6_DUR_PORT = 4, /* Port unreachable */ - ICMP6_DUR_POLICY = 5, /* Source address failed ingress/egress policy */ - ICMP6_DUR_REJECT_ROUTE = 6 /* Reject route to destination */ -}; - -enum icmp6_te_code { - ICMP6_TE_HL = 0, /* Hop limit exceeded in transit */ - ICMP6_TE_FRAG = 1 /* Fragment reassembly time exceeded */ -}; - -enum icmp6_pp_code { - ICMP6_PP_FIELD = 0, /* Erroneous header field encountered */ - ICMP6_PP_HEADER = 1, /* Unrecognized next header type encountered */ - ICMP6_PP_OPTION = 2 /* Unrecognized IPv6 option encountered */ -}; - -/** This is the standard ICMP6 header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct icmp6_hdr { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u32_t data); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** This is the ICMP6 header adapted for echo req/resp. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct icmp6_echo_hdr { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u16_t id); - PACK_STRUCT_FIELD(u16_t seqno); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - - #if LWIP_ICMP6 && LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ void icmp6_input(struct pbuf *p, struct netif *inp); diff --git a/tools/sdk/include/lwip/lwip/igmp.h b/tools/sdk/include/lwip/lwip/igmp.h index bff1a613..ffd80e68 100644 --- a/tools/sdk/include/lwip/lwip/igmp.h +++ b/tools/sdk/include/lwip/lwip/igmp.h @@ -1,3 +1,8 @@ +/** + * @file + * IGMP API + */ + /* * Copyright (c) 2002 CITEL Technologies Ltd. * All rights reserved. @@ -46,17 +51,14 @@ extern "C" { #endif - /* IGMP timer */ #define IGMP_TMR_INTERVAL 100 /* Milliseconds */ #define IGMP_V1_DELAYING_MEMBER_TMR (1000/IGMP_TMR_INTERVAL) #define IGMP_JOIN_DELAYING_MEMBER_TMR (500 /IGMP_TMR_INTERVAL) -/* MAC Filter Actions, these are passed to a netif's - * igmp_mac_filter callback function. */ -#define IGMP_DEL_MAC_FILTER 0 -#define IGMP_ADD_MAC_FILTER 1 - +/* Compatibility defines (don't use for new code) */ +#define IGMP_DEL_MAC_FILTER NETIF_DEL_MAC_FILTER +#define IGMP_ADD_MAC_FILTER NETIF_ADD_MAC_FILTER /** * igmp group structure - there is @@ -70,10 +72,8 @@ extern "C" { * from all the other groups */ struct igmp_group { - /** next link */ + /** next link */ struct igmp_group *next; - /** interface on which the group is active */ - struct netif *netif; /** multicast address */ ip4_addr_t group_address; /** signifies we were the last person to report */ @@ -83,7 +83,7 @@ struct igmp_group { /** timer for reporting, negative is OFF */ u16_t timer; /** counter of simultaneous uses */ - u8_t use; + u8_t use; }; /* Prototypes */ @@ -99,6 +99,13 @@ err_t igmp_leavegroup(const ip4_addr_t *ifaddr, const ip4_addr_t *groupaddr); err_t igmp_leavegroup_netif(struct netif *netif, const ip4_addr_t *groupaddr); void igmp_tmr(void); +/** @ingroup igmp + * Get list head of IGMP groups for netif. + * Note: The allsystems group IP is contained in the list as first entry. + * @see @ref netif_set_igmp_mac_filter() + */ +#define netif_igmp_data(netif) ((struct igmp_group *)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_IGMP)) + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/inet.h b/tools/sdk/include/lwip/lwip/inet.h index 036cd988..4a34f026 100644 --- a/tools/sdk/include/lwip/lwip/inet.h +++ b/tools/sdk/include/lwip/lwip/inet.h @@ -132,10 +132,10 @@ extern const struct in6_addr in6addr_any; #if LWIP_IPV4 -#define inet_addr_from_ipaddr(target_inaddr, source_ipaddr) ((target_inaddr)->s_addr = ip4_addr_get_u32(source_ipaddr)) -#define inet_addr_to_ipaddr(target_ipaddr, source_inaddr) (ip4_addr_set_u32(target_ipaddr, (source_inaddr)->s_addr)) -/* ATTENTION: the next define only works because both s_addr and ip_addr_t are an u32_t effectively! */ -#define inet_addr_to_ipaddr_p(target_ipaddr_p, source_inaddr) ((target_ipaddr_p) = (ip_addr_t*)&((source_inaddr)->s_addr)) +#define inet_addr_from_ip4addr(target_inaddr, source_ipaddr) ((target_inaddr)->s_addr = ip4_addr_get_u32(source_ipaddr)) +#define inet_addr_to_ip4addr(target_ipaddr, source_inaddr) (ip4_addr_set_u32(target_ipaddr, (source_inaddr)->s_addr)) +/* ATTENTION: the next define only works because both s_addr and ip4_addr_t are an u32_t effectively! */ +#define inet_addr_to_ip4addr_p(target_ip4addr_p, source_inaddr) ((target_ip4addr_p) = (ip4_addr_t*)&((source_inaddr)->s_addr)) /* directly map this to the lwip internal functions */ #define inet_addr(cp) ipaddr_addr(cp) diff --git a/tools/sdk/include/lwip/lwip/inet_chksum.h b/tools/sdk/include/lwip/lwip/inet_chksum.h index 1766f4b5..4e23d7f1 100644 --- a/tools/sdk/include/lwip/lwip/inet_chksum.h +++ b/tools/sdk/include/lwip/lwip/inet_chksum.h @@ -1,3 +1,8 @@ +/** + * @file + * IP checksum calculation functions + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -37,15 +42,9 @@ #include "lwip/pbuf.h" #include "lwip/ip_addr.h" -/** Swap the bytes in an u16_t: much like htons() for little-endian */ +/** Swap the bytes in an u16_t: much like lwip_htons() for little-endian */ #ifndef SWAP_BYTES_IN_WORD -#if LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN) -/* little endian and PLATFORM_BYTESWAP defined */ -#define SWAP_BYTES_IN_WORD(w) LWIP_PLATFORM_HTONS(w) -#else /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN) */ -/* can't use htons on big endian (or PLATFORM_BYTESWAP not defined)... */ #define SWAP_BYTES_IN_WORD(w) (((w) & 0xff) << 8) | (((w) & 0xff00) >> 8) -#endif /* LWIP_PLATFORM_BYTESWAP && (BYTE_ORDER == LITTLE_ENDIAN)*/ #endif /* SWAP_BYTES_IN_WORD */ /** Split an u32_t in two u16_ts and add them up */ diff --git a/tools/sdk/include/lwip/lwip/init.h b/tools/sdk/include/lwip/lwip/init.h index 70351b86..3c234cb5 100644 --- a/tools/sdk/include/lwip/lwip/init.h +++ b/tools/sdk/include/lwip/lwip/init.h @@ -1,3 +1,8 @@ +/** + * @file + * lwIP initialization API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,29 +43,52 @@ extern "C" { #endif +/** + * @defgroup lwip_version Version + * @ingroup lwip + * @{ + */ + /** X.x.x: Major version of the stack */ -#define LWIP_VERSION_MAJOR 1U +#define LWIP_VERSION_MAJOR 2 /** x.X.x: Minor version of the stack */ -#define LWIP_VERSION_MINOR 5U +#define LWIP_VERSION_MINOR 0 /** x.x.X: Revision of the stack */ -#define LWIP_VERSION_REVISION 0U +#define LWIP_VERSION_REVISION 3 /** For release candidates, this is set to 1..254 * For official releases, this is set to 255 (LWIP_RC_RELEASE) * For development versions (Git), this is set to 0 (LWIP_RC_DEVELOPMENT) */ -#define LWIP_VERSION_RC 0U +#define LWIP_VERSION_RC LWIP_RC_RELEASE /** LWIP_VERSION_RC is set to LWIP_RC_RELEASE for official releases */ -#define LWIP_RC_RELEASE 255U +#define LWIP_RC_RELEASE 255 /** LWIP_VERSION_RC is set to LWIP_RC_DEVELOPMENT for Git versions */ -#define LWIP_RC_DEVELOPMENT 0U +#define LWIP_RC_DEVELOPMENT 0 #define LWIP_VERSION_IS_RELEASE (LWIP_VERSION_RC == LWIP_RC_RELEASE) #define LWIP_VERSION_IS_DEVELOPMENT (LWIP_VERSION_RC == LWIP_RC_DEVELOPMENT) #define LWIP_VERSION_IS_RC ((LWIP_VERSION_RC != LWIP_RC_RELEASE) && (LWIP_VERSION_RC != LWIP_RC_DEVELOPMENT)) +/* Some helper defines to get a version string */ +#define LWIP_VERSTR2(x) #x +#define LWIP_VERSTR(x) LWIP_VERSTR2(x) +#if LWIP_VERSION_IS_RELEASE +#define LWIP_VERSION_STRING_SUFFIX "" +#elif LWIP_VERSION_IS_DEVELOPMENT +#define LWIP_VERSION_STRING_SUFFIX "d" +#else +#define LWIP_VERSION_STRING_SUFFIX "rc" LWIP_VERSTR(LWIP_VERSION_RC) +#endif + /** Provides the version of the stack */ -#define LWIP_VERSION (LWIP_VERSION_MAJOR << 24 | LWIP_VERSION_MINOR << 16 | \ - LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC) +#define LWIP_VERSION (((u32_t)LWIP_VERSION_MAJOR) << 24 | ((u32_t)LWIP_VERSION_MINOR) << 16 | \ + ((u32_t)LWIP_VERSION_REVISION) << 8 | ((u32_t)LWIP_VERSION_RC)) +/** Provides the version of the stack as string */ +#define LWIP_VERSION_STRING LWIP_VERSTR(LWIP_VERSION_MAJOR) "." LWIP_VERSTR(LWIP_VERSION_MINOR) "." LWIP_VERSTR(LWIP_VERSION_REVISION) LWIP_VERSION_STRING_SUFFIX + +/** + * @} + */ /* Modules initialization */ void lwip_init(void); diff --git a/tools/sdk/include/lwip/lwip/ip.h b/tools/sdk/include/lwip/lwip/ip.h index d42fe681..0673be9b 100644 --- a/tools/sdk/include/lwip/lwip/ip.h +++ b/tools/sdk/include/lwip/lwip/ip.h @@ -1,3 +1,8 @@ +/** + * @file + * IP API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -29,8 +34,8 @@ * Author: Adam Dunkels * */ -#ifndef LWIP_HDR_IP_H__ -#define LWIP_HDR_IP_H__ +#ifndef LWIP_HDR_IP_H +#define LWIP_HDR_IP_H #include "lwip/opt.h" @@ -41,27 +46,16 @@ #include "lwip/netif.h" #include "lwip/ip4.h" #include "lwip/ip6.h" +#include "lwip/prot/ip.h" #ifdef __cplusplus extern "C" { #endif -#define IP_PROTO_ICMP 1 -#define IP_PROTO_IGMP 2 -#define IP_PROTO_UDP 17 -#define IP_PROTO_UDPLITE 136 -#define IP_PROTO_TCP 6 - -/** This operates on a void* by loading the first byte */ -#define IP_HDR_GET_VERSION(ptr) ((*(u8_t*)(ptr)) >> 4) - /* This is passed as the destination address to ip_output_if (not to ip_output), meaning that an IP header already is constructed in the pbuf. This is used when TCP retransmits. */ -#ifdef IP_HDRINCL -#undef IP_HDRINCL -#endif /* IP_HDRINCL */ -#define IP_HDRINCL NULL +#define LWIP_IP_HDRINCL NULL /** pbufs passed to IP must have a ref-count of 1 as their payload pointer gets altered as the packet is passed down the stack */ @@ -75,7 +69,7 @@ extern "C" { #define IP_PCB_ADDRHINT #endif /* LWIP_NETIF_HWADDRHINT */ -/* This is the common part of all PCB types. It needs to be at the +/** This is the common part of all PCB types. It needs to be at the beginning of a PCB type definition. It is located here so that changes to this common part are made in one location instead of having to change all PCB structs. */ @@ -107,7 +101,7 @@ struct ip_pcb { /* These flags are inherited (e.g. from a listen-pcb to a connection-pcb): */ #define SOF_INHERITED (SOF_REUSEADDR|SOF_KEEPALIVE) -/* Global variables of this module, kept in a struct for efficient access using base+index. */ +/** Global variables of this module, kept in a struct for efficient access using base+index. */ struct ip_globals { /** The interface that accepted the packet for the current callback invocation. */ @@ -225,26 +219,47 @@ extern struct ip_globals ip_data; #define ip_reset_option(pcb, opt) ((pcb)->so_options &= ~(opt)) #if LWIP_IPV4 && LWIP_IPV6 +/** + * @ingroup ip + * Output IP packet, netif is selected by source address + */ #define ip_output(p, src, dest, ttl, tos, proto) \ (IP_IS_V6(dest) ? \ ip6_output(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto) : \ ip4_output(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto)) +/** + * @ingroup ip + * Output IP packet to specified interface + */ #define ip_output_if(p, src, dest, ttl, tos, proto, netif) \ (IP_IS_V6(dest) ? \ ip6_output_if(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto, netif) : \ ip4_output_if(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto, netif)) +/** + * @ingroup ip + * Output IP packet to interface specifying source address + */ #define ip_output_if_src(p, src, dest, ttl, tos, proto, netif) \ (IP_IS_V6(dest) ? \ ip6_output_if_src(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto, netif) : \ ip4_output_if_src(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto, netif)) +/** Output IP packet with addr_hint */ #define ip_output_hinted(p, src, dest, ttl, tos, proto, addr_hint) \ (IP_IS_V6(dest) ? \ ip6_output_hinted(p, ip_2_ip6(src), ip_2_ip6(dest), ttl, tos, proto, addr_hint) : \ ip4_output_hinted(p, ip_2_ip4(src), ip_2_ip4(dest), ttl, tos, proto, addr_hint)) +/** + * @ingroup ip + * Get netif for address combination. See \ref ip6_route and \ref ip4_route + */ #define ip_route(src, dest) \ (IP_IS_V6(dest) ? \ ip6_route(ip_2_ip6(src), ip_2_ip6(dest)) : \ ip4_route_src(ip_2_ip4(dest), ip_2_ip4(src))) +/** + * @ingroup ip + * Get netif for IP. + */ #define ip_netif_get_local_ip(netif, dest) (IP_IS_V6(dest) ? \ ip6_netif_get_local_ip(netif, ip_2_ip6(dest)) : \ ip4_netif_get_local_ip(netif)) @@ -299,6 +314,6 @@ err_t ip_input(struct pbuf *p, struct netif *inp); } #endif -#endif /* LWIP_HDR_IP_H__ */ +#endif /* LWIP_HDR_IP_H */ diff --git a/tools/sdk/include/lwip/lwip/ip4.h b/tools/sdk/include/lwip/lwip/ip4.h index e69e55c7..48246ecc 100644 --- a/tools/sdk/include/lwip/lwip/ip4.h +++ b/tools/sdk/include/lwip/lwip/ip4.h @@ -1,3 +1,8 @@ +/** + * @file + * IPv4 API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -41,6 +46,7 @@ #include "lwip/ip4_addr.h" #include "lwip/err.h" #include "lwip/netif.h" +#include "lwip/prot/ip4.h" #ifdef __cplusplus extern "C" { @@ -55,62 +61,6 @@ extern "C" { /** Currently, the function ip_output_if_opt() is only used with IGMP */ #define IP_OPTIONS_SEND (LWIP_IPV4 && LWIP_IGMP) -#define IP_HLEN 20 - - -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip_hdr { - /* version / header length */ - PACK_STRUCT_FLD_8(u8_t _v_hl); - /* type of service */ - PACK_STRUCT_FLD_8(u8_t _tos); - /* total length */ - PACK_STRUCT_FIELD(u16_t _len); - /* identification */ - PACK_STRUCT_FIELD(u16_t _id); - /* fragment offset field */ - PACK_STRUCT_FIELD(u16_t _offset); -#define IP_RF 0x8000U /* reserved fragment flag */ -#define IP_DF 0x4000U /* don't fragment flag */ -#define IP_MF 0x2000U /* more fragments flag */ -#define IP_OFFMASK 0x1fffU /* mask for fragmenting bits */ - /* time to live */ - PACK_STRUCT_FLD_8(u8_t _ttl); - /* protocol*/ - PACK_STRUCT_FLD_8(u8_t _proto); - /* checksum */ - PACK_STRUCT_FIELD(u16_t _chksum); - /* source and destination IP addresses */ - PACK_STRUCT_FLD_S(ip4_addr_p_t src); - PACK_STRUCT_FLD_S(ip4_addr_p_t dest); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define IPH_V(hdr) ((hdr)->_v_hl >> 4) -#define IPH_HL(hdr) ((hdr)->_v_hl & 0x0f) -#define IPH_TOS(hdr) ((hdr)->_tos) -#define IPH_LEN(hdr) ((hdr)->_len) -#define IPH_ID(hdr) ((hdr)->_id) -#define IPH_OFFSET(hdr) ((hdr)->_offset) -#define IPH_TTL(hdr) ((hdr)->_ttl) -#define IPH_PROTO(hdr) ((hdr)->_proto) -#define IPH_CHKSUM(hdr) ((hdr)->_chksum) - -#define IPH_VHL_SET(hdr, v, hl) (hdr)->_v_hl = (u8_t)((((v) << 4) | (hl))) -#define IPH_TOS_SET(hdr, tos) (hdr)->_tos = (tos) -#define IPH_LEN_SET(hdr, len) (hdr)->_len = (len) -#define IPH_ID_SET(hdr, id) (hdr)->_id = (id) -#define IPH_OFFSET_SET(hdr, off) (hdr)->_offset = (off) -#define IPH_TTL_SET(hdr, ttl) (hdr)->_ttl = (u8_t)(ttl) -#define IPH_PROTO_SET(hdr, proto) (hdr)->_proto = (u8_t)(proto) -#define IPH_CHKSUM_SET(hdr, chksum) (hdr)->_chksum = (chksum) - #define ip_init() /* Compatibility define, no init needed. */ struct netif *ip4_route(const ip4_addr_t *dest); #if LWIP_IPV4_SRC_ROUTING diff --git a/tools/sdk/include/lwip/lwip/ip4_addr.h b/tools/sdk/include/lwip/lwip/ip4_addr.h index 9483a2f7..51b46b8d 100644 --- a/tools/sdk/include/lwip/lwip/ip4_addr.h +++ b/tools/sdk/include/lwip/lwip/ip4_addr.h @@ -1,3 +1,8 @@ +/** + * @file + * IPv4 address API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -41,32 +46,17 @@ extern "C" { #endif -/* This is the aligned version of ip4_addr_t, +/** This is the aligned version of ip4_addr_t, used as local variable, on the stack, etc. */ struct ip4_addr { u32_t addr; }; -/* This is the packed version of ip4_addr_t, - used in network headers that are itself packed */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip4_addr_packed { - PACK_STRUCT_FIELD(u32_t addr); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - /** ip4_addr_t uses a struct for convenience only, so that the same defines can * operate both on ip4_addr_t as well as on ip4_addr_p_t. */ typedef struct ip4_addr ip4_addr_t; -typedef struct ip4_addr_packed ip4_addr_p_t; -/* +/** * struct ipaddr2 is used in the definition of the ARP packet format in * order to support compilers that don't have structure packing. */ @@ -126,23 +116,8 @@ struct netif; #define IP_LOOPBACKNET 127 /* official! */ - -#if BYTE_ORDER == BIG_ENDIAN /** Set an IP address given by the four byte-parts */ -#define IP4_ADDR(ipaddr, a,b,c,d) \ - (ipaddr)->addr = ((u32_t)((a) & 0xff) << 24) | \ - ((u32_t)((b) & 0xff) << 16) | \ - ((u32_t)((c) & 0xff) << 8) | \ - (u32_t)((d) & 0xff) -#else -/** Set an IP address given by the four byte-parts. - Little-endian version that prevents the use of htonl. */ -#define IP4_ADDR(ipaddr, a,b,c,d) \ - (ipaddr)->addr = ((u32_t)((d) & 0xff) << 24) | \ - ((u32_t)((c) & 0xff) << 16) | \ - ((u32_t)((b) & 0xff) << 8) | \ - (u32_t)((a) & 0xff) -#endif +#define IP4_ADDR(ipaddr, a,b,c,d) (ipaddr)->addr = PP_HTONL(LWIP_MAKEU32(a,b,c,d)) /** MEMCPY-like copying of IP addresses where addresses are known to be * 16-bit-aligned if the port is correctly configured (so a port could define @@ -159,7 +134,7 @@ struct netif; (src)->addr)) /** Set complete address to zero */ #define ip4_addr_set_zero(ipaddr) ((ipaddr)->addr = 0) -/** Set address to IPADDR_ANY (no need for htonl()) */ +/** Set address to IPADDR_ANY (no need for lwip_htonl()) */ #define ip4_addr_set_any(ipaddr) ((ipaddr)->addr = IPADDR_ANY) /** Set address to loopback address */ #define ip4_addr_set_loopback(ipaddr) ((ipaddr)->addr = PP_HTONL(IPADDR_LOOPBACK)) @@ -169,7 +144,7 @@ struct netif; * from host- to network-order. */ #define ip4_addr_set_hton(dest, src) ((dest)->addr = \ ((src) == NULL ? 0:\ - htonl((src)->addr))) + lwip_htonl((src)->addr))) /** IPv4 only: set the IP address given as an u32_t */ #define ip4_addr_set_u32(dest_ipaddr, src_u32) ((dest_ipaddr)->addr = (src_u32)) /** IPv4 only: get the IP address as an u32_t */ @@ -209,10 +184,10 @@ u8_t ip4_addr_netmask_valid(u32_t netmask); LWIP_DEBUGF(debug, ("%" U16_F ".%" U16_F ".%" U16_F ".%" U16_F, a, b, c, d)) #define ip4_addr_debug_print(debug, ipaddr) \ ip4_addr_debug_print_parts(debug, \ - (ipaddr) != NULL ? ip4_addr1_16(ipaddr) : 0, \ - (ipaddr) != NULL ? ip4_addr2_16(ipaddr) : 0, \ - (ipaddr) != NULL ? ip4_addr3_16(ipaddr) : 0, \ - (ipaddr) != NULL ? ip4_addr4_16(ipaddr) : 0) + (u16_t)((ipaddr) != NULL ? ip4_addr1_16(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? ip4_addr2_16(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? ip4_addr3_16(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? ip4_addr4_16(ipaddr) : 0)) #define ip4_addr_debug_print_val(debug, ipaddr) \ ip4_addr_debug_print_parts(debug, \ ip4_addr1_16(&(ipaddr)), \ @@ -233,7 +208,6 @@ u8_t ip4_addr_netmask_valid(u32_t netmask); #define ip4_addr4_16(ipaddr) ((u16_t)ip4_addr4(ipaddr)) #define IP4ADDR_STRLEN_MAX 16 -#define IPADDR_STRLEN_MAX IP4ADDR_STRLEN_MAX /** For backwards compatibility */ #define ip_ntoa(ipaddr) ipaddr_ntoa(ipaddr) diff --git a/tools/sdk/include/lwip/lwip/ip_frag.h b/tools/sdk/include/lwip/lwip/ip4_frag.h similarity index 92% rename from tools/sdk/include/lwip/lwip/ip_frag.h rename to tools/sdk/include/lwip/lwip/ip4_frag.h index deeb2f4e..ed5bf14a 100644 --- a/tools/sdk/include/lwip/lwip/ip_frag.h +++ b/tools/sdk/include/lwip/lwip/ip4_frag.h @@ -1,3 +1,8 @@ +/** + * @file + * IP fragmentation/reassembly + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -30,8 +35,8 @@ * */ -#ifndef LWIP_HDR_IP_FRAG_H -#define LWIP_HDR_IP_FRAG_H +#ifndef LWIP_HDR_IP4_FRAG_H +#define LWIP_HDR_IP4_FRAG_H #include "lwip/opt.h" #include "lwip/err.h" @@ -50,7 +55,7 @@ extern "C" { /* The IP reassembly timer interval in milliseconds. */ #define IP_TMR_INTERVAL 1000 -/* IP reassembly helper struct. +/** IP reassembly helper struct. * This is exported because memp needs to know the size. */ struct ip_reassdata { @@ -68,12 +73,12 @@ struct pbuf * ip4_reass(struct pbuf *p); #endif /* IP_REASSEMBLY */ #if IP_FRAG -#if !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF +#if !LWIP_NETIF_TX_SINGLE_PBUF +#ifndef LWIP_PBUF_CUSTOM_REF_DEFINED +#define LWIP_PBUF_CUSTOM_REF_DEFINED /** A custom pbuf that holds a reference to another pbuf, which is freed * when this custom pbuf is freed. This is used to create a custom PBUF_REF * that points into the original pbuf. */ -#ifndef LWIP_PBUF_CUSTOM_REF_DEFINED -#define LWIP_PBUF_CUSTOM_REF_DEFINED struct pbuf_custom_ref { /** 'base class' */ struct pbuf_custom pc; @@ -81,7 +86,7 @@ struct pbuf_custom_ref { struct pbuf *original; }; #endif /* LWIP_PBUF_CUSTOM_REF_DEFINED */ -#endif /* !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF */ +#endif /* !LWIP_NETIF_TX_SINGLE_PBUF */ err_t ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest); #endif /* IP_FRAG */ @@ -92,4 +97,4 @@ err_t ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest); #endif /* LWIP_IPV4 */ -#endif /* LWIP_HDR_IP_FRAG_H */ +#endif /* LWIP_HDR_IP4_FRAG_H */ diff --git a/tools/sdk/include/lwip/lwip/ip6.h b/tools/sdk/include/lwip/lwip/ip6.h index f1ffb6b7..099b94fb 100644 --- a/tools/sdk/include/lwip/lwip/ip6.h +++ b/tools/sdk/include/lwip/lwip/ip6.h @@ -46,6 +46,7 @@ #if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ #include "lwip/ip6_addr.h" +#include "lwip/prot/ip6.h" #include "lwip/def.h" #include "lwip/pbuf.h" #include "lwip/netif.h" @@ -56,111 +57,6 @@ extern "C" { #endif -#define IP6_HLEN 40 - -#define IP6_NEXTH_HOPBYHOP 0 -#define IP6_NEXTH_TCP 6 -#define IP6_NEXTH_UDP 17 -#define IP6_NEXTH_ENCAPS 41 -#define IP6_NEXTH_ROUTING 43 -#define IP6_NEXTH_FRAGMENT 44 -#define IP6_NEXTH_ICMP6 58 -#define IP6_NEXTH_NONE 59 -#define IP6_NEXTH_DESTOPTS 60 -#define IP6_NEXTH_UDPLITE 136 - - -/* The IPv6 header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip6_hdr { - /* version / traffic class / flow label */ - PACK_STRUCT_FIELD(u32_t _v_tc_fl); - /* payload length */ - PACK_STRUCT_FIELD(u16_t _plen); - /* next header */ - PACK_STRUCT_FLD_8(u8_t _nexth); - /* hop limit */ - PACK_STRUCT_FLD_8(u8_t _hoplim); - /* source and destination IP addresses */ - PACK_STRUCT_FLD_S(ip6_addr_p_t src); - PACK_STRUCT_FLD_S(ip6_addr_p_t dest); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/* Hop-by-hop router alert option. */ -#define IP6_HBH_HLEN 8 -#define IP6_PAD1_OPTION 0 -#define IP6_PADN_ALERT_OPTION 1 -#define IP6_ROUTER_ALERT_OPTION 5 -#define IP6_ROUTER_ALERT_VALUE_MLD 0 -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip6_hbh_hdr { - /* next header */ - PACK_STRUCT_FLD_8(u8_t _nexth); - /* header length */ - PACK_STRUCT_FLD_8(u8_t _hlen); - /* router alert option type */ - PACK_STRUCT_FLD_8(u8_t _ra_opt_type); - /* router alert option data len */ - PACK_STRUCT_FLD_8(u8_t _ra_opt_dlen); - /* router alert option data */ - PACK_STRUCT_FIELD(u16_t _ra_opt_data); - /* PadN option type */ - PACK_STRUCT_FLD_8(u8_t _padn_opt_type); - /* PadN option data len */ - PACK_STRUCT_FLD_8(u8_t _padn_opt_dlen); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/* Fragment header. */ -#define IP6_FRAG_HLEN 8 -#define IP6_FRAG_OFFSET_MASK 0xfff8 -#define IP6_FRAG_MORE_FLAG 0x0001 -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip6_frag_hdr { - /* next header */ - PACK_STRUCT_FLD_8(u8_t _nexth); - /* reserved */ - PACK_STRUCT_FLD_8(u8_t reserved); - /* fragment offset */ - PACK_STRUCT_FIELD(u16_t _fragment_offset); - /* fragmented packet identification */ - PACK_STRUCT_FIELD(u32_t _identification); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define IP6H_V(hdr) ((ntohl((hdr)->_v_tc_fl) >> 28) & 0x0f) -#define IP6H_TC(hdr) ((ntohl((hdr)->_v_tc_fl) >> 20) & 0xff) -#define IP6H_FL(hdr) (ntohl((hdr)->_v_tc_fl) & 0x000fffff) -#define IP6H_PLEN(hdr) (ntohs((hdr)->_plen)) -#define IP6H_NEXTH(hdr) ((hdr)->_nexth) -#define IP6H_NEXTH_P(hdr) ((u8_t *)(hdr) + 6) -#define IP6H_HOPLIM(hdr) ((hdr)->_hoplim) - -#define IP6H_VTCFL_SET(hdr, v, tc, fl) (hdr)->_v_tc_fl = (htonl((((u32_t)(v)) << 28) | (((u32_t)(tc)) << 20) | (fl))) -#define IP6H_PLEN_SET(hdr, plen) (hdr)->_plen = htons(plen) -#define IP6H_NEXTH_SET(hdr, nexth) (hdr)->_nexth = (nexth) -#define IP6H_HOPLIM_SET(hdr, hl) (hdr)->_hoplim = (u8_t)(hl) - - struct netif *ip6_route(const ip6_addr_t *src, const ip6_addr_t *dest); const ip_addr_t *ip6_select_source_address(struct netif *netif, const ip6_addr_t * dest); err_t ip6_input(struct pbuf *p, struct netif *inp); diff --git a/tools/sdk/include/lwip/lwip/ip6_addr.h b/tools/sdk/include/lwip/lwip/ip6_addr.h index a75d8948..ee381aeb 100644 --- a/tools/sdk/include/lwip/lwip/ip6_addr.h +++ b/tools/sdk/include/lwip/lwip/ip6_addr.h @@ -43,6 +43,7 @@ #define LWIP_HDR_IP6_ADDR_H #include "lwip/opt.h" +#include "def.h" #if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ @@ -52,46 +53,18 @@ extern "C" { #endif -/* This is the aligned version of ip6_addr_t, - used as local variable, on the stack, etc. */ +/** This is the aligned version of ip6_addr_t, + used as local variable, on the stack, etc. */ struct ip6_addr { u32_t addr[4]; }; -/* This is the packed version of ip6_addr_t, - used in network headers that are itself packed */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ip6_addr_packed { - PACK_STRUCT_FIELD(u32_t addr[4]); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - +/** IPv6 address */ typedef struct ip6_addr ip6_addr_t; -typedef struct ip6_addr_packed ip6_addr_p_t; - -#if BYTE_ORDER == BIG_ENDIAN -/** Set an IPv6 partial address given by byte-parts. */ +/** Set an IPv6 partial address given by byte-parts */ #define IP6_ADDR_PART(ip6addr, index, a,b,c,d) \ - (ip6addr)->addr[index] = ((u32_t)((a) & 0xff) << 24) | \ - ((u32_t)((b) & 0xff) << 16) | \ - ((u32_t)((c) & 0xff) << 8) | \ - (u32_t)((d) & 0xff) -#else -/** Set an IPv6 partial address given by byte-parts. -Little-endian version, stored in network order (no htonl). */ -#define IP6_ADDR_PART(ip6addr, index, a,b,c,d) \ - (ip6addr)->addr[index] = ((u32_t)((d) & 0xff) << 24) | \ - ((u32_t)((c) & 0xff) << 16) | \ - ((u32_t)((b) & 0xff) << 8) | \ - (u32_t)((a) & 0xff) -#endif + (ip6addr)->addr[index] = PP_HTONL(LWIP_MAKEU32(a,b,c,d)) /** Set a full IPv6 address by passing the 4 u32_t indices in network byte order (use PP_HTONL() for constants) */ @@ -102,14 +75,21 @@ Little-endian version, stored in network order (no htonl). */ (ip6addr)->addr[3] = idx3; } while(0) /** Access address in 16-bit block */ -#define IP6_ADDR_BLOCK1(ip6addr) ((u16_t)(htonl((ip6addr)->addr[0]) >> 16) & 0xffff) -#define IP6_ADDR_BLOCK2(ip6addr) ((u16_t)(htonl((ip6addr)->addr[0])) & 0xffff) -#define IP6_ADDR_BLOCK3(ip6addr) ((u16_t)(htonl((ip6addr)->addr[1]) >> 16) & 0xffff) -#define IP6_ADDR_BLOCK4(ip6addr) ((u16_t)(htonl((ip6addr)->addr[1])) & 0xffff) -#define IP6_ADDR_BLOCK5(ip6addr) ((u16_t)(htonl((ip6addr)->addr[2]) >> 16) & 0xffff) -#define IP6_ADDR_BLOCK6(ip6addr) ((u16_t)(htonl((ip6addr)->addr[2])) & 0xffff) -#define IP6_ADDR_BLOCK7(ip6addr) ((u16_t)(htonl((ip6addr)->addr[3]) >> 16) & 0xffff) -#define IP6_ADDR_BLOCK8(ip6addr) ((u16_t)(htonl((ip6addr)->addr[3])) & 0xffff) +#define IP6_ADDR_BLOCK1(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[0]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK2(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[0])) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK3(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[1]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK4(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[1])) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK5(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[2]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK6(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[2])) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK7(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[3]) >> 16) & 0xffff)) +/** Access address in 16-bit block */ +#define IP6_ADDR_BLOCK8(ip6addr) ((u16_t)((lwip_htonl((ip6addr)->addr[3])) & 0xffff)) /** Copy IPv6 address - faster than ip6_addr_set: no NULL check */ #define ip6_addr_copy(dest, src) do{(dest).addr[0] = (src).addr[0]; \ @@ -128,7 +108,7 @@ Little-endian version, stored in network order (no htonl). */ (ip6addr)->addr[2] = 0; \ (ip6addr)->addr[3] = 0;}while(0) -/** Set address to ipv6 'any' (no need for htonl()) */ +/** Set address to ipv6 'any' (no need for lwip_htonl()) */ #define ip6_addr_set_any(ip6addr) ip6_addr_set_zero(ip6addr) /** Set address to ipv6 loopback address */ #define ip6_addr_set_loopback(ip6addr) do{(ip6addr)->addr[0] = 0; \ @@ -137,10 +117,10 @@ Little-endian version, stored in network order (no htonl). */ (ip6addr)->addr[3] = PP_HTONL(0x00000001UL);}while(0) /** Safely copy one IPv6 address to another and change byte order * from host- to network-order. */ -#define ip6_addr_set_hton(dest, src) do{(dest)->addr[0] = (src) == NULL ? 0 : htonl((src)->addr[0]); \ - (dest)->addr[1] = (src) == NULL ? 0 : htonl((src)->addr[1]); \ - (dest)->addr[2] = (src) == NULL ? 0 : htonl((src)->addr[2]); \ - (dest)->addr[3] = (src) == NULL ? 0 : htonl((src)->addr[3]);}while(0) +#define ip6_addr_set_hton(dest, src) do{(dest)->addr[0] = (src) == NULL ? 0 : lwip_htonl((src)->addr[0]); \ + (dest)->addr[1] = (src) == NULL ? 0 : lwip_htonl((src)->addr[1]); \ + (dest)->addr[2] = (src) == NULL ? 0 : lwip_htonl((src)->addr[2]); \ + (dest)->addr[3] = (src) == NULL ? 0 : lwip_htonl((src)->addr[3]);}while(0) /** @@ -158,7 +138,7 @@ Little-endian version, stored in network order (no htonl). */ ((addr1)->addr[2] == (addr2)->addr[2]) && \ ((addr1)->addr[3] == (addr2)->addr[3])) -#define ip6_get_subnet_id(ip6addr) (htonl((ip6addr)->addr[2]) & 0x0000ffffUL) +#define ip6_get_subnet_id(ip6addr) (lwip_htonl((ip6addr)->addr[2]) & 0x0000ffffUL) #define ip6_addr_isany_val(ip6addr) (((ip6addr).addr[0] == 0) && \ ((ip6addr).addr[1] == 0) && \ @@ -179,11 +159,13 @@ Little-endian version, stored in network order (no htonl). */ #define ip6_addr_isuniquelocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xfe000000UL)) == PP_HTONL(0xfc000000UL)) +#define ip6_addr_isipv4mappedipv6(ip6addr) (((ip6addr)->addr[0] == 0) && ((ip6addr)->addr[1] == 0) && (((ip6addr)->addr[2]) == PP_HTONL(0x0000FFFFUL))) + #define ip6_addr_ismulticast(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff000000UL)) == PP_HTONL(0xff000000UL)) #define ip6_addr_multicast_transient_flag(ip6addr) ((ip6addr)->addr[0] & PP_HTONL(0x00100000UL)) #define ip6_addr_multicast_prefix_flag(ip6addr) ((ip6addr)->addr[0] & PP_HTONL(0x00200000UL)) #define ip6_addr_multicast_rendezvous_flag(ip6addr) ((ip6addr)->addr[0] & PP_HTONL(0x00400000UL)) -#define ip6_addr_multicast_scope(ip6addr) ((htonl((ip6addr)->addr[0]) >> 16) & 0xf) +#define ip6_addr_multicast_scope(ip6addr) ((lwip_htonl((ip6addr)->addr[0]) >> 16) & 0xf) #define IP6_MULTICAST_SCOPE_RESERVED 0x0 #define IP6_MULTICAST_SCOPE_RESERVED0 0x0 #define IP6_MULTICAST_SCOPE_INTERFACE_LOCAL 0x1 @@ -201,7 +183,7 @@ Little-endian version, stored in network order (no htonl). */ #define ip6_addr_ismulticast_orglocal(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff8f0000UL)) == PP_HTONL(0xff080000UL)) #define ip6_addr_ismulticast_global(ip6addr) (((ip6addr)->addr[0] & PP_HTONL(0xff8f0000UL)) == PP_HTONL(0xff0e0000UL)) -/* TODO define get/set for well-know multicast addresses, e.g. ff02::1 */ +/* @todo define get/set for well-know multicast addresses, e.g. ff02::1 */ #define ip6_addr_isallnodes_iflocal(ip6addr) (((ip6addr)->addr[0] == PP_HTONL(0xff010000UL)) && \ ((ip6addr)->addr[1] == 0UL) && \ ((ip6addr)->addr[2] == 0UL) && \ @@ -249,9 +231,11 @@ Little-endian version, stored in network order (no htonl). */ #define IP6_ADDR_TENTATIVE_5 0x0d /* 5 probes sent */ #define IP6_ADDR_TENTATIVE_6 0x0e /* 6 probes sent */ #define IP6_ADDR_TENTATIVE_7 0x0f /* 7 probes sent */ -#define IP6_ADDR_VALID 0x10 +#define IP6_ADDR_VALID 0x10 /* This bit marks an address as valid (preferred or deprecated) */ #define IP6_ADDR_PREFERRED 0x30 -#define IP6_ADDR_DEPRECATED 0x50 +#define IP6_ADDR_DEPRECATED 0x10 /* Same as VALID (valid but not preferred) */ + +#define IP6_ADDR_TENTATIVE_COUNT_MASK 0x07 /* 1-7 probes sent */ #define ip6_addr_isinvalid(addr_state) (addr_state == IP6_ADDR_INVALID) #define ip6_addr_istentative(addr_state) (addr_state & IP6_ADDR_TENTATIVE) @@ -264,14 +248,14 @@ Little-endian version, stored in network order (no htonl). */ a, b, c, d, e, f, g, h)) #define ip6_addr_debug_print(debug, ipaddr) \ ip6_addr_debug_print_parts(debug, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK1(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK2(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK3(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK4(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK5(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK6(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK7(ipaddr) : 0, \ - (ipaddr) != NULL ? IP6_ADDR_BLOCK8(ipaddr) : 0) + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK1(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK2(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK3(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK4(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK5(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK6(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK7(ipaddr) : 0), \ + (u16_t)((ipaddr) != NULL ? IP6_ADDR_BLOCK8(ipaddr) : 0)) #define ip6_addr_debug_print_val(debug, ipaddr) \ ip6_addr_debug_print_parts(debug, \ IP6_ADDR_BLOCK1(&(ipaddr)), \ diff --git a/tools/sdk/include/lwip/lwip/ip6_frag.h b/tools/sdk/include/lwip/lwip/ip6_frag.h index 16336e58..6be27473 100644 --- a/tools/sdk/include/lwip/lwip/ip6_frag.h +++ b/tools/sdk/include/lwip/lwip/ip6_frag.h @@ -61,7 +61,7 @@ extern "C" { #define IPV6_FRAG_COPYHEADER 0 #endif -/* The IPv6 reassembly timer interval in milliseconds. */ +/** The IPv6 reassembly timer interval in milliseconds. */ #define IP6_REASS_TMR_INTERVAL 1000 /* Copy the complete header of the first fragment to struct ip6_reassdata @@ -74,7 +74,7 @@ extern "C" { #define IPV6_FRAG_HDRREF(hdr) (hdr) #endif /* IPV6_FRAG_COPYHEADER */ -/* IPv6 reassembly helper struct. +/** IPv6 reassembly helper struct. * This is exported because memp needs to know the size. */ struct ip6_reassdata { @@ -89,17 +89,17 @@ struct ip6_reassdata { #define ip6_reass_init() /* Compatibility define */ void ip6_reass_tmr(void); -struct pbuf * ip6_reass(struct pbuf *p); +struct pbuf *ip6_reass(struct pbuf *p); #endif /* LWIP_IPV6 && LWIP_IPV6_REASS */ #if LWIP_IPV6 && LWIP_IPV6_FRAG /* don't build if not configured for use in lwipopts.h */ +#ifndef LWIP_PBUF_CUSTOM_REF_DEFINED +#define LWIP_PBUF_CUSTOM_REF_DEFINED /** A custom pbuf that holds a reference to another pbuf, which is freed * when this custom pbuf is freed. This is used to create a custom PBUF_REF * that points into the original pbuf. */ -#ifndef LWIP_PBUF_CUSTOM_REF_DEFINED -#define LWIP_PBUF_CUSTOM_REF_DEFINED struct pbuf_custom_ref { /** 'base class' */ struct pbuf_custom pc; diff --git a/tools/sdk/include/lwip/lwip/ip_addr.h b/tools/sdk/include/lwip/lwip/ip_addr.h index 74897a9e..ca09ed39 100644 --- a/tools/sdk/include/lwip/lwip/ip_addr.h +++ b/tools/sdk/include/lwip/lwip/ip_addr.h @@ -1,3 +1,8 @@ +/** + * @file + * IP address API (common IPv4 and IPv6) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -29,8 +34,8 @@ * Author: Adam Dunkels * */ -#ifndef LWIP_HDR_IP_ADDR_H__ -#define LWIP_HDR_IP_ADDR_H__ +#ifndef LWIP_HDR_IP_ADDR_H +#define LWIP_HDR_IP_ADDR_H #include "lwip/opt.h" #include "lwip/def.h" @@ -42,36 +47,63 @@ extern "C" { #endif -/** These are the values for ip_addr_t.type */ -#define IPADDR_TYPE_V4 0U -#define IPADDR_TYPE_V6 6U -#define IPADDR_TYPE_ANY 46U +/** @ingroup ipaddr + * IP address types for use in ip_addr_t.type member. + * @see tcp_new_ip_type(), udp_new_ip_type(), raw_new_ip_type(). + */ +enum lwip_ip_addr_type { + /** IPv4 */ + IPADDR_TYPE_V4 = 0U, + /** IPv6 */ + IPADDR_TYPE_V6 = 6U, + /** IPv4+IPv6 ("dual-stack") */ + IPADDR_TYPE_ANY = 46U +}; #if LWIP_IPV4 && LWIP_IPV6 -/** A union struct for both IP version's addresses. +/** + * @ingroup ipaddr + * A union struct for both IP version's addresses. * ATTENTION: watch out for its size when adding IPv6 address scope! */ -typedef struct _ip_addr { +typedef struct ip_addr { union { ip6_addr_t ip6; ip4_addr_t ip4; } u_addr; + /** @ref lwip_ip_addr_type */ u8_t type; } ip_addr_t; extern const ip_addr_t ip_addr_any_type; +/** @ingroup ip4addr */ #define IPADDR4_INIT(u32val) { { { { u32val, 0ul, 0ul, 0ul } } }, IPADDR_TYPE_V4 } +/** @ingroup ip4addr */ +#define IPADDR4_INIT_BYTES(a,b,c,d) IPADDR4_INIT(PP_HTONL(LWIP_MAKEU32(a,b,c,d))) +/** @ingroup ip6addr */ #define IPADDR6_INIT(a, b, c, d) { { { { a, b, c, d } } }, IPADDR_TYPE_V6 } +/** @ingroup ip6addr */ +#define IPADDR6_INIT_HOST(a, b, c, d) { { { { PP_HTONL(a), PP_HTONL(b), PP_HTONL(c), PP_HTONL(d) } } }, IPADDR_TYPE_V6 } +/** @ingroup ipaddr */ #define IP_IS_ANY_TYPE_VAL(ipaddr) (IP_GET_TYPE(&ipaddr) == IPADDR_TYPE_ANY) +/** @ingroup ipaddr */ #define IPADDR_ANY_TYPE_INIT { { { { 0ul, 0ul, 0ul, 0ul } } }, IPADDR_TYPE_ANY } +/** @ingroup ip4addr */ +#define IP_IS_V4_VAL(ipaddr) (IP_GET_TYPE(&ipaddr) == IPADDR_TYPE_V4) +/** @ingroup ip6addr */ #define IP_IS_V6_VAL(ipaddr) (IP_GET_TYPE(&ipaddr) == IPADDR_TYPE_V6) +/** @ingroup ip4addr */ +#define IP_IS_V4(ipaddr) (((ipaddr) == NULL) || IP_IS_V4_VAL(*(ipaddr))) +/** @ingroup ip6addr */ #define IP_IS_V6(ipaddr) (((ipaddr) != NULL) && IP_IS_V6_VAL(*(ipaddr))) +#if ESP_LWIP #define IP_V6_EQ_PART(ipaddr, WORD, VAL) (ip_2_ip6(ipaddr)->addr[WORD] == htonl(VAL)) #define IP_IS_V4MAPPEDV6(ipaddr) (IP_IS_V6(ipaddr) && IP_V6_EQ_PART(ipaddr, 0, 0) && IP_V6_EQ_PART(ipaddr, 1, 0) && IP_V6_EQ_PART(ipaddr, 2, 0x0000FFFF)) +#endif #define IP_SET_TYPE_VAL(ipaddr, iptype) do { (ipaddr).type = (iptype); }while(0) #define IP_SET_TYPE(ipaddr, iptype) do { if((ipaddr) != NULL) { IP_SET_TYPE_VAL(*(ipaddr), iptype); }}while(0) @@ -80,71 +112,100 @@ extern const ip_addr_t ip_addr_any_type; #define IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr) (IP_GET_TYPE(&pcb->local_ip) == IP_GET_TYPE(ipaddr)) #define IP_ADDR_PCB_VERSION_MATCH(pcb, ipaddr) (IP_IS_ANY_TYPE_VAL(pcb->local_ip) || IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ipaddr)) -/* Convert generic ip address to specific protocol version */ +/** @ingroup ip6addr + * Convert generic ip address to specific protocol version + */ #define ip_2_ip6(ipaddr) (&((ipaddr)->u_addr.ip6)) +/** @ingroup ip4addr + * Convert generic ip address to specific protocol version + */ #define ip_2_ip4(ipaddr) (&((ipaddr)->u_addr.ip4)) +/** @ingroup ip4addr */ #define IP_ADDR4(ipaddr,a,b,c,d) do { IP4_ADDR(ip_2_ip4(ipaddr),a,b,c,d); \ IP_SET_TYPE_VAL(*(ipaddr), IPADDR_TYPE_V4); } while(0) +/** @ingroup ip6addr */ #define IP_ADDR6(ipaddr,i0,i1,i2,i3) do { IP6_ADDR(ip_2_ip6(ipaddr),i0,i1,i2,i3); \ IP_SET_TYPE_VAL(*(ipaddr), IPADDR_TYPE_V6); } while(0) +/** @ingroup ip6addr */ +#define IP_ADDR6_HOST(ipaddr,i0,i1,i2,i3) IP_ADDR6(ipaddr,PP_HTONL(i0),PP_HTONL(i1),PP_HTONL(i2),PP_HTONL(i3)) +/** @ingroup ipaddr */ #define ip_addr_copy(dest, src) do{ IP_SET_TYPE_VAL(dest, IP_GET_TYPE(&src)); if(IP_IS_V6_VAL(src)){ \ ip6_addr_copy(*ip_2_ip6(&(dest)), *ip_2_ip6(&(src))); }else{ \ ip4_addr_copy(*ip_2_ip4(&(dest)), *ip_2_ip4(&(src))); }}while(0) +/** @ingroup ip6addr */ #define ip_addr_copy_from_ip6(dest, src) do{ \ ip6_addr_copy(*ip_2_ip6(&(dest)), src); IP_SET_TYPE_VAL(dest, IPADDR_TYPE_V6); }while(0) +/** @ingroup ip4addr */ #define ip_addr_copy_from_ip4(dest, src) do{ \ ip4_addr_copy(*ip_2_ip4(&(dest)), src); IP_SET_TYPE_VAL(dest, IPADDR_TYPE_V4); }while(0) +/** @ingroup ip4addr */ #define ip_addr_set_ip4_u32(ipaddr, val) do{if(ipaddr){ip4_addr_set_u32(ip_2_ip4(ipaddr), val); \ IP_SET_TYPE(ipaddr, IPADDR_TYPE_V4); }}while(0) -#define ip_addr_get_ip4_u32(ipaddr) (((ipaddr) && !IP_IS_V6(ipaddr)) ? \ +/** @ingroup ip4addr */ +#define ip_addr_get_ip4_u32(ipaddr) (((ipaddr) && IP_IS_V4(ipaddr)) ? \ ip4_addr_get_u32(ip_2_ip4(ipaddr)) : 0) - +/** @ingroup ipaddr */ #define ip_addr_set(dest, src) do{ IP_SET_TYPE(dest, IP_GET_TYPE(src)); if(IP_IS_V6(src)){ \ ip6_addr_set(ip_2_ip6(dest), ip_2_ip6(src)); }else{ \ ip4_addr_set(ip_2_ip4(dest), ip_2_ip4(src)); }}while(0) - +/** @ingroup ipaddr */ #define ip_addr_set_ipaddr(dest, src) ip_addr_set(dest, src) +/** @ingroup ipaddr */ #define ip_addr_set_zero(ipaddr) do{ \ ip6_addr_set_zero(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, 0); }while(0) +/** @ingroup ip5addr */ #define ip_addr_set_zero_ip4(ipaddr) do{ \ ip6_addr_set_zero(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V4); }while(0) +/** @ingroup ip6addr */ #define ip_addr_set_zero_ip6(ipaddr) do{ \ ip6_addr_set_zero(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V6); }while(0) +/** @ingroup ipaddr */ #define ip_addr_set_any(is_ipv6, ipaddr) do{if(is_ipv6){ \ ip6_addr_set_any(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V6); }else{ \ ip4_addr_set_any(ip_2_ip4(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V4); }}while(0) +/** @ingroup ipaddr */ #define ip_addr_set_loopback(is_ipv6, ipaddr) do{if(is_ipv6){ \ ip6_addr_set_loopback(ip_2_ip6(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V6); }else{ \ ip4_addr_set_loopback(ip_2_ip4(ipaddr)); IP_SET_TYPE(ipaddr, IPADDR_TYPE_V4); }}while(0) +/** @ingroup ipaddr */ #define ip_addr_set_hton(dest, src) do{if(IP_IS_V6(src)){ \ ip6_addr_set_hton(ip_2_ip6(ipaddr), (src)); IP_SET_TYPE(dest, IPADDR_TYPE_V6); }else{ \ ip4_addr_set_hton(ip_2_ip4(ipaddr), (src)); IP_SET_TYPE(dest, IPADDR_TYPE_V4); }}while(0) +/** @ingroup ipaddr */ #define ip_addr_get_network(target, host, netmask) do{if(IP_IS_V6(host)){ \ ip4_addr_set_zero(ip_2_ip4(target)); IP_SET_TYPE(target, IPADDR_TYPE_V6); } else { \ ip4_addr_get_network(ip_2_ip4(target), ip_2_ip4(host), ip_2_ip4(netmask)); IP_SET_TYPE(target, IPADDR_TYPE_V4); }}while(0) +/** @ingroup ipaddr */ #define ip_addr_netcmp(addr1, addr2, mask) ((IP_IS_V6(addr1) && IP_IS_V6(addr2)) ? \ 0 : \ ip4_addr_netcmp(ip_2_ip4(addr1), ip_2_ip4(addr2), mask)) +/** @ingroup ipaddr */ #define ip_addr_cmp(addr1, addr2) ((IP_GET_TYPE(addr1) != IP_GET_TYPE(addr2)) ? 0 : (IP_IS_V6_VAL(*(addr1)) ? \ ip6_addr_cmp(ip_2_ip6(addr1), ip_2_ip6(addr2)) : \ ip4_addr_cmp(ip_2_ip4(addr1), ip_2_ip4(addr2)))) +/** @ingroup ipaddr */ #define ip_addr_isany(ipaddr) ((IP_IS_V6(ipaddr)) ? \ ip6_addr_isany(ip_2_ip6(ipaddr)) : \ ip4_addr_isany(ip_2_ip4(ipaddr))) +/** @ingroup ipaddr */ #define ip_addr_isany_val(ipaddr) ((IP_IS_V6_VAL(ipaddr)) ? \ ip6_addr_isany_val(*ip_2_ip6(&(ipaddr))) : \ ip4_addr_isany_val(*ip_2_ip4(&(ipaddr)))) +/** @ingroup ipaddr */ #define ip_addr_isbroadcast(ipaddr, netif) ((IP_IS_V6(ipaddr)) ? \ 0 : \ ip4_addr_isbroadcast(ip_2_ip4(ipaddr), netif)) +/** @ingroup ipaddr */ #define ip_addr_ismulticast(ipaddr) ((IP_IS_V6(ipaddr)) ? \ ip6_addr_ismulticast(ip_2_ip6(ipaddr)) : \ ip4_addr_ismulticast(ip_2_ip4(ipaddr))) +/** @ingroup ipaddr */ #define ip_addr_isloopback(ipaddr) ((IP_IS_V6(ipaddr)) ? \ ip6_addr_isloopback(ip_2_ip6(ipaddr)) : \ ip4_addr_isloopback(ip_2_ip4(ipaddr))) +/** @ingroup ipaddr */ #define ip_addr_islinklocal(ipaddr) ((IP_IS_V6(ipaddr)) ? \ ip6_addr_islinklocal(ip_2_ip6(ipaddr)) : \ ip4_addr_islinklocal(ip_2_ip4(ipaddr))) @@ -154,32 +215,29 @@ extern const ip_addr_t ip_addr_any_type; #define ip_addr_debug_print_val(debug, ipaddr) do { if(IP_IS_V6_VAL(ipaddr)) { \ ip6_addr_debug_print_val(debug, *ip_2_ip6(&(ipaddr))); } else { \ ip4_addr_debug_print_val(debug, *ip_2_ip4(&(ipaddr))); }}while(0) +/** @ingroup ipaddr */ #define ipaddr_ntoa(addr) (((addr) == NULL) ? "NULL" : \ ((IP_IS_V6(addr)) ? ip6addr_ntoa(ip_2_ip6(addr)) : ip4addr_ntoa(ip_2_ip4(addr)))) +/** @ingroup ipaddr */ #define ipaddr_ntoa_r(addr, buf, buflen) (((addr) == NULL) ? "NULL" : \ ((IP_IS_V6(addr)) ? ip6addr_ntoa_r(ip_2_ip6(addr), buf, buflen) : ip4addr_ntoa_r(ip_2_ip4(addr), buf, buflen))) int ipaddr_aton(const char *cp, ip_addr_t *addr); -/* Map an IPv4 ip_addr into an IPV6 ip_addr, using format - defined in RFC4291 2.5.5.2. +/** @ingroup ipaddr */ +#define IPADDR_STRLEN_MAX IP6ADDR_STRLEN_MAX - Safe to call when dest==src. -*/ -#define ip_addr_make_ip4_mapped_ip6(dest, src) do { \ - u32_t tmp = ip_2_ip4(src)->addr; \ - IP_ADDR6((dest), 0x0, 0x0, htonl(0x0000FFFF), tmp); \ - } while(0) +/** @ingroup ipaddr */ +#define ip4_2_ipv4_mapped_ipv6(ip6addr, ip4addr) do { \ + (ip6addr)->addr[3] = (ip4addr)->addr; \ + (ip6addr)->addr[2] = PP_HTONL(0x0000FFFFUL); \ + (ip6addr)->addr[1] = 0; \ + (ip6addr)->addr[0] = 0; } while(0); -/* Convert an IPv4 mapped V6 address to an IPV4 address. +/** @ingroup ipaddr */ +#define unmap_ipv4_mapped_ipv6(ip4addr, ip6addr) \ + (ip4addr)->addr = (ip6addr)->addr[3]; - Check IP_IS_V4MAPPEDV6(src) before using this. - - Safe to call when dest == src. -*/ -#define ip_addr_ip4_from_mapped_ip6(dest, src) do { \ - ip_2_ip4(dest)->addr = ip_2_ip6(src)->addr[3]; \ - IP_SET_TYPE(dest, IPADDR_TYPE_V4); \ - } while(0) +#define IP46_ADDR_ANY(type) (((type) == IPADDR_TYPE_V6)? IP6_ADDR_ANY : IP4_ADDR_ANY) #else /* LWIP_IPV4 && LWIP_IPV6 */ @@ -190,7 +248,10 @@ int ipaddr_aton(const char *cp, ip_addr_t *addr); typedef ip4_addr_t ip_addr_t; #define IPADDR4_INIT(u32val) { u32val } +#define IPADDR4_INIT_BYTES(a,b,c,d) IPADDR4_INIT(PP_HTONL(LWIP_MAKEU32(a,b,c,d))) +#define IP_IS_V4_VAL(ipaddr) 1 #define IP_IS_V6_VAL(ipaddr) 0 +#define IP_IS_V4(ipaddr) 1 #define IP_IS_V6(ipaddr) 0 #define IP_IS_ANY_TYPE_VAL(ipaddr) 0 #define IP_SET_TYPE_VAL(ipaddr, iptype) @@ -225,11 +286,18 @@ typedef ip4_addr_t ip_addr_t; #define ipaddr_ntoa_r(ipaddr, buf, buflen) ip4addr_ntoa_r(ipaddr, buf, buflen) #define ipaddr_aton(cp, addr) ip4addr_aton(cp, addr) +#define IPADDR_STRLEN_MAX IP4ADDR_STRLEN_MAX + +#define IP46_ADDR_ANY(type) (IP4_ADDR_ANY) + #else /* LWIP_IPV4 */ typedef ip6_addr_t ip_addr_t; #define IPADDR6_INIT(a, b, c, d) { { a, b, c, d } } +#define IPADDR6_INIT_HOST(a, b, c, d) { { PP_HTONL(a), PP_HTONL(b), PP_HTONL(c), PP_HTONL(d) } } +#define IP_IS_V4_VAL(ipaddr) 0 #define IP_IS_V6_VAL(ipaddr) 1 +#define IP_IS_V4(ipaddr) 0 #define IP_IS_V6(ipaddr) 1 #define IP_IS_ANY_TYPE_VAL(ipaddr) 0 #define IP_SET_TYPE_VAL(ipaddr, iptype) @@ -237,6 +305,7 @@ typedef ip6_addr_t ip_addr_t; #define IP_GET_TYPE(ipaddr) IPADDR_TYPE_V6 #define ip_2_ip6(ipaddr) (ipaddr) #define IP_ADDR6(ipaddr,i0,i1,i2,i3) IP6_ADDR(ipaddr,i0,i1,i2,i3) +#define IP_ADDR6_HOST(ipaddr,i0,i1,i2,i3) IP_ADDR6(ipaddr,PP_HTONL(i0),PP_HTONL(i1),PP_HTONL(i2),PP_HTONL(i3)) #define ip_addr_copy(dest, src) ip6_addr_copy(dest, src) #define ip_addr_copy_from_ip6(dest, src) ip6_addr_copy(dest, src) @@ -262,6 +331,10 @@ typedef ip6_addr_t ip_addr_t; #define ipaddr_ntoa_r(ipaddr, buf, buflen) ip6addr_ntoa_r(ipaddr, buf, buflen) #define ipaddr_aton(cp, addr) ip6addr_aton(cp, addr) +#define IPADDR_STRLEN_MAX IP6ADDR_STRLEN_MAX + +#define IP46_ADDR_ANY(type) (IP6_ADDR_ANY) + #endif /* LWIP_IPV4 */ #endif /* LWIP_IPV4 && LWIP_IPV6 */ @@ -270,15 +343,33 @@ typedef ip6_addr_t ip_addr_t; extern const ip_addr_t ip_addr_any; extern const ip_addr_t ip_addr_broadcast; -/** IP_ADDR_ can be used as a fixed/const ip_addr_t - * for the IPv4 wildcard and the broadcast address +/** + * @ingroup ip4addr + * Can be used as a fixed/const ip_addr_t + * for the IP wildcard. + * Defined to @ref IP4_ADDR_ANY when IPv4 is enabled. + * Defined to @ref IP6_ADDR_ANY in IPv6 only systems. + * Use this if you can handle IPv4 _AND_ IPv6 addresses. + * Use @ref IP4_ADDR_ANY or @ref IP6_ADDR_ANY when the IP + * type matters. */ -#define IP_ADDR_ANY (&ip_addr_any) +#define IP_ADDR_ANY IP4_ADDR_ANY +/** + * @ingroup ip4addr + * Can be used as a fixed/const ip_addr_t + * for the IPv4 wildcard and the broadcast address + */ +#define IP4_ADDR_ANY (&ip_addr_any) +/** + * @ingroup ip4addr + * Can be used as a fixed/const ip4_addr_t + * for the wildcard and the broadcast address + */ +#define IP4_ADDR_ANY4 (ip_2_ip4(&ip_addr_any)) + +/** @ingroup ip4addr */ #define IP_ADDR_BROADCAST (&ip_addr_broadcast) -/** IP4_ADDR_ can be used as a fixed/const ip4_addr_t - * for the wildcard and the broadcast address - */ -#define IP4_ADDR_ANY (ip_2_ip4(&ip_addr_any)) +/** @ingroup ip4addr */ #define IP4_ADDR_BROADCAST (ip_2_ip4(&ip_addr_broadcast)) #endif /* LWIP_IPV4*/ @@ -287,23 +378,28 @@ extern const ip_addr_t ip_addr_broadcast; extern const ip_addr_t ip6_addr_any; -/** IP6_ADDR_ANY can be used as a fixed ip_addr_t - * for the IPv6 wildcard address +/** + * @ingroup ip6addr + * IP6_ADDR_ANY can be used as a fixed ip_addr_t + * for the IPv6 wildcard address */ #define IP6_ADDR_ANY (&ip6_addr_any) -/** IP6_ADDR_ANY6 can be used as a fixed ip6_addr_t - * for the IPv6 wildcard address +/** + * @ingroup ip6addr + * IP6_ADDR_ANY6 can be used as a fixed ip6_addr_t + * for the IPv6 wildcard address */ #define IP6_ADDR_ANY6 (ip_2_ip6(&ip6_addr_any)) #if !LWIP_IPV4 -/** Just a little upgrade-helper for IPv6-only configurations: */ +/** IPv6-only configurations */ #define IP_ADDR_ANY IP6_ADDR_ANY #endif /* !LWIP_IPV4 */ #endif #if LWIP_IPV4 && LWIP_IPV6 +/** @ingroup ipaddr */ #define IP_ANY_TYPE (&ip_addr_any_type) #else #define IP_ANY_TYPE IP_ADDR_ANY @@ -313,4 +409,4 @@ extern const ip_addr_t ip6_addr_any; } #endif -#endif /* LWIP_HDR_IP_ADDR_H__ */ +#endif /* LWIP_HDR_IP_ADDR_H */ diff --git a/tools/sdk/include/lwip/lwip/mem.h b/tools/sdk/include/lwip/lwip/mem.h index 966d6bbb..73540f7e 100644 --- a/tools/sdk/include/lwip/lwip/mem.h +++ b/tools/sdk/include/lwip/lwip/mem.h @@ -1,3 +1,8 @@ +/** + * @file + * Heap API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -40,20 +45,17 @@ extern "C" { #if MEM_LIBC_MALLOC -#include /* for size_t */ +#include "lwip/arch.h" typedef size_t mem_size_t; #define MEM_SIZE_F SZT_F -/* aliases for C library malloc() */ -#define mem_init() -/* in case C library malloc() needs extra protection, - * allow these defines to be overridden. - */ +#elif MEM_USE_POOLS -#ifndef mem_free -#define mem_free free -#endif +typedef u16_t mem_size_t; +#define MEM_SIZE_F U16_F + +#if ESP_LWIP /** * lwip_malloc: if CONFIG_ALLOC_MEMORY_IN_SPIRAM_FIRST is enabled, Try to * allocate memory for lwip in SPIRAM firstly. If failed, try to allocate @@ -66,21 +68,10 @@ typedef size_t mem_size_t; #ifndef mem_calloc #define mem_calloc(n, size) heap_caps_calloc_prefer(n, size, 2, MALLOC_CAP_DEFAULT|MALLOC_CAP_SPIRAM, MALLOC_CAP_DEFAULT|MALLOC_CAP_INTERNAL) #endif -#else -#ifndef mem_malloc -#define mem_malloc malloc -#endif -#ifndef mem_calloc -#define mem_calloc calloc #endif #endif -/* Since there is no C library allocation function to shrink memory without - moving it, define this to nothing. */ -#ifndef mem_trim -#define mem_trim(mem, size) (mem) -#endif -#else /* MEM_LIBC_MALLOC */ +#else /* MEM_SIZE would have to be aligned, but using 64000 here instead of * 65535 leaves some room for alignment... @@ -92,45 +83,13 @@ typedef u32_t mem_size_t; typedef u16_t mem_size_t; #define MEM_SIZE_F U16_F #endif /* MEM_SIZE > 64000 */ +#endif -#if MEM_USE_POOLS -/** mem_init is not used when using pools instead of a heap */ -#define mem_init() -/** mem_trim is not used when using pools instead of a heap: - we can't free part of a pool element and don't want to copy the rest */ -#define mem_trim(mem, size) (mem) -#else /* MEM_USE_POOLS */ -/* lwIP alternative malloc */ void mem_init(void); void *mem_trim(void *mem, mem_size_t size); -#endif /* MEM_USE_POOLS */ void *mem_malloc(mem_size_t size); void *mem_calloc(mem_size_t count, mem_size_t size); void mem_free(void *mem); -#endif /* MEM_LIBC_MALLOC */ - -/** Calculate memory size for an aligned buffer - returns the next highest - * multiple of MEM_ALIGNMENT (e.g. LWIP_MEM_ALIGN_SIZE(3) and - * LWIP_MEM_ALIGN_SIZE(4) will both yield 4 for MEM_ALIGNMENT == 4). - */ -#ifndef LWIP_MEM_ALIGN_SIZE -#define LWIP_MEM_ALIGN_SIZE(size) (((size) + MEM_ALIGNMENT - 1U) & ~(MEM_ALIGNMENT-1U)) -#endif - -/** Calculate safe memory size for an aligned buffer when using an unaligned - * type as storage. This includes a safety-margin on (MEM_ALIGNMENT - 1) at the - * start (e.g. if buffer is u8_t[] and actual data will be u32_t*) - */ -#ifndef LWIP_MEM_ALIGN_BUFFER -#define LWIP_MEM_ALIGN_BUFFER(size) (((size) + MEM_ALIGNMENT - 1U)) -#endif - -/** Align a memory pointer to the alignment defined by MEM_ALIGNMENT - * so that ADDR % MEM_ALIGNMENT == 0 - */ -#ifndef LWIP_MEM_ALIGN -#define LWIP_MEM_ALIGN(addr) ((void *)(((mem_ptr_t)(addr) + MEM_ALIGNMENT - 1) & ~(mem_ptr_t)(MEM_ALIGNMENT-1))) -#endif #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/memp.h b/tools/sdk/include/lwip/lwip/memp.h index abb8e57f..562cd05b 100644 --- a/tools/sdk/include/lwip/lwip/memp.h +++ b/tools/sdk/include/lwip/lwip/memp.h @@ -1,3 +1,8 @@ +/** + * @file + * Memory pool API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -33,6 +38,8 @@ #ifndef LWIP_HDR_MEMP_H #define LWIP_HDR_MEMP_H +#include "lwip/opt.h" + #ifdef __cplusplus extern "C" { #endif @@ -41,7 +48,7 @@ extern "C" { #define LWIP_MEMPOOL(name,num,size,desc) #include "lwip/priv/memp_std.h" -/* Create the list of all memory pools managed by memp. MEMP_MAX represents a NULL pool at the end */ +/** Create the list of all memory pools managed by memp. MEMP_MAX represents a NULL pool at the end */ typedef enum { #define LWIP_MEMPOOL(name,num,size,desc) MEMP_##name, #include "lwip/priv/memp_std.h" @@ -49,8 +56,32 @@ typedef enum { } memp_t; #include "lwip/priv/memp_priv.h" +#include "lwip/stats.h" -/* Private mempools example: +extern const struct memp_desc* const memp_pools[MEMP_MAX]; + +/** + * @ingroup mempool + * Declare prototype for private memory pool if it is used in multiple files + */ +#define LWIP_MEMPOOL_PROTOTYPE(name) extern const struct memp_desc memp_ ## name + +#if MEMP_MEM_MALLOC + +#define LWIP_MEMPOOL_DECLARE(name,num,size,desc) \ + LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(memp_stats_ ## name) \ + const struct memp_desc memp_ ## name = { \ + DECLARE_LWIP_MEMPOOL_DESC(desc) \ + LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(memp_stats_ ## name) \ + LWIP_MEM_ALIGN_SIZE(size) \ + }; + +#else /* MEMP_MEM_MALLOC */ + +/** + * @ingroup mempool + * Declare a private memory pool + * Private mempools example: * .h: only when pool is used in multiple .c files: LWIP_MEMPOOL_PROTOTYPE(my_private_pool); * .c: * - in global variables section: LWIP_MEMPOOL_DECLARE(my_private_pool, 10, sizeof(foo), "Some description") @@ -61,74 +92,50 @@ typedef enum { * To relocate a pool, declare it as extern in cc.h. Example for GCC: * extern u8_t __attribute__((section(".onchip_mem"))) memp_memory_my_private_pool[]; */ - -extern const struct memp_desc* const memp_pools[MEMP_MAX]; - -#define LWIP_MEMPOOL_PROTOTYPE(name) extern const struct memp_desc memp_ ## name - -#if MEMP_MEM_MALLOC - -#include "lwip/mem.h" - -#define memp_init() -#if ESP_STATS_MEM -static inline void* memp_malloc(int type) -{ - ESP_CNT_MEM_MALLOC_INC(type); - return mem_malloc(memp_pools[type]->size); -} - -static inline void memp_free(int type, void *mem) -{ - ESP_CNT_MEM_FREE_INC(type); - mem_free(mem); -} - -//#define memp_malloc(type) mem_malloc(memp_pools[type]->size); ESP_CNT_MEM_MALLOC_INC(type) -//#define memp_free(type, mem) mem_free(mem); ESP_CNT_MEM_FREE_INC(type) -#else -#define memp_malloc(type) mem_malloc(memp_pools[type]->size) -#define memp_free(type, mem) mem_free(mem) -#endif - #define LWIP_MEMPOOL_DECLARE(name,num,size,desc) \ - const struct memp_desc memp_ ## name = { \ - LWIP_MEM_ALIGN_SIZE(size) \ - }; - -#define LWIP_MEMPOOL_INIT(name) -#define LWIP_MEMPOOL_ALLOC(name) mem_malloc(memp_ ## name.size) -#define LWIP_MEMPOOL_FREE(name, x) mem_free(x) - -#else /* MEMP_MEM_MALLOC */ - -#define LWIP_MEMPOOL_DECLARE(name,num,size,desc) u8_t memp_memory_ ## name ## _base \ - [((num) * (MEMP_SIZE + MEMP_ALIGN_SIZE(size)))]; \ + LWIP_DECLARE_MEMORY_ALIGNED(memp_memory_ ## name ## _base, ((num) * (MEMP_SIZE + MEMP_ALIGN_SIZE(size)))); \ + \ + LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(memp_stats_ ## name) \ \ static struct memp *memp_tab_ ## name; \ \ const struct memp_desc memp_ ## name = { \ + DECLARE_LWIP_MEMPOOL_DESC(desc) \ + LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(memp_stats_ ## name) \ LWIP_MEM_ALIGN_SIZE(size), \ (num), \ - DECLARE_LWIP_MEMPOOL_DESC(desc) \ memp_memory_ ## name ## _base, \ &memp_tab_ ## name \ }; +#endif /* MEMP_MEM_MALLOC */ + +/** + * @ingroup mempool + * Initialize a private memory pool + */ #define LWIP_MEMPOOL_INIT(name) memp_init_pool(&memp_ ## name) +/** + * @ingroup mempool + * Allocate from a private memory pool + */ #define LWIP_MEMPOOL_ALLOC(name) memp_malloc_pool(&memp_ ## name) +/** + * @ingroup mempool + * Free element from a private memory pool + */ #define LWIP_MEMPOOL_FREE(name, x) memp_free_pool(&memp_ ## name, (x)) #if MEM_USE_POOLS -/** This structure is used to save the pool one element came from. */ +/** This structure is used to save the pool one element came from. + * This has to be defined here as it is required for pool size calculation. */ struct memp_malloc_helper { memp_t poolnr; -#if MEMP_OVERFLOW_CHECK +#if MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS) u16_t size; -#endif /* MEMP_OVERFLOW_CHECK */ +#endif /* MEMP_OVERFLOW_CHECK || (LWIP_STATS && MEM_STATS) */ }; - #endif /* MEM_USE_POOLS */ void memp_init(void); @@ -141,8 +148,6 @@ void *memp_malloc(memp_t type); #endif void memp_free(memp_t type, void *mem); -#endif /* MEMP_MEM_MALLOC */ - #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/mld6.h b/tools/sdk/include/lwip/lwip/mld6.h index a54dd49e..7fa0797f 100644 --- a/tools/sdk/include/lwip/lwip/mld6.h +++ b/tools/sdk/include/lwip/lwip/mld6.h @@ -50,16 +50,14 @@ #include "lwip/pbuf.h" #include "lwip/netif.h" - #ifdef __cplusplus extern "C" { #endif +/** MLD group */ struct mld_group { /** next link */ struct mld_group *next; - /** interface on which the group is active */ - struct netif *netif; /** multicast address */ ip6_addr_t group_address; /** signifies we were the last person to report */ @@ -72,33 +70,8 @@ struct mld_group { u8_t use; }; -/** Multicast listener report/query/done message header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct mld_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u16_t max_resp_delay); - PACK_STRUCT_FIELD(u16_t reserved); - PACK_STRUCT_FLD_S(ip6_addr_p_t multicast_address); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - #define MLD6_TMR_INTERVAL 100 /* Milliseconds */ -/* MAC Filter Actions, these are passed to a netif's - * mld_mac_filter callback function. */ -#define MLD6_DEL_MAC_FILTER 0 -#define MLD6_ADD_MAC_FILTER 1 - - err_t mld6_stop(struct netif *netif); void mld6_report_groups(struct netif *netif); void mld6_tmr(void); @@ -109,6 +82,13 @@ err_t mld6_joingroup_netif(struct netif *netif, const ip6_addr_t *groupaddr); err_t mld6_leavegroup(const ip6_addr_t *srcaddr, const ip6_addr_t *groupaddr); err_t mld6_leavegroup_netif(struct netif *netif, const ip6_addr_t *groupaddr); +/** @ingroup mld6 + * Get list head of MLD6 groups for netif. + * Note: The allnodes group IP is NOT in the list, since it must always + * be received for correct IPv6 operation. + * @see @ref netif_set_mld_mac_filter() + */ +#define netif_mld6_data(netif) ((struct mld_group *)netif_get_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_MLD6)) #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/nd6.h b/tools/sdk/include/lwip/lwip/nd6.h index 27a4c813..d9fba970 100644 --- a/tools/sdk/include/lwip/lwip/nd6.h +++ b/tools/sdk/include/lwip/lwip/nd6.h @@ -48,314 +48,38 @@ #if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ -#include "lwip/pbuf.h" -#include "lwip/ip6.h" #include "lwip/ip6_addr.h" -#include "lwip/netif.h" - +#include "lwip/err.h" #ifdef __cplusplus extern "C" { #endif -/* Struct for tables. */ -struct nd6_neighbor_cache_entry { - ip6_addr_t next_hop_address; - struct netif * netif; - u8_t lladdr[NETIF_MAX_HWADDR_LEN]; - /*u32_t pmtu;*/ -#if LWIP_ND6_QUEUEING - /** Pointer to queue of pending outgoing packets on this entry. */ - struct nd6_q_entry *q; -#else /* LWIP_ND6_QUEUEING */ - /** Pointer to a single pending outgoing packet on this entry. */ - struct pbuf *q; -#endif /* LWIP_ND6_QUEUEING */ - u8_t state; - u8_t isrouter; - union { - u32_t reachable_time; - u32_t delay_time; - u32_t probes_sent; - u32_t stale_time; - } counter; -}; - -struct nd6_destination_cache_entry { - ip6_addr_t destination_addr; - ip6_addr_t next_hop_addr; - u16_t pmtu; - u32_t age; -}; - -struct nd6_prefix_list_entry { - ip6_addr_t prefix; - struct netif * netif; - u32_t invalidation_timer; -#if LWIP_IPV6_AUTOCONFIG - u8_t flags; -#define ND6_PREFIX_AUTOCONFIG_AUTONOMOUS 0x01 -#define ND6_PREFIX_AUTOCONFIG_ADDRESS_GENERATED 0x02 -#define ND6_PREFIX_AUTOCONFIG_ADDRESS_DUPLICATE 0x04 -#endif /* LWIP_IPV6_AUTOCONFIG */ -}; - -struct nd6_router_list_entry { - struct nd6_neighbor_cache_entry * neighbor_entry; - u32_t invalidation_timer; - u8_t flags; -}; - - -enum nd6_neighbor_cache_entry_state { - ND6_NO_ENTRY = 0, - ND6_INCOMPLETE, - ND6_REACHABLE, - ND6_STALE, - ND6_DELAY, - ND6_PROBE -}; - -#if LWIP_ND6_QUEUEING -/** struct for queueing outgoing packets for unknown address - * defined here to be accessed by memp.h - */ -struct nd6_q_entry { - struct nd6_q_entry *next; - struct pbuf *p; -}; -#endif /* LWIP_ND6_QUEUEING */ - -/** Neighbor solicitation message header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ns_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u32_t reserved); - PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Neighbor advertisement message header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct na_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FLD_8(u8_t flags); - PACK_STRUCT_FLD_8(u8_t reserved[3]); - PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif -#define ND6_FLAG_ROUTER (0x80) -#define ND6_FLAG_SOLICITED (0x40) -#define ND6_FLAG_OVERRIDE (0x20) - -/** Router solicitation message header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct rs_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u32_t reserved); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Router advertisement message header. */ -#define ND6_RA_FLAG_MANAGED_ADDR_CONFIG (0x80) -#define ND6_RA_FLAG_OTHER_CONFIG (0x40) -#define ND6_RA_FLAG_HOME_AGENT (0x20) -#define ND6_RA_PREFERENCE_MASK (0x18) -#define ND6_RA_PREFERENCE_HIGH (0x08) -#define ND6_RA_PREFERENCE_MEDIUM (0x00) -#define ND6_RA_PREFERENCE_LOW (0x18) -#define ND6_RA_PREFERENCE_DISABLED (0x10) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct ra_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FLD_8(u8_t current_hop_limit); - PACK_STRUCT_FLD_8(u8_t flags); - PACK_STRUCT_FIELD(u16_t router_lifetime); - PACK_STRUCT_FIELD(u32_t reachable_time); - PACK_STRUCT_FIELD(u32_t retrans_timer); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Redirect message header. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct redirect_header { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t code); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u32_t reserved); - PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); - PACK_STRUCT_FLD_S(ip6_addr_p_t destination_address); - /* Options follow. */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Link-layer address option. */ -#define ND6_OPTION_TYPE_SOURCE_LLADDR (0x01) -#define ND6_OPTION_TYPE_TARGET_LLADDR (0x02) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct lladdr_option { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t length); - PACK_STRUCT_FLD_8(u8_t addr[NETIF_MAX_HWADDR_LEN]); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Prefix information option. */ -#define ND6_OPTION_TYPE_PREFIX_INFO (0x03) -#define ND6_PREFIX_FLAG_ON_LINK (0x80) -#define ND6_PREFIX_FLAG_AUTONOMOUS (0x40) -#define ND6_PREFIX_FLAG_ROUTER_ADDRESS (0x20) -#define ND6_PREFIX_FLAG_SITE_PREFIX (0x10) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct prefix_option { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t length); - PACK_STRUCT_FLD_8(u8_t prefix_length); - PACK_STRUCT_FLD_8(u8_t flags); - PACK_STRUCT_FIELD(u32_t valid_lifetime); - PACK_STRUCT_FIELD(u32_t preferred_lifetime); - PACK_STRUCT_FLD_8(u8_t reserved2[3]); - PACK_STRUCT_FLD_8(u8_t site_prefix_length); - PACK_STRUCT_FLD_S(ip6_addr_p_t prefix); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Redirected header option. */ -#define ND6_OPTION_TYPE_REDIR_HDR (0x04) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct redirected_header_option { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t length); - PACK_STRUCT_FLD_8(u8_t reserved[6]); - /* Portion of redirected packet follows. */ - /* PACK_STRUCT_FLD_8(u8_t redirected[8]); */ -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** MTU option. */ -#define ND6_OPTION_TYPE_MTU (0x05) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct mtu_option { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t length); - PACK_STRUCT_FIELD(u16_t reserved); - PACK_STRUCT_FIELD(u32_t mtu); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -/** Route information option. */ -#define ND6_OPTION_TYPE_ROUTE_INFO (24) -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct route_option { - PACK_STRUCT_FLD_8(u8_t type); - PACK_STRUCT_FLD_8(u8_t length); - PACK_STRUCT_FLD_8(u8_t prefix_length); - PACK_STRUCT_FLD_8(u8_t preference); - PACK_STRUCT_FIELD(u32_t route_lifetime); - PACK_STRUCT_FLD_S(ip6_addr_p_t prefix); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - /** 1 second period */ #define ND6_TMR_INTERVAL 1000 -/* Router tables. */ -/* TODO make these static? and entries accessible through API? */ -extern struct nd6_neighbor_cache_entry neighbor_cache[]; -extern struct nd6_destination_cache_entry destination_cache[]; -extern struct nd6_prefix_list_entry prefix_list[]; -extern struct nd6_router_list_entry default_router_list[]; - -/* Default values, can be updated by a RA message. */ -extern u32_t reachable_time; -extern u32_t retrans_timer; +struct pbuf; +struct netif; void nd6_tmr(void); void nd6_input(struct pbuf *p, struct netif *inp); -s8_t nd6_get_next_hop_entry(const ip6_addr_t * ip6addr, struct netif * netif); -s8_t nd6_select_router(const ip6_addr_t * ip6addr, struct netif * netif); -u16_t nd6_get_destination_mtu(const ip6_addr_t * ip6addr, struct netif * netif); -err_t nd6_queue_packet(s8_t neighbor_index, struct pbuf * p); +void nd6_clear_destination_cache(void); +struct netif *nd6_find_route(const ip6_addr_t *ip6addr); +err_t nd6_get_next_hop_addr_or_queue(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr, const u8_t **hwaddrp); +u16_t nd6_get_destination_mtu(const ip6_addr_t *ip6addr, struct netif *netif); #if LWIP_ND6_TCP_REACHABILITY_HINTS -void nd6_reachability_hint(const ip6_addr_t * ip6addr); +void nd6_reachability_hint(const ip6_addr_t *ip6addr); #endif /* LWIP_ND6_TCP_REACHABILITY_HINTS */ +void nd6_cleanup_netif(struct netif *netif); +#if LWIP_IPV6_MLD +void nd6_adjust_mld_membership(struct netif *netif, s8_t addr_idx, u8_t new_state); +#endif /* LWIP_IPV6_MLD */ #if ESP_LWIP /** set nd6 callback when ipv6 addr state pref*/ void nd6_set_cb(struct netif *netif, void (*cb)(struct netif *netif, u8_t ip_index)); #endif + #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/netbuf.h b/tools/sdk/include/lwip/lwip/netbuf.h index 8875e12d..e6865f80 100644 --- a/tools/sdk/include/lwip/lwip/netbuf.h +++ b/tools/sdk/include/lwip/lwip/netbuf.h @@ -1,3 +1,8 @@ +/** + * @file + * netbuf API (for netconn API) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -51,6 +56,7 @@ extern "C" { /** This netbuf includes a checksum */ #define NETBUF_FLAG_CHKSUM 0x02 +/** "Network buffer" - contains data and addressing info */ struct netbuf { struct pbuf *p, *ptr; ip_addr_t addr; diff --git a/tools/sdk/include/lwip/lwip/netdb.h b/tools/sdk/include/lwip/lwip/netdb.h index 144a6e0b..e0b07acc 100644 --- a/tools/sdk/include/lwip/lwip/netdb.h +++ b/tools/sdk/include/lwip/lwip/netdb.h @@ -1,3 +1,8 @@ +/** + * @file + * NETDB API (sockets) + */ + /* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -33,8 +38,7 @@ #if LWIP_DNS && LWIP_SOCKET -#include /* for size_t */ - +#include "lwip/arch.h" #include "lwip/inet.h" #include "lwip/sockets.h" @@ -125,12 +129,47 @@ int lwip_getaddrinfo(const char *nodename, struct addrinfo **res); #if LWIP_COMPAT_SOCKETS +#if ESP_LWIP +#if LWIP_COMPAT_SOCKET_ADDR == 1 +/* Some libraries have problems with inet_... being macros, so please use this define + to declare normal functions */ +static inline int gethostbyname_r(const char *name, struct hostent *ret, char *buf, size_t buflen, struct hostent **result, int *h_errnop) +{ return lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop); } +static inline struct hostent *gethostbyname(const char *name) +{ return lwip_gethostbyname(name); } +static inline void freeaddrinfo(struct addrinfo *ai) +{ lwip_freeaddrinfo(ai); } +static inline int getaddrinfo(const char *nodename, const char *servname, const struct addrinfo *hints, struct addrinfo **res) +{ return lwip_getaddrinfo(nodename, servname, hints, res); } +#else +/* By default fall back to original inet_... macros */ + +/** @ingroup netdbapi */ #define gethostbyname(name) lwip_gethostbyname(name) +/** @ingroup netdbapi */ #define gethostbyname_r(name, ret, buf, buflen, result, h_errnop) \ lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop) +/** @ingroup netdbapi */ #define freeaddrinfo(addrinfo) lwip_freeaddrinfo(addrinfo) +/** @ingroup netdbapi */ #define getaddrinfo(nodname, servname, hints, res) \ lwip_getaddrinfo(nodname, servname, hints, res) +#endif /* LWIP_COMPAT_SOCKET_ADDR == 1 */ + +#else /* ESP_LWIP */ + +/** @ingroup netdbapi */ +#define gethostbyname(name) lwip_gethostbyname(name) +/** @ingroup netdbapi */ +#define gethostbyname_r(name, ret, buf, buflen, result, h_errnop) \ + lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop) +/** @ingroup netdbapi */ +#define freeaddrinfo(addrinfo) lwip_freeaddrinfo(addrinfo) +/** @ingroup netdbapi */ +#define getaddrinfo(nodname, servname, hints, res) \ + lwip_getaddrinfo(nodname, servname, hints, res) + +#endif /* ESP_LWIP */ #endif /* LWIP_COMPAT_SOCKETS */ #ifdef __cplusplus diff --git a/tools/sdk/include/lwip/lwip/netif.h b/tools/sdk/include/lwip/lwip/netif.h index bd25b821..bcc9c5b1 100644 --- a/tools/sdk/include/lwip/lwip/netif.h +++ b/tools/sdk/include/lwip/lwip/netif.h @@ -1,3 +1,8 @@ +/** + * @file + * netif API (to be used from TCPIP thread) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -44,16 +49,6 @@ #include "lwip/pbuf.h" #include "lwip/stats.h" -#if LWIP_DHCP -struct dhcp; -#endif -#if LWIP_AUTOIP -struct autoip; -#endif -#if LWIP_IPV6_DHCP6 -struct dhcp6; -#endif /* LWIP_IPV6_DHCP6 */ - #ifdef __cplusplus extern "C" { #endif @@ -68,6 +63,12 @@ extern "C" { #define NETIF_MAX_HWADDR_LEN 6U #endif +/** + * @defgroup netif_flags Flags + * @ingroup netif + * @{ + */ + /** Whether the network interface is 'up'. This is * a software flag used to control whether this network * interface is enabled and processes traffic. @@ -99,6 +100,32 @@ extern "C" { * Set by the netif driver in its init function. */ #define NETIF_FLAG_MLD6 0x40U +#if ESP_GRATUITOUS_ARP +/** If set, the netif will send gratuitous ARP periodically */ +#define NETIF_FLAG_GARP 0x80U +#endif + +/** + * @} + */ + +enum lwip_internal_netif_client_data_index +{ +#if LWIP_DHCP + LWIP_NETIF_CLIENT_DATA_INDEX_DHCP, +#endif +#if LWIP_AUTOIP + LWIP_NETIF_CLIENT_DATA_INDEX_AUTOIP, +#endif +#if LWIP_IGMP + LWIP_NETIF_CLIENT_DATA_INDEX_IGMP, +#endif +#if LWIP_IPV6_MLD + LWIP_NETIF_CLIENT_DATA_INDEX_MLD6, +#endif + LWIP_NETIF_CLIENT_DATA_INDEX_MAX +}; + #if LWIP_CHECKSUM_CTRL_PER_NETIF #define NETIF_CHECKSUM_GEN_IP 0x0001 #define NETIF_CHECKSUM_GEN_UDP 0x0002 @@ -116,6 +143,15 @@ extern "C" { struct netif; +/** MAC Filter Actions, these are passed to a netif's igmp_mac_filter or + * mld_mac_filter callback function. */ +enum netif_mac_filter_action { + /** Delete a filter entry */ + NETIF_DEL_MAC_FILTER = 0, + /** Add a filter entry */ + NETIF_ADD_MAC_FILTER = 1 +}; + /** Function prototype for netif init functions. Set up flags and output/linkoutput * callback functions in this function. * @@ -168,21 +204,31 @@ typedef void (*netif_status_callback_fn)(struct netif *netif); #if LWIP_IPV4 && LWIP_IGMP /** Function prototype for netif igmp_mac_filter functions */ typedef err_t (*netif_igmp_mac_filter_fn)(struct netif *netif, - const ip4_addr_t *group, u8_t action); + const ip4_addr_t *group, enum netif_mac_filter_action action); #endif /* LWIP_IPV4 && LWIP_IGMP */ #if LWIP_IPV6 && LWIP_IPV6_MLD /** Function prototype for netif mld_mac_filter functions */ typedef err_t (*netif_mld_mac_filter_fn)(struct netif *netif, - const ip6_addr_t *group, u8_t action); + const ip6_addr_t *group, enum netif_mac_filter_action action); #endif /* LWIP_IPV6 && LWIP_IPV6_MLD */ +#if LWIP_DHCP || LWIP_AUTOIP || LWIP_IGMP || LWIP_IPV6_MLD || (LWIP_NUM_NETIF_CLIENT_DATA > 0) +u8_t netif_alloc_client_data_id(void); +/** @ingroup netif_cd + * Set client data. Obtain ID from netif_alloc_client_data_id(). + */ +#define netif_set_client_data(netif, id, data) netif_get_client_data(netif, id) = (data) +/** @ingroup netif_cd + * Get client data. Obtain ID from netif_alloc_client_data_id(). + */ +#define netif_get_client_data(netif, id) (netif)->client_data[(id)] +#endif /* LWIP_DHCP || LWIP_AUTOIP || (LWIP_NUM_NETIF_CLIENT_DATA > 0) */ #if ESP_DHCP /*add DHCP event processing by LiuHan*/ typedef void (*dhcp_event_fn)(void); #endif - /** Generic data structure used for all lwIP network interfaces. * The following fields should be filled in by the initialization * function for the device driver: hwaddr_len, hwaddr[], mtu, flags */ @@ -213,17 +259,19 @@ struct netif { #if LWIP_IPV4 /** This function is called by the IP module when it wants * to send a packet on the interface. This function typically - * first resolves the hardware address, then sends the packet. */ + * first resolves the hardware address, then sends the packet. + * For ethernet physical layer, this is usually etharp_output() */ netif_output_fn output; #endif /* LWIP_IPV4 */ - /** This function is called by the ARP module when it wants + /** This function is called by ethernet_output() when it wants * to send a packet on the interface. This function outputs * the pbuf as-is on the link medium. */ netif_linkoutput_fn linkoutput; #if LWIP_IPV6 /** This function is called by the IPv6 module when it wants * to send a packet on the interface. This function typically - * first resolves the hardware address, then sends the packet. */ + * first resolves the hardware address, then sends the packet. + * For ethernet physical layer, this is usually ethip6_output() */ netif_output_ip6_fn output_ip6; #endif /* LWIP_IPV6 */ #if LWIP_NETIF_STATUS_CALLBACK @@ -243,59 +291,42 @@ struct netif { /** This field can be set by the device driver and could point * to state information for the device. */ void *state; -#if LWIP_DHCP - /** the DHCP client state information for this netif */ - struct dhcp *dhcp; +#ifdef netif_get_client_data + void* client_data[LWIP_NETIF_CLIENT_DATA_INDEX_MAX + LWIP_NUM_NETIF_CLIENT_DATA]; +#endif -#if ESP_LWIP +#if ESP_DHCP struct udp_pcb *dhcps_pcb; dhcp_event_fn dhcp_event; -#endif - -#endif /* LWIP_DHCP */ - -#if LWIP_AUTOIP - /** the AutoIP client state information for this netif */ - struct autoip *autoip; #endif #if LWIP_IPV6_AUTOCONFIG /** is this netif enabled for IPv6 autoconfiguration */ u8_t ip6_autoconfig_enabled; #endif /* LWIP_IPV6_AUTOCONFIG */ - #if LWIP_IPV6_SEND_ROUTER_SOLICIT /** Number of Router Solicitation messages that remain to be sent. */ u8_t rs_count; #endif /* LWIP_IPV6_SEND_ROUTER_SOLICIT */ - -#if LWIP_IPV6_DHCP6 - /** the DHCPv6 client state information for this netif */ - struct dhcp6 *dhcp6; -#endif /* LWIP_IPV6_DHCP6 */ - #if LWIP_NETIF_HOSTNAME /* the hostname for this netif, NULL is a valid value */ const char* hostname; #endif /* LWIP_NETIF_HOSTNAME */ - #if LWIP_CHECKSUM_CTRL_PER_NETIF u16_t chksum_flags; #endif /* LWIP_CHECKSUM_CTRL_PER_NETIF*/ - /** maximum transfer unit (in bytes) */ u16_t mtu; /** number of bytes used in hwaddr */ u8_t hwaddr_len; /** link level hardware address of this interface */ u8_t hwaddr[NETIF_MAX_HWADDR_LEN]; - /** flags (see NETIF_FLAG_ above) */ + /** flags (@see @ref netif_flags) */ u8_t flags; /** descriptive abbreviation */ char name[2]; /** number of this interface */ u8_t num; - #if MIB2_STATS /** link type (from "snmp_ifType" enum from snmp_mib2.h) */ u8_t link_type; @@ -306,19 +337,16 @@ struct netif { /** counters */ struct stats_mib2_netif_ctrs mib2_counters; #endif /* MIB2_STATS */ - #if LWIP_IPV4 && LWIP_IGMP /** This function could be called to add or delete an entry in the multicast filter table of the ethernet MAC.*/ netif_igmp_mac_filter_fn igmp_mac_filter; #endif /* LWIP_IPV4 && LWIP_IGMP */ - #if LWIP_IPV6 && LWIP_IPV6_MLD /** This function could be called to add or delete an entry in the IPv6 multicast filter table of the ethernet MAC. */ netif_mld_mac_filter_fn mld_mac_filter; #endif /* LWIP_IPV6 && LWIP_IPV6_MLD */ - #if LWIP_NETIF_HWADDRHINT u8_t *addr_hint; #endif /* LWIP_NETIF_HWADDRHINT */ @@ -362,6 +390,11 @@ struct netif *netif_add(struct netif *netif, void netif_set_addr(struct netif *netif, const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw); #endif /* LWIP_IPV4 */ + +#if ESP_GRATUITOUS_ARP +void netif_set_garp_flag(struct netif *netif); +#endif + void netif_remove(struct netif * netif); /* Returns a network interface given its name. The name is of the form @@ -376,17 +409,30 @@ void netif_set_default(struct netif *netif); void netif_set_ipaddr(struct netif *netif, const ip4_addr_t *ipaddr); void netif_set_netmask(struct netif *netif, const ip4_addr_t *netmask); void netif_set_gw(struct netif *netif, const ip4_addr_t *gw); +/** @ingroup netif_ip4 */ #define netif_ip4_addr(netif) ((const ip4_addr_t*)ip_2_ip4(&((netif)->ip_addr))) +/** @ingroup netif_ip4 */ #define netif_ip4_netmask(netif) ((const ip4_addr_t*)ip_2_ip4(&((netif)->netmask))) +/** @ingroup netif_ip4 */ #define netif_ip4_gw(netif) ((const ip4_addr_t*)ip_2_ip4(&((netif)->gw))) +/** @ingroup netif_ip4 */ #define netif_ip_addr4(netif) ((const ip_addr_t*)&((netif)->ip_addr)) +/** @ingroup netif_ip4 */ +#define netif_ip_netmask4(netif) ((const ip_addr_t*)&((netif)->netmask)) +/** @ingroup netif_ip4 */ #define netif_ip_gw4(netif) ((const ip_addr_t*)&((netif)->gw)) #endif /* LWIP_IPV4 */ void netif_set_up(struct netif *netif); void netif_set_down(struct netif *netif); -/** Ask if an interface is up */ +/** @ingroup netif + * Ask if an interface is up + */ +#if ESP_LWIP #define netif_is_up(netif) ( ((netif) && ((netif)->flags & NETIF_FLAG_UP)) ? (u8_t)1 : (u8_t)0) +#else +#define netif_is_up(netif) (((netif)->flags & NETIF_FLAG_UP) ? (u8_t)1 : (u8_t)0) +#endif #if LWIP_NETIF_STATUS_CALLBACK void netif_set_status_callback(struct netif *netif, netif_status_callback_fn status_callback); @@ -405,18 +451,23 @@ void netif_set_link_callback(struct netif *netif, netif_status_callback_fn link_ #endif /* LWIP_NETIF_LINK_CALLBACK */ #if LWIP_NETIF_HOSTNAME +/** @ingroup netif */ #define netif_set_hostname(netif, name) do { if((netif) != NULL) { (netif)->hostname = name; }}while(0) +/** @ingroup netif */ #define netif_get_hostname(netif) (((netif) != NULL) ? ((netif)->hostname) : NULL) #endif /* LWIP_NETIF_HOSTNAME */ #if LWIP_IGMP +/** @ingroup netif */ #define netif_set_igmp_mac_filter(netif, function) do { if((netif) != NULL) { (netif)->igmp_mac_filter = function; }}while(0) #define netif_get_igmp_mac_filter(netif) (((netif) != NULL) ? ((netif)->igmp_mac_filter) : NULL) #endif /* LWIP_IGMP */ #if LWIP_IPV6 && LWIP_IPV6_MLD +/** @ingroup netif */ #define netif_set_mld_mac_filter(netif, function) do { if((netif) != NULL) { (netif)->mld_mac_filter = function; }}while(0) #define netif_get_mld_mac_filter(netif) (((netif) != NULL) ? ((netif)->mld_mac_filter) : NULL) +#define netif_mld_mac_filter(netif, addr, action) do { if((netif) && (netif)->mld_mac_filter) { (netif)->mld_mac_filter((netif), (addr), (action)); }}while(0) #endif /* LWIP_IPV6 && LWIP_IPV6_MLD */ #if ENABLE_LOOPBACK @@ -427,15 +478,21 @@ void netif_poll_all(void); #endif /* !LWIP_NETIF_LOOPBACK_MULTITHREADING */ #endif /* ENABLE_LOOPBACK */ +err_t netif_input(struct pbuf *p, struct netif *inp); + #if LWIP_IPV6 +/** @ingroup netif_ip6 */ #define netif_ip_addr6(netif, i) ((const ip_addr_t*)(&((netif)->ip6_addr[i]))) +/** @ingroup netif_ip6 */ #define netif_ip6_addr(netif, i) ((const ip6_addr_t*)ip_2_ip6(&((netif)->ip6_addr[i]))) -#define netif_ip6_addr_set(netif, i, addr6) do { ip6_addr_set(ip_2_ip6(&((netif)->ip6_addr[i])), addr6); IP_SET_TYPE_VAL((netif)->ip6_addr[i], IPADDR_TYPE_V6); } while(0) +void netif_ip6_addr_set(struct netif *netif, s8_t addr_idx, const ip6_addr_t *addr6); +void netif_ip6_addr_set_parts(struct netif *netif, s8_t addr_idx, u32_t i0, u32_t i1, u32_t i2, u32_t i3); #define netif_ip6_addr_state(netif, i) ((netif)->ip6_addr_state[i]) -#define netif_ip6_addr_set_state(netif, i, state) ((netif)->ip6_addr_state[i] = (state)) +void netif_ip6_addr_set_state(struct netif* netif, s8_t addr_idx, u8_t state); s8_t netif_get_ip6_addr_match(struct netif *netif, const ip6_addr_t *ip6addr); void netif_create_ip6_linklocal_address(struct netif *netif, u8_t from_mac_48bit); err_t netif_add_ip6_address(struct netif *netif, const ip6_addr_t *ip6addr, s8_t *chosen_idx); +#define netif_set_ip6_autoconfig_enabled(netif, action) do { if(netif) { (netif)->ip6_autoconfig_enabled = (action); }}while(0) #endif /* LWIP_IPV6 */ #if LWIP_NETIF_HWADDRHINT diff --git a/tools/sdk/include/lwip/lwip/netifapi.h b/tools/sdk/include/lwip/lwip/netifapi.h index b09316be..8bd2b4f7 100644 --- a/tools/sdk/include/lwip/lwip/netifapi.h +++ b/tools/sdk/include/lwip/lwip/netifapi.h @@ -1,3 +1,8 @@ +/** + * @file + * netif API (to be used from non-TCPIP threads) + */ + /* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: @@ -51,7 +56,7 @@ typedef void (*netifapi_void_fn)(struct netif *netif); typedef err_t (*netifapi_errt_fn)(struct netif *netif); struct netifapi_msg { - struct tcpip_api_call call; + struct tcpip_api_call_data call; struct netif *netif; union { struct { @@ -87,16 +92,43 @@ err_t netifapi_netif_set_addr(struct netif *netif, const ip4_addr_t *ipaddr, err_t netifapi_netif_common(struct netif *netif, netifapi_void_fn voidfunc, netifapi_errt_fn errtfunc); -#define netifapi_netif_remove(n) netifapi_netif_common(n, netif_remove, NULL) -#define netifapi_netif_set_up(n) netifapi_netif_common(n, netif_set_up, NULL) -#define netifapi_netif_set_down(n) netifapi_netif_common(n, netif_set_down, NULL) -#define netifapi_netif_set_default(n) netifapi_netif_common(n, netif_set_default, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_remove(n) netifapi_netif_common(n, netif_remove, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_set_up(n) netifapi_netif_common(n, netif_set_up, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_set_down(n) netifapi_netif_common(n, netif_set_down, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_set_default(n) netifapi_netif_common(n, netif_set_default, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_set_link_up(n) netifapi_netif_common(n, netif_set_link_up, NULL) +/** @ingroup netifapi_netif */ +#define netifapi_netif_set_link_down(n) netifapi_netif_common(n, netif_set_link_down, NULL) + +/** + * @defgroup netifapi_dhcp4 DHCPv4 + * @ingroup netifapi + * To be called from non-TCPIP threads + */ +/** @ingroup netifapi_dhcp4 */ #define netifapi_dhcp_start(n) netifapi_netif_common(n, NULL, dhcp_start) +/** @ingroup netifapi_dhcp4 */ #define netifapi_dhcp_stop(n) netifapi_netif_common(n, dhcp_stop, NULL) +/** @ingroup netifapi_dhcp4 */ #define netifapi_dhcp_inform(n) netifapi_netif_common(n, dhcp_inform, NULL) +/** @ingroup netifapi_dhcp4 */ #define netifapi_dhcp_renew(n) netifapi_netif_common(n, NULL, dhcp_renew) +/** @ingroup netifapi_dhcp4 */ #define netifapi_dhcp_release(n) netifapi_netif_common(n, NULL, dhcp_release) + +/** + * @defgroup netifapi_autoip AUTOIP + * @ingroup netifapi + * To be called from non-TCPIP threads + */ +/** @ingroup netifapi_autoip */ #define netifapi_autoip_start(n) netifapi_netif_common(n, NULL, autoip_start) +/** @ingroup netifapi_autoip */ #define netifapi_autoip_stop(n) netifapi_netif_common(n, NULL, autoip_stop) #ifdef __cplusplus diff --git a/tools/sdk/include/lwip/lwip/opt.h b/tools/sdk/include/lwip/lwip/opt.h index 6ea556ac..f15aa7b6 100644 --- a/tools/sdk/include/lwip/lwip/opt.h +++ b/tools/sdk/include/lwip/lwip/opt.h @@ -35,7 +35,13 @@ * Author: Adam Dunkels * */ -#ifndef LWIP_HDR_OPT_H + +/* + * NOTE: || defined __DOXYGEN__ is a workaround for doxygen bug - + * without this, doxygen does not see the actual #define + */ + +#if !defined LWIP_HDR_OPT_H #define LWIP_HDR_OPT_H /* @@ -45,42 +51,89 @@ #include "lwipopts.h" #include "lwip/debug.h" -/* - ----------------------------------------------- - ---------- Platform specific locking ---------- - ----------------------------------------------- +/** + * @defgroup lwip_opts Options (lwipopts.h) + * @ingroup lwip + * + * @defgroup lwip_opts_debug Debugging + * @ingroup lwip_opts + * + * @defgroup lwip_opts_infrastructure Infrastructure + * @ingroup lwip_opts + * + * @defgroup lwip_opts_callback Callback-style APIs + * @ingroup lwip_opts + * + * @defgroup lwip_opts_threadsafe_apis Thread-safe APIs + * @ingroup lwip_opts + */ + + /* + ------------------------------------ + -------------- NO SYS -------------- + ------------------------------------ */ - /** - * SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain - * critical regions during buffer allocation, deallocation and memory - * allocation and deallocation. + * @defgroup lwip_opts_nosys NO_SYS + * @ingroup lwip_opts_infrastructure + * @{ */ -#ifndef SYS_LIGHTWEIGHT_PROT -#define SYS_LIGHTWEIGHT_PROT 0 -#endif - /** - * NO_SYS==1: Provides VERY minimal functionality. Otherwise, - * use lwIP facilities. + * NO_SYS==1: Use lwIP without OS-awareness (no thread, semaphores, mutexes or + * mboxes). This means threaded APIs cannot be used (socket, netconn, + * i.e. everything in the 'api' folder), only the callback-style raw API is + * available (and you have to watch out for yourself that you don't access + * lwIP functions/structures from more than one context at a time!) */ -#ifndef NO_SYS +#if !defined NO_SYS || defined __DOXYGEN__ #define NO_SYS 0 #endif +/** + * @} + */ /** - * NO_SYS_NO_TIMERS==1: Drop support for sys_timeout when NO_SYS==1 - * Mainly for compatibility to old versions. + * @defgroup lwip_opts_timers Timers + * @ingroup lwip_opts_infrastructure + * @{ */ -#ifndef NO_SYS_NO_TIMERS -#define NO_SYS_NO_TIMERS 0 +/** + * LWIP_TIMERS==0: Drop support for sys_timeout and lwip-internal cyclic timers. + * (the array of lwip-internal cyclic timers is still provided) + * (check NO_SYS_NO_TIMERS for compatibility to old versions) + */ +#if !defined LWIP_TIMERS || defined __DOXYGEN__ +#ifdef NO_SYS_NO_TIMERS +#define LWIP_TIMERS (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) +#else +#define LWIP_TIMERS 1 +#endif #endif +/** + * LWIP_TIMERS_CUSTOM==1: Provide your own timer implementation. + * Function prototypes in timeouts.h and the array of lwip-internal cyclic timers + * are still included, but the implementation is not. The following functions + * will be required: sys_timeouts_init(), sys_timeout(), sys_untimeout(), + * sys_timeouts_mbox_fetch() + */ +#if !defined LWIP_TIMERS_CUSTOM || defined __DOXYGEN__ +#define LWIP_TIMERS_CUSTOM 0 +#endif +/** + * @} + */ + +/** + * @defgroup lwip_opts_memcpy memcpy + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * MEMCPY: override this if you have a faster implementation at hand than the * one included in your C library */ -#ifndef MEMCPY +#if !defined MEMCPY || defined __DOXYGEN__ #define MEMCPY(dst,src,len) memcpy(dst,src,len) #endif @@ -88,49 +141,110 @@ * SMEMCPY: override this with care! Some compilers (e.g. gcc) can inline a * call to memcpy() if the length is known at compile time and is small. */ -#ifndef SMEMCPY +#if !defined SMEMCPY || defined __DOXYGEN__ #define SMEMCPY(dst,src,len) memcpy(dst,src,len) #endif +/** + * @} + */ +/* + ------------------------------------ + ----------- Core locking ----------- + ------------------------------------ +*/ +/** + * @defgroup lwip_opts_lock Core locking and MPU + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * LWIP_MPU_COMPATIBLE: enables special memory management mechanism * which makes lwip able to work on MPU (Memory Protection Unit) system * by not passing stack-pointers to other threads - * (this decreases performance) + * (this decreases performance as memory is allocated from pools instead + * of keeping it on the stack) */ -#ifndef LWIP_MPU_COMPATIBLE +#if !defined LWIP_MPU_COMPATIBLE || defined __DOXYGEN__ #define LWIP_MPU_COMPATIBLE 0 #endif +/** + * LWIP_TCPIP_CORE_LOCKING + * Creates a global mutex that is held during TCPIP thread operations. + * Can be locked by client code to perform lwIP operations without changing + * into TCPIP thread using callbacks. See LOCK_TCPIP_CORE() and + * UNLOCK_TCPIP_CORE(). + * Your system should provide mutexes supporting priority inversion to use this. + */ +#if !defined LWIP_TCPIP_CORE_LOCKING || defined __DOXYGEN__ +#define LWIP_TCPIP_CORE_LOCKING 1 +#endif + +/** + * LWIP_TCPIP_CORE_LOCKING_INPUT: when LWIP_TCPIP_CORE_LOCKING is enabled, + * this lets tcpip_input() grab the mutex for input packets as well, + * instead of allocating a message and passing it to tcpip_thread. + * + * ATTENTION: this does not work when tcpip_input() is called from + * interrupt context! + */ +#if !defined LWIP_TCPIP_CORE_LOCKING_INPUT || defined __DOXYGEN__ +#define LWIP_TCPIP_CORE_LOCKING_INPUT 0 +#endif + +/** + * SYS_LIGHTWEIGHT_PROT==1: enable inter-task protection (and task-vs-interrupt + * protection) for certain critical regions during buffer allocation, deallocation + * and memory allocation and deallocation. + * ATTENTION: This is required when using lwIP from more than one context! If + * you disable this, you must be sure what you are doing! + */ +#if !defined SYS_LIGHTWEIGHT_PROT || defined __DOXYGEN__ +#define SYS_LIGHTWEIGHT_PROT 1 +#endif +/** + * @} + */ + /* ------------------------------------ ---------- Memory options ---------- ------------------------------------ */ +/** + * @defgroup lwip_opts_mem Heap and memory pools + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C-library * instead of the lwip internal allocator. Can save code size if you * already use it. */ -#ifndef MEM_LIBC_MALLOC +#if !defined MEM_LIBC_MALLOC || defined __DOXYGEN__ #define MEM_LIBC_MALLOC 0 #endif /** -* MEMP_MEM_MALLOC==1: Use mem_malloc/mem_free instead of the lwip pool allocator. -* Especially useful with MEM_LIBC_MALLOC but handle with care regarding execution -* speed and usage from interrupts! -*/ -#ifndef MEMP_MEM_MALLOC + * MEMP_MEM_MALLOC==1: Use mem_malloc/mem_free instead of the lwip pool allocator. + * Especially useful with MEM_LIBC_MALLOC but handle with care regarding execution + * speed (heap alloc can be much slower than pool alloc) and usage from interrupts + * (especially if your netif driver allocates PBUF_POOL pbufs for received frames + * from interrupt)! + * ATTENTION: Currently, this uses the heap for ALL pools (also for private pools, + * not only for internal pools defined in memp_std.h)! + */ +#if !defined MEMP_MEM_MALLOC || defined __DOXYGEN__ #define MEMP_MEM_MALLOC 0 #endif /** * MEM_ALIGNMENT: should be set to the alignment of the CPU - * 4 byte alignment -> #define MEM_ALIGNMENT 4 - * 2 byte alignment -> #define MEM_ALIGNMENT 2 + * 4 byte alignment -> \#define MEM_ALIGNMENT 4 + * 2 byte alignment -> \#define MEM_ALIGNMENT 2 */ -#ifndef MEM_ALIGNMENT +#if !defined MEM_ALIGNMENT || defined __DOXYGEN__ #define MEM_ALIGNMENT 1 #endif @@ -138,7 +252,7 @@ * MEM_SIZE: the size of the heap memory. If the application will send * a lot of data that needs to be copied, this should be set high. */ -#ifndef MEM_SIZE +#if !defined MEM_SIZE || defined __DOXYGEN__ #define MEM_SIZE 1600 #endif @@ -151,7 +265,7 @@ * MEMP_OVERFLOW_CHECK >= 2 checks each element in every pool every time * memp_malloc() or memp_free() is called (useful but slow!) */ -#ifndef MEMP_OVERFLOW_CHECK +#if !defined MEMP_OVERFLOW_CHECK || defined __DOXYGEN__ #define MEMP_OVERFLOW_CHECK 0 #endif @@ -159,7 +273,7 @@ * MEMP_SANITY_CHECK==1: run a sanity check after each memp_free() to make * sure that there are no cycles in the linked lists. */ -#ifndef MEMP_SANITY_CHECK +#if !defined MEMP_SANITY_CHECK || defined __DOXYGEN__ #define MEMP_SANITY_CHECK 0 #endif @@ -169,7 +283,7 @@ * the smallest pool that can provide the length needed is returned. * To use this, MEMP_USE_CUSTOM_POOLS also has to be enabled. */ -#ifndef MEM_USE_POOLS +#if !defined MEM_USE_POOLS || defined __DOXYGEN__ #define MEM_USE_POOLS 0 #endif @@ -177,7 +291,7 @@ * MEM_USE_POOLS_TRY_BIGGER_POOL==1: if one malloc-pool is empty, try the next * bigger pool - WARNING: THIS MIGHT WASTE MEMORY but it can make a system more * reliable. */ -#ifndef MEM_USE_POOLS_TRY_BIGGER_POOL +#if !defined MEM_USE_POOLS_TRY_BIGGER_POOL || defined __DOXYGEN__ #define MEM_USE_POOLS_TRY_BIGGER_POOL 0 #endif @@ -187,7 +301,7 @@ * by lwIP. If you set this to 1, you must have lwippools.h in your * include path somewhere. */ -#ifndef MEMP_USE_CUSTOM_POOLS +#if !defined MEMP_USE_CUSTOM_POOLS || defined __DOXYGEN__ #define MEMP_USE_CUSTOM_POOLS 0 #endif @@ -209,21 +323,29 @@ * - pbuf_free_callback(p); * - mem_free_callback(m); */ -#ifndef LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT +#if !defined LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT || defined __DOXYGEN__ #define LWIP_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT 0 #endif +/** + * @} + */ /* ------------------------------------------------ ---------- Internal Memory Pool Sizes ---------- ------------------------------------------------ */ +/** + * @defgroup lwip_opts_memp Internal memory pools + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * MEMP_NUM_PBUF: the number of memp struct pbufs (used for PBUF_ROM and PBUF_REF). * If the application sends a lot of data out of ROM (or other static memory), * this should be set high. */ -#ifndef MEMP_NUM_PBUF +#if !defined MEMP_NUM_PBUF || defined __DOXYGEN__ #define MEMP_NUM_PBUF 16 #endif @@ -231,7 +353,7 @@ * MEMP_NUM_RAW_PCB: Number of raw connection PCBs * (requires the LWIP_RAW option) */ -#ifndef MEMP_NUM_RAW_PCB +#if !defined MEMP_NUM_RAW_PCB || defined __DOXYGEN__ #define MEMP_NUM_RAW_PCB 4 #endif @@ -240,7 +362,7 @@ * per active UDP "connection". * (requires the LWIP_UDP option) */ -#ifndef MEMP_NUM_UDP_PCB +#if !defined MEMP_NUM_UDP_PCB || defined __DOXYGEN__ #define MEMP_NUM_UDP_PCB 4 #endif @@ -248,7 +370,7 @@ * MEMP_NUM_TCP_PCB: the number of simultaneously active TCP connections. * (requires the LWIP_TCP option) */ -#ifndef MEMP_NUM_TCP_PCB +#if !defined MEMP_NUM_TCP_PCB || defined __DOXYGEN__ #define MEMP_NUM_TCP_PCB 5 #endif @@ -256,7 +378,7 @@ * MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP connections. * (requires the LWIP_TCP option) */ -#ifndef MEMP_NUM_TCP_PCB_LISTEN +#if !defined MEMP_NUM_TCP_PCB_LISTEN || defined __DOXYGEN__ #define MEMP_NUM_TCP_PCB_LISTEN 8 #endif @@ -264,7 +386,7 @@ * MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments. * (requires the LWIP_TCP option) */ -#ifndef MEMP_NUM_TCP_SEG +#if !defined MEMP_NUM_TCP_SEG || defined __DOXYGEN__ #define MEMP_NUM_TCP_SEG 16 #endif @@ -272,18 +394,18 @@ * MEMP_NUM_REASSDATA: the number of IP packets simultaneously queued for * reassembly (whole packets, not fragments!) */ -#ifndef MEMP_NUM_REASSDATA +#if !defined MEMP_NUM_REASSDATA || defined __DOXYGEN__ #define MEMP_NUM_REASSDATA 5 #endif /** * MEMP_NUM_FRAG_PBUF: the number of IP fragments simultaneously sent * (fragments, not whole packets!). - * This is only used with IP_FRAG_USES_STATIC_BUF==0 and - * LWIP_NETIF_TX_SINGLE_PBUF==0 and only has to be > 1 with DMA-enabled MACs - * where the packet is not yet sent when netif->output returns. + * This is only used with LWIP_NETIF_TX_SINGLE_PBUF==0 and only has to be > 1 + * with DMA-enabled MACs where the packet is not yet sent when netif->output + * returns. */ -#ifndef MEMP_NUM_FRAG_PBUF +#if !defined MEMP_NUM_FRAG_PBUF || defined __DOXYGEN__ #define MEMP_NUM_FRAG_PBUF 15 #endif @@ -293,7 +415,7 @@ * their destination address) to finish. * (requires the ARP_QUEUEING option) */ -#ifndef MEMP_NUM_ARP_QUEUE +#if !defined MEMP_NUM_ARP_QUEUE || defined __DOXYGEN__ #define MEMP_NUM_ARP_QUEUE 30 #endif @@ -303,7 +425,7 @@ * per netif membership). * (requires the LWIP_IGMP option) */ -#ifndef MEMP_NUM_IGMP_GROUP +#if !defined MEMP_NUM_IGMP_GROUP || defined __DOXYGEN__ #define MEMP_NUM_IGMP_GROUP 8 #endif @@ -312,15 +434,19 @@ * The default number of timeouts is calculated here for all enabled modules. * The formula expects settings to be either '0' or '1'. */ -#ifndef MEMP_NUM_SYS_TIMEOUT +#if !defined MEMP_NUM_SYS_TIMEOUT || defined __DOXYGEN__ +#if ESP_LWIP +#define MEMP_NUM_SYS_TIMEOUT (LWIP_TCP + IP_REASSEMBLY + (LWIP_ARP + (ESP_GRATUITOUS_ARP ? 1 : 0)) + (2*LWIP_DHCP + (ESP_DHCPS_TIMER ? 1 : 0)) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + (PPP_SUPPORT*6*MEMP_NUM_PPP_PCB) + (LWIP_IPV6 ? (1 + LWIP_IPV6_REASS + LWIP_IPV6_MLD) : 0)) +#else #define MEMP_NUM_SYS_TIMEOUT (LWIP_TCP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + (PPP_SUPPORT*6*MEMP_NUM_PPP_PCB) + (LWIP_IPV6 ? (1 + LWIP_IPV6_REASS + LWIP_IPV6_MLD) : 0)) #endif +#endif /** * MEMP_NUM_NETBUF: the number of struct netbufs. * (only needed if you use the sequential API, like api_lib.c) */ -#ifndef MEMP_NUM_NETBUF +#if !defined MEMP_NUM_NETBUF || defined __DOXYGEN__ #define MEMP_NUM_NETBUF 2 #endif @@ -328,7 +454,7 @@ * MEMP_NUM_NETCONN: the number of struct netconns. * (only needed if you use the sequential API, like api_lib.c) */ -#ifndef MEMP_NUM_NETCONN +#if !defined MEMP_NUM_NETCONN || defined __DOXYGEN__ #define MEMP_NUM_NETCONN 4 #endif @@ -337,7 +463,7 @@ * for callback/timeout API communication. * (only needed if you use tcpip.c) */ -#ifndef MEMP_NUM_TCPIP_MSG_API +#if !defined MEMP_NUM_TCPIP_MSG_API || defined __DOXYGEN__ #define MEMP_NUM_TCPIP_MSG_API 8 #endif @@ -346,7 +472,7 @@ * for incoming packets. * (only needed if you use tcpip.c) */ -#ifndef MEMP_NUM_TCPIP_MSG_INPKT +#if !defined MEMP_NUM_TCPIP_MSG_INPKT || defined __DOXYGEN__ #define MEMP_NUM_TCPIP_MSG_INPKT 8 #endif @@ -354,7 +480,7 @@ * MEMP_NUM_NETDB: the number of concurrently running lwip_addrinfo() calls * (before freeing the corresponding memory using lwip_freeaddrinfo()). */ -#ifndef MEMP_NUM_NETDB +#if !defined MEMP_NUM_NETDB || defined __DOXYGEN__ #define MEMP_NUM_NETDB 1 #endif @@ -362,92 +488,68 @@ * MEMP_NUM_LOCALHOSTLIST: the number of host entries in the local host list * if DNS_LOCAL_HOSTLIST_IS_DYNAMIC==1. */ -#ifndef MEMP_NUM_LOCALHOSTLIST +#if !defined MEMP_NUM_LOCALHOSTLIST || defined __DOXYGEN__ #define MEMP_NUM_LOCALHOSTLIST 1 #endif -/** - * MEMP_NUM_PPP_PCB: the number of simultaneously active PPP - * connections (requires the PPP_SUPPORT option) - */ -#ifndef MEMP_NUM_PPP_PCB -#define MEMP_NUM_PPP_PCB 1 -#endif - -/** - * MEMP_NUM_PPPOS_INTERFACES: the number of concurrently active PPPoS - * interfaces (only used with PPPOS_SUPPORT==1) - */ -#ifndef MEMP_NUM_PPPOS_INTERFACES -#define MEMP_NUM_PPPOS_INTERFACES MEMP_NUM_PPP_PCB -#endif - -/** - * MEMP_NUM_PPPOE_INTERFACES: the number of concurrently active PPPoE - * interfaces (only used with PPPOE_SUPPORT==1) - */ -#ifndef MEMP_NUM_PPPOE_INTERFACES -#define MEMP_NUM_PPPOE_INTERFACES 1 -#endif - -/** - * MEMP_NUM_PPPOL2TP_INTERFACES: the number of concurrently active PPPoL2TP - * interfaces (only used with PPPOL2TP_SUPPORT==1) - */ -#ifndef MEMP_NUM_PPPOL2TP_INTERFACES -#define MEMP_NUM_PPPOL2TP_INTERFACES 1 -#endif - /** * PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ -#ifndef PBUF_POOL_SIZE +#if !defined PBUF_POOL_SIZE || defined __DOXYGEN__ #define PBUF_POOL_SIZE 16 #endif /** MEMP_NUM_API_MSG: the number of concurrently active calls to various * socket, netconn, and tcpip functions */ -#ifndef MEMP_NUM_API_MSG +#if !defined MEMP_NUM_API_MSG || defined __DOXYGEN__ #define MEMP_NUM_API_MSG MEMP_NUM_TCPIP_MSG_API #endif /** MEMP_NUM_DNS_API_MSG: the number of concurrently active calls to netconn_gethostbyname */ -#ifndef MEMP_NUM_DNS_API_MSG +#if !defined MEMP_NUM_DNS_API_MSG || defined __DOXYGEN__ #define MEMP_NUM_DNS_API_MSG MEMP_NUM_TCPIP_MSG_API #endif /** MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA: the number of concurrently active calls * to getsockopt/setsockopt */ -#ifndef MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA +#if !defined MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA || defined __DOXYGEN__ #define MEMP_NUM_SOCKET_SETGETSOCKOPT_DATA MEMP_NUM_TCPIP_MSG_API #endif /** MEMP_NUM_NETIFAPI_MSG: the number of concurrently active calls to the * netifapi functions */ -#ifndef MEMP_NUM_NETIFAPI_MSG +#if !defined MEMP_NUM_NETIFAPI_MSG || defined __DOXYGEN__ #define MEMP_NUM_NETIFAPI_MSG MEMP_NUM_TCPIP_MSG_API #endif +/** + * @} + */ /* --------------------------------- ---------- ARP options ---------- --------------------------------- */ +/** + * @defgroup lwip_opts_arp ARP + * @ingroup lwip_opts_ipv4 + * @{ + */ /** * LWIP_ARP==1: Enable ARP functionality. */ -#ifndef LWIP_ARP +#if !defined LWIP_ARP || defined __DOXYGEN__ #define LWIP_ARP 1 #endif /** * ARP_TABLE_SIZE: Number of active MAC-IP address pairs cached. */ -#ifndef ARP_TABLE_SIZE +#if !defined ARP_TABLE_SIZE || defined __DOXYGEN__ #define ARP_TABLE_SIZE 10 #endif @@ -455,7 +557,7 @@ * for ARP_TMR_INTERVAL = 1000, this is * (60 * 5) seconds = 5 minutes. */ -#ifndef ARP_MAXAGE +#if !defined ARP_MAXAGE || defined __DOXYGEN__ #define ARP_MAXAGE 300 #endif @@ -466,7 +568,7 @@ * startup time. Set this to 1 if you know your application sends more than one * packet in a row to an IP address that is not in the ARP cache. */ -#ifndef ARP_QUEUEING +#if !defined ARP_QUEUEING || defined __DOXYGEN__ #define ARP_QUEUEING 0 #endif @@ -474,24 +576,10 @@ * unresolved address by other network layers. Defaults to 3, 0 means disabled. * Old packets are dropped, new packets are queued. */ -#ifndef ARP_QUEUE_LEN +#if !defined ARP_QUEUE_LEN || defined __DOXYGEN__ #define ARP_QUEUE_LEN 3 #endif -/** - * ETHARP_TRUST_IP_MAC==1: Incoming IP packets cause the ARP table to be - * updated with the source MAC and IP addresses supplied in the packet. - * You may want to disable this if you do not trust LAN peers to have the - * correct addresses, or as a limited approach to attempt to handle - * spoofing. If disabled, lwIP will need to make a new ARP request if - * the peer is not already in the ARP table, adding a little latency. - * The peer *is* in the ARP table if it requested our address before. - * Also notice that this slows down input processing of every IP packet! - */ -#ifndef ETHARP_TRUST_IP_MAC -#define ETHARP_TRUST_IP_MAC 0 -#endif - /** * ETHARP_SUPPORT_VLAN==1: support receiving and sending ethernet packets with * VLAN header. See the description of LWIP_HOOK_VLAN_CHECK and @@ -502,15 +590,14 @@ * Alternatively, define a function/define ETHARP_VLAN_CHECK_FN(eth_hdr, vlan) * that returns 1 to accept a packet or 0 to drop a packet. */ -#ifndef ETHARP_SUPPORT_VLAN +#if !defined ETHARP_SUPPORT_VLAN || defined __DOXYGEN__ #define ETHARP_SUPPORT_VLAN 0 #endif -/** LWIP_ETHERNET==1: enable ethernet support for PPPoE even though ARP - * might be disabled +/** LWIP_ETHERNET==1: enable ethernet support even though ARP might be disabled */ -#ifndef LWIP_ETHERNET -#define LWIP_ETHERNET (LWIP_ARP || PPPOE_SUPPORT) +#if !defined LWIP_ETHERNET || defined __DOXYGEN__ +#define LWIP_ETHERNET LWIP_ARP #endif /** ETH_PAD_SIZE: number of bytes added before the ethernet header to ensure @@ -518,14 +605,14 @@ * without this padding e.g. addresses in the IP header will not be aligned * on a 32-bit boundary, so setting this to 2 can speed up 32-bit-platforms. */ -#ifndef ETH_PAD_SIZE +#if !defined ETH_PAD_SIZE || defined __DOXYGEN__ #define ETH_PAD_SIZE 0 #endif /** ETHARP_SUPPORT_STATIC_ENTRIES==1: enable code to support static ARP table * entries (using etharp_add_static_entry/etharp_remove_static_entry). */ -#ifndef ETHARP_SUPPORT_STATIC_ENTRIES +#if !defined ETHARP_SUPPORT_STATIC_ENTRIES || defined __DOXYGEN__ #define ETHARP_SUPPORT_STATIC_ENTRIES 0 #endif @@ -533,19 +620,27 @@ * If disabled, duplicate IP address on multiple netifs are not supported * (but this should only occur for AutoIP). */ -#ifndef ETHARP_TABLE_MATCH_NETIF +#if !defined ETHARP_TABLE_MATCH_NETIF || defined __DOXYGEN__ #define ETHARP_TABLE_MATCH_NETIF 0 #endif +/** + * @} + */ /* -------------------------------- ---------- IP options ---------- -------------------------------- */ +/** + * @defgroup lwip_opts_ipv4 IPv4 + * @ingroup lwip_opts + * @{ + */ /** * LWIP_IPV4==1: Enable IPv4 */ -#ifndef LWIP_IPV4 +#if !defined LWIP_IPV4 || defined __DOXYGEN__ #define LWIP_IPV4 1 #endif @@ -554,7 +649,7 @@ * interfaces. If you are going to run lwIP on a device with only one network * interface, define this to 0. */ -#ifndef IP_FORWARD +#if !defined IP_FORWARD || defined __DOXYGEN__ #define IP_FORWARD 0 #endif @@ -563,7 +658,7 @@ * this option does not affect outgoing packet sizes, which can be controlled * via IP_FRAG. */ -#ifndef IP_REASSEMBLY +#if !defined IP_REASSEMBLY || defined __DOXYGEN__ #define IP_REASSEMBLY 1 #endif @@ -572,7 +667,7 @@ * that this option does not affect incoming packet sizes, which can be * controlled via IP_REASSEMBLY. */ -#ifndef IP_FRAG +#if !defined IP_FRAG || defined __DOXYGEN__ #define IP_FRAG 1 #endif @@ -591,7 +686,7 @@ * IP_OPTIONS_ALLOWED==0: All packets with IP options are dropped. * IP_OPTIONS_ALLOWED==1: IP options are allowed (but not parsed). */ -#ifndef IP_OPTIONS_ALLOWED +#if !defined IP_OPTIONS_ALLOWED || defined __DOXYGEN__ #define IP_OPTIONS_ALLOWED 1 #endif @@ -600,7 +695,7 @@ * a fragmented IP packet waits for all fragments to arrive. If not all fragments arrived * in this time, the whole packet is discarded. */ -#ifndef IP_REASS_MAXAGE +#if !defined IP_REASS_MAXAGE || defined __DOXYGEN__ #define IP_REASS_MAXAGE 3 #endif @@ -610,33 +705,14 @@ * PBUF_POOL_SIZE > IP_REASS_MAX_PBUFS so that the stack is still able to receive * packets even if the maximum amount of fragments is enqueued for reassembly! */ -#ifndef IP_REASS_MAX_PBUFS +#if !defined IP_REASS_MAX_PBUFS || defined __DOXYGEN__ #define IP_REASS_MAX_PBUFS 10 #endif -/** - * IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP - * fragmentation. Otherwise pbufs are allocated and reference the original - * packet data to be fragmented (or with LWIP_NETIF_TX_SINGLE_PBUF==1, - * new PBUF_RAM pbufs are used for fragments). - * ATTENTION: IP_FRAG_USES_STATIC_BUF==1 may not be used for DMA-enabled MACs! - */ -#ifndef IP_FRAG_USES_STATIC_BUF -#define IP_FRAG_USES_STATIC_BUF 0 -#endif - -/** - * IP_FRAG_MAX_MTU: Assumed max MTU on any interface for IP frag buffer - * (requires IP_FRAG_USES_STATIC_BUF==1) - */ -#if IP_FRAG_USES_STATIC_BUF && !defined(IP_FRAG_MAX_MTU) -#define IP_FRAG_MAX_MTU 1500 -#endif - /** * IP_DEFAULT_TTL: Default value for Time-To-Live used by transport layers. */ -#ifndef IP_DEFAULT_TTL +#if !defined IP_DEFAULT_TTL || defined __DOXYGEN__ #define IP_DEFAULT_TTL 255 #endif @@ -645,7 +721,7 @@ * filter per pcb on udp and raw send operations. To enable broadcast filter * on recv operations, you also have to set IP_SOF_BROADCAST_RECV=1. */ -#ifndef IP_SOF_BROADCAST +#if !defined IP_SOF_BROADCAST || defined __DOXYGEN__ #define IP_SOF_BROADCAST 0 #endif @@ -653,7 +729,7 @@ * IP_SOF_BROADCAST_RECV (requires IP_SOF_BROADCAST=1) enable the broadcast * filter on recv operations. */ -#ifndef IP_SOF_BROADCAST_RECV +#if !defined IP_SOF_BROADCAST_RECV || defined __DOXYGEN__ #define IP_SOF_BROADCAST_RECV 0 #endif @@ -664,7 +740,7 @@ * ATTENTION: When this is 1, make sure your netif driver correctly marks incoming * link-layer-broadcast/multicast packets as such using the corresponding pbuf flags! */ -#ifndef IP_FORWARD_ALLOW_TX_ON_RX_NETIF +#if !defined IP_FORWARD_ALLOW_TX_ON_RX_NETIF || defined __DOXYGEN__ #define IP_FORWARD_ALLOW_TX_ON_RX_NETIF 0 #endif @@ -673,72 +749,96 @@ * local TCP/UDP pcb (default==0). This can prevent creating predictable port * numbers after booting a device. */ -#ifndef LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS +#if !defined LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS || defined __DOXYGEN__ #define LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS 0 #endif +/** + * @} + */ /* ---------------------------------- ---------- ICMP options ---------- ---------------------------------- */ +/** + * @defgroup lwip_opts_icmp ICMP + * @ingroup lwip_opts_ipv4 + * @{ + */ /** * LWIP_ICMP==1: Enable ICMP module inside the IP stack. * Be careful, disable that make your product non-compliant to RFC1122 */ -#ifndef LWIP_ICMP +#if !defined LWIP_ICMP || defined __DOXYGEN__ #define LWIP_ICMP 1 #endif /** * ICMP_TTL: Default value for Time-To-Live used by ICMP packets. */ -#ifndef ICMP_TTL +#if !defined ICMP_TTL || defined __DOXYGEN__ #define ICMP_TTL (IP_DEFAULT_TTL) #endif /** * LWIP_BROADCAST_PING==1: respond to broadcast pings (default is unicast only) */ -#ifndef LWIP_BROADCAST_PING +#if !defined LWIP_BROADCAST_PING || defined __DOXYGEN__ #define LWIP_BROADCAST_PING 0 #endif /** * LWIP_MULTICAST_PING==1: respond to multicast pings (default is unicast only) */ -#ifndef LWIP_MULTICAST_PING +#if !defined LWIP_MULTICAST_PING || defined __DOXYGEN__ #define LWIP_MULTICAST_PING 0 #endif +/** + * @} + */ /* --------------------------------- ---------- RAW options ---------- --------------------------------- */ +/** + * @defgroup lwip_opts_raw RAW + * @ingroup lwip_opts_callback + * @{ + */ /** * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. */ -#ifndef LWIP_RAW +#if !defined LWIP_RAW || defined __DOXYGEN__ #define LWIP_RAW 0 #endif /** * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. */ -#ifndef RAW_TTL +#if !defined RAW_TTL || defined __DOXYGEN__ #define RAW_TTL (IP_DEFAULT_TTL) #endif +/** + * @} + */ /* ---------------------------------- ---------- DHCP options ---------- ---------------------------------- */ +/** + * @defgroup lwip_opts_dhcp DHCP + * @ingroup lwip_opts_ipv4 + * @{ + */ /** * LWIP_DHCP==1: Enable DHCP module. */ -#ifndef LWIP_DHCP +#if !defined LWIP_DHCP || defined __DOXYGEN__ #define LWIP_DHCP 0 #endif #if !LWIP_IPV4 @@ -750,7 +850,7 @@ /** * DHCP_DOES_ARP_CHECK==1: Do an ARP check on the offered address. */ -#ifndef DHCP_DOES_ARP_CHECK +#if !defined DHCP_DOES_ARP_CHECK || defined __DOXYGEN__ #define DHCP_DOES_ARP_CHECK ((LWIP_DHCP) && (LWIP_ARP)) #endif @@ -760,14 +860,14 @@ * netif drivers might not set this flag, the default is off. If enabled, * netif_set_link_up() must be called to continue dhcp starting. */ -#ifndef LWIP_DHCP_CHECK_LINK_UP +#if !defined LWIP_DHCP_CHECK_LINK_UP #define LWIP_DHCP_CHECK_LINK_UP 0 #endif /** * LWIP_DHCP_BOOTP_FILE==1: Store offered_si_addr and boot_file_name. */ -#ifndef LWIP_DHCP_BOOTP_FILE +#if !defined LWIP_DHCP_BOOTP_FILE || defined __DOXYGEN__ #define LWIP_DHCP_BOOTP_FILE 0 #endif @@ -776,26 +876,55 @@ * response packet, an callback is called, which has to be provided by the port: * void dhcp_set_ntp_servers(u8_t num_ntp_servers, ip_addr_t* ntp_server_addrs); */ -#ifndef LWIP_DHCP_GET_NTP_SRV +#if !defined LWIP_DHCP_GET_NTP_SRV || defined __DOXYGEN__ #define LWIP_DHCP_GET_NTP_SRV 0 #endif /** * The maximum of NTP servers requested */ -#ifndef LWIP_DHCP_MAX_NTP_SERVERS +#if !defined LWIP_DHCP_MAX_NTP_SERVERS || defined __DOXYGEN__ #define LWIP_DHCP_MAX_NTP_SERVERS 1 #endif +/** + * LWIP_DHCP_MAX_DNS_SERVERS > 0: Request DNS servers with discover/select. + * DHCP servers received in the response are passed to DNS via @ref dns_setserver() + * (up to the maximum limit defined here). + */ +#if !defined LWIP_DHCP_MAX_DNS_SERVERS || defined __DOXYGEN__ +#define LWIP_DHCP_MAX_DNS_SERVERS DNS_MAX_SERVERS +#endif +/** + * @} + */ + +#ifndef LWIP_DHCP_IP_ADDR_RESTORE +#define LWIP_DHCP_IP_ADDR_RESTORE() 0 +#endif + +#ifndef LWIP_DHCP_IP_ADDR_STORE +#define LWIP_DHCP_IP_ADDR_STORE() +#endif + +#ifndef LWIP_DHCP_IP_ADDR_ERASE +#define LWIP_DHCP_IP_ADDR_ERASE() +#endif + /* ------------------------------------ ---------- AUTOIP options ---------- ------------------------------------ */ +/** + * @defgroup lwip_opts_autoip AUTOIP + * @ingroup lwip_opts_ipv4 + * @{ + */ /** * LWIP_AUTOIP==1: Enable AUTOIP module. */ -#ifndef LWIP_AUTOIP +#if !defined LWIP_AUTOIP || defined __DOXYGEN__ #define LWIP_AUTOIP 0 #endif #if !LWIP_IPV4 @@ -808,61 +937,61 @@ * LWIP_DHCP_AUTOIP_COOP==1: Allow DHCP and AUTOIP to be both enabled on * the same interface at the same time. */ -#ifndef LWIP_DHCP_AUTOIP_COOP +#if !defined LWIP_DHCP_AUTOIP_COOP || defined __DOXYGEN__ #define LWIP_DHCP_AUTOIP_COOP 0 #endif /** * LWIP_DHCP_AUTOIP_COOP_TRIES: Set to the number of DHCP DISCOVER probes - * that should be sent before falling back on AUTOIP. This can be set - * as low as 1 to get an AutoIP address very quickly, but you should - * be prepared to handle a changing IP address when DHCP overrides - * AutoIP. + * that should be sent before falling back on AUTOIP (the DHCP client keeps + * running in this case). This can be set as low as 1 to get an AutoIP address + * very quickly, but you should be prepared to handle a changing IP address + * when DHCP overrides AutoIP. */ -#ifndef LWIP_DHCP_AUTOIP_COOP_TRIES +#if !defined LWIP_DHCP_AUTOIP_COOP_TRIES || defined __DOXYGEN__ #define LWIP_DHCP_AUTOIP_COOP_TRIES 9 #endif - /** - * LWIP_AUTOIP_MAX_CONFLICTS: - * Maximum number of AutoIP IP conflicts before rate limiting is enabled. + * @} */ -#ifndef LWIP_AUTOIP_MAX_CONFLICTS -#define LWIP_AUTOIP_MAX_CONFLICTS 10 -#endif - -/** - * LWIP_AUTOIP_RATE_LIMIT_INTERVAL: - * Rate limited request interval, in seconds. - */ -#ifndef LWIP_AUTOIP_RATE_LIMIT_INTERVAL -#define LWIP_AUTOIP_RATE_LIMIT_INTERVAL 60 -#endif /* ---------------------------------- ----- SNMP MIB2 support ----- ---------------------------------- */ +/** + * @defgroup lwip_opts_mib2 SNMP MIB2 callbacks + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * LWIP_MIB2_CALLBACKS==1: Turn on SNMP MIB2 callbacks. * Turn this on to get callbacks needed to implement MIB2. * Usually MIB2_STATS should be enabled, too. */ -#ifndef LWIP_MIB2_CALLBACKS +#if !defined LWIP_MIB2_CALLBACKS || defined __DOXYGEN__ #define LWIP_MIB2_CALLBACKS 0 #endif +/** + * @} + */ /* ---------------------------------- ----- Multicast/IGMP options ----- ---------------------------------- */ +/** + * @defgroup lwip_opts_igmp IGMP + * @ingroup lwip_opts_ipv4 + * @{ + */ /** * LWIP_IGMP==1: Turn on IGMP module. */ -#ifndef LWIP_IGMP -#define LWIP_IGMP 1 +#if !defined LWIP_IGMP || defined __DOXYGEN__ +#define LWIP_IGMP 0 #endif #if !LWIP_IPV4 #undef LWIP_IGMP @@ -873,30 +1002,38 @@ * LWIP_MULTICAST_TX_OPTIONS==1: Enable multicast TX support like the socket options * IP_MULTICAST_TTL/IP_MULTICAST_IF/IP_MULTICAST_LOOP */ -#ifndef LWIP_MULTICAST_TX_OPTIONS -#define LWIP_MULTICAST_TX_OPTIONS LWIP_IGMP +#if !defined LWIP_MULTICAST_TX_OPTIONS || defined __DOXYGEN__ +#define LWIP_MULTICAST_TX_OPTIONS (LWIP_IGMP && LWIP_UDP) #endif +/** + * @} + */ /* ---------------------------------- ---------- DNS options ----------- ---------------------------------- */ +/** + * @defgroup lwip_opts_dns DNS + * @ingroup lwip_opts_callback + * @{ + */ /** * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS * transport. */ -#ifndef LWIP_DNS +#if !defined LWIP_DNS || defined __DOXYGEN__ #define LWIP_DNS 0 #endif /** DNS maximum number of entries to maintain locally. */ -#ifndef DNS_TABLE_SIZE +#if !defined DNS_TABLE_SIZE || defined __DOXYGEN__ #define DNS_TABLE_SIZE 4 #endif /** DNS maximum host name length supported in the name table. */ -#ifndef DNS_MAX_NAME_LENGTH +#if !defined DNS_MAX_NAME_LENGTH || defined __DOXYGEN__ #define DNS_MAX_NAME_LENGTH 256 #endif @@ -904,12 +1041,12 @@ * The first server can be initialized automatically by defining * DNS_SERVER_ADDRESS(ipaddr), where 'ipaddr' is an 'ip_addr_t*' */ -#ifndef DNS_MAX_SERVERS +#if !defined DNS_MAX_SERVERS || defined __DOXYGEN__ #define DNS_MAX_SERVERS 2 #endif /** DNS do a name checking between the query and the response. */ -#ifndef DNS_DOES_NAME_CHECK +#if !defined DNS_DOES_NAME_CHECK || defined __DOXYGEN__ #define DNS_DOES_NAME_CHECK 1 #endif @@ -917,105 +1054,129 @@ * Use all DNS security features by default. * This is overridable but should only be needed by very small targets * or when using against non standard DNS servers. */ -#ifndef LWIP_DNS_SECURE +#if !defined LWIP_DNS_SECURE || defined __DOXYGEN__ #define LWIP_DNS_SECURE (LWIP_DNS_SECURE_RAND_XID | LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING | LWIP_DNS_SECURE_RAND_SRC_PORT) #endif + /* A list of DNS security features follows */ #define LWIP_DNS_SECURE_RAND_XID 1 #define LWIP_DNS_SECURE_NO_MULTIPLE_OUTSTANDING 2 #define LWIP_DNS_SECURE_RAND_SRC_PORT 4 -/** DNS_LOCAL_HOSTLIST: Implements a local host-to-address list. If enabled, - * you have to define - * #define DNS_LOCAL_HOSTLIST_INIT {{"host1", 0x123}, {"host2", 0x234}} - * (an array of structs name/address, where address is an u32_t in network - * byte order). +/** DNS_LOCAL_HOSTLIST: Implements a local host-to-address list. If enabled, you have to define an initializer: + * \#define DNS_LOCAL_HOSTLIST_INIT {DNS_LOCAL_HOSTLIST_ELEM("host_ip4", IPADDR4_INIT_BYTES(1,2,3,4)), \ + * DNS_LOCAL_HOSTLIST_ELEM("host_ip6", IPADDR6_INIT_HOST(123, 234, 345, 456)} * * Instead, you can also use an external function: - * #define DNS_LOOKUP_LOCAL_EXTERN(x) extern u32_t my_lookup_function(const char *name) - * that returns the IP address or INADDR_NONE if not found. + * \#define DNS_LOOKUP_LOCAL_EXTERN(x) extern err_t my_lookup_function(const char *name, ip_addr_t *addr, u8_t dns_addrtype) + * that looks up the IP address and returns ERR_OK if found (LWIP_DNS_ADDRTYPE_xxx is passed in dns_addrtype). */ -#ifndef DNS_LOCAL_HOSTLIST +#if !defined DNS_LOCAL_HOSTLIST || defined __DOXYGEN__ #define DNS_LOCAL_HOSTLIST 0 #endif /* DNS_LOCAL_HOSTLIST */ /** If this is turned on, the local host-list can be dynamically changed * at runtime. */ -#ifndef DNS_LOCAL_HOSTLIST_IS_DYNAMIC +#if !defined DNS_LOCAL_HOSTLIST_IS_DYNAMIC || defined __DOXYGEN__ #define DNS_LOCAL_HOSTLIST_IS_DYNAMIC 0 #endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ +/** Set this to 1 to enable querying ".local" names via mDNS + * using a One-Shot Multicast DNS Query */ +#if !defined LWIP_DNS_SUPPORT_MDNS_QUERIES || defined __DOXYGEN__ +#define LWIP_DNS_SUPPORT_MDNS_QUERIES 0 +#endif +/** + * @} + */ + /* --------------------------------- ---------- UDP options ---------- --------------------------------- */ +/** + * @defgroup lwip_opts_udp UDP + * @ingroup lwip_opts_callback + * @{ + */ /** * LWIP_UDP==1: Turn on UDP. */ -#ifndef LWIP_UDP +#if !defined LWIP_UDP || defined __DOXYGEN__ #define LWIP_UDP 1 #endif /** * LWIP_UDPLITE==1: Turn on UDP-Lite. (Requires LWIP_UDP) */ -#ifndef LWIP_UDPLITE +#if !defined LWIP_UDPLITE || defined __DOXYGEN__ #define LWIP_UDPLITE 0 #endif /** * UDP_TTL: Default Time-To-Live value. */ -#ifndef UDP_TTL +#if !defined UDP_TTL || defined __DOXYGEN__ #define UDP_TTL (IP_DEFAULT_TTL) #endif /** * LWIP_NETBUF_RECVINFO==1: append destination addr and port to every netbuf. */ -#ifndef LWIP_NETBUF_RECVINFO +#if !defined LWIP_NETBUF_RECVINFO || defined __DOXYGEN__ #define LWIP_NETBUF_RECVINFO 0 #endif +/** + * @} + */ /* --------------------------------- ---------- TCP options ---------- --------------------------------- */ +/** + * @defgroup lwip_opts_tcp TCP + * @ingroup lwip_opts_callback + * @{ + */ /** * LWIP_TCP==1: Turn on TCP. */ -#ifndef LWIP_TCP +#if !defined LWIP_TCP || defined __DOXYGEN__ #define LWIP_TCP 1 #endif /** * TCP_TTL: Default Time-To-Live value. */ -#ifndef TCP_TTL +#if !defined TCP_TTL || defined __DOXYGEN__ #define TCP_TTL (IP_DEFAULT_TTL) #endif /** * TCP_WND: The size of a TCP window. This must be at least - * (2 * TCP_MSS) for things to work well + * (2 * TCP_MSS) for things to work well. + * ATTENTION: when using TCP_RCV_SCALE, TCP_WND is the total size + * with scaling applied. Maximum window value in the TCP header + * will be TCP_WND >> TCP_RCV_SCALE */ -#ifndef TCP_WND -#define TCP_WND(pcb) (4 * TCP_MSS) +#if !defined TCP_WND || defined __DOXYGEN__ +#define TCP_WND (4 * TCP_MSS) #endif /** * TCP_MAXRTX: Maximum number of retransmissions of data segments. */ -#ifndef TCP_MAXRTX +#if !defined TCP_MAXRTX || defined __DOXYGEN__ #define TCP_MAXRTX 12 #endif /** * TCP_SYNMAXRTX: Maximum number of retransmissions of SYN segments. */ -#ifndef TCP_SYNMAXRTX +#if !defined TCP_SYNMAXRTX || defined __DOXYGEN__ #define TCP_SYNMAXRTX 6 #endif @@ -1023,7 +1184,7 @@ * TCP_QUEUE_OOSEQ==1: TCP will queue segments that arrive out of order. * Define to 0 if your device is low on memory. */ -#ifndef TCP_QUEUE_OOSEQ +#if !defined TCP_QUEUE_OOSEQ || defined __DOXYGEN__ #define TCP_QUEUE_OOSEQ (LWIP_TCP) #endif @@ -1034,7 +1195,7 @@ * when opening a connection. For the transmit size, this MSS sets * an upper limit on the MSS advertised by the remote host. */ -#ifndef TCP_MSS +#if !defined TCP_MSS || defined __DOXYGEN__ #define TCP_MSS 536 #endif @@ -1046,7 +1207,7 @@ * Setting this to 1 enables code that checks TCP_MSS against the MTU of the * netif used for a connection and limits the MSS if it would be too big otherwise. */ -#ifndef TCP_CALCULATE_EFF_SEND_MSS +#if !defined TCP_CALCULATE_EFF_SEND_MSS || defined __DOXYGEN__ #define TCP_CALCULATE_EFF_SEND_MSS 1 #endif @@ -1055,16 +1216,16 @@ * TCP_SND_BUF: TCP sender buffer space (bytes). * To achieve good performance, this should be at least 2 * TCP_MSS. */ -#ifndef TCP_SND_BUF -#define TCP_SND_BUF(pcb) (2 * TCP_MSS) +#if !defined TCP_SND_BUF || defined __DOXYGEN__ +#define TCP_SND_BUF (2 * TCP_MSS) #endif /** * TCP_SND_QUEUELEN: TCP sender buffer space (pbufs). This must be at least * as much as (2 * TCP_SND_BUF/TCP_MSS) for things to work. */ -#ifndef TCP_SND_QUEUELEN -#define TCP_SND_QUEUELEN(pcb) ((4 * (TCP_SND_BUF((pcb))) + (TCP_MSS - 1))/(TCP_MSS)) +#if !defined TCP_SND_QUEUELEN || defined __DOXYGEN__ +#define TCP_SND_QUEUELEN ((4 * (TCP_SND_BUF) + (TCP_MSS - 1))/(TCP_MSS)) #endif /** @@ -1072,8 +1233,8 @@ * TCP_SND_BUF. It is the amount of space which must be available in the * TCP snd_buf for select to return writable (combined with TCP_SNDQUEUELOWAT). */ -#ifndef TCP_SNDLOWAT -#define TCP_SNDLOWAT(pcb) LWIP_MIN(LWIP_MAX(((TCP_SND_BUF((pcb)))/2), (2 * TCP_MSS) + 1), (TCP_SND_BUF((pcb))) - 1) +#if !defined TCP_SNDLOWAT || defined __DOXYGEN__ +#define TCP_SNDLOWAT LWIP_MIN(LWIP_MAX(((TCP_SND_BUF)/2), (2 * TCP_MSS) + 1), (TCP_SND_BUF) - 1) #endif /** @@ -1081,30 +1242,30 @@ * than TCP_SND_QUEUELEN. If the number of pbufs queued on a pcb drops below * this number, select returns writable (combined with TCP_SNDLOWAT). */ -#ifndef TCP_SNDQUEUELOWAT -#define TCP_SNDQUEUELOWAT(pcb) LWIP_MAX(((TCP_SND_QUEUELEN((pcb)))/2), 5) +#if !defined TCP_SNDQUEUELOWAT || defined __DOXYGEN__ +#define TCP_SNDQUEUELOWAT LWIP_MAX(((TCP_SND_QUEUELEN)/2), 5) #endif /** * TCP_OOSEQ_MAX_BYTES: The maximum number of bytes queued on ooseq per pcb. - * Default is 0 (no limit). Only valid for TCP_QUEUE_OOSEQ==0. + * Default is 0 (no limit). Only valid for TCP_QUEUE_OOSEQ==1. */ -#ifndef TCP_OOSEQ_MAX_BYTES +#if !defined TCP_OOSEQ_MAX_BYTES || defined __DOXYGEN__ #define TCP_OOSEQ_MAX_BYTES 0 #endif /** * TCP_OOSEQ_MAX_PBUFS: The maximum number of pbufs queued on ooseq per pcb. - * Default is 0 (no limit). Only valid for TCP_QUEUE_OOSEQ==0. + * Default is 0 (no limit). Only valid for TCP_QUEUE_OOSEQ==1. */ -#ifndef TCP_OOSEQ_MAX_PBUFS +#if !defined TCP_OOSEQ_MAX_PBUFS || defined __DOXYGEN__ #define TCP_OOSEQ_MAX_PBUFS 0 #endif /** * TCP_LISTEN_BACKLOG: Enable the backlog option for tcp listen pcb. */ -#ifndef TCP_LISTEN_BACKLOG +#if !defined TCP_LISTEN_BACKLOG || defined __DOXYGEN__ #define TCP_LISTEN_BACKLOG 0 #endif @@ -1113,7 +1274,7 @@ * This backlog is used unless another is explicitly specified. * 0xff is the maximum (u8_t). */ -#ifndef TCP_DEFAULT_LISTEN_BACKLOG +#if !defined TCP_DEFAULT_LISTEN_BACKLOG || defined __DOXYGEN__ #define TCP_DEFAULT_LISTEN_BACKLOG 0xff #endif @@ -1131,7 +1292,7 @@ * TCP_MSS: Try to create unfragmented TCP packets. * TCP_MSS/4: Try to create 4 fragments or less per TCP packet. */ -#ifndef TCP_OVERSIZE +#if !defined TCP_OVERSIZE || defined __DOXYGEN__ #define TCP_OVERSIZE TCP_MSS #endif @@ -1141,7 +1302,7 @@ * really used locally. Therefore, it is only enabled when a TS option is * received in the initial SYN packet from a remote host. */ -#ifndef LWIP_TCP_TIMESTAMPS +#if !defined LWIP_TCP_TIMESTAMPS || defined __DOXYGEN__ #define LWIP_TCP_TIMESTAMPS 0 #endif @@ -1149,8 +1310,8 @@ * TCP_WND_UPDATE_THRESHOLD: difference in window to trigger an * explicit window update */ -#ifndef TCP_WND_UPDATE_THRESHOLD -#define TCP_WND_UPDATE_THRESHOLD(pcb) LWIP_MIN((TCP_WND((pcb)) / 4), (TCP_MSS * 4)) +#if !defined TCP_WND_UPDATE_THRESHOLD || defined __DOXYGEN__ +#define TCP_WND_UPDATE_THRESHOLD LWIP_MIN((TCP_WND / 4), (TCP_MSS * 4)) #endif /** @@ -1160,9 +1321,16 @@ * LWIP_CALLBACK_API==1: The PCB callback function is called directly * for the event. This is the default. */ -#if !defined(LWIP_EVENT_API) && !defined(LWIP_CALLBACK_API) +#if !defined(LWIP_EVENT_API) && !defined(LWIP_CALLBACK_API) || defined __DOXYGEN__ #define LWIP_EVENT_API 0 #define LWIP_CALLBACK_API 1 +#else +#ifndef LWIP_EVENT_API +#define LWIP_EVENT_API 0 +#endif +#ifndef LWIP_CALLBACK_API +#define LWIP_CALLBACK_API 0 +#endif #endif /** @@ -1173,24 +1341,31 @@ * When LWIP_WND_SCALE is enabled but TCP_RCV_SCALE is 0, we can use a large * send window while having a small receive window only. */ -#ifndef LWIP_WND_SCALE +#if !defined LWIP_WND_SCALE || defined __DOXYGEN__ #define LWIP_WND_SCALE 0 #define TCP_RCV_SCALE 0 #endif - +/** + * @} + */ /* ---------------------------------- ---------- Pbuf options ---------- ---------------------------------- */ +/** + * @defgroup lwip_opts_pbuf PBUF + * @ingroup lwip_opts + * @{ + */ /** * PBUF_LINK_HLEN: the number of bytes that should be allocated for a * link level header. The default is 14, the standard value for * Ethernet. */ -#ifndef PBUF_LINK_HLEN -#ifdef LWIP_HOOK_VLAN_SET +#if !defined PBUF_LINK_HLEN || defined __DOXYGEN__ +#if defined LWIP_HOOK_VLAN_SET && !defined __DOXYGEN__ #define PBUF_LINK_HLEN (18 + ETH_PAD_SIZE) #else /* LWIP_HOOK_VLAN_SET */ #define PBUF_LINK_HLEN (14 + ETH_PAD_SIZE) @@ -1201,8 +1376,8 @@ * PBUF_LINK_ENCAPSULATION_HLEN: the number of bytes that should be allocated * for an additional encapsulation header before ethernet headers (e.g. 802.11) */ -#ifndef PBUF_LINK_ENCAPSULATION_HLEN -#define PBUF_LINK_ENCAPSULATION_HLEN 0 +#if !defined PBUF_LINK_ENCAPSULATION_HLEN || defined __DOXYGEN__ +#define PBUF_LINK_ENCAPSULATION_HLEN 0u #endif /** @@ -1210,27 +1385,35 @@ * designed to accommodate single full size TCP frame in one pbuf, including * TCP_MSS, IP header, and link header. */ -#ifndef PBUF_POOL_BUFSIZE +#if !defined PBUF_POOL_BUFSIZE || defined __DOXYGEN__ #define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE(TCP_MSS+40+PBUF_LINK_ENCAPSULATION_HLEN+PBUF_LINK_HLEN) #endif +/** + * @} + */ /* ------------------------------------------------ ---------- Network Interfaces options ---------- ------------------------------------------------ */ +/** + * @defgroup lwip_opts_netif NETIF + * @ingroup lwip_opts + * @{ + */ /** * LWIP_NETIF_HOSTNAME==1: use DHCP_OPTION_HOSTNAME with netif's hostname * field. */ -#ifndef LWIP_NETIF_HOSTNAME +#if !defined LWIP_NETIF_HOSTNAME || defined __DOXYGEN__ #define LWIP_NETIF_HOSTNAME 0 #endif /** * LWIP_NETIF_API==1: Support netif api (in netifapi.c) */ -#ifndef LWIP_NETIF_API +#if !defined LWIP_NETIF_API || defined __DOXYGEN__ #define LWIP_NETIF_API 0 #endif @@ -1238,7 +1421,7 @@ * LWIP_NETIF_STATUS_CALLBACK==1: Support a callback function whenever an interface * changes its up/down status (i.e., due to DHCP IP acquisition) */ -#ifndef LWIP_NETIF_STATUS_CALLBACK +#if !defined LWIP_NETIF_STATUS_CALLBACK || defined __DOXYGEN__ #define LWIP_NETIF_STATUS_CALLBACK 0 #endif @@ -1246,7 +1429,7 @@ * LWIP_NETIF_LINK_CALLBACK==1: Support a callback function from an interface * whenever the link changes (i.e., link down) */ -#ifndef LWIP_NETIF_LINK_CALLBACK +#if !defined LWIP_NETIF_LINK_CALLBACK || defined __DOXYGEN__ #define LWIP_NETIF_LINK_CALLBACK 0 #endif @@ -1254,7 +1437,7 @@ * LWIP_NETIF_REMOVE_CALLBACK==1: Support a callback function that is called * when a netif has been removed */ -#ifndef LWIP_NETIF_REMOVE_CALLBACK +#if !defined LWIP_NETIF_REMOVE_CALLBACK || defined __DOXYGEN__ #define LWIP_NETIF_REMOVE_CALLBACK 0 #endif @@ -1265,15 +1448,65 @@ * ARP tables or many concurrent connections, it might be counterproductive * if you have a tiny ARP table or if there never are concurrent connections. */ -#ifndef LWIP_NETIF_HWADDRHINT +#if !defined LWIP_NETIF_HWADDRHINT || defined __DOXYGEN__ #define LWIP_NETIF_HWADDRHINT 0 #endif +/** + * LWIP_NETIF_TX_SINGLE_PBUF: if this is set to 1, lwIP tries to put all data + * to be sent into one single pbuf. This is for compatibility with DMA-enabled + * MACs that do not support scatter-gather. + * Beware that this might involve CPU-memcpy before transmitting that would not + * be needed without this flag! Use this only if you need to! + * + * @todo: TCP and IP-frag do not work with this, yet: + */ +#if !defined LWIP_NETIF_TX_SINGLE_PBUF || defined __DOXYGEN__ +#define LWIP_NETIF_TX_SINGLE_PBUF 0 +#endif /* LWIP_NETIF_TX_SINGLE_PBUF */ + +/** + * LWIP_NUM_NETIF_CLIENT_DATA: Number of clients that may store + * data in client_data member array of struct netif. + */ +#if !defined LWIP_NUM_NETIF_CLIENT_DATA || defined __DOXYGEN__ +#define LWIP_NUM_NETIF_CLIENT_DATA 0 +#endif +/** + * @} + */ + +/* + ------------------------------------ + ---------- LOOPIF options ---------- + ------------------------------------ +*/ +/** + * @defgroup lwip_opts_loop Loopback interface + * @ingroup lwip_opts_netif + * @{ + */ +/** + * LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1). + * This is only needed when no real netifs are available. If at least one other + * netif is available, loopback traffic uses this netif. + */ +#if !defined LWIP_HAVE_LOOPIF || defined __DOXYGEN__ +#define LWIP_HAVE_LOOPIF LWIP_NETIF_LOOPBACK +#endif + +/** + * LWIP_LOOPIF_MULTICAST==1: Support multicast/IGMP on loop interface (127.0.0.1). + */ +#if !defined LWIP_LOOPIF_MULTICAST || defined __DOXYGEN__ +#define LWIP_LOOPIF_MULTICAST 0 +#endif + /** * LWIP_NETIF_LOOPBACK==1: Support sending packets with a destination IP * address equal to the netif IP address, looping them back up the stack. */ -#ifndef LWIP_NETIF_LOOPBACK +#if !defined LWIP_NETIF_LOOPBACK || defined __DOXYGEN__ #define LWIP_NETIF_LOOPBACK 0 #endif @@ -1281,7 +1514,7 @@ * LWIP_LOOPBACK_MAX_PBUFS: Maximum number of pbufs on queue for loopback * sending for each netif (0 = disabled) */ -#ifndef LWIP_LOOPBACK_MAX_PBUFS +#if !defined LWIP_LOOPBACK_MAX_PBUFS || defined __DOXYGEN__ #define LWIP_LOOPBACK_MAX_PBUFS 0 #endif @@ -1298,65 +1531,27 @@ * The packets are put on a list and netif_poll() must be called in * the main application loop. */ -#ifndef LWIP_NETIF_LOOPBACK_MULTITHREADING +#if !defined LWIP_NETIF_LOOPBACK_MULTITHREADING || defined __DOXYGEN__ #define LWIP_NETIF_LOOPBACK_MULTITHREADING (!NO_SYS) #endif - /** - * LWIP_NETIF_TX_SINGLE_PBUF: if this is set to 1, lwIP tries to put all data - * to be sent into one single pbuf. This is for compatibility with DMA-enabled - * MACs that do not support scatter-gather. - * Beware that this might involve CPU-memcpy before transmitting that would not - * be needed without this flag! Use this only if you need to! - * - * @todo: TCP and IP-frag do not work with this, yet: + * @} */ -#ifndef LWIP_NETIF_TX_SINGLE_PBUF -#define LWIP_NETIF_TX_SINGLE_PBUF 0 -#endif /* LWIP_NETIF_TX_SINGLE_PBUF */ - -/* - ------------------------------------ - ---------- LOOPIF options ---------- - ------------------------------------ -*/ -/** - * LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1). - * This is only needed when no real netifs are available. If at least one other - * netif is available, loopback traffic uses this netif. - */ -#ifndef LWIP_HAVE_LOOPIF -#define LWIP_HAVE_LOOPIF LWIP_NETIF_LOOPBACK -#endif - -/** - * LWIP_LOOPIF_MULTICAST==1: Support multicast/IGMP on loop interface (127.0.0.1). - */ -#ifndef LWIP_LOOPIF_MULTICAST -#define LWIP_LOOPIF_MULTICAST 0 -#endif - -/* - ------------------------------------ - ---------- SLIPIF options ---------- - ------------------------------------ -*/ -/** - * LWIP_HAVE_SLIPIF==1: Support slip interface and slipif.c - */ -#ifndef LWIP_HAVE_SLIPIF -#define LWIP_HAVE_SLIPIF 0 -#endif /* ------------------------------------ ---------- Thread options ---------- ------------------------------------ */ +/** + * @defgroup lwip_opts_thread Threading + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * TCPIP_THREAD_NAME: The name assigned to the main tcpip thread. */ -#ifndef TCPIP_THREAD_NAME +#if !defined TCPIP_THREAD_NAME || defined __DOXYGEN__ #define TCPIP_THREAD_NAME "tcpip_thread" #endif @@ -1365,7 +1560,7 @@ * The stack size value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef TCPIP_THREAD_STACKSIZE +#if !defined TCPIP_THREAD_STACKSIZE || defined __DOXYGEN__ #define TCPIP_THREAD_STACKSIZE 0 #endif @@ -1374,7 +1569,7 @@ * The priority value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef TCPIP_THREAD_PRIO +#if !defined TCPIP_THREAD_PRIO || defined __DOXYGEN__ #define TCPIP_THREAD_PRIO 1 #endif @@ -1383,14 +1578,22 @@ * The queue size value itself is platform-dependent, but is passed to * sys_mbox_new() when tcpip_init is called. */ -#ifndef TCPIP_MBOX_SIZE +#if !defined TCPIP_MBOX_SIZE || defined __DOXYGEN__ #define TCPIP_MBOX_SIZE 0 #endif +/** + * Define this to something that triggers a watchdog. This is called from + * tcpip_thread after processing a message. + */ +#if !defined LWIP_TCPIP_THREAD_ALIVE || defined __DOXYGEN__ +#define LWIP_TCPIP_THREAD_ALIVE() +#endif + /** * SLIPIF_THREAD_NAME: The name assigned to the slipif_loop thread. */ -#ifndef SLIPIF_THREAD_NAME +#if !defined SLIPIF_THREAD_NAME || defined __DOXYGEN__ #define SLIPIF_THREAD_NAME "slipif_loop" #endif @@ -1399,7 +1602,7 @@ * The stack size value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef SLIPIF_THREAD_STACKSIZE +#if !defined SLIPIF_THREAD_STACKSIZE || defined __DOXYGEN__ #define SLIPIF_THREAD_STACKSIZE 0 #endif @@ -1408,14 +1611,14 @@ * The priority value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef SLIPIF_THREAD_PRIO +#if !defined SLIPIF_THREAD_PRIO || defined __DOXYGEN__ #define SLIPIF_THREAD_PRIO 1 #endif /** * DEFAULT_THREAD_NAME: The name assigned to any other lwIP thread. */ -#ifndef DEFAULT_THREAD_NAME +#if !defined DEFAULT_THREAD_NAME || defined __DOXYGEN__ #define DEFAULT_THREAD_NAME "lwIP" #endif @@ -1424,7 +1627,7 @@ * The stack size value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef DEFAULT_THREAD_STACKSIZE +#if !defined DEFAULT_THREAD_STACKSIZE || defined __DOXYGEN__ #define DEFAULT_THREAD_STACKSIZE 0 #endif @@ -1433,7 +1636,7 @@ * The priority value itself is platform-dependent, but is passed to * sys_thread_new() when the thread is created. */ -#ifndef DEFAULT_THREAD_PRIO +#if !defined DEFAULT_THREAD_PRIO || defined __DOXYGEN__ #define DEFAULT_THREAD_PRIO 1 #endif @@ -1442,7 +1645,7 @@ * NETCONN_RAW. The queue size value itself is platform-dependent, but is passed * to sys_mbox_new() when the recvmbox is created. */ -#ifndef DEFAULT_RAW_RECVMBOX_SIZE +#if !defined DEFAULT_RAW_RECVMBOX_SIZE || defined __DOXYGEN__ #define DEFAULT_RAW_RECVMBOX_SIZE 0 #endif @@ -1451,7 +1654,7 @@ * NETCONN_UDP. The queue size value itself is platform-dependent, but is passed * to sys_mbox_new() when the recvmbox is created. */ -#ifndef DEFAULT_UDP_RECVMBOX_SIZE +#if !defined DEFAULT_UDP_RECVMBOX_SIZE || defined __DOXYGEN__ #define DEFAULT_UDP_RECVMBOX_SIZE 0 #endif @@ -1460,7 +1663,7 @@ * NETCONN_TCP. The queue size value itself is platform-dependent, but is passed * to sys_mbox_new() when the recvmbox is created. */ -#ifndef DEFAULT_TCP_RECVMBOX_SIZE +#if !defined DEFAULT_TCP_RECVMBOX_SIZE || defined __DOXYGEN__ #define DEFAULT_TCP_RECVMBOX_SIZE 0 #endif @@ -1469,9 +1672,12 @@ * The queue size value itself is platform-dependent, but is passed to * sys_mbox_new() when the acceptmbox is created. */ -#ifndef DEFAULT_ACCEPTMBOX_SIZE +#if !defined DEFAULT_ACCEPTMBOX_SIZE || defined __DOXYGEN__ #define DEFAULT_ACCEPTMBOX_SIZE 0 #endif +/** + * @} + */ /* ---------------------------------------------- @@ -1479,32 +1685,21 @@ ---------------------------------------------- */ /** - * LWIP_TCPIP_CORE_LOCKING: (EXPERIMENTAL!) - * Don't use it if you're not an active lwIP project member + * @defgroup lwip_opts_netconn Netconn + * @ingroup lwip_opts_threadsafe_apis + * @{ */ -#ifndef LWIP_TCPIP_CORE_LOCKING -#define LWIP_TCPIP_CORE_LOCKING 0 -#endif - -/** - * LWIP_TCPIP_CORE_LOCKING_INPUT: (EXPERIMENTAL!) - * Don't use it if you're not an active lwIP project member - */ -#ifndef LWIP_TCPIP_CORE_LOCKING_INPUT -#define LWIP_TCPIP_CORE_LOCKING_INPUT 0 -#endif - /** * LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c) */ -#ifndef LWIP_NETCONN +#if !defined LWIP_NETCONN || defined __DOXYGEN__ #define LWIP_NETCONN 1 #endif /** LWIP_TCPIP_TIMEOUT==1: Enable tcpip_timeout/tcpip_untimeout to create * timers running in tcpip_thread from another thread. */ -#ifndef LWIP_TCPIP_TIMEOUT +#if !defined LWIP_TCPIP_TIMEOUT || defined __DOXYGEN__ #define LWIP_TCPIP_TIMEOUT 0 #endif @@ -1518,7 +1713,7 @@ * The latter 2 can be invoked up by calling netconn_thread_init()/netconn_thread_cleanup(). * Ports may call these for threads created with sys_thread_new(). */ -#ifndef LWIP_NETCONN_SEM_PER_THREAD +#if !defined LWIP_NETCONN_SEM_PER_THREAD || defined __DOXYGEN__ #define LWIP_NETCONN_SEM_PER_THREAD 0 #endif @@ -1530,26 +1725,34 @@ * - sys_mbox_free() has to unblock receive tasks waiting on recvmbox/acceptmbox * and prevent a task pending on this during/after deletion */ -#ifndef LWIP_NETCONN_FULLDUPLEX +#if !defined LWIP_NETCONN_FULLDUPLEX || defined __DOXYGEN__ #define LWIP_NETCONN_FULLDUPLEX 0 #endif +/** + * @} + */ /* ------------------------------------ ---------- Socket options ---------- ------------------------------------ */ +/** + * @defgroup lwip_opts_socket Sockets + * @ingroup lwip_opts_threadsafe_apis + * @{ + */ /** * LWIP_SOCKET==1: Enable Socket API (require to use sockets.c) */ -#ifndef LWIP_SOCKET +#if !defined LWIP_SOCKET || defined __DOXYGEN__ #define LWIP_SOCKET 1 #endif /* LWIP_SOCKET_SET_ERRNO==1: Set errno when socket functions cannot complete * successfully, as required by POSIX. Default is POSIX-compliant. */ -#ifndef LWIP_SOCKET_SET_ERRNO +#if !defined LWIP_SOCKET_SET_ERRNO || defined __DOXYGEN__ #define LWIP_SOCKET_SET_ERRNO 1 #endif @@ -1559,7 +1762,7 @@ * While this helps code completion, it might conflict with existing libraries. * (only used if you use sockets.c) */ -#ifndef LWIP_COMPAT_SOCKETS +#if !defined LWIP_COMPAT_SOCKETS || defined __DOXYGEN__ #define LWIP_COMPAT_SOCKETS 1 #endif @@ -1568,7 +1771,7 @@ * Disable this option if you use a POSIX operating system that uses the same * names (read, write & close). (only used if you use sockets.c) */ -#ifndef LWIP_POSIX_SOCKETS_IO_NAMES +#if !defined LWIP_POSIX_SOCKETS_IO_NAMES || defined __DOXYGEN__ #define LWIP_POSIX_SOCKETS_IO_NAMES 1 #endif @@ -1579,7 +1782,7 @@ * re implement read/write/close/ioctl/fnctl to send the requested action to the right * library (sharing select will need more work though). */ -#ifndef LWIP_SOCKET_OFFSET +#if !defined LWIP_SOCKET_OFFSET || defined __DOXYGEN__ #define LWIP_SOCKET_OFFSET 0 #endif @@ -1588,7 +1791,7 @@ * options processing. Note that TCP_KEEPIDLE and TCP_KEEPINTVL have to be set * in seconds. (does not require sockets.c, and will affect tcp.c) */ -#ifndef LWIP_TCP_KEEPALIVE +#if !defined LWIP_TCP_KEEPALIVE || defined __DOXYGEN__ #define LWIP_TCP_KEEPALIVE 0 #endif @@ -1596,7 +1799,7 @@ * LWIP_SO_SNDTIMEO==1: Enable send timeout for sockets/netconns and * SO_SNDTIMEO processing. */ -#ifndef LWIP_SO_SNDTIMEO +#if !defined LWIP_SO_SNDTIMEO || defined __DOXYGEN__ #define LWIP_SO_SNDTIMEO 0 #endif @@ -1604,7 +1807,7 @@ * LWIP_SO_RCVTIMEO==1: Enable receive timeout for sockets/netconns and * SO_RCVTIMEO processing. */ -#ifndef LWIP_SO_RCVTIMEO +#if !defined LWIP_SO_RCVTIMEO || defined __DOXYGEN__ #define LWIP_SO_RCVTIMEO 0 #endif @@ -1612,42 +1815,42 @@ * LWIP_SO_SNDRCVTIMEO_NONSTANDARD==1: SO_RCVTIMEO/SO_SNDTIMEO take an int * (milliseconds, much like winsock does) instead of a struct timeval (default). */ -#ifndef LWIP_SO_SNDRCVTIMEO_NONSTANDARD +#if !defined LWIP_SO_SNDRCVTIMEO_NONSTANDARD || defined __DOXYGEN__ #define LWIP_SO_SNDRCVTIMEO_NONSTANDARD 0 #endif /** * LWIP_SO_RCVBUF==1: Enable SO_RCVBUF processing. */ -#ifndef LWIP_SO_RCVBUF +#if !defined LWIP_SO_RCVBUF || defined __DOXYGEN__ #define LWIP_SO_RCVBUF 0 #endif /** * LWIP_SO_LINGER==1: Enable SO_LINGER processing. */ -#ifndef LWIP_SO_LINGER +#if !defined LWIP_SO_LINGER || defined __DOXYGEN__ #define LWIP_SO_LINGER 0 #endif /** * If LWIP_SO_RCVBUF is used, this is the default value for recv_bufsize. */ -#ifndef RECV_BUFSIZE_DEFAULT +#if !defined RECV_BUFSIZE_DEFAULT || defined __DOXYGEN__ #define RECV_BUFSIZE_DEFAULT INT_MAX #endif /** * By default, TCP socket/netconn close waits 20 seconds max to send the FIN */ -#ifndef LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT +#if !defined LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT || defined __DOXYGEN__ #define LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT 20000 #endif /** * SO_REUSE==1: Enable SO_REUSEADDR option. */ -#ifndef SO_REUSE +#if !defined SO_REUSE || defined __DOXYGEN__ #define SO_REUSE 0 #endif @@ -1656,7 +1859,7 @@ * to all local matches if SO_REUSEADDR is turned on. * WARNING: Adds a memcpy for every packet if passing to more than one pcb! */ -#ifndef SO_REUSE_RXTOALL +#if !defined SO_REUSE_RXTOALL || defined __DOXYGEN__ #define SO_REUSE_RXTOALL 0 #endif @@ -1668,20 +1871,28 @@ * pending datagram in bytes. This is the way linux does it. This code is only * here for compatibility. */ -#ifndef LWIP_FIONREAD_LINUXMODE +#if !defined LWIP_FIONREAD_LINUXMODE || defined __DOXYGEN__ #define LWIP_FIONREAD_LINUXMODE 0 #endif +/** + * @} + */ /* ---------------------------------------- ---------- Statistics options ---------- ---------------------------------------- */ +/** + * @defgroup lwip_opts_stats Statistics + * @ingroup lwip_opts_debug + * @{ + */ /** * LWIP_STATS==1: Enable statistics collection in lwip_stats. */ -#ifndef LWIP_STATS -#define LWIP_STATS 0 +#if !defined LWIP_STATS || defined __DOXYGEN__ +#define LWIP_STATS 1 #endif #if LWIP_STATS @@ -1689,28 +1900,28 @@ /** * LWIP_STATS_DISPLAY==1: Compile in the statistics output functions. */ -#ifndef LWIP_STATS_DISPLAY +#if !defined LWIP_STATS_DISPLAY || defined __DOXYGEN__ #define LWIP_STATS_DISPLAY 0 #endif /** * LINK_STATS==1: Enable link stats. */ -#ifndef LINK_STATS +#if !defined LINK_STATS || defined __DOXYGEN__ #define LINK_STATS 1 #endif /** * ETHARP_STATS==1: Enable etharp stats. */ -#ifndef ETHARP_STATS +#if !defined ETHARP_STATS || defined __DOXYGEN__ #define ETHARP_STATS (LWIP_ARP) #endif /** * IP_STATS==1: Enable IP stats. */ -#ifndef IP_STATS +#if !defined IP_STATS || defined __DOXYGEN__ #define IP_STATS 1 #endif @@ -1718,21 +1929,21 @@ * IPFRAG_STATS==1: Enable IP fragmentation stats. Default is * on if using either frag or reass. */ -#ifndef IPFRAG_STATS +#if !defined IPFRAG_STATS || defined __DOXYGEN__ #define IPFRAG_STATS (IP_REASSEMBLY || IP_FRAG) #endif /** * ICMP_STATS==1: Enable ICMP stats. */ -#ifndef ICMP_STATS +#if !defined ICMP_STATS || defined __DOXYGEN__ #define ICMP_STATS 1 #endif /** * IGMP_STATS==1: Enable IGMP stats. */ -#ifndef IGMP_STATS +#if !defined IGMP_STATS || defined __DOXYGEN__ #define IGMP_STATS (LWIP_IGMP) #endif @@ -1740,7 +1951,7 @@ * UDP_STATS==1: Enable UDP stats. Default is on if * UDP enabled, otherwise off. */ -#ifndef UDP_STATS +#if !defined UDP_STATS || defined __DOXYGEN__ #define UDP_STATS (LWIP_UDP) #endif @@ -1748,70 +1959,70 @@ * TCP_STATS==1: Enable TCP stats. Default is on if TCP * enabled, otherwise off. */ -#ifndef TCP_STATS +#if !defined TCP_STATS || defined __DOXYGEN__ #define TCP_STATS (LWIP_TCP) #endif /** * MEM_STATS==1: Enable mem.c stats. */ -#ifndef MEM_STATS +#if !defined MEM_STATS || defined __DOXYGEN__ #define MEM_STATS ((MEM_LIBC_MALLOC == 0) && (MEM_USE_POOLS == 0)) #endif /** * MEMP_STATS==1: Enable memp.c pool stats. */ -#ifndef MEMP_STATS +#if !defined MEMP_STATS || defined __DOXYGEN__ #define MEMP_STATS (MEMP_MEM_MALLOC == 0) #endif /** * SYS_STATS==1: Enable system stats (sem and mbox counts, etc). */ -#ifndef SYS_STATS +#if !defined SYS_STATS || defined __DOXYGEN__ #define SYS_STATS (NO_SYS == 0) #endif /** * IP6_STATS==1: Enable IPv6 stats. */ -#ifndef IP6_STATS +#if !defined IP6_STATS || defined __DOXYGEN__ #define IP6_STATS (LWIP_IPV6) #endif /** * ICMP6_STATS==1: Enable ICMP for IPv6 stats. */ -#ifndef ICMP6_STATS +#if !defined ICMP6_STATS || defined __DOXYGEN__ #define ICMP6_STATS (LWIP_IPV6 && LWIP_ICMP6) #endif /** * IP6_FRAG_STATS==1: Enable IPv6 fragmentation stats. */ -#ifndef IP6_FRAG_STATS +#if !defined IP6_FRAG_STATS || defined __DOXYGEN__ #define IP6_FRAG_STATS (LWIP_IPV6 && (LWIP_IPV6_FRAG || LWIP_IPV6_REASS)) #endif /** * MLD6_STATS==1: Enable MLD for IPv6 stats. */ -#ifndef MLD6_STATS +#if !defined MLD6_STATS || defined __DOXYGEN__ #define MLD6_STATS (LWIP_IPV6 && LWIP_IPV6_MLD) #endif /** * ND6_STATS==1: Enable Neighbor discovery for IPv6 stats. */ -#ifndef ND6_STATS +#if !defined ND6_STATS || defined __DOXYGEN__ #define ND6_STATS (LWIP_IPV6) #endif /** * MIB2_STATS==1: Stats for SNMP MIB2. */ -#ifndef MIB2_STATS +#if !defined MIB2_STATS || defined __DOXYGEN__ #define MIB2_STATS 0 #endif @@ -1837,602 +2048,96 @@ #define MIB2_STATS 0 #endif /* LWIP_STATS */ - -/* - --------------------------------- - ---------- PPP options ---------- - --------------------------------- -*/ - /** - * PPP_SUPPORT==1: Enable PPP. + * @} */ -#ifndef PPP_SUPPORT -#define PPP_SUPPORT 0 -#endif - -/** - * PPPOE_SUPPORT==1: Enable PPP Over Ethernet - */ -#ifndef PPPOE_SUPPORT -#define PPPOE_SUPPORT 0 -#endif - -/** - * PPPOL2TP_SUPPORT==1: Enable PPP Over L2TP - */ -#ifndef PPPOL2TP_SUPPORT -#define PPPOL2TP_SUPPORT 0 -#endif - -/** - * PPPOL2TP_AUTH_SUPPORT==1: Enable PPP Over L2TP Auth (enable MD5 support) - */ -#ifndef PPPOL2TP_AUTH_SUPPORT -#define PPPOL2TP_AUTH_SUPPORT PPPOL2TP_SUPPORT -#endif - -/** - * PPPOS_SUPPORT==1: Enable PPP Over Serial - */ -#ifndef PPPOS_SUPPORT -#define PPPOS_SUPPORT PPP_SUPPORT -#endif - -/** - * LWIP_PPP_API==1: Enable PPP API (in pppapi.c) - */ -#ifndef LWIP_PPP_API -#define LWIP_PPP_API (PPP_SUPPORT && (NO_SYS == 0)) -#endif - -#if PPP_SUPPORT - -/** - * PPP_INPROC_IRQ_SAFE==1 call pppos_input() using tcpip_callback(). - * - * Please read the "PPPoS input path" chapter in the PPP documentation about this option. - */ -#ifndef PPP_INPROC_IRQ_SAFE -#define PPP_INPROC_IRQ_SAFE 0 -#endif - -/** - * PRINTPKT_SUPPORT==1: Enable PPP print packet support - * - * Mandatory for debugging, it displays exchanged packet content in debug trace. - */ -#ifndef PRINTPKT_SUPPORT -#define PRINTPKT_SUPPORT 0 -#endif - -/** - * PPP_IPV4_SUPPORT==1: Enable PPP IPv4 support - */ -#ifndef PPP_IPV4_SUPPORT -#define PPP_IPV4_SUPPORT (LWIP_IPV4) -#endif - -/** - * PPP_IPV6_SUPPORT==1: Enable PPP IPv6 support - */ -#ifndef PPP_IPV6_SUPPORT -#define PPP_IPV6_SUPPORT (LWIP_IPV6) -#endif - -/** - * PPP_NOTIFY_PHASE==1: Support PPP notify phase support - * - * PPP notify phase support allows you to set a callback which is - * called on change of the internal PPP state machine. - * - * This can be used for example to set a LED pattern depending on the - * current phase of the PPP session. - */ -#ifndef PPP_NOTIFY_PHASE -#define PPP_NOTIFY_PHASE 0 -#endif - -/** - * pbuf_type PPP is using for LCP, PAP, CHAP, EAP, CCP, IPCP and IP6CP packets. - * - * Memory allocated must be single buffered for PPP to works, it requires pbuf - * that are not going to be chained when allocated. This requires setting - * PBUF_POOL_BUFSIZE to at least 512 bytes, which is quite huge for small systems. - * - * Setting PPP_USE_PBUF_RAM to 1 makes PPP use memory from heap where continuous - * buffers are required, allowing you to use a smaller PBUF_POOL_BUFSIZE. - */ -#ifndef PPP_USE_PBUF_RAM -#define PPP_USE_PBUF_RAM 0 -#endif - -/** - * PPP_FCS_TABLE: Keep a 256*2 byte table to speed up FCS calculation for PPPoS - */ -#ifndef PPP_FCS_TABLE -#define PPP_FCS_TABLE 1 -#endif - -/** - * PAP_SUPPORT==1: Support PAP. - */ -#ifndef PAP_SUPPORT -#define PAP_SUPPORT 0 -#endif - -/** - * CHAP_SUPPORT==1: Support CHAP. - */ -#ifndef CHAP_SUPPORT -#define CHAP_SUPPORT 0 -#endif - -/** - * MSCHAP_SUPPORT==1: Support MSCHAP. - */ -#ifndef MSCHAP_SUPPORT -#define MSCHAP_SUPPORT 0 -#endif -#if MSCHAP_SUPPORT -/* MSCHAP requires CHAP support */ -#undef CHAP_SUPPORT -#define CHAP_SUPPORT 1 -#endif /* MSCHAP_SUPPORT */ - -/** - * EAP_SUPPORT==1: Support EAP. - */ -#ifndef EAP_SUPPORT -#define EAP_SUPPORT 0 -#endif - -/** - * CCP_SUPPORT==1: Support CCP. - */ -#ifndef CCP_SUPPORT -#define CCP_SUPPORT 0 -#endif - -/** - * MPPE_SUPPORT==1: Support MPPE. - */ -#ifndef MPPE_SUPPORT -#define MPPE_SUPPORT 0 -#endif -#if MPPE_SUPPORT -/* MPPE requires CCP support */ -#undef CCP_SUPPORT -#define CCP_SUPPORT 1 -/* MPPE requires MSCHAP support */ -#undef MSCHAP_SUPPORT -#define MSCHAP_SUPPORT 1 -/* MSCHAP requires CHAP support */ -#undef CHAP_SUPPORT -#define CHAP_SUPPORT 1 -#endif /* MPPE_SUPPORT */ - -/** - * CBCP_SUPPORT==1: Support CBCP. CURRENTLY NOT SUPPORTED! DO NOT SET! - */ -#ifndef CBCP_SUPPORT -#define CBCP_SUPPORT 0 -#endif - -/** - * ECP_SUPPORT==1: Support ECP. CURRENTLY NOT SUPPORTED! DO NOT SET! - */ -#ifndef ECP_SUPPORT -#define ECP_SUPPORT 0 -#endif - -/** - * DEMAND_SUPPORT==1: Support dial on demand. CURRENTLY NOT SUPPORTED! DO NOT SET! - */ -#ifndef DEMAND_SUPPORT -#define DEMAND_SUPPORT 0 -#endif - -/** - * LQR_SUPPORT==1: Support Link Quality Report. Do nothing except exchanging some LCP packets. - */ -#ifndef LQR_SUPPORT -#define LQR_SUPPORT 0 -#endif - -/** - * PPP_SERVER==1: Enable PPP server support (waiting for incoming PPP session). - * - * Currently only supported for PPPoS. - */ -#ifndef PPP_SERVER -#define PPP_SERVER 0 -#endif - -#if PPP_SERVER -/* - * PPP_OUR_NAME: Our name for authentication purposes - */ -#ifndef PPP_OUR_NAME -#define PPP_OUR_NAME "lwIP" -#endif -#endif /* PPP_SERVER */ - -/** - * VJ_SUPPORT==1: Support VJ header compression. - */ -#ifndef VJ_SUPPORT -#define VJ_SUPPORT 1 -#endif -/* VJ compression is only supported for IPv4 over PPPoS. */ -#if !PPPOS_SUPPORT || !PPP_IPV4_SUPPORT -#undef VJ_SUPPORT -#define VJ_SUPPORT 0 -#endif /* !PPPOS_SUPPORT */ - -/** - * PPP_MD5_RANDM==1: Use MD5 for better randomness. - * Enabled by default if CHAP, EAP, or L2TP AUTH support is enabled. - */ -#ifndef PPP_MD5_RANDM -#define PPP_MD5_RANDM (CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT) -#endif - -/** - * PolarSSL library, used if necessary and not previously disabled - * - * - * lwIP contains some files fetched from the latest BSD release of - * the PolarSSL project for ciphers and encryption methods we need for lwIP - * PPP support. - * - * The PolarSSL files were cleaned to contain only the necessary struct - * fields and functions needed for lwIP. - * - * The PolarSSL API was not changed at all, so if you are already using - * PolarSSL you can choose to skip the compilation of the included PolarSSL - * library into lwIP: - * - * The following defines are available for flexibility: - * - * LWIP_INCLUDED_POLARSSL_MD4 ; Use lwIP internal PolarSSL for MD4 - * LWIP_INCLUDED_POLARSSL_MD5 ; Use lwIP internal PolarSSL for MD5 - * LWIP_INCLUDED_POLARSSL_SHA1 ; Use lwIP internal PolarSSL for SHA1 - * LWIP_INCLUDED_POLARSSL_DES ; Use lwIP internal PolarSSL for DES - * - * If set (=1), the default if required by another enabled PPP feature unless - * explicitly set to 0, using included lwIP PolarSSL. - * - * If clear (=0), not needed or using external PolarSSL. - * - * Beware of the stack requirements which can be a lot larger if you are not - * using our cleaned PolarSSL library. - */ - -/* CHAP, EAP, L2TP AUTH and MD5 Random require MD5 support */ -#if CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM -#ifndef LWIP_INCLUDED_POLARSSL_MD5 -#define LWIP_INCLUDED_POLARSSL_MD5 1 -#endif /* LWIP_INCLUDED_POLARSSL_MD5 */ -#endif /* CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM */ - -#if MSCHAP_SUPPORT -/* MSCHAP require MD4 support */ -#ifndef LWIP_INCLUDED_POLARSSL_MD4 -#define LWIP_INCLUDED_POLARSSL_MD4 1 -#endif /* LWIP_INCLUDED_POLARSSL_MD4 */ -/* MSCHAP require SHA1 support */ -#ifndef LWIP_INCLUDED_POLARSSL_SHA1 -#define LWIP_INCLUDED_POLARSSL_SHA1 1 -#endif /* LWIP_INCLUDED_POLARSSL_SHA1 */ -/* MSCHAP require DES support */ -#ifndef LWIP_INCLUDED_POLARSSL_DES -#define LWIP_INCLUDED_POLARSSL_DES 1 -#endif /* LWIP_INCLUDED_POLARSSL_DES */ -/* MS-CHAP support is required for MPPE */ -#if MPPE_SUPPORT -/* MPPE require ARC4 support */ -#ifndef LWIP_INCLUDED_POLARSSL_ARC4 -#define LWIP_INCLUDED_POLARSSL_ARC4 1 -#endif /* LWIP_INCLUDED_POLARSSL_ARC4*/ -#endif /* MPPE_SUPPORT */ -#endif /* MSCHAP_SUPPORT */ - -/* Default value if unset */ -#ifndef LWIP_INCLUDED_POLARSSL_MD4 -#define LWIP_INCLUDED_POLARSSL_MD4 0 -#endif /* LWIP_INCLUDED_POLARSSL_MD4 */ -#ifndef LWIP_INCLUDED_POLARSSL_MD5 -#define LWIP_INCLUDED_POLARSSL_MD5 0 -#endif /* LWIP_INCLUDED_POLARSSL_MD5 */ -#ifndef LWIP_INCLUDED_POLARSSL_SHA1 -#define LWIP_INCLUDED_POLARSSL_SHA1 0 -#endif /* LWIP_INCLUDED_POLARSSL_SHA1 */ -#ifndef LWIP_INCLUDED_POLARSSL_DES -#define LWIP_INCLUDED_POLARSSL_DES 0 -#endif /* LWIP_INCLUDED_POLARSSL_DES */ -#ifndef LWIP_INCLUDED_POLARSSL_ARC4 -#define LWIP_INCLUDED_POLARSSL_ARC4 0 -#endif /* LWIP_INCLUDED_POLARSSL_ARC4 */ - -/* - * PPP Timeouts - */ - -/** - * FSM_DEFTIMEOUT: Timeout time in seconds - */ -#ifndef FSM_DEFTIMEOUT -#define FSM_DEFTIMEOUT 6 -#endif - -/** - * FSM_DEFMAXTERMREQS: Maximum Terminate-Request transmissions - */ -#ifndef FSM_DEFMAXTERMREQS -#define FSM_DEFMAXTERMREQS 2 -#endif - -/** - * FSM_DEFMAXCONFREQS: Maximum Configure-Request transmissions - */ -#ifndef FSM_DEFMAXCONFREQS -#define FSM_DEFMAXCONFREQS 10 -#endif - -/** - * FSM_DEFMAXNAKLOOPS: Maximum number of nak loops - */ -#ifndef FSM_DEFMAXNAKLOOPS -#define FSM_DEFMAXNAKLOOPS 5 -#endif - -/** - * UPAP_DEFTIMEOUT: Timeout (seconds) for retransmitting req - */ -#ifndef UPAP_DEFTIMEOUT -#define UPAP_DEFTIMEOUT 6 -#endif - -/** - * UPAP_DEFTRANSMITS: Maximum number of auth-reqs to send - */ -#ifndef UPAP_DEFTRANSMITS -#define UPAP_DEFTRANSMITS 10 -#endif - -#if PPP_SERVER -/** - * UPAP_DEFREQTIME: Time to wait for auth-req from peer - */ -#ifndef UPAP_DEFREQTIME -#define UPAP_DEFREQTIME 30 -#endif -#endif /* PPP_SERVER */ - -/** - * CHAP_DEFTIMEOUT: Timeout (seconds) for retransmitting req - */ -#ifndef CHAP_DEFTIMEOUT -#define CHAP_DEFTIMEOUT 6 -#endif - -/** - * CHAP_DEFTRANSMITS: max # times to send challenge - */ -#ifndef CHAP_DEFTRANSMITS -#define CHAP_DEFTRANSMITS 10 -#endif - -#if PPP_SERVER -/** - * CHAP_DEFRECHALLENGETIME: If this option is > 0, rechallenge the peer every n seconds - */ -#ifndef CHAP_DEFRECHALLENGETIME -#define CHAP_DEFRECHALLENGETIME 0 -#endif -#endif /* PPP_SERVER */ - -/** - * EAP_DEFREQTIME: Time to wait for peer request - */ -#ifndef EAP_DEFREQTIME -#define EAP_DEFREQTIME 6 -#endif - -/** - * EAP_DEFALLOWREQ: max # times to accept requests - */ -#ifndef EAP_DEFALLOWREQ -#define EAP_DEFALLOWREQ 10 -#endif - -#if PPP_SERVER -/** - * EAP_DEFTIMEOUT: Timeout (seconds) for rexmit - */ -#ifndef EAP_DEFTIMEOUT -#define EAP_DEFTIMEOUT 6 -#endif - -/** - * EAP_DEFTRANSMITS: max # times to transmit - */ -#ifndef EAP_DEFTRANSMITS -#define EAP_DEFTRANSMITS 10 -#endif -#endif /* PPP_SERVER */ - -/** - * LCP_DEFLOOPBACKFAIL: Default number of times we receive our magic number from the peer - * before deciding the link is looped-back. - */ -#ifndef LCP_DEFLOOPBACKFAIL -#define LCP_DEFLOOPBACKFAIL 10 -#endif - -/** - * LCP_ECHOINTERVAL: Interval in seconds between keepalive echo requests, 0 to disable. - */ -#ifndef LCP_ECHOINTERVAL -#define LCP_ECHOINTERVAL 0 -#endif - -/** - * LCP_MAXECHOFAILS: Number of unanswered echo requests before failure. - */ -#ifndef LCP_MAXECHOFAILS -#define LCP_MAXECHOFAILS 3 -#endif - -/** - * PPP_MAXIDLEFLAG: Max Xmit idle time (in ms) before resend flag char. - */ -#ifndef PPP_MAXIDLEFLAG -#define PPP_MAXIDLEFLAG 100 -#endif - -/** - * PPP Packet sizes - */ - -/** - * PPP_MRU: Default MRU - */ -#ifndef PPP_MRU -#define PPP_MRU 1500 -#endif - -/** - * PPP_DEFMRU: Default MRU to try - */ -#ifndef PPP_DEFMRU -#define PPP_DEFMRU 1500 -#endif - -/** - * PPP_MAXMRU: Normally limit MRU to this (pppd default = 16384) - */ -#ifndef PPP_MAXMRU -#define PPP_MAXMRU 1500 -#endif - -/** - * PPP_MINMRU: No MRUs below this - */ -#ifndef PPP_MINMRU -#define PPP_MINMRU 128 -#endif - -/** - * PPPOL2TP_DEFMRU: Default MTU and MRU for L2TP - * Default = 1500 - PPPoE(6) - PPP Protocol(2) - IPv4 header(20) - UDP Header(8) - * - L2TP Header(6) - HDLC Header(2) - PPP Protocol(2) - MPPE Header(2) - PPP Protocol(2) - */ -#if PPPOL2TP_SUPPORT -#ifndef PPPOL2TP_DEFMRU -#define PPPOL2TP_DEFMRU 1450 -#endif -#endif /* PPPOL2TP_SUPPORT */ - -/** - * MAXNAMELEN: max length of hostname or name for auth - */ -#ifndef MAXNAMELEN -#define MAXNAMELEN 256 -#endif - -/** - * MAXSECRETLEN: max length of password or secret - */ -#ifndef MAXSECRETLEN -#define MAXSECRETLEN 256 -#endif - -#endif /* PPP_SUPPORT */ /* -------------------------------------- ---------- Checksum options ---------- -------------------------------------- */ - +/** + * @defgroup lwip_opts_checksum Checksum + * @ingroup lwip_opts_infrastructure + * @{ + */ /** * LWIP_CHECKSUM_CTRL_PER_NETIF==1: Checksum generation/check can be enabled/disabled * per netif. * ATTENTION: if enabled, the CHECKSUM_GEN_* and CHECKSUM_CHECK_* defines must be enabled! */ -#ifndef LWIP_CHECKSUM_CTRL_PER_NETIF +#if !defined LWIP_CHECKSUM_CTRL_PER_NETIF || defined __DOXYGEN__ #define LWIP_CHECKSUM_CTRL_PER_NETIF 0 #endif /** * CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets. */ -#ifndef CHECKSUM_GEN_IP +#if !defined CHECKSUM_GEN_IP || defined __DOXYGEN__ #define CHECKSUM_GEN_IP 1 #endif /** * CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets. */ -#ifndef CHECKSUM_GEN_UDP +#if !defined CHECKSUM_GEN_UDP || defined __DOXYGEN__ #define CHECKSUM_GEN_UDP 1 #endif /** * CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets. */ -#ifndef CHECKSUM_GEN_TCP +#if !defined CHECKSUM_GEN_TCP || defined __DOXYGEN__ #define CHECKSUM_GEN_TCP 1 #endif /** * CHECKSUM_GEN_ICMP==1: Generate checksums in software for outgoing ICMP packets. */ -#ifndef CHECKSUM_GEN_ICMP +#if !defined CHECKSUM_GEN_ICMP || defined __DOXYGEN__ #define CHECKSUM_GEN_ICMP 1 #endif /** * CHECKSUM_GEN_ICMP6==1: Generate checksums in software for outgoing ICMP6 packets. */ -#ifndef CHECKSUM_GEN_ICMP6 +#if !defined CHECKSUM_GEN_ICMP6 || defined __DOXYGEN__ #define CHECKSUM_GEN_ICMP6 1 #endif /** * CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets. */ -#ifndef CHECKSUM_CHECK_IP +#if !defined CHECKSUM_CHECK_IP || defined __DOXYGEN__ #define CHECKSUM_CHECK_IP 1 #endif /** * CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets. */ -#ifndef CHECKSUM_CHECK_UDP +#if !defined CHECKSUM_CHECK_UDP || defined __DOXYGEN__ #define CHECKSUM_CHECK_UDP 1 #endif /** * CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets. */ -#ifndef CHECKSUM_CHECK_TCP +#if !defined CHECKSUM_CHECK_TCP || defined __DOXYGEN__ #define CHECKSUM_CHECK_TCP 1 #endif /** * CHECKSUM_CHECK_ICMP==1: Check checksums in software for incoming ICMP packets. */ -#ifndef CHECKSUM_CHECK_ICMP +#if !defined CHECKSUM_CHECK_ICMP || defined __DOXYGEN__ #define CHECKSUM_CHECK_ICMP 1 #endif /** * CHECKSUM_CHECK_ICMP6==1: Check checksums in software for incoming ICMPv6 packets */ -#ifndef CHECKSUM_CHECK_ICMP6 +#if !defined CHECKSUM_CHECK_ICMP6 || defined __DOXYGEN__ #define CHECKSUM_CHECK_ICMP6 1 #endif @@ -2440,40 +2145,92 @@ * LWIP_CHECKSUM_ON_COPY==1: Calculate checksum when copying data from * application buffers to pbufs. */ -#ifndef LWIP_CHECKSUM_ON_COPY +#if !defined LWIP_CHECKSUM_ON_COPY || defined __DOXYGEN__ #define LWIP_CHECKSUM_ON_COPY 0 #endif +/** + * @} + */ /* --------------------------------------- ---------- IPv6 options --------------- --------------------------------------- */ +/** + * @defgroup lwip_opts_ipv6 IPv6 + * @ingroup lwip_opts + * @{ + */ /** * LWIP_IPV6==1: Enable IPv6 */ -#ifndef LWIP_IPV6 +#if !defined LWIP_IPV6 || defined __DOXYGEN__ #define LWIP_IPV6 0 #endif /** * LWIP_IPV6_NUM_ADDRESSES: Number of IPv6 addresses per netif. */ -#ifndef LWIP_IPV6_NUM_ADDRESSES +#if !defined LWIP_IPV6_NUM_ADDRESSES || defined __DOXYGEN__ #define LWIP_IPV6_NUM_ADDRESSES 3 #endif /** * LWIP_IPV6_FORWARD==1: Forward IPv6 packets across netifs */ -#ifndef LWIP_IPV6_FORWARD +#if !defined LWIP_IPV6_FORWARD || defined __DOXYGEN__ #define LWIP_IPV6_FORWARD 0 #endif +/** + * LWIP_IPV6_FRAG==1: Fragment outgoing IPv6 packets that are too big. + */ +#if !defined LWIP_IPV6_FRAG || defined __DOXYGEN__ +#define LWIP_IPV6_FRAG 0 +#endif + +/** + * LWIP_IPV6_REASS==1: reassemble incoming IPv6 packets that fragmented + */ +#if !defined LWIP_IPV6_REASS || defined __DOXYGEN__ +#define LWIP_IPV6_REASS (LWIP_IPV6) +#endif + +/** + * LWIP_IPV6_SEND_ROUTER_SOLICIT==1: Send router solicitation messages during + * network startup. + */ +#if !defined LWIP_IPV6_SEND_ROUTER_SOLICIT || defined __DOXYGEN__ +#define LWIP_IPV6_SEND_ROUTER_SOLICIT 1 +#endif + +/** + * LWIP_IPV6_AUTOCONFIG==1: Enable stateless address autoconfiguration as per RFC 4862. + */ +#if !defined LWIP_IPV6_AUTOCONFIG || defined __DOXYGEN__ +#define LWIP_IPV6_AUTOCONFIG (LWIP_IPV6) +#endif + +/** + * LWIP_IPV6_DUP_DETECT_ATTEMPTS=[0..7]: Number of duplicate address detection attempts. + */ +#if !defined LWIP_IPV6_DUP_DETECT_ATTEMPTS || defined __DOXYGEN__ +#define LWIP_IPV6_DUP_DETECT_ATTEMPTS 1 +#endif +/** + * @} + */ + +/** + * @defgroup lwip_opts_icmp6 ICMP6 + * @ingroup lwip_opts_ipv6 + * @{ + */ /** * LWIP_ICMP6==1: Enable ICMPv6 (mandatory per RFC) */ -#ifndef LWIP_ICMP6 +#if !defined LWIP_ICMP6 || defined __DOXYGEN__ #define LWIP_ICMP6 (LWIP_IPV6) #endif @@ -2481,85 +2238,92 @@ * LWIP_ICMP6_DATASIZE: bytes from original packet to send back in * ICMPv6 error messages. */ -#ifndef LWIP_ICMP6_DATASIZE +#if !defined LWIP_ICMP6_DATASIZE || defined __DOXYGEN__ #define LWIP_ICMP6_DATASIZE 8 #endif /** * LWIP_ICMP6_HL: default hop limit for ICMPv6 messages */ -#ifndef LWIP_ICMP6_HL +#if !defined LWIP_ICMP6_HL || defined __DOXYGEN__ #define LWIP_ICMP6_HL 255 #endif +/** + * @} + */ /** - * LWIP_IPV6_MLD==1: Enable multicast listener discovery protocol. + * @defgroup lwip_opts_mld6 Multicast listener discovery + * @ingroup lwip_opts_ipv6 + * @{ */ -#ifndef LWIP_IPV6_MLD +/** + * LWIP_IPV6_MLD==1: Enable multicast listener discovery protocol. + * If LWIP_IPV6 is enabled but this setting is disabled, the MAC layer must + * indiscriminately pass all inbound IPv6 multicast traffic to lwIP. + */ +#if !defined LWIP_IPV6_MLD || defined __DOXYGEN__ #define LWIP_IPV6_MLD (LWIP_IPV6) #endif /** - * MEMP_NUM_MLD6_GROUP: Max number of IPv6 multicast that can be joined. + * MEMP_NUM_MLD6_GROUP: Max number of IPv6 multicast groups that can be joined. + * There must be enough groups so that each netif can join the solicited-node + * multicast group for each of its local addresses, plus one for MDNS if + * applicable, plus any number of groups to be joined on UDP sockets. */ -#ifndef MEMP_NUM_MLD6_GROUP +#if !defined MEMP_NUM_MLD6_GROUP || defined __DOXYGEN__ #define MEMP_NUM_MLD6_GROUP 4 #endif +/** + * @} + */ /** - * LWIP_IPV6_FRAG==1: Fragment outgoing IPv6 packets that are too big. + * @defgroup lwip_opts_nd6 Neighbor discovery + * @ingroup lwip_opts_ipv6 + * @{ */ -#ifndef LWIP_IPV6_FRAG -#define LWIP_IPV6_FRAG 0 -#endif - -/** - * LWIP_IPV6_REASS==1: reassemble incoming IPv6 packets that fragmented - */ -#ifndef LWIP_IPV6_REASS -#define LWIP_IPV6_REASS (LWIP_IPV6) -#endif - /** * LWIP_ND6_QUEUEING==1: queue outgoing IPv6 packets while MAC address * is being resolved. */ -#ifndef LWIP_ND6_QUEUEING +#if !defined LWIP_ND6_QUEUEING || defined __DOXYGEN__ #define LWIP_ND6_QUEUEING (LWIP_IPV6) #endif /** * MEMP_NUM_ND6_QUEUE: Max number of IPv6 packets to queue during MAC resolution. */ -#ifndef MEMP_NUM_ND6_QUEUE +#if !defined MEMP_NUM_ND6_QUEUE || defined __DOXYGEN__ #define MEMP_NUM_ND6_QUEUE 20 #endif /** * LWIP_ND6_NUM_NEIGHBORS: Number of entries in IPv6 neighbor cache */ -#ifndef LWIP_ND6_NUM_NEIGHBORS +#if !defined LWIP_ND6_NUM_NEIGHBORS || defined __DOXYGEN__ #define LWIP_ND6_NUM_NEIGHBORS 10 #endif /** * LWIP_ND6_NUM_DESTINATIONS: number of entries in IPv6 destination cache */ -#ifndef LWIP_ND6_NUM_DESTINATIONS +#if !defined LWIP_ND6_NUM_DESTINATIONS || defined __DOXYGEN__ #define LWIP_ND6_NUM_DESTINATIONS 10 #endif /** * LWIP_ND6_NUM_PREFIXES: number of entries in IPv6 on-link prefixes cache */ -#ifndef LWIP_ND6_NUM_PREFIXES +#if !defined LWIP_ND6_NUM_PREFIXES || defined __DOXYGEN__ #define LWIP_ND6_NUM_PREFIXES 5 #endif /** * LWIP_ND6_NUM_ROUTERS: number of entries in IPv6 default router cache */ -#ifndef LWIP_ND6_NUM_ROUTERS +#if !defined LWIP_ND6_NUM_ROUTERS || defined __DOXYGEN__ #define LWIP_ND6_NUM_ROUTERS 3 #endif @@ -2567,7 +2331,7 @@ * LWIP_ND6_MAX_MULTICAST_SOLICIT: max number of multicast solicit messages to send * (neighbor solicit and router solicit) */ -#ifndef LWIP_ND6_MAX_MULTICAST_SOLICIT +#if !defined LWIP_ND6_MAX_MULTICAST_SOLICIT || defined __DOXYGEN__ #define LWIP_ND6_MAX_MULTICAST_SOLICIT 3 #endif @@ -2575,21 +2339,21 @@ * LWIP_ND6_MAX_UNICAST_SOLICIT: max number of unicast neighbor solicitation messages * to send during neighbor reachability detection. */ -#ifndef LWIP_ND6_MAX_UNICAST_SOLICIT +#if !defined LWIP_ND6_MAX_UNICAST_SOLICIT || defined __DOXYGEN__ #define LWIP_ND6_MAX_UNICAST_SOLICIT 3 #endif /** * Unused: See ND RFC (time in milliseconds). */ -#ifndef LWIP_ND6_MAX_ANYCAST_DELAY_TIME +#if !defined LWIP_ND6_MAX_ANYCAST_DELAY_TIME || defined __DOXYGEN__ #define LWIP_ND6_MAX_ANYCAST_DELAY_TIME 1000 #endif /** * Unused: See ND RFC */ -#ifndef LWIP_ND6_MAX_NEIGHBOR_ADVERTISEMENT +#if !defined LWIP_ND6_MAX_NEIGHBOR_ADVERTISEMENT || defined __DOXYGEN__ #define LWIP_ND6_MAX_NEIGHBOR_ADVERTISEMENT 3 #endif @@ -2597,14 +2361,14 @@ * LWIP_ND6_REACHABLE_TIME: default neighbor reachable time (in milliseconds). * May be updated by router advertisement messages. */ -#ifndef LWIP_ND6_REACHABLE_TIME +#if !defined LWIP_ND6_REACHABLE_TIME || defined __DOXYGEN__ #define LWIP_ND6_REACHABLE_TIME 30000 #endif /** * LWIP_ND6_RETRANS_TIMER: default retransmission timer for solicitation messages */ -#ifndef LWIP_ND6_RETRANS_TIMER +#if !defined LWIP_ND6_RETRANS_TIMER || defined __DOXYGEN__ #define LWIP_ND6_RETRANS_TIMER 1000 #endif @@ -2612,7 +2376,7 @@ * LWIP_ND6_DELAY_FIRST_PROBE_TIME: Delay before first unicast neighbor solicitation * message is sent, during neighbor reachability detection. */ -#ifndef LWIP_ND6_DELAY_FIRST_PROBE_TIME +#if !defined LWIP_ND6_DELAY_FIRST_PROBE_TIME || defined __DOXYGEN__ #define LWIP_ND6_DELAY_FIRST_PROBE_TIME 5000 #endif @@ -2620,45 +2384,35 @@ * LWIP_ND6_ALLOW_RA_UPDATES==1: Allow Router Advertisement messages to update * Reachable time and retransmission timers, and netif MTU. */ -#ifndef LWIP_ND6_ALLOW_RA_UPDATES +#if !defined LWIP_ND6_ALLOW_RA_UPDATES || defined __DOXYGEN__ #define LWIP_ND6_ALLOW_RA_UPDATES 1 #endif -/** - * LWIP_IPV6_SEND_ROUTER_SOLICIT==1: Send router solicitation messages during - * network startup. - */ -#ifndef LWIP_IPV6_SEND_ROUTER_SOLICIT -#define LWIP_IPV6_SEND_ROUTER_SOLICIT 1 -#endif - /** * LWIP_ND6_TCP_REACHABILITY_HINTS==1: Allow TCP to provide Neighbor Discovery * with reachability hints for connected destinations. This helps avoid sending * unicast neighbor solicitation messages. */ -#ifndef LWIP_ND6_TCP_REACHABILITY_HINTS +#if !defined LWIP_ND6_TCP_REACHABILITY_HINTS || defined __DOXYGEN__ #define LWIP_ND6_TCP_REACHABILITY_HINTS 1 #endif /** - * LWIP_IPV6_AUTOCONFIG==1: Enable stateless address autoconfiguration as per RFC 4862. + * LWIP_ND6_RDNSS_MAX_DNS_SERVERS > 0: Use IPv6 Router Advertisement Recursive + * DNS Server Option (as per RFC 6106) to copy a defined maximum number of DNS + * servers to the DNS module. */ -#ifndef LWIP_IPV6_AUTOCONFIG -#define LWIP_IPV6_AUTOCONFIG (LWIP_IPV6) +#if !defined LWIP_ND6_RDNSS_MAX_DNS_SERVERS || defined __DOXYGEN__ +#define LWIP_ND6_RDNSS_MAX_DNS_SERVERS 0 #endif - /** - * LWIP_IPV6_DUP_DETECT_ATTEMPTS: Number of duplicate address detection attempts. + * @} */ -#ifndef LWIP_IPV6_DUP_DETECT_ATTEMPTS -#define LWIP_IPV6_DUP_DETECT_ATTEMPTS 1 -#endif /** * LWIP_IPV6_DHCP6==1: enable DHCPv6 stateful address autoconfiguration. */ -#ifndef LWIP_IPV6_DHCP6 +#if !defined LWIP_IPV6_DHCP6 || defined __DOXYGEN__ #define LWIP_IPV6_DHCP6 0 #endif @@ -2668,7 +2422,44 @@ --------------------------------------- */ -/* Hooks are undefined by default, define them to a function if you need them. */ +/** + * @defgroup lwip_opts_hooks Hooks + * @ingroup lwip_opts_infrastructure + * Hooks are undefined by default, define them to a function if you need them. + * @{ + */ + +/** + * LWIP_HOOK_FILENAME: Custom filename to #include in files that provide hooks. + * Declare your hook function prototypes in there, you may also #include all headers + * providing data types that are need in this file. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_FILENAME "path/to/my/lwip_hooks.h" +#endif + +/** + * LWIP_HOOK_TCP_ISN: + * Hook for generation of the Initial Sequence Number (ISN) for a new TCP + * connection. The default lwIP ISN generation algorithm is very basic and may + * allow for TCP spoofing attacks. This hook provides the means to implement + * the standardized ISN generation algorithm from RFC 6528 (see contrib/adons/tcp_isn), + * or any other desired algorithm as a replacement. + * Called from tcp_connect() and tcp_listen_input() when an ISN is needed for + * a new TCP connection, if TCP support (@ref LWIP_TCP) is enabled.\n + * Signature: u32_t my_hook_tcp_isn(const ip_addr_t* local_ip, u16_t local_port, const ip_addr_t* remote_ip, u16_t remote_port); + * - it may be necessary to use "struct ip_addr" (ip4_addr, ip6_addr) instead of "ip_addr_t" in function declarations\n + * Arguments: + * - local_ip: pointer to the local IP address of the connection + * - local_port: local port number of the connection (host-byte order) + * - remote_ip: pointer to the remote IP address of the connection + * - remote_port: remote port number of the connection (host-byte order)\n + * Return value: + * - the 32-bit Initial Sequence Number to use for the new TCP connection. + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_TCP_ISN(local_ip, local_port, remote_ip, remote_port) +#endif /** * LWIP_HOOK_IP4_INPUT(pbuf, input_netif): @@ -2681,6 +2472,9 @@ * If the hook consumed the packet, 'pbuf' is in the responsibility of the hook * (i.e. free it when done). */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP4_INPUT(pbuf, input_netif) +#endif /** * LWIP_HOOK_IP4_ROUTE(dest): @@ -2689,11 +2483,17 @@ * Returns the destination netif or NULL if no destination netif is found. In * that case, ip_route() continues as normal. */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP4_ROUTE() +#endif /** * LWIP_HOOK_IP4_ROUTE_SRC(dest, src): * - source-based routing for IPv4 (see LWIP_HOOK_IP4_ROUTE(), src may be NULL) */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP4_ROUTE_SRC(dest, src) +#endif /** * LWIP_HOOK_ETHARP_GET_GW(netif, dest): @@ -2702,11 +2502,14 @@ * - dest: the destination IPv4 address * Returns the IPv4 address of the gateway to handle the specified destination * IPv4 address. If NULL is returned, the netif's default gateway is used. - * The returned address MUST be reachable on the specified netif! + * The returned address MUST be directly reachable on the specified netif! * This function is meant to implement advanced IPv4 routing together with * LWIP_HOOK_IP4_ROUTE(). The actual routing/gateway table implementation is * not part of lwIP but can e.g. be hidden in the netif's state argument. */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_ETHARP_GET_GW(netif, dest) +#endif /** * LWIP_HOOK_IP6_INPUT(pbuf, input_netif): @@ -2719,6 +2522,9 @@ * If the hook consumed the packet, 'pbuf' is in the responsibility of the hook * (i.e. free it when done). */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP6_INPUT(pbuf, input_netif) +#endif /** * LWIP_HOOK_IP6_ROUTE(src, dest): @@ -2728,6 +2534,25 @@ * Returns the destination netif or NULL if no destination netif is found. In * that case, ip6_route() continues as normal. */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_IP6_ROUTE(src, dest) +#endif + +/** + * LWIP_HOOK_ND6_GET_GW(netif, dest): + * - called from nd6_get_next_hop_entry() (IPv6) + * - netif: the netif used for sending + * - dest: the destination IPv6 address + * Returns the IPv6 address of the next hop to handle the specified destination + * IPv6 address. If NULL is returned, a NDP-discovered router is used instead. + * The returned address MUST be directly reachable on the specified netif! + * This function is meant to implement advanced IPv6 routing together with + * LWIP_HOOK_IP6_ROUTE(). The actual routing/gateway table implementation is + * not part of lwIP but can e.g. be hidden in the netif's state argument. +*/ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_ND6_GET_GW(netif, dest) +#endif /** * LWIP_HOOK_VLAN_CHECK(netif, eth_hdr, vlan_hdr): @@ -2739,176 +2564,212 @@ * - 0: Packet must be dropped. * - != 0: Packet must be accepted. */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_VLAN_CHECK(netif, eth_hdr, vlan_hdr) +#endif /** - * LWIP_HOOK_VLAN_SET(netif, eth_hdr, vlan_hdr): - * - called from etharp_raw() and etharp_send_ip() if VLAN support is enabled + * LWIP_HOOK_VLAN_SET: + * Hook can be used to set prio_vid field of vlan_hdr. If you need to store data + * on per-netif basis to implement this callback, see @ref netif_cd. + * Called from ethernet_output() if VLAN support (@ref ETHARP_SUPPORT_VLAN) is enabled.\n + * Signature: s32_t my_hook_vlan_set(struct netif* netif, struct pbuf* pbuf, const struct eth_addr* src, const struct eth_addr* dst, u16_t eth_type);\n + * Arguments: * - netif: struct netif that the packet will be sent through - * - eth_hdr: struct eth_hdr of the packet - * - vlan_hdr: struct eth_vlan_hdr of the packet + * - p: struct pbuf packet to be sent + * - src: source eth address + * - dst: destination eth address + * - eth_type: ethernet type to packet to be sent\n + * + * * Return values: - * - 0: Packet shall not contain VLAN header. - * - != 0: Packet shall contain VLAN header. - * Hook can be used to set prio_vid field of vlan_hdr. + * - <0: Packet shall not contain VLAN header. + * - 0 <= return value <= 0xFFFF: Packet shall contain VLAN header. Return value is prio_vid in host byte order. */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_VLAN_SET(netif, p, src, dst, eth_type) +#endif /** * LWIP_HOOK_MEMP_AVAILABLE(memp_t_type): * - called from memp_free() when a memp pool was empty and an item is now available */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_MEMP_AVAILABLE(memp_t_type) +#endif + +/** + * LWIP_HOOK_UNKNOWN_ETH_PROTOCOL(pbuf, netif): + * Called from ethernet_input() when an unknown eth type is encountered. + * Return ERR_OK if packet is accepted, any error code otherwise. + * Payload points to ethernet header! + */ +#ifdef __DOXYGEN__ +#define LWIP_HOOK_UNKNOWN_ETH_PROTOCOL(pbuf, netif) +#endif +/** + * @} + */ /* --------------------------------------- ---------- Debugging options ---------- --------------------------------------- */ +/** + * @defgroup lwip_opts_debugmsg Debug messages + * @ingroup lwip_opts_debug + * @{ + */ /** * LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is * compared against this value. If it is smaller, then debugging * messages are written. + * @see debugging_levels */ -#ifndef LWIP_DBG_MIN_LEVEL +#if !defined LWIP_DBG_MIN_LEVEL || defined __DOXYGEN__ #define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_ALL #endif /** * LWIP_DBG_TYPES_ON: A mask that can be used to globally enable/disable * debug messages of certain types. + * @see debugging_levels */ -#ifndef LWIP_DBG_TYPES_ON +#if !defined LWIP_DBG_TYPES_ON || defined __DOXYGEN__ #define LWIP_DBG_TYPES_ON LWIP_DBG_ON #endif /** * ETHARP_DEBUG: Enable debugging in etharp.c. */ -#ifndef ETHARP_DEBUG +#if !defined ETHARP_DEBUG || defined __DOXYGEN__ #define ETHARP_DEBUG LWIP_DBG_OFF #endif /** * NETIF_DEBUG: Enable debugging in netif.c. */ -#ifndef NETIF_DEBUG +#if !defined NETIF_DEBUG || defined __DOXYGEN__ #define NETIF_DEBUG LWIP_DBG_OFF #endif /** * PBUF_DEBUG: Enable debugging in pbuf.c. */ -#ifndef PBUF_DEBUG +#if !defined PBUF_DEBUG || defined __DOXYGEN__ #define PBUF_DEBUG LWIP_DBG_OFF #endif /** * API_LIB_DEBUG: Enable debugging in api_lib.c. */ -#ifndef API_LIB_DEBUG +#if !defined API_LIB_DEBUG || defined __DOXYGEN__ #define API_LIB_DEBUG LWIP_DBG_OFF #endif /** * API_MSG_DEBUG: Enable debugging in api_msg.c. */ -#ifndef API_MSG_DEBUG +#if !defined API_MSG_DEBUG || defined __DOXYGEN__ #define API_MSG_DEBUG LWIP_DBG_OFF #endif /** * SOCKETS_DEBUG: Enable debugging in sockets.c. */ -#ifndef SOCKETS_DEBUG +#if !defined SOCKETS_DEBUG || defined __DOXYGEN__ #define SOCKETS_DEBUG LWIP_DBG_OFF #endif /** * ICMP_DEBUG: Enable debugging in icmp.c. */ -#ifndef ICMP_DEBUG +#if !defined ICMP_DEBUG || defined __DOXYGEN__ #define ICMP_DEBUG LWIP_DBG_OFF #endif /** * IGMP_DEBUG: Enable debugging in igmp.c. */ -#ifndef IGMP_DEBUG +#if !defined IGMP_DEBUG || defined __DOXYGEN__ #define IGMP_DEBUG LWIP_DBG_OFF #endif /** * INET_DEBUG: Enable debugging in inet.c. */ -#ifndef INET_DEBUG +#if !defined INET_DEBUG || defined __DOXYGEN__ #define INET_DEBUG LWIP_DBG_OFF #endif /** * IP_DEBUG: Enable debugging for IP. */ -#ifndef IP_DEBUG +#if !defined IP_DEBUG || defined __DOXYGEN__ #define IP_DEBUG LWIP_DBG_OFF #endif /** * IP_REASS_DEBUG: Enable debugging in ip_frag.c for both frag & reass. */ -#ifndef IP_REASS_DEBUG +#if !defined IP_REASS_DEBUG || defined __DOXYGEN__ #define IP_REASS_DEBUG LWIP_DBG_OFF #endif /** * RAW_DEBUG: Enable debugging in raw.c. */ -#ifndef RAW_DEBUG +#if !defined RAW_DEBUG || defined __DOXYGEN__ #define RAW_DEBUG LWIP_DBG_OFF #endif /** * MEM_DEBUG: Enable debugging in mem.c. */ -#ifndef MEM_DEBUG +#if !defined MEM_DEBUG || defined __DOXYGEN__ #define MEM_DEBUG LWIP_DBG_OFF #endif /** * MEMP_DEBUG: Enable debugging in memp.c. */ -#ifndef MEMP_DEBUG +#if !defined MEMP_DEBUG || defined __DOXYGEN__ #define MEMP_DEBUG LWIP_DBG_OFF #endif /** * SYS_DEBUG: Enable debugging in sys.c. */ -#ifndef SYS_DEBUG +#if !defined SYS_DEBUG || defined __DOXYGEN__ #define SYS_DEBUG LWIP_DBG_OFF #endif /** * TIMERS_DEBUG: Enable debugging in timers.c. */ -#ifndef TIMERS_DEBUG +#if !defined TIMERS_DEBUG || defined __DOXYGEN__ #define TIMERS_DEBUG LWIP_DBG_OFF #endif /** * TCP_DEBUG: Enable debugging for TCP. */ -#ifndef TCP_DEBUG +#if !defined TCP_DEBUG || defined __DOXYGEN__ #define TCP_DEBUG LWIP_DBG_OFF #endif /** * TCP_INPUT_DEBUG: Enable debugging in tcp_in.c for incoming debug. */ -#ifndef TCP_INPUT_DEBUG +#if !defined TCP_INPUT_DEBUG || defined __DOXYGEN__ #define TCP_INPUT_DEBUG LWIP_DBG_OFF #endif /** * TCP_FR_DEBUG: Enable debugging in tcp_in.c for fast retransmit. */ -#ifndef TCP_FR_DEBUG +#if !defined TCP_FR_DEBUG || defined __DOXYGEN__ #define TCP_FR_DEBUG LWIP_DBG_OFF #endif @@ -2916,123 +2777,116 @@ * TCP_RTO_DEBUG: Enable debugging in TCP for retransmit * timeout. */ -#ifndef TCP_RTO_DEBUG +#if !defined TCP_RTO_DEBUG || defined __DOXYGEN__ #define TCP_RTO_DEBUG LWIP_DBG_OFF #endif /** * TCP_CWND_DEBUG: Enable debugging for TCP congestion window. */ -#ifndef TCP_CWND_DEBUG +#if !defined TCP_CWND_DEBUG || defined __DOXYGEN__ #define TCP_CWND_DEBUG LWIP_DBG_OFF #endif /** * TCP_WND_DEBUG: Enable debugging in tcp_in.c for window updating. */ -#ifndef TCP_WND_DEBUG +#if !defined TCP_WND_DEBUG || defined __DOXYGEN__ #define TCP_WND_DEBUG LWIP_DBG_OFF #endif /** * TCP_OUTPUT_DEBUG: Enable debugging in tcp_out.c output functions. */ -#ifndef TCP_OUTPUT_DEBUG +#if !defined TCP_OUTPUT_DEBUG || defined __DOXYGEN__ #define TCP_OUTPUT_DEBUG LWIP_DBG_OFF #endif /** * TCP_RST_DEBUG: Enable debugging for TCP with the RST message. */ -#ifndef TCP_RST_DEBUG +#if !defined TCP_RST_DEBUG || defined __DOXYGEN__ #define TCP_RST_DEBUG LWIP_DBG_OFF #endif /** * TCP_QLEN_DEBUG: Enable debugging for TCP queue lengths. */ -#ifndef TCP_QLEN_DEBUG +#if !defined TCP_QLEN_DEBUG || defined __DOXYGEN__ #define TCP_QLEN_DEBUG LWIP_DBG_OFF #endif /** * UDP_DEBUG: Enable debugging in UDP. */ -#ifndef UDP_DEBUG +#if !defined UDP_DEBUG || defined __DOXYGEN__ #define UDP_DEBUG LWIP_DBG_OFF #endif /** * TCPIP_DEBUG: Enable debugging in tcpip.c. */ -#ifndef TCPIP_DEBUG +#if !defined TCPIP_DEBUG || defined __DOXYGEN__ #define TCPIP_DEBUG LWIP_DBG_OFF #endif -/** - * PPP_DEBUG: Enable debugging for PPP. - */ -#ifndef PPP_DEBUG -#define PPP_DEBUG LWIP_DBG_OFF -#endif - /** * SLIP_DEBUG: Enable debugging in slipif.c. */ -#ifndef SLIP_DEBUG +#if !defined SLIP_DEBUG || defined __DOXYGEN__ #define SLIP_DEBUG LWIP_DBG_OFF #endif /** * DHCP_DEBUG: Enable debugging in dhcp.c. */ -#ifndef DHCP_DEBUG +#if !defined DHCP_DEBUG || defined __DOXYGEN__ #define DHCP_DEBUG LWIP_DBG_OFF #endif /** * AUTOIP_DEBUG: Enable debugging in autoip.c. */ -#ifndef AUTOIP_DEBUG +#if !defined AUTOIP_DEBUG || defined __DOXYGEN__ #define AUTOIP_DEBUG LWIP_DBG_OFF #endif /** * DNS_DEBUG: Enable debugging for DNS. */ -#ifndef DNS_DEBUG +#if !defined DNS_DEBUG || defined __DOXYGEN__ #define DNS_DEBUG LWIP_DBG_OFF #endif /** * IP6_DEBUG: Enable debugging for IPv6. */ -#ifndef IP6_DEBUG +#if !defined IP6_DEBUG || defined __DOXYGEN__ #define IP6_DEBUG LWIP_DBG_OFF #endif +/** + * @} + */ /* -------------------------------------------------- ---------- Performance tracking options ---------- -------------------------------------------------- */ +/** + * @defgroup lwip_opts_perf Performance + * @ingroup lwip_opts_debug + * @{ + */ /** * LWIP_PERF: Enable performance testing for lwIP * (if enabled, arch/perf.h is included) */ -#ifndef LWIP_PERF +#if !defined LWIP_PERF || defined __DOXYGEN__ #define LWIP_PERF 0 #endif - /** - * ESP_L2_TO_L3_COPY: enable memcpy when receiving packet from L2 + * @} */ -#ifndef ESP_L2_TO_L3_COPY -#define ESP_L2_TO_L3_COPY 0 -#endif - -#ifndef ESP_THREAD_SAFE_DEBUG -#define ESP_THREAD_SAFE_DEBUG 0 -#endif #endif /* LWIP_HDR_OPT_H */ diff --git a/tools/sdk/include/lwip/lwip/pbuf.h b/tools/sdk/include/lwip/lwip/pbuf.h index 42146f6f..a8f1d951 100644 --- a/tools/sdk/include/lwip/lwip/pbuf.h +++ b/tools/sdk/include/lwip/lwip/pbuf.h @@ -1,3 +1,8 @@ +/** + * @file + * pbuf API + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -47,7 +52,7 @@ extern "C" { * Currently, the pbuf_custom code is only needed for one specific configuration * of IP_FRAG, unless required by external driver/application code. */ #ifndef LWIP_SUPPORT_CUSTOM_PBUF -#define LWIP_SUPPORT_CUSTOM_PBUF ((IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF) || (LWIP_IPV6 && LWIP_IPV6_FRAG)) +#define LWIP_SUPPORT_CUSTOM_PBUF ((IP_FRAG && !LWIP_NETIF_TX_SINGLE_PBUF) || (LWIP_IPV6 && LWIP_IPV6_FRAG)) #endif /* @todo: We need a mechanism to prevent wasting memory in every pbuf @@ -60,20 +65,46 @@ extern "C" { #define PBUF_IP_HLEN 20 #endif +/** + * @ingroup pbuf + * Enumeration of pbuf layers + */ typedef enum { + /** Includes spare room for transport layer header, e.g. UDP header. + * Use this if you intend to pass the pbuf to functions like udp_send(). + */ PBUF_TRANSPORT, + /** Includes spare room for IP header. + * Use this if you intend to pass the pbuf to functions like raw_send(). + */ PBUF_IP, + /** Includes spare room for link layer header (ethernet header). + * Use this if you intend to pass the pbuf to functions like ethernet_output(). + * @see PBUF_LINK_HLEN + */ PBUF_LINK, + /** Includes spare room for additional encapsulation header before ethernet + * headers (e.g. 802.11). + * Use this if you intend to pass the pbuf to functions like netif->linkoutput(). + * @see PBUF_LINK_ENCAPSULATION_HLEN + */ PBUF_RAW_TX, + /** Use this for input packets in a netif driver when calling netif->input() + * in the most common case - ethernet-layer netif driver. */ PBUF_RAW } pbuf_layer; +/** + * @ingroup pbuf + * Enumeration of pbuf types + */ typedef enum { /** pbuf data is stored in RAM, used for TX mostly, struct pbuf and its payload are allocated in one piece of contiguous memory (so the first payload byte - can be calculated from struct pbuf) + can be calculated from struct pbuf). pbuf_alloc() allocates PBUF_RAM pbufs as unchained pbufs (although that might - change in future versions) */ + change in future versions). + This should be used for all OUTGOING packets (TX).*/ PBUF_RAM, /** pbuf data is stored in ROM, i.e. struct pbuf and its payload are located in totally different memory areas. Since it points to ROM, payload does not @@ -86,7 +117,9 @@ typedef enum { /** pbuf payload refers to RAM. This one comes from a pool and should be used for RX. Payload can be chained (scatter-gather RX) but like PBUF_RAM, struct pbuf and its payload are allocated in one piece of contiguous memory (so - the first payload byte can be calculated from struct pbuf) */ + the first payload byte can be calculated from struct pbuf). + Don't use this for TX, if the pool becomes empty e.g. because of TCP queuing, + you are unable to receive TCP acks! */ PBUF_POOL } pbuf_type; @@ -105,6 +138,7 @@ typedef enum { /** indicates this pbuf includes a TCP FIN flag */ #define PBUF_FLAG_TCP_FIN 0x20U +/** Main packet buffer struct */ struct pbuf { /** next pbuf in singly linked pbuf chain */ struct pbuf *next; @@ -169,12 +203,11 @@ struct pbuf_custom { }; #endif /* LWIP_SUPPORT_CUSTOM_PBUF */ -#if LWIP_TCP && TCP_QUEUE_OOSEQ /** Define this to 0 to prevent freeing ooseq pbufs when the PBUF_POOL is empty */ #ifndef PBUF_POOL_FREE_OOSEQ #define PBUF_POOL_FREE_OOSEQ 1 #endif /* PBUF_POOL_FREE_OOSEQ */ -#if NO_SYS && PBUF_POOL_FREE_OOSEQ +#if LWIP_TCP && TCP_QUEUE_OOSEQ && NO_SYS && PBUF_POOL_FREE_OOSEQ extern volatile u8_t pbuf_free_ooseq_pending; void pbuf_free_ooseq(void); /** When not using sys_check_timeouts(), call PBUF_CHECK_FREE_OOSEQ() @@ -184,8 +217,10 @@ void pbuf_free_ooseq(void); /* pbuf_alloc() reported PBUF_POOL to be empty -> try to free some \ ooseq queued pbufs now */ \ pbuf_free_ooseq(); }}while(0) -#endif /* NO_SYS && PBUF_POOL_FREE_OOSEQ*/ -#endif /* LWIP_TCP && TCP_QUEUE_OOSEQ */ +#else /* LWIP_TCP && TCP_QUEUE_OOSEQ && NO_SYS && PBUF_POOL_FREE_OOSEQ */ + /* Otherwise declare an empty PBUF_CHECK_FREE_OOSEQ */ + #define PBUF_CHECK_FREE_OOSEQ() +#endif /* LWIP_TCP && TCP_QUEUE_OOSEQ && NO_SYS && PBUF_POOL_FREE_OOSEQ*/ /* Initializes the pbuf module. This call is empty for now, but may not be in future. */ #define pbuf_init() @@ -201,12 +236,12 @@ u8_t pbuf_header(struct pbuf *p, s16_t header_size); u8_t pbuf_header_force(struct pbuf *p, s16_t header_size); void pbuf_ref(struct pbuf *p); u8_t pbuf_free(struct pbuf *p); -u8_t pbuf_clen(struct pbuf *p); +u16_t pbuf_clen(const struct pbuf *p); void pbuf_cat(struct pbuf *head, struct pbuf *tail); void pbuf_chain(struct pbuf *head, struct pbuf *tail); struct pbuf *pbuf_dechain(struct pbuf *p); -err_t pbuf_copy(struct pbuf *p_to, struct pbuf *p_from); -u16_t pbuf_copy_partial(struct pbuf *p, void *dataptr, u16_t len, u16_t offset); +err_t pbuf_copy(struct pbuf *p_to, const struct pbuf *p_from); +u16_t pbuf_copy_partial(const struct pbuf *p, void *dataptr, u16_t len, u16_t offset); err_t pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len); err_t pbuf_take_at(struct pbuf *buf, const void *dataptr, u16_t len, u16_t offset); struct pbuf *pbuf_skip(struct pbuf* in, u16_t in_offset, u16_t* out_offset); @@ -219,11 +254,12 @@ err_t pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr, void pbuf_split_64k(struct pbuf *p, struct pbuf **rest); #endif /* LWIP_TCP && TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */ -u8_t pbuf_get_at(struct pbuf* p, u16_t offset); +u8_t pbuf_get_at(const struct pbuf* p, u16_t offset); +int pbuf_try_get_at(const struct pbuf* p, u16_t offset); void pbuf_put_at(struct pbuf* p, u16_t offset, u8_t data); -u16_t pbuf_memcmp(struct pbuf* p, u16_t offset, const void* s2, u16_t n); -u16_t pbuf_memfind(struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset); -u16_t pbuf_strstr(struct pbuf* p, const char* substr); +u16_t pbuf_memcmp(const struct pbuf* p, u16_t offset, const void* s2, u16_t n); +u16_t pbuf_memfind(const struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset); +u16_t pbuf_strstr(const struct pbuf* p, const char* substr); #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/priv/api_msg.h b/tools/sdk/include/lwip/lwip/priv/api_msg.h index 02d191a5..bcc0b501 100644 --- a/tools/sdk/include/lwip/lwip/priv/api_msg.h +++ b/tools/sdk/include/lwip/lwip/priv/api_msg.h @@ -1,3 +1,8 @@ +/** + * @file + * netconn API lwIP internal implementations (do not use in application code) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,29 +43,25 @@ /* Note: Netconn API is always available when sockets are enabled - * sockets are implemented on top of them */ -#include /* for size_t */ - +#include "lwip/arch.h" #include "lwip/ip_addr.h" #include "lwip/err.h" #include "lwip/sys.h" #include "lwip/igmp.h" #include "lwip/api.h" +#include "lwip/priv/tcpip_priv.h" #ifdef __cplusplus extern "C" { #endif #if LWIP_MPU_COMPATIBLE -#define API_MSG_M_DEF(m) m -#define API_MSG_M_DEF_C(t, m) t m #if LWIP_NETCONN_SEM_PER_THREAD #define API_MSG_M_DEF_SEM(m) *m #else #define API_MSG_M_DEF_SEM(m) API_MSG_M_DEF(m) #endif #else /* LWIP_MPU_COMPATIBLE */ -#define API_MSG_M_DEF(m) *m -#define API_MSG_M_DEF_C(t, m) const t * m #define API_MSG_M_DEF_SEM(m) API_MSG_M_DEF(m) #endif /* LWIP_MPU_COMPATIBLE */ @@ -75,7 +76,7 @@ extern "C" { /** This struct includes everything that is necessary to execute a function for a netconn in another thread context (mainly used to process netconns in the tcpip_thread context to be thread safe). */ -struct api_msg_msg { +struct api_msg { /** The netconn which to process - always needed: it includes the semaphore which is used to block the application thread until the function finished. */ struct netconn *conn; @@ -150,16 +151,6 @@ struct api_msg_msg { #endif /* LWIP_NETCONN_SEM_PER_THREAD */ -/** This struct contains a function to execute in another thread context and - a struct api_msg_msg that serves as an argument for this function. - This is passed to tcpip_apimsg to execute functions in tcpip_thread context. */ -struct api_msg { - /** function to execute in tcpip_thread context */ - void (* function)(void *msg); - /** arguments for this function */ - struct api_msg_msg msg; -}; - #if LWIP_DNS /** As lwip_netconn_do_gethostbyname requires more arguments but doesn't require a netconn, it has its own struct (to avoid struct api_msg getting bigger than necessary). @@ -194,35 +185,9 @@ struct dns_api_msg { #endif #endif -#if LWIP_TCPIP_CORE_LOCKING -#ifdef LWIP_DEBUG -#define TCIP_APIMSG_SET_ERR(m, e) (m)->msg.err = e /* catch functions that don't set err */ -#else -#define TCIP_APIMSG_SET_ERR(m, e) -#endif -#if LWIP_NETCONN_SEM_PER_THREAD -#define TCPIP_APIMSG_SET_SEM(m) ((m)->msg.op_completed_sem = LWIP_NETCONN_THREAD_SEM_GET()) -#else -#define TCPIP_APIMSG_SET_SEM(m) -#endif -#define TCPIP_APIMSG_NOERR(m,f) do { \ - TCIP_APIMSG_SET_ERR(m, ERR_VAL); \ - TCPIP_APIMSG_SET_SEM(m); \ - LOCK_TCPIP_CORE(); \ - f(&((m)->msg)); \ - UNLOCK_TCPIP_CORE(); \ -} while(0) -#define TCPIP_APIMSG(m,f,e) do { \ - TCPIP_APIMSG_NOERR(m,f); \ - (e) = (m)->msg.err; \ -} while(0) -#define TCPIP_APIMSG_ACK(m) NETCONN_SET_SAFE_ERR((m)->conn, (m)->err) -#else /* LWIP_TCPIP_CORE_LOCKING */ -#define TCPIP_APIMSG_NOERR(m,f) do { (m)->function = f; tcpip_apimsg(m); } while(0) -#define TCPIP_APIMSG(m,f,e) do { (m)->function = f; (e) = tcpip_apimsg(m); } while(0) -#define TCPIP_APIMSG_ACK(m) do { NETCONN_SET_SAFE_ERR((m)->conn, (m)->err); sys_sem_signal(LWIP_API_MSG_SEM(m)); } while(0) - -#endif /* LWIP_TCPIP_CORE_LOCKING */ +#if LWIP_TCP +extern u8_t netconn_aborted; +#endif /* LWIP_TCP */ void lwip_netconn_do_newconn (void *m); void lwip_netconn_do_delconn (void *m); @@ -232,6 +197,9 @@ void lwip_netconn_do_disconnect (void *m); void lwip_netconn_do_listen (void *m); void lwip_netconn_do_send (void *m); void lwip_netconn_do_recv (void *m); +#if TCP_LISTEN_BACKLOG +void lwip_netconn_do_accepted (void *m); +#endif /* TCP_LISTEN_BACKLOG */ void lwip_netconn_do_write (void *m); void lwip_netconn_do_getaddr (void *m); void lwip_netconn_do_close (void *m); diff --git a/tools/sdk/include/lwip/lwip/priv/memp_priv.h b/tools/sdk/include/lwip/lwip/priv/memp_priv.h index abb5ebcf..f246061d 100644 --- a/tools/sdk/include/lwip/lwip/priv/memp_priv.h +++ b/tools/sdk/include/lwip/lwip/priv/memp_priv.h @@ -1,3 +1,8 @@ +/** + * @file + * memory pools lwIP internal implementations (do not use in application code) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,7 +43,7 @@ #ifdef __cplusplus extern "C" { #endif - + #include "lwip/mem.h" #if MEMP_OVERFLOW_CHECK @@ -82,6 +87,7 @@ extern "C" { #endif /* MEMP_OVERFLOW_CHECK */ +#if !MEMP_MEM_MALLOC || MEMP_OVERFLOW_CHECK struct memp { struct memp *next; #if MEMP_OVERFLOW_CHECK @@ -89,8 +95,9 @@ struct memp { int line; #endif /* MEMP_OVERFLOW_CHECK */ }; +#endif /* !MEMP_MEM_MALLOC || MEMP_OVERFLOW_CHECK */ -#if MEM_USE_POOLS +#if MEM_USE_POOLS && MEMP_USE_CUSTOM_POOLS /* Use a helper type to get the start and end of the user "memory pools" for mem_malloc */ typedef enum { /* Get the first (via: @@ -117,9 +124,19 @@ typedef enum { We use this helper type and these defines so we can avoid using const memp_t values */ #define MEMP_POOL_FIRST ((memp_t) MEMP_POOL_HELPER_FIRST) #define MEMP_POOL_LAST ((memp_t) MEMP_POOL_HELPER_LAST) -#endif /* MEM_USE_POOLS */ +#endif /* MEM_USE_POOLS && MEMP_USE_CUSTOM_POOLS */ +/** Memory pool descriptor */ struct memp_desc { +#if defined(LWIP_DEBUG) || MEMP_OVERFLOW_CHECK || LWIP_STATS_DISPLAY + /** Textual description */ + const char *desc; +#endif /* LWIP_DEBUG || MEMP_OVERFLOW_CHECK || LWIP_STATS_DISPLAY */ +#if MEMP_STATS + /** Statistics */ + struct stats_mem *stats; +#endif + /** Element size */ u16_t size; @@ -127,35 +144,28 @@ struct memp_desc { /** Number of elements */ u16_t num; -#if defined(LWIP_DEBUG) || MEMP_OVERFLOW_CHECK - /** Textual description */ - const char *desc; -#endif /* LWIP_DEBUG || MEMP_OVERFLOW_CHECK */ - - /** Base */ - u8_t *base; + /** Base address */ + u8_t *base; /** First free element of each pool. Elements form a linked list. */ struct memp **tab; #endif /* MEMP_MEM_MALLOC */ }; -#if (ESP_STATS_MEM == 1) -extern uint32_t g_lwip_mem_cnt[MEMP_MAX][2]; -#define ESP_CNT_MEM_MALLOC_INC(type) g_lwip_mem_cnt[type][0]++ -#define ESP_CNT_MEM_FREE_INC(type) g_lwip_mem_cnt[type][1]++ -#else -#define ESP_CNT_MEM_MALLOC_INC(type) -#define ESP_CNT_MEM_FREE_INC(type) -#endif - - -#ifdef LWIP_DEBUG +#if defined(LWIP_DEBUG) || MEMP_OVERFLOW_CHECK || LWIP_STATS_DISPLAY #define DECLARE_LWIP_MEMPOOL_DESC(desc) (desc), #else #define DECLARE_LWIP_MEMPOOL_DESC(desc) #endif +#if MEMP_STATS +#define LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(name) static struct stats_mem name; +#define LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(name) &name, +#else +#define LWIP_MEMPOOL_DECLARE_STATS_INSTANCE(name) +#define LWIP_MEMPOOL_DECLARE_STATS_REFERENCE(name) +#endif + void memp_init_pool(const struct memp_desc *desc); #if MEMP_OVERFLOW_CHECK diff --git a/tools/sdk/include/lwip/lwip/priv/memp_std.h b/tools/sdk/include/lwip/lwip/priv/memp_std.h index 4def116d..ce9fd500 100644 --- a/tools/sdk/include/lwip/lwip/priv/memp_std.h +++ b/tools/sdk/include/lwip/lwip/priv/memp_std.h @@ -1,3 +1,11 @@ +/** + * @file + * lwIP internal memory pools (do not use in application code) + * This file is deliberately included multiple times: once with empty + * definition of LWIP_MEMPOOL() to handle all includes and multiple times + * to build up various lists of mem pools. + */ + /* * SETUP: Make sure we define everything we will need. * @@ -47,9 +55,9 @@ LWIP_MEMPOOL(TCP_SEG, MEMP_NUM_TCP_SEG, sizeof(struct tcp_seg), #if LWIP_IPV4 && IP_REASSEMBLY LWIP_MEMPOOL(REASSDATA, MEMP_NUM_REASSDATA, sizeof(struct ip_reassdata), "REASSDATA") #endif /* LWIP_IPV4 && IP_REASSEMBLY */ -#if (IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF) || (LWIP_IPV6 && LWIP_IPV6_FRAG) +#if (IP_FRAG && !LWIP_NETIF_TX_SINGLE_PBUF) || (LWIP_IPV6 && LWIP_IPV6_FRAG) LWIP_MEMPOOL(FRAG_PBUF, MEMP_NUM_FRAG_PBUF, sizeof(struct pbuf_custom_ref),"FRAG_PBUF") -#endif /* IP_FRAG && !IP_FRAG_USES_STATIC_BUF && !LWIP_NETIF_TX_SINGLE_PBUF */ +#endif /* IP_FRAG && !LWIP_NETIF_TX_SINGLE_PBUF || (LWIP_IPV6 && LWIP_IPV6_FRAG) */ #if LWIP_NETCONN || LWIP_SOCKET LWIP_MEMPOOL(NETBUF, MEMP_NUM_NETBUF, sizeof(struct netbuf), "NETBUF") @@ -83,9 +91,9 @@ LWIP_MEMPOOL(ARP_QUEUE, MEMP_NUM_ARP_QUEUE, sizeof(struct etharp_q_en LWIP_MEMPOOL(IGMP_GROUP, MEMP_NUM_IGMP_GROUP, sizeof(struct igmp_group), "IGMP_GROUP") #endif /* LWIP_IGMP */ -#if (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) /* LWIP_TIMERS */ +#if LWIP_TIMERS && !LWIP_TIMERS_CUSTOM LWIP_MEMPOOL(SYS_TIMEOUT, MEMP_NUM_SYS_TIMEOUT, sizeof(struct sys_timeo), "SYS_TIMEOUT") -#endif /* LWIP_TIMERS */ +#endif /* LWIP_TIMERS && !LWIP_TIMERS_CUSTOM */ #if LWIP_DNS && LWIP_SOCKET LWIP_MEMPOOL(NETDB, MEMP_NUM_NETDB, NETDB_ELEM_SIZE, "NETDB") @@ -94,19 +102,6 @@ LWIP_MEMPOOL(NETDB, MEMP_NUM_NETDB, NETDB_ELEM_SIZE, LWIP_MEMPOOL(LOCALHOSTLIST, MEMP_NUM_LOCALHOSTLIST, LOCALHOSTLIST_ELEM_SIZE, "LOCALHOSTLIST") #endif /* LWIP_DNS && DNS_LOCAL_HOSTLIST && DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ -#if PPP_SUPPORT -LWIP_MEMPOOL(PPP_PCB, MEMP_NUM_PPP_PCB, sizeof(ppp_pcb), "PPP_PCB") -#if PPPOS_SUPPORT -LWIP_MEMPOOL(PPPOS_PCB, MEMP_NUM_PPPOS_INTERFACES, sizeof(pppos_pcb), "PPPOS_PCB") -#endif /* PPPOS_SUPPORT */ -#if PPPOE_SUPPORT -LWIP_MEMPOOL(PPPOE_IF, MEMP_NUM_PPPOE_INTERFACES, sizeof(struct pppoe_softc), "PPPOE_IF") -#endif /* PPPOE_SUPPORT */ -#if PPPOL2TP_SUPPORT -LWIP_MEMPOOL(PPPOL2TP_PCB, MEMP_NUM_PPPOL2TP_INTERFACES, sizeof(pppol2tp_pcb), "PPPOL2TP_PCB") -#endif /* PPPOL2TP_SUPPORT */ -#endif /* PPP_SUPPORT */ - #if LWIP_IPV6 && LWIP_ND6_QUEUEING LWIP_MEMPOOL(ND6_QUEUE, MEMP_NUM_ND6_QUEUE, sizeof(struct nd6_q_entry), "ND6_QUEUE") #endif /* LWIP_IPV6 && LWIP_ND6_QUEUEING */ diff --git a/tools/sdk/include/lwip/lwip/priv/nd6_priv.h b/tools/sdk/include/lwip/lwip/priv/nd6_priv.h new file mode 100644 index 00000000..4bda0b79 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/priv/nd6_priv.h @@ -0,0 +1,144 @@ +/** + * @file + * + * Neighbor discovery and stateless address autoconfiguration for IPv6. + * Aims to be compliant with RFC 4861 (Neighbor discovery) and RFC 4862 + * (Address autoconfiguration). + */ + +/* + * Copyright (c) 2010 Inico Technologies Ltd. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Ivan Delamer + * + * + * Please coordinate changes and requests with Ivan Delamer + * + */ + +#ifndef LWIP_HDR_ND6_PRIV_H +#define LWIP_HDR_ND6_PRIV_H + +#include "lwip/opt.h" + +#if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ + +#include "lwip/pbuf.h" +#include "lwip/ip6_addr.h" +#include "lwip/netif.h" + + +#ifdef __cplusplus +extern "C" { +#endif + +#if LWIP_ND6_QUEUEING +/** struct for queueing outgoing packets for unknown address + * defined here to be accessed by memp.h + */ +struct nd6_q_entry { + struct nd6_q_entry *next; + struct pbuf *p; +}; +#endif /* LWIP_ND6_QUEUEING */ + +/** Struct for tables. */ +struct nd6_neighbor_cache_entry { + ip6_addr_t next_hop_address; + struct netif *netif; + u8_t lladdr[NETIF_MAX_HWADDR_LEN]; + /*u32_t pmtu;*/ +#if LWIP_ND6_QUEUEING + /** Pointer to queue of pending outgoing packets on this entry. */ + struct nd6_q_entry *q; +#else /* LWIP_ND6_QUEUEING */ + /** Pointer to a single pending outgoing packet on this entry. */ + struct pbuf *q; +#endif /* LWIP_ND6_QUEUEING */ + u8_t state; + u8_t isrouter; + union { + u32_t reachable_time; /* in ms since value may originate from network packet */ + u32_t delay_time; /* ticks (ND6_TMR_INTERVAL) */ + u32_t probes_sent; + u32_t stale_time; /* ticks (ND6_TMR_INTERVAL) */ + } counter; +}; + +struct nd6_destination_cache_entry { + ip6_addr_t destination_addr; + ip6_addr_t next_hop_addr; + u16_t pmtu; + u32_t age; +}; + +struct nd6_prefix_list_entry { + ip6_addr_t prefix; + struct netif *netif; + u32_t invalidation_timer; /* in ms since value may originate from network packet */ +#if LWIP_IPV6_AUTOCONFIG + u8_t flags; +#define ND6_PREFIX_AUTOCONFIG_AUTONOMOUS 0x01 +#define ND6_PREFIX_AUTOCONFIG_ADDRESS_GENERATED 0x02 +#define ND6_PREFIX_AUTOCONFIG_ADDRESS_DUPLICATE 0x04 +#endif /* LWIP_IPV6_AUTOCONFIG */ +}; + +struct nd6_router_list_entry { + struct nd6_neighbor_cache_entry *neighbor_entry; + u32_t invalidation_timer; /* in ms since value may originate from network packet */ + u8_t flags; +}; + +enum nd6_neighbor_cache_entry_state { + ND6_NO_ENTRY = 0, + ND6_INCOMPLETE, + ND6_REACHABLE, + ND6_STALE, + ND6_DELAY, + ND6_PROBE +}; + +/* Router tables. */ +/* @todo make these static? and entries accessible through API? */ +extern struct nd6_neighbor_cache_entry neighbor_cache[]; +extern struct nd6_destination_cache_entry destination_cache[]; +extern struct nd6_prefix_list_entry prefix_list[]; +extern struct nd6_router_list_entry default_router_list[]; + +/* Default values, can be updated by a RA message. */ +extern u32_t reachable_time; +extern u32_t retrans_timer; + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_IPV6 */ + +#endif /* LWIP_HDR_ND6_PRIV_H */ diff --git a/tools/sdk/include/lwip/lwip/priv/tcp_priv.h b/tools/sdk/include/lwip/lwip/priv/tcp_priv.h index 0c498944..73e8967e 100644 --- a/tools/sdk/include/lwip/lwip/priv/tcp_priv.h +++ b/tools/sdk/include/lwip/lwip/priv/tcp_priv.h @@ -1,3 +1,8 @@ +/** + * @file + * TCP internal implementations (do not use in application code) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -29,8 +34,8 @@ * Author: Adam Dunkels * */ -#ifndef LWIP_HDR_TCP_IMPL_H -#define LWIP_HDR_TCP_IMPL_H +#ifndef LWIP_HDR_TCP_PRIV_H +#define LWIP_HDR_TCP_PRIV_H #include "lwip/opt.h" @@ -44,6 +49,7 @@ #include "lwip/err.h" #include "lwip/ip6.h" #include "lwip/ip6_addr.h" +#include "lwip/prot/tcp.h" #ifdef __cplusplus extern "C" { @@ -92,7 +98,7 @@ err_t tcp_process_refused_data(struct tcp_pcb *pcb); ((tpcb)->flags & (TF_NODELAY | TF_INFR)) || \ (((tpcb)->unsent != NULL) && (((tpcb)->unsent->next != NULL) || \ ((tpcb)->unsent->len >= (tpcb)->mss))) || \ - ((tcp_sndbuf(tpcb) == 0) || (tcp_sndqueuelen(tpcb) >= TCP_SND_QUEUELEN(tpcb))) \ + ((tcp_sndbuf(tpcb) == 0) || (tcp_sndqueuelen(tpcb) >= TCP_SND_QUEUELEN)) \ ) ? 1 : 0) #define tcp_output_nagle(tpcb) (tcp_do_output_nagle(tpcb) ? tcp_output(tpcb) : ERR_OK) @@ -106,19 +112,6 @@ err_t tcp_process_refused_data(struct tcp_pcb *pcb); #define TCP_SEQ_BETWEEN(a,b,c) ((c)-(b) >= (a)-(b)) #endif #define TCP_SEQ_BETWEEN(a,b,c) (TCP_SEQ_GEQ(a,b) && TCP_SEQ_LEQ(a,c)) -#define TCP_FIN 0x01U -#define TCP_SYN 0x02U -#define TCP_RST 0x04U -#define TCP_PSH 0x08U -#define TCP_ACK 0x10U -#define TCP_URG 0x20U -#define TCP_ECE 0x40U -#define TCP_CWR 0x80U - -#define TCP_FLAGS 0x3fU - -/* Length of the TCP header, excluding options. */ -#define TCP_HLEN 20 #ifndef TCP_TMR_INTERVAL #define TCP_TMR_INTERVAL 250 /* The TCP timer interval in milliseconds. */ @@ -156,38 +149,6 @@ err_t tcp_process_refused_data(struct tcp_pcb *pcb); #define TCP_MAXIDLE TCP_KEEPCNT_DEFAULT * TCP_KEEPINTVL_DEFAULT /* Maximum KEEPALIVE probe time */ -/* Fields are (of course) in network byte order. - * Some fields are converted to host byte order in tcp_input(). - */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct tcp_hdr { - PACK_STRUCT_FIELD(u16_t src); - PACK_STRUCT_FIELD(u16_t dest); - PACK_STRUCT_FIELD(u32_t seqno); - PACK_STRUCT_FIELD(u32_t ackno); - PACK_STRUCT_FIELD(u16_t _hdrlen_rsvd_flags); - PACK_STRUCT_FIELD(u16_t wnd); - PACK_STRUCT_FIELD(u16_t chksum); - PACK_STRUCT_FIELD(u16_t urgp); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define TCPH_HDRLEN(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) >> 12) -#define TCPH_FLAGS(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS) - -#define TCPH_HDRLEN_SET(phdr, len) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | TCPH_FLAGS(phdr)) -#define TCPH_FLAGS_SET(phdr, flags) (phdr)->_hdrlen_rsvd_flags = (((phdr)->_hdrlen_rsvd_flags & PP_HTONS(~TCP_FLAGS)) | htons(flags)) -#define TCPH_HDRLEN_FLAGS_SET(phdr, len, flags) (phdr)->_hdrlen_rsvd_flags = htons(((len) << 12) | (flags)) - -#define TCPH_SET_FLAG(phdr, flags ) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags | htons(flags)) -#define TCPH_UNSET_FLAG(phdr, flags) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags & ~htons(flags)) - #define TCP_TCPLEN(seg) ((seg)->len + (((TCPH_FLAGS((seg)->tcphdr) & (TCP_FIN | TCP_SYN)) != 0) ? 1U : 0U)) /** Flags used on input processing, not on pcb->flags @@ -199,7 +160,7 @@ PACK_STRUCT_END #if LWIP_EVENT_API -#define TCP_EVENT_ACCEPT(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ +#define TCP_EVENT_ACCEPT(lpcb,pcb,arg,err,ret) ret = lwip_tcp_event(arg, (pcb),\ LWIP_EVENT_ACCEPT, NULL, 0, err) #define TCP_EVENT_SENT(pcb,space,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ LWIP_EVENT_SENT, NULL, space, ERR_OK) @@ -209,17 +170,19 @@ PACK_STRUCT_END LWIP_EVENT_RECV, NULL, 0, ERR_OK) #define TCP_EVENT_CONNECTED(pcb,err,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ LWIP_EVENT_CONNECTED, NULL, 0, (err)) -#define TCP_EVENT_POLL(pcb,ret) ret = lwip_tcp_event((pcb)->callback_arg, (pcb),\ - LWIP_EVENT_POLL, NULL, 0, ERR_OK) -#define TCP_EVENT_ERR(errf,arg,err) lwip_tcp_event((arg), NULL, \ - LWIP_EVENT_ERR, NULL, 0, (err)) +#define TCP_EVENT_POLL(pcb,ret) do { if ((pcb)->state != SYN_RCVD) { \ + ret = lwip_tcp_event((pcb)->callback_arg, (pcb), LWIP_EVENT_POLL, NULL, 0, ERR_OK); \ + } else { \ + ret = ERR_ARG; } } while(0) +#define TCP_EVENT_ERR(last_state,errf,arg,err) do { if (last_state != SYN_RCVD) { \ + lwip_tcp_event((arg), NULL, LWIP_EVENT_ERR, NULL, 0, (err)); } } while(0) #else /* LWIP_EVENT_API */ -#define TCP_EVENT_ACCEPT(pcb,err,ret) \ +#define TCP_EVENT_ACCEPT(lpcb,pcb,arg,err,ret) \ do { \ - if((pcb)->accept != NULL) \ - (ret) = (pcb)->accept((pcb)->callback_arg,(pcb),(err)); \ + if((lpcb)->accept != NULL) \ + (ret) = (lpcb)->accept((arg),(pcb),(err)); \ else (ret) = ERR_ARG; \ } while (0) @@ -262,8 +225,9 @@ PACK_STRUCT_END else (ret) = ERR_OK; \ } while (0) -#define TCP_EVENT_ERR(errf,arg,err) \ +#define TCP_EVENT_ERR(last_state,errf,arg,err) \ do { \ + LWIP_UNUSED_ARG(last_state); \ if((errf) != NULL) \ (errf)((arg),(err)); \ } while (0) @@ -288,7 +252,7 @@ struct tcp_seg { #if TCP_OVERSIZE_DBGCHECK u16_t oversize_left; /* Extra bytes available at the end of the last pbuf in unsent (used for asserting vs. - tcp_pcb.unsent_oversized only) */ + tcp_pcb.unsent_oversize only) */ #endif /* TCP_OVERSIZE_DBGCHECK */ #if TCP_CHECKSUM_ON_COPY u16_t chksum; @@ -329,7 +293,7 @@ struct tcp_seg { (flags & TF_SEG_OPTS_WND_SCALE ? LWIP_TCP_OPT_LEN_WS_OUT : 0) /** This returns a TCP header option for MSS in an u32_t */ -#define TCP_BUILD_MSS_OPTION(mss) htonl(0x02040000 | ((mss) & 0xFFFF)) +#define TCP_BUILD_MSS_OPTION(mss) lwip_htonl(0x02040000 | ((mss) & 0xFFFF)) #if LWIP_WND_SCALE #define TCPWNDSIZE_F U32_F @@ -491,7 +455,7 @@ void tcp_rst(u32_t seqno, u32_t ackno, const ip_addr_t *local_ip, const ip_addr_t *remote_ip, u16_t local_port, u16_t remote_port); -u32_t tcp_next_iss(void); +u32_t tcp_next_iss(struct tcp_pcb *pcb); err_t tcp_keepalive(struct tcp_pcb *pcb); err_t tcp_zero_window_probe(struct tcp_pcb *pcb); @@ -532,9 +496,7 @@ s16_t tcp_pcbs_sane(void); * that a timer is needed (i.e. active- or time-wait-pcb found). */ void tcp_timer_needed(void); -#if LWIP_IPV4 -void tcp_netif_ipv4_addr_changed(const ip4_addr_t* old_addr, const ip4_addr_t* new_addr); -#endif /* LWIP_IPV4 */ +void tcp_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr); #ifdef __cplusplus } @@ -542,4 +504,4 @@ void tcp_netif_ipv4_addr_changed(const ip4_addr_t* old_addr, const ip4_addr_t* n #endif /* LWIP_TCP */ -#endif /* LWIP_HDR_TCP_H */ +#endif /* LWIP_HDR_TCP_PRIV_H */ diff --git a/tools/sdk/include/lwip/lwip/priv/tcpip_priv.h b/tools/sdk/include/lwip/lwip/priv/tcpip_priv.h index cc1c54eb..630efb14 100644 --- a/tools/sdk/include/lwip/lwip/priv/tcpip_priv.h +++ b/tools/sdk/include/lwip/lwip/priv/tcpip_priv.h @@ -1,3 +1,8 @@ +/** + * @file + * TCPIP API internal implementations (do not use in application code) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,91 +43,79 @@ #include "lwip/tcpip.h" #include "lwip/sys.h" -#include "lwip/timers.h" +#include "lwip/timeouts.h" #ifdef __cplusplus extern "C" { #endif - + struct pbuf; struct netif; -/** Define this to something that triggers a watchdog. This is called from - * tcpip_thread after processing a message. */ -#ifndef LWIP_TCPIP_THREAD_ALIVE -#define LWIP_TCPIP_THREAD_ALIVE() -#endif - -#if LWIP_TCPIP_CORE_LOCKING -/** The global semaphore to lock the stack. */ -extern sys_mutex_t lock_tcpip_core; -#define LOCK_TCPIP_CORE() sys_mutex_lock(&lock_tcpip_core) -#define UNLOCK_TCPIP_CORE() sys_mutex_unlock(&lock_tcpip_core) -#else /* LWIP_TCPIP_CORE_LOCKING */ -#define LOCK_TCPIP_CORE() -#define UNLOCK_TCPIP_CORE() -#endif /* LWIP_TCPIP_CORE_LOCKING */ - #if LWIP_MPU_COMPATIBLE #define API_VAR_REF(name) (*(name)) #define API_VAR_DECLARE(type, name) type * name -#define API_VAR_ALLOC(type, pool, name) do { \ +#define API_VAR_ALLOC(type, pool, name, errorval) do { \ name = (type *)memp_malloc(pool); \ if (name == NULL) { \ - return ERR_MEM; \ + return errorval; \ } \ } while(0) -#define API_VAR_ALLOC_DONTFAIL(type, pool, name) do { \ - name = (type *)memp_malloc(pool); \ - LWIP_ASSERT("pool empty", name != NULL); \ +#define API_VAR_ALLOC_POOL(type, pool, name, errorval) do { \ + name = (type *)LWIP_MEMPOOL_ALLOC(pool); \ + if (name == NULL) { \ + return errorval; \ + } \ } while(0) #define API_VAR_FREE(pool, name) memp_free(pool, name) -#define API_EXPR_REF(expr) &(expr) +#define API_VAR_FREE_POOL(pool, name) LWIP_MEMPOOL_FREE(pool, name) +#define API_EXPR_REF(expr) (&(expr)) #if LWIP_NETCONN_SEM_PER_THREAD #define API_EXPR_REF_SEM(expr) (expr) #else #define API_EXPR_REF_SEM(expr) API_EXPR_REF(expr) #endif #define API_EXPR_DEREF(expr) expr +#define API_MSG_M_DEF(m) m +#define API_MSG_M_DEF_C(t, m) t m #else /* LWIP_MPU_COMPATIBLE */ #define API_VAR_REF(name) name #define API_VAR_DECLARE(type, name) type name -#define API_VAR_ALLOC(type, pool, name) -#define API_VAR_ALLOC_DONTFAIL(type, pool, name) +#define API_VAR_ALLOC(type, pool, name, errorval) +#define API_VAR_ALLOC_POOL(type, pool, name, errorval) #define API_VAR_FREE(pool, name) +#define API_VAR_FREE_POOL(pool, name) #define API_EXPR_REF(expr) expr #define API_EXPR_REF_SEM(expr) API_EXPR_REF(expr) -#define API_EXPR_DEREF(expr) *(expr) +#define API_EXPR_DEREF(expr) (*(expr)) +#define API_MSG_M_DEF(m) *m +#define API_MSG_M_DEF_C(t, m) const t * m #endif /* LWIP_MPU_COMPATIBLE */ -#if !LWIP_TCPIP_CORE_LOCKING -err_t tcpip_send_api_msg(tcpip_callback_fn fn, void *apimsg, sys_sem_t* sem); -#endif /* !LWIP_TCPIP_CORE_LOCKING */ +err_t tcpip_send_msg_wait_sem(tcpip_callback_fn fn, void *apimsg, sys_sem_t* sem); -struct tcpip_api_call; -typedef err_t (*tcpip_api_call_fn)(struct tcpip_api_call* call); -struct tcpip_api_call +struct tcpip_api_call_data { - tcpip_api_call_fn function; #if !LWIP_TCPIP_CORE_LOCKING -#if LWIP_NETCONN_SEM_PER_THREAD - sys_sem_t *sem; -#else /* LWIP_NETCONN_SEM_PER_THREAD */ + err_t err; +#if !LWIP_NETCONN_SEM_PER_THREAD sys_sem_t sem; #endif /* LWIP_NETCONN_SEM_PER_THREAD */ - err_t err; +#else /* !LWIP_TCPIP_CORE_LOCKING */ + u8_t dummy; /* avoid empty struct :-( */ #endif /* !LWIP_TCPIP_CORE_LOCKING */ }; -err_t tcpip_api_call(tcpip_api_call_fn fn, struct tcpip_api_call *call); +typedef err_t (*tcpip_api_call_fn)(struct tcpip_api_call_data* call); +err_t tcpip_api_call(tcpip_api_call_fn fn, struct tcpip_api_call_data *call); enum tcpip_msg_type { TCPIP_MSG_API, TCPIP_MSG_API_CALL, TCPIP_MSG_INPKT, -#if LWIP_TCPIP_TIMEOUT +#if LWIP_TCPIP_TIMEOUT && LWIP_TIMERS TCPIP_MSG_TIMEOUT, TCPIP_MSG_UNTIMEOUT, -#endif /* LWIP_TCPIP_TIMEOUT */ +#endif /* LWIP_TCPIP_TIMEOUT && LWIP_TIMERS */ TCPIP_MSG_CALLBACK, TCPIP_MSG_CALLBACK_STATIC }; @@ -133,8 +126,12 @@ struct tcpip_msg { struct { tcpip_callback_fn function; void* msg; - } api; - struct tcpip_api_call *api_call; + } api_msg; + struct { + tcpip_api_call_fn function; + struct tcpip_api_call_data *arg; + sys_sem_t *sem; + } api_call; struct { struct pbuf *p; struct netif *netif; @@ -144,13 +141,13 @@ struct tcpip_msg { tcpip_callback_fn function; void *ctx; } cb; -#if LWIP_TCPIP_TIMEOUT +#if LWIP_TCPIP_TIMEOUT && LWIP_TIMERS struct { u32_t msecs; sys_timeout_handler h; void *arg; } tmo; -#endif /* LWIP_TCPIP_TIMEOUT */ +#endif /* LWIP_TCPIP_TIMEOUT && LWIP_TIMERS */ } msg; }; diff --git a/tools/sdk/include/lwip/lwip/prot/autoip.h b/tools/sdk/include/lwip/lwip/prot/autoip.h new file mode 100644 index 00000000..96f93f57 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/autoip.h @@ -0,0 +1,83 @@ +/** + * @file + * AutoIP protocol definitions + */ + +/* + * + * Copyright (c) 2007 Dominik Spies + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * Author: Dominik Spies + * + * This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform + * with RFC 3927. + * + */ + +#ifndef LWIP_HDR_PROT_AUTOIP_H +#define LWIP_HDR_PROT_AUTOIP_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* 169.254.0.0 */ +#define AUTOIP_NET 0xA9FE0000 +/* 169.254.1.0 */ +#define AUTOIP_RANGE_START (AUTOIP_NET | 0x0100) +/* 169.254.254.255 */ +#define AUTOIP_RANGE_END (AUTOIP_NET | 0xFEFF) + +/* RFC 3927 Constants */ +#define PROBE_WAIT 1 /* second (initial random delay) */ +#define PROBE_MIN 1 /* second (minimum delay till repeated probe) */ +#define PROBE_MAX 2 /* seconds (maximum delay till repeated probe) */ +#define PROBE_NUM 3 /* (number of probe packets) */ +#define ANNOUNCE_NUM 2 /* (number of announcement packets) */ +#define ANNOUNCE_INTERVAL 2 /* seconds (time between announcement packets) */ +#define ANNOUNCE_WAIT 2 /* seconds (delay before announcing) */ +#if ESP_LWIP +#define MAX_CONFLICTS LWIP_AUTOIP_MAX_CONFLICTS /* (max conflicts before rate limiting) */ +#define RATE_LIMIT_INTERVAL LWIP_AUTOIP_RATE_LIMIT_INTERVAL /* seconds (delay between successive attempts) */ +#else +#define MAX_CONFLICTS 10 /* (max conflicts before rate limiting) */ +#define RATE_LIMIT_INTERVAL 60 /* seconds (delay between successive attempts) */ +#endif +#define DEFEND_INTERVAL 10 /* seconds (min. wait between defensive ARPs) */ + +/* AutoIP client states */ +typedef enum { + AUTOIP_STATE_OFF = 0, + AUTOIP_STATE_PROBING = 1, + AUTOIP_STATE_ANNOUNCING = 2, + AUTOIP_STATE_BOUND = 3 +} autoip_state_enum_t; + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_AUTOIP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/dhcp.h b/tools/sdk/include/lwip/lwip/prot/dhcp.h new file mode 100644 index 00000000..036a33a8 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/dhcp.h @@ -0,0 +1,195 @@ +/** + * @file + * DHCP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Leon Woestenberg + * Copyright (c) 2001-2004 Axon Digital Design B.V., The Netherlands. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Leon Woestenberg + * + */ +#ifndef LWIP_HDR_PROT_DHCP_H +#define LWIP_HDR_PROT_DHCP_H + +#include "lwip/opt.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define DHCP_CLIENT_PORT 68 +#define DHCP_SERVER_PORT 67 + + + /* DHCP message item offsets and length */ +#define DHCP_CHADDR_LEN 16U +#define DHCP_SNAME_OFS 44U +#define DHCP_SNAME_LEN 64U +#define DHCP_FILE_OFS 108U +#define DHCP_FILE_LEN 128U +#define DHCP_MSG_LEN 236U +#define DHCP_OPTIONS_OFS (DHCP_MSG_LEN + 4U) /* 4 byte: cookie */ + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** minimum set of fields of any DHCP message */ +struct dhcp_msg +{ + PACK_STRUCT_FLD_8(u8_t op); + PACK_STRUCT_FLD_8(u8_t htype); + PACK_STRUCT_FLD_8(u8_t hlen); + PACK_STRUCT_FLD_8(u8_t hops); + PACK_STRUCT_FIELD(u32_t xid); + PACK_STRUCT_FIELD(u16_t secs); + PACK_STRUCT_FIELD(u16_t flags); + PACK_STRUCT_FLD_S(ip4_addr_p_t ciaddr); + PACK_STRUCT_FLD_S(ip4_addr_p_t yiaddr); + PACK_STRUCT_FLD_S(ip4_addr_p_t siaddr); + PACK_STRUCT_FLD_S(ip4_addr_p_t giaddr); + PACK_STRUCT_FLD_8(u8_t chaddr[DHCP_CHADDR_LEN]); + PACK_STRUCT_FLD_8(u8_t sname[DHCP_SNAME_LEN]); + PACK_STRUCT_FLD_8(u8_t file[DHCP_FILE_LEN]); + PACK_STRUCT_FIELD(u32_t cookie); +#define DHCP_MIN_OPTIONS_LEN 68U +/** make sure user does not configure this too small */ +#if ((defined(DHCP_OPTIONS_LEN)) && (DHCP_OPTIONS_LEN < DHCP_MIN_OPTIONS_LEN)) +# undef DHCP_OPTIONS_LEN +#endif +/** allow this to be configured in lwipopts.h, but not too small */ +#if (!defined(DHCP_OPTIONS_LEN)) +/** set this to be sufficient for your options in outgoing DHCP msgs */ +# define DHCP_OPTIONS_LEN DHCP_MIN_OPTIONS_LEN +#endif + PACK_STRUCT_FLD_8(u8_t options[DHCP_OPTIONS_LEN]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + + +/* DHCP client states */ +typedef enum { + DHCP_STATE_OFF = 0, + DHCP_STATE_REQUESTING = 1, + DHCP_STATE_INIT = 2, + DHCP_STATE_REBOOTING = 3, + DHCP_STATE_REBINDING = 4, + DHCP_STATE_RENEWING = 5, + DHCP_STATE_SELECTING = 6, + DHCP_STATE_INFORMING = 7, + DHCP_STATE_CHECKING = 8, + DHCP_STATE_PERMANENT = 9, /* not yet implemented */ + DHCP_STATE_BOUND = 10, + DHCP_STATE_RELEASING = 11, /* not yet implemented */ + DHCP_STATE_BACKING_OFF = 12 +} dhcp_state_enum_t; + +/* DHCP op codes */ +#define DHCP_BOOTREQUEST 1 +#define DHCP_BOOTREPLY 2 + +/* DHCP message types */ +#define DHCP_DISCOVER 1 +#define DHCP_OFFER 2 +#define DHCP_REQUEST 3 +#define DHCP_DECLINE 4 +#define DHCP_ACK 5 +#define DHCP_NAK 6 +#define DHCP_RELEASE 7 +#define DHCP_INFORM 8 + +/** DHCP hardware type, currently only ethernet is supported */ +#define DHCP_HTYPE_ETH 1 + +#define DHCP_MAGIC_COOKIE 0x63825363UL + +/* This is a list of options for BOOTP and DHCP, see RFC 2132 for descriptions */ + +/* BootP options */ +#define DHCP_OPTION_PAD 0 +#define DHCP_OPTION_SUBNET_MASK 1 /* RFC 2132 3.3 */ +#define DHCP_OPTION_ROUTER 3 +#define DHCP_OPTION_DNS_SERVER 6 +#define DHCP_OPTION_HOSTNAME 12 +#define DHCP_OPTION_IP_TTL 23 +#define DHCP_OPTION_MTU 26 +#define DHCP_OPTION_BROADCAST 28 +#define DHCP_OPTION_TCP_TTL 37 +#define DHCP_OPTION_NTP 42 +#define DHCP_OPTION_END 255 + +#if ESP_LWIP +/**add options for support more router by liuHan**/ +#define DHCP_OPTION_DOMAIN_NAME 15 +#define DHCP_OPTION_PRD 31 +#define DHCP_OPTION_STATIC_ROUTER 33 +#define DHCP_OPTION_VSN 43 +#define DHCP_OPTION_NB_TINS 44 +#define DHCP_OPTION_NB_TINT 46 +#define DHCP_OPTION_NB_TIS 47 +#define DHCP_OPTION_CLASSLESS_STATIC_ROUTER 121 +#endif + +/* DHCP options */ +#define DHCP_OPTION_REQUESTED_IP 50 /* RFC 2132 9.1, requested IP address */ +#define DHCP_OPTION_LEASE_TIME 51 /* RFC 2132 9.2, time in seconds, in 4 bytes */ +#define DHCP_OPTION_OVERLOAD 52 /* RFC2132 9.3, use file and/or sname field for options */ + +#define DHCP_OPTION_MESSAGE_TYPE 53 /* RFC 2132 9.6, important for DHCP */ +#define DHCP_OPTION_MESSAGE_TYPE_LEN 1 + +#define DHCP_OPTION_SERVER_ID 54 /* RFC 2132 9.7, server IP address */ +#define DHCP_OPTION_PARAMETER_REQUEST_LIST 55 /* RFC 2132 9.8, requested option types */ + +#define DHCP_OPTION_MAX_MSG_SIZE 57 /* RFC 2132 9.10, message size accepted >= 576 */ +#define DHCP_OPTION_MAX_MSG_SIZE_LEN 2 + +#define DHCP_OPTION_T1 58 /* T1 renewal time */ +#define DHCP_OPTION_T2 59 /* T2 rebinding time */ +#define DHCP_OPTION_US 60 +#define DHCP_OPTION_CLIENT_ID 61 +#define DHCP_OPTION_TFTP_SERVERNAME 66 +#define DHCP_OPTION_BOOTFILE 67 + +/* possible combinations of overloading the file and sname fields with options */ +#define DHCP_OVERLOAD_NONE 0 +#define DHCP_OVERLOAD_FILE 1 +#define DHCP_OVERLOAD_SNAME 2 +#define DHCP_OVERLOAD_SNAME_FILE 3 + + +#ifdef __cplusplus +} +#endif + +#endif /*LWIP_HDR_PROT_DHCP_H*/ diff --git a/tools/sdk/include/lwip/lwip/prot/dns.h b/tools/sdk/include/lwip/lwip/prot/dns.h new file mode 100644 index 00000000..94782d6e --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/dns.h @@ -0,0 +1,140 @@ +/** + * @file + * DNS - host name to IP address resolver. + */ + +/* + * Port to lwIP from uIP + * by Jim Pettinato April 2007 + * + * security fixes and more by Simon Goldschmidt + * + * uIP version Copyright (c) 2002-2003, Adam Dunkels. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef LWIP_HDR_PROT_DNS_H +#define LWIP_HDR_PROT_DNS_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** DNS server port address */ +#ifndef DNS_SERVER_PORT +#define DNS_SERVER_PORT 53 +#endif + +/* DNS field TYPE used for "Resource Records" */ +#define DNS_RRTYPE_A 1 /* a host address */ +#define DNS_RRTYPE_NS 2 /* an authoritative name server */ +#define DNS_RRTYPE_MD 3 /* a mail destination (Obsolete - use MX) */ +#define DNS_RRTYPE_MF 4 /* a mail forwarder (Obsolete - use MX) */ +#define DNS_RRTYPE_CNAME 5 /* the canonical name for an alias */ +#define DNS_RRTYPE_SOA 6 /* marks the start of a zone of authority */ +#define DNS_RRTYPE_MB 7 /* a mailbox domain name (EXPERIMENTAL) */ +#define DNS_RRTYPE_MG 8 /* a mail group member (EXPERIMENTAL) */ +#define DNS_RRTYPE_MR 9 /* a mail rename domain name (EXPERIMENTAL) */ +#define DNS_RRTYPE_NULL 10 /* a null RR (EXPERIMENTAL) */ +#define DNS_RRTYPE_WKS 11 /* a well known service description */ +#define DNS_RRTYPE_PTR 12 /* a domain name pointer */ +#define DNS_RRTYPE_HINFO 13 /* host information */ +#define DNS_RRTYPE_MINFO 14 /* mailbox or mail list information */ +#define DNS_RRTYPE_MX 15 /* mail exchange */ +#define DNS_RRTYPE_TXT 16 /* text strings */ +#define DNS_RRTYPE_AAAA 28 /* IPv6 address */ +#define DNS_RRTYPE_SRV 33 /* service location */ +#define DNS_RRTYPE_ANY 255 /* any type */ + +/* DNS field CLASS used for "Resource Records" */ +#define DNS_RRCLASS_IN 1 /* the Internet */ +#define DNS_RRCLASS_CS 2 /* the CSNET class (Obsolete - used only for examples in some obsolete RFCs) */ +#define DNS_RRCLASS_CH 3 /* the CHAOS class */ +#define DNS_RRCLASS_HS 4 /* Hesiod [Dyer 87] */ +#define DNS_RRCLASS_ANY 255 /* any class */ +#define DNS_RRCLASS_FLUSH 0x800 /* Flush bit */ + +/* DNS protocol flags */ +#define DNS_FLAG1_RESPONSE 0x80 +#define DNS_FLAG1_OPCODE_STATUS 0x10 +#define DNS_FLAG1_OPCODE_INVERSE 0x08 +#define DNS_FLAG1_OPCODE_STANDARD 0x00 +#define DNS_FLAG1_AUTHORATIVE 0x04 +#define DNS_FLAG1_TRUNC 0x02 +#define DNS_FLAG1_RD 0x01 +#define DNS_FLAG2_RA 0x80 +#define DNS_FLAG2_ERR_MASK 0x0f +#define DNS_FLAG2_ERR_NONE 0x00 +#define DNS_FLAG2_ERR_NAME 0x03 + +#define DNS_HDR_GET_OPCODE(hdr) ((((hdr)->flags1) >> 3) & 0xF) + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** DNS message header */ +struct dns_hdr { + PACK_STRUCT_FIELD(u16_t id); + PACK_STRUCT_FLD_8(u8_t flags1); + PACK_STRUCT_FLD_8(u8_t flags2); + PACK_STRUCT_FIELD(u16_t numquestions); + PACK_STRUCT_FIELD(u16_t numanswers); + PACK_STRUCT_FIELD(u16_t numauthrr); + PACK_STRUCT_FIELD(u16_t numextrarr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif +#define SIZEOF_DNS_HDR 12 + + +/* Multicast DNS definitions */ + +/** UDP port for multicast DNS queries */ +#ifndef DNS_MQUERY_PORT +#define DNS_MQUERY_PORT 5353 +#endif + +/* IPv4 group for multicast DNS queries: 224.0.0.251 */ +#ifndef DNS_MQUERY_IPV4_GROUP_INIT +#define DNS_MQUERY_IPV4_GROUP_INIT IPADDR4_INIT_BYTES(224,0,0,251) +#endif + +/* IPv6 group for multicast DNS queries: FF02::FB */ +#ifndef DNS_MQUERY_IPV6_GROUP_INIT +#define DNS_MQUERY_IPV6_GROUP_INIT IPADDR6_INIT_HOST(0xFF020000,0,0,0xFB) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_DNS_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/etharp.h b/tools/sdk/include/lwip/lwip/prot/etharp.h new file mode 100644 index 00000000..ec78305b --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/etharp.h @@ -0,0 +1,91 @@ +/** + * @file + * ARP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ETHARP_H +#define LWIP_HDR_PROT_ETHARP_H + +#include "lwip/arch.h" +#include "lwip/prot/ethernet.h" +#include "lwip/ip4_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef ETHARP_HWADDR_LEN +#define ETHARP_HWADDR_LEN ETH_HWADDR_LEN +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** the ARP message, see RFC 826 ("Packet format") */ +struct etharp_hdr { + PACK_STRUCT_FIELD(u16_t hwtype); + PACK_STRUCT_FIELD(u16_t proto); + PACK_STRUCT_FLD_8(u8_t hwlen); + PACK_STRUCT_FLD_8(u8_t protolen); + PACK_STRUCT_FIELD(u16_t opcode); + PACK_STRUCT_FLD_S(struct eth_addr shwaddr); + PACK_STRUCT_FLD_S(struct ip4_addr2 sipaddr); + PACK_STRUCT_FLD_S(struct eth_addr dhwaddr); + PACK_STRUCT_FLD_S(struct ip4_addr2 dipaddr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_ETHARP_HDR 28 + +/* ARP hwtype values */ +enum etharp_hwtype { + HWTYPE_ETHERNET = 1 + /* others not used */ +}; + +/* ARP message types (opcodes) */ +enum etharp_opcode { + ARP_REQUEST = 1, + ARP_REPLY = 2 +}; + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ETHARP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/ethernet.h b/tools/sdk/include/lwip/lwip/prot/ethernet.h new file mode 100644 index 00000000..e4baa29d --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/ethernet.h @@ -0,0 +1,170 @@ +/** + * @file + * Ethernet protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ETHERNET_H +#define LWIP_HDR_PROT_ETHERNET_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef ETH_HWADDR_LEN +#ifdef ETHARP_HWADDR_LEN +#define ETH_HWADDR_LEN ETHARP_HWADDR_LEN /* compatibility mode */ +#else +#define ETH_HWADDR_LEN 6 +#endif +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct eth_addr { + PACK_STRUCT_FLD_8(u8_t addr[ETH_HWADDR_LEN]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** Ethernet header */ +struct eth_hdr { +#if ETH_PAD_SIZE + PACK_STRUCT_FLD_8(u8_t padding[ETH_PAD_SIZE]); +#endif + PACK_STRUCT_FLD_S(struct eth_addr dest); + PACK_STRUCT_FLD_S(struct eth_addr src); + PACK_STRUCT_FIELD(u16_t type); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_ETH_HDR (14 + ETH_PAD_SIZE) + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/** VLAN header inserted between ethernet header and payload + * if 'type' in ethernet header is ETHTYPE_VLAN. + * See IEEE802.Q */ +struct eth_vlan_hdr { + PACK_STRUCT_FIELD(u16_t prio_vid); + PACK_STRUCT_FIELD(u16_t tpid); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define SIZEOF_VLAN_HDR 4 +#define VLAN_ID(vlan_hdr) (lwip_htons((vlan_hdr)->prio_vid) & 0xFFF) + +/** + * @ingroup ethernet + * A list of often ethtypes (although lwIP does not use all of them): */ +enum eth_type { + /** Internet protocol v4 */ + ETHTYPE_IP = 0x0800U, + /** Address resolution protocol */ + ETHTYPE_ARP = 0x0806U, + /** Wake on lan */ + ETHTYPE_WOL = 0x0842U, + /** RARP */ + ETHTYPE_RARP = 0x8035U, + /** Virtual local area network */ + ETHTYPE_VLAN = 0x8100U, + /** Internet protocol v6 */ + ETHTYPE_IPV6 = 0x86DDU, + /** PPP Over Ethernet Discovery Stage */ + ETHTYPE_PPPOEDISC = 0x8863U, + /** PPP Over Ethernet Session Stage */ + ETHTYPE_PPPOE = 0x8864U, + /** Jumbo Frames */ + ETHTYPE_JUMBO = 0x8870U, + /** Process field network */ + ETHTYPE_PROFINET = 0x8892U, + /** Ethernet for control automation technology */ + ETHTYPE_ETHERCAT = 0x88A4U, + /** Link layer discovery protocol */ + ETHTYPE_LLDP = 0x88CCU, + /** Serial real-time communication system */ + ETHTYPE_SERCOS = 0x88CDU, + /** Media redundancy protocol */ + ETHTYPE_MRP = 0x88E3U, + /** Precision time protocol */ + ETHTYPE_PTP = 0x88F7U, + /** Q-in-Q, 802.1ad */ + ETHTYPE_QINQ = 0x9100U +}; + +/** The 24-bit IANA IPv4-multicast OUI is 01-00-5e: */ +#define LL_IP4_MULTICAST_ADDR_0 0x01 +#define LL_IP4_MULTICAST_ADDR_1 0x00 +#define LL_IP4_MULTICAST_ADDR_2 0x5e + +/** IPv6 multicast uses this prefix */ +#define LL_IP6_MULTICAST_ADDR_0 0x33 +#define LL_IP6_MULTICAST_ADDR_1 0x33 + +/** MEMCPY-like macro to copy to/from struct eth_addr's that are local variables + * or known to be 32-bit aligned within the protocol header. */ +#ifndef ETHADDR32_COPY +#define ETHADDR32_COPY(dst, src) SMEMCPY(dst, src, ETH_HWADDR_LEN) +#endif + +/** MEMCPY-like macro to copy to/from struct eth_addr's that are no local + * variables and known to be 16-bit aligned within the protocol header. */ +#ifndef ETHADDR16_COPY +#define ETHADDR16_COPY(dst, src) SMEMCPY(dst, src, ETH_HWADDR_LEN) +#endif + +#define eth_addr_cmp(addr1, addr2) (memcmp((addr1)->addr, (addr2)->addr, ETH_HWADDR_LEN) == 0) + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ETHERNET_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/icmp.h b/tools/sdk/include/lwip/lwip/prot/icmp.h new file mode 100644 index 00000000..7d19385c --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/icmp.h @@ -0,0 +1,91 @@ +/** + * @file + * ICMP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ICMP_H +#define LWIP_HDR_PROT_ICMP_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ICMP_ER 0 /* echo reply */ +#define ICMP_DUR 3 /* destination unreachable */ +#define ICMP_SQ 4 /* source quench */ +#define ICMP_RD 5 /* redirect */ +#define ICMP_ECHO 8 /* echo */ +#define ICMP_TE 11 /* time exceeded */ +#define ICMP_PP 12 /* parameter problem */ +#define ICMP_TS 13 /* timestamp */ +#define ICMP_TSR 14 /* timestamp reply */ +#define ICMP_IRQ 15 /* information request */ +#define ICMP_IR 16 /* information reply */ +#define ICMP_AM 17 /* address mask request */ +#define ICMP_AMR 18 /* address mask reply */ + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +/** This is the standard ICMP header only that the u32_t data + * is split to two u16_t like ICMP echo needs it. + * This header is also used for other ICMP types that do not + * use the data part. + */ +PACK_STRUCT_BEGIN +struct icmp_echo_hdr { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t id); + PACK_STRUCT_FIELD(u16_t seqno); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Compatibility defines, old versions used to combine type and code to an u16_t */ +#define ICMPH_TYPE(hdr) ((hdr)->type) +#define ICMPH_CODE(hdr) ((hdr)->code) +#define ICMPH_TYPE_SET(hdr, t) ((hdr)->type = (t)) +#define ICMPH_CODE_SET(hdr, c) ((hdr)->code = (c)) + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ICMP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/icmp6.h b/tools/sdk/include/lwip/lwip/prot/icmp6.h new file mode 100644 index 00000000..34611204 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/icmp6.h @@ -0,0 +1,170 @@ +/** + * @file + * ICMP6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ICMP6_H +#define LWIP_HDR_PROT_ICMP6_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** ICMP type */ +enum icmp6_type { + /** Destination unreachable */ + ICMP6_TYPE_DUR = 1, + /** Packet too big */ + ICMP6_TYPE_PTB = 2, + /** Time exceeded */ + ICMP6_TYPE_TE = 3, + /** Parameter problem */ + ICMP6_TYPE_PP = 4, + /** Private experimentation */ + ICMP6_TYPE_PE1 = 100, + /** Private experimentation */ + ICMP6_TYPE_PE2 = 101, + /** Reserved for expansion of error messages */ + ICMP6_TYPE_RSV_ERR = 127, + + /** Echo request */ + ICMP6_TYPE_EREQ = 128, + /** Echo reply */ + ICMP6_TYPE_EREP = 129, + /** Multicast listener query */ + ICMP6_TYPE_MLQ = 130, + /** Multicast listener report */ + ICMP6_TYPE_MLR = 131, + /** Multicast listener done */ + ICMP6_TYPE_MLD = 132, + /** Router solicitation */ + ICMP6_TYPE_RS = 133, + /** Router advertisement */ + ICMP6_TYPE_RA = 134, + /** Neighbor solicitation */ + ICMP6_TYPE_NS = 135, + /** Neighbor advertisement */ + ICMP6_TYPE_NA = 136, + /** Redirect */ + ICMP6_TYPE_RD = 137, + /** Multicast router advertisement */ + ICMP6_TYPE_MRA = 151, + /** Multicast router solicitation */ + ICMP6_TYPE_MRS = 152, + /** Multicast router termination */ + ICMP6_TYPE_MRT = 153, + /** Private experimentation */ + ICMP6_TYPE_PE3 = 200, + /** Private experimentation */ + ICMP6_TYPE_PE4 = 201, + /** Reserved for expansion of informational messages */ + ICMP6_TYPE_RSV_INF = 255 +}; + +/** ICMP destination unreachable codes */ +enum icmp6_dur_code { + /** No route to destination */ + ICMP6_DUR_NO_ROUTE = 0, + /** Communication with destination administratively prohibited */ + ICMP6_DUR_PROHIBITED = 1, + /** Beyond scope of source address */ + ICMP6_DUR_SCOPE = 2, + /** Address unreachable */ + ICMP6_DUR_ADDRESS = 3, + /** Port unreachable */ + ICMP6_DUR_PORT = 4, + /** Source address failed ingress/egress policy */ + ICMP6_DUR_POLICY = 5, + /** Reject route to destination */ + ICMP6_DUR_REJECT_ROUTE = 6 +}; + +/** ICMP time exceeded codes */ +enum icmp6_te_code { + /** Hop limit exceeded in transit */ + ICMP6_TE_HL = 0, + /** Fragment reassembly time exceeded */ + ICMP6_TE_FRAG = 1 +}; + +/** ICMP parameter code */ +enum icmp6_pp_code { + /** Erroneous header field encountered */ + ICMP6_PP_FIELD = 0, + /** Unrecognized next header type encountered */ + ICMP6_PP_HEADER = 1, + /** Unrecognized IPv6 option encountered */ + ICMP6_PP_OPTION = 2 +}; + +/** This is the standard ICMP6 header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct icmp6_hdr { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t data); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** This is the ICMP6 header adapted for echo req/resp. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct icmp6_echo_hdr { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t id); + PACK_STRUCT_FIELD(u16_t seqno); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ICMP6_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/igmp.h b/tools/sdk/include/lwip/lwip/prot/igmp.h new file mode 100644 index 00000000..d60cb31e --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/igmp.h @@ -0,0 +1,90 @@ +/** + * @file + * IGMP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IGMP_H +#define LWIP_HDR_PROT_IGMP_H + +#include "lwip/arch.h" +#include "lwip/ip4_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * IGMP constants + */ +#define IGMP_TTL 1 +#define IGMP_MINLEN 8 +#define ROUTER_ALERT 0x9404U +#define ROUTER_ALERTLEN 4 + +/* + * IGMP message types, including version number. + */ +#define IGMP_MEMB_QUERY 0x11 /* Membership query */ +#define IGMP_V1_MEMB_REPORT 0x12 /* Ver. 1 membership report */ +#define IGMP_V2_MEMB_REPORT 0x16 /* Ver. 2 membership report */ +#define IGMP_LEAVE_GROUP 0x17 /* Leave-group message */ + +/* Group membership states */ +#define IGMP_GROUP_NON_MEMBER 0 +#define IGMP_GROUP_DELAYING_MEMBER 1 +#define IGMP_GROUP_IDLE_MEMBER 2 + +/** + * IGMP packet format. + */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct igmp_msg { + PACK_STRUCT_FLD_8(u8_t igmp_msgtype); + PACK_STRUCT_FLD_8(u8_t igmp_maxresp); + PACK_STRUCT_FIELD(u16_t igmp_checksum); + PACK_STRUCT_FLD_S(ip4_addr_p_t igmp_group_address); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_IGMP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/ip.h b/tools/sdk/include/lwip/lwip/prot/ip.h new file mode 100644 index 00000000..bbfae367 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/ip.h @@ -0,0 +1,51 @@ +/** + * @file + * IP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IP_H +#define LWIP_HDR_PROT_IP_H + +#include "lwip/arch.h" + +#define IP_PROTO_ICMP 1 +#define IP_PROTO_IGMP 2 +#define IP_PROTO_UDP 17 +#define IP_PROTO_UDPLITE 136 +#define IP_PROTO_TCP 6 + +/** This operates on a void* by loading the first byte */ +#define IP_HDR_GET_VERSION(ptr) ((*(u8_t*)(ptr)) >> 4) + +#endif /* LWIP_HDR_PROT_IP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/ip4.h b/tools/sdk/include/lwip/lwip/prot/ip4.h new file mode 100644 index 00000000..bd442c68 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/ip4.h @@ -0,0 +1,127 @@ +/** + * @file + * IPv4 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IP4_H +#define LWIP_HDR_PROT_IP4_H + +#include "lwip/arch.h" +#include "lwip/ip4_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** This is the packed version of ip4_addr_t, + used in network headers that are itself packed */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip4_addr_packed { + PACK_STRUCT_FIELD(u32_t addr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +typedef struct ip4_addr_packed ip4_addr_p_t; + +/* Size of the IPv4 header. Same as 'sizeof(struct ip_hdr)'. */ +#define IP_HLEN 20 + +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +/* The IPv4 header */ +struct ip_hdr { + /* version / header length */ + PACK_STRUCT_FLD_8(u8_t _v_hl); + /* type of service */ + PACK_STRUCT_FLD_8(u8_t _tos); + /* total length */ + PACK_STRUCT_FIELD(u16_t _len); + /* identification */ + PACK_STRUCT_FIELD(u16_t _id); + /* fragment offset field */ + PACK_STRUCT_FIELD(u16_t _offset); +#define IP_RF 0x8000U /* reserved fragment flag */ +#define IP_DF 0x4000U /* don't fragment flag */ +#define IP_MF 0x2000U /* more fragments flag */ +#define IP_OFFMASK 0x1fffU /* mask for fragmenting bits */ + /* time to live */ + PACK_STRUCT_FLD_8(u8_t _ttl); + /* protocol*/ + PACK_STRUCT_FLD_8(u8_t _proto); + /* checksum */ + PACK_STRUCT_FIELD(u16_t _chksum); + /* source and destination IP addresses */ + PACK_STRUCT_FLD_S(ip4_addr_p_t src); + PACK_STRUCT_FLD_S(ip4_addr_p_t dest); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Macros to get struct ip_hdr fields: */ +#define IPH_V(hdr) ((hdr)->_v_hl >> 4) +#define IPH_HL(hdr) ((hdr)->_v_hl & 0x0f) +#define IPH_TOS(hdr) ((hdr)->_tos) +#define IPH_LEN(hdr) ((hdr)->_len) +#define IPH_ID(hdr) ((hdr)->_id) +#define IPH_OFFSET(hdr) ((hdr)->_offset) +#define IPH_TTL(hdr) ((hdr)->_ttl) +#define IPH_PROTO(hdr) ((hdr)->_proto) +#define IPH_CHKSUM(hdr) ((hdr)->_chksum) + +/* Macros to set struct ip_hdr fields: */ +#define IPH_VHL_SET(hdr, v, hl) (hdr)->_v_hl = (u8_t)((((v) << 4) | (hl))) +#define IPH_TOS_SET(hdr, tos) (hdr)->_tos = (tos) +#define IPH_LEN_SET(hdr, len) (hdr)->_len = (len) +#define IPH_ID_SET(hdr, id) (hdr)->_id = (id) +#define IPH_OFFSET_SET(hdr, off) (hdr)->_offset = (off) +#define IPH_TTL_SET(hdr, ttl) (hdr)->_ttl = (u8_t)(ttl) +#define IPH_PROTO_SET(hdr, proto) (hdr)->_proto = (u8_t)(proto) +#define IPH_CHKSUM_SET(hdr, chksum) (hdr)->_chksum = (chksum) + + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_IP4_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/ip6.h b/tools/sdk/include/lwip/lwip/prot/ip6.h new file mode 100644 index 00000000..6e1e2632 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/ip6.h @@ -0,0 +1,169 @@ +/** + * @file + * IPv6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_IP6_H +#define LWIP_HDR_PROT_IP6_H + +#include "lwip/arch.h" +#include "lwip/ip6_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** This is the packed version of ip6_addr_t, + used in network headers that are itself packed */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_addr_packed { + PACK_STRUCT_FIELD(u32_t addr[4]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif +typedef struct ip6_addr_packed ip6_addr_p_t; + +#define IP6_HLEN 40 + +#define IP6_NEXTH_HOPBYHOP 0 +#define IP6_NEXTH_TCP 6 +#define IP6_NEXTH_UDP 17 +#define IP6_NEXTH_ENCAPS 41 +#define IP6_NEXTH_ROUTING 43 +#define IP6_NEXTH_FRAGMENT 44 +#define IP6_NEXTH_ICMP6 58 +#define IP6_NEXTH_NONE 59 +#define IP6_NEXTH_DESTOPTS 60 +#define IP6_NEXTH_UDPLITE 136 + +/** The IPv6 header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_hdr { + /** version / traffic class / flow label */ + PACK_STRUCT_FIELD(u32_t _v_tc_fl); + /** payload length */ + PACK_STRUCT_FIELD(u16_t _plen); + /** next header */ + PACK_STRUCT_FLD_8(u8_t _nexth); + /** hop limit */ + PACK_STRUCT_FLD_8(u8_t _hoplim); + /** source and destination IP addresses */ + PACK_STRUCT_FLD_S(ip6_addr_p_t src); + PACK_STRUCT_FLD_S(ip6_addr_p_t dest); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Hop-by-hop router alert option. */ +#define IP6_HBH_HLEN 8 +#define IP6_PAD1_OPTION 0 +#define IP6_PADN_ALERT_OPTION 1 +#define IP6_ROUTER_ALERT_OPTION 5 +#define IP6_ROUTER_ALERT_VALUE_MLD 0 +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_hbh_hdr { + /* next header */ + PACK_STRUCT_FLD_8(u8_t _nexth); + /* header length */ + PACK_STRUCT_FLD_8(u8_t _hlen); + /* router alert option type */ + PACK_STRUCT_FLD_8(u8_t _ra_opt_type); + /* router alert option data len */ + PACK_STRUCT_FLD_8(u8_t _ra_opt_dlen); + /* router alert option data */ + PACK_STRUCT_FIELD(u16_t _ra_opt_data); + /* PadN option type */ + PACK_STRUCT_FLD_8(u8_t _padn_opt_type); + /* PadN option data len */ + PACK_STRUCT_FLD_8(u8_t _padn_opt_dlen); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* Fragment header. */ +#define IP6_FRAG_HLEN 8 +#define IP6_FRAG_OFFSET_MASK 0xfff8 +#define IP6_FRAG_MORE_FLAG 0x0001 +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ip6_frag_hdr { + /* next header */ + PACK_STRUCT_FLD_8(u8_t _nexth); + /* reserved */ + PACK_STRUCT_FLD_8(u8_t reserved); + /* fragment offset */ + PACK_STRUCT_FIELD(u16_t _fragment_offset); + /* fragmented packet identification */ + PACK_STRUCT_FIELD(u32_t _identification); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#define IP6H_V(hdr) ((lwip_ntohl((hdr)->_v_tc_fl) >> 28) & 0x0f) +#define IP6H_TC(hdr) ((lwip_ntohl((hdr)->_v_tc_fl) >> 20) & 0xff) +#define IP6H_FL(hdr) (lwip_ntohl((hdr)->_v_tc_fl) & 0x000fffff) +#define IP6H_PLEN(hdr) (lwip_ntohs((hdr)->_plen)) +#define IP6H_NEXTH(hdr) ((hdr)->_nexth) +#define IP6H_NEXTH_P(hdr) ((u8_t *)(hdr) + 6) +#define IP6H_HOPLIM(hdr) ((hdr)->_hoplim) + +#define IP6H_VTCFL_SET(hdr, v, tc, fl) (hdr)->_v_tc_fl = (lwip_htonl((((u32_t)(v)) << 28) | (((u32_t)(tc)) << 20) | (fl))) +#define IP6H_PLEN_SET(hdr, plen) (hdr)->_plen = lwip_htons(plen) +#define IP6H_NEXTH_SET(hdr, nexth) (hdr)->_nexth = (nexth) +#define IP6H_HOPLIM_SET(hdr, hl) (hdr)->_hoplim = (u8_t)(hl) + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_IP6_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/mld6.h b/tools/sdk/include/lwip/lwip/prot/mld6.h new file mode 100644 index 00000000..be3a006a --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/mld6.h @@ -0,0 +1,70 @@ +/** + * @file + * MLD6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_MLD6_H +#define LWIP_HDR_PROT_MLD6_H + +#include "lwip/arch.h" +#include "lwip/prot/ip6.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Multicast listener report/query/done message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct mld_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t max_resp_delay); + PACK_STRUCT_FIELD(u16_t reserved); + PACK_STRUCT_FLD_S(ip6_addr_p_t multicast_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_MLD6_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/nd6.h b/tools/sdk/include/lwip/lwip/prot/nd6.h new file mode 100644 index 00000000..2d4903d1 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/nd6.h @@ -0,0 +1,277 @@ +/** + * @file + * ND6 protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_ND6_H +#define LWIP_HDR_PROT_ND6_H + +#include "lwip/arch.h" +#include "lwip/ip6_addr.h" +#include "lwip/prot/ip6.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Neighbor solicitation message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ns_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t reserved); + PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Neighbor advertisement message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct na_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FLD_8(u8_t flags); + PACK_STRUCT_FLD_8(u8_t reserved[3]); + PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif +#define ND6_FLAG_ROUTER (0x80) +#define ND6_FLAG_SOLICITED (0x40) +#define ND6_FLAG_OVERRIDE (0x20) + +/** Router solicitation message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct rs_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t reserved); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Router advertisement message header. */ +#define ND6_RA_FLAG_MANAGED_ADDR_CONFIG (0x80) +#define ND6_RA_FLAG_OTHER_CONFIG (0x40) +#define ND6_RA_FLAG_HOME_AGENT (0x20) +#define ND6_RA_PREFERENCE_MASK (0x18) +#define ND6_RA_PREFERENCE_HIGH (0x08) +#define ND6_RA_PREFERENCE_MEDIUM (0x00) +#define ND6_RA_PREFERENCE_LOW (0x18) +#define ND6_RA_PREFERENCE_DISABLED (0x10) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct ra_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FLD_8(u8_t current_hop_limit); + PACK_STRUCT_FLD_8(u8_t flags); + PACK_STRUCT_FIELD(u16_t router_lifetime); + PACK_STRUCT_FIELD(u32_t reachable_time); + PACK_STRUCT_FIELD(u32_t retrans_timer); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Redirect message header. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct redirect_header { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t code); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u32_t reserved); + PACK_STRUCT_FLD_S(ip6_addr_p_t target_address); + PACK_STRUCT_FLD_S(ip6_addr_p_t destination_address); + /* Options follow. */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Link-layer address option. */ +#define ND6_OPTION_TYPE_SOURCE_LLADDR (0x01) +#define ND6_OPTION_TYPE_TARGET_LLADDR (0x02) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct lladdr_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t addr[NETIF_MAX_HWADDR_LEN]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Prefix information option. */ +#define ND6_OPTION_TYPE_PREFIX_INFO (0x03) +#define ND6_PREFIX_FLAG_ON_LINK (0x80) +#define ND6_PREFIX_FLAG_AUTONOMOUS (0x40) +#define ND6_PREFIX_FLAG_ROUTER_ADDRESS (0x20) +#define ND6_PREFIX_FLAG_SITE_PREFIX (0x10) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct prefix_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t prefix_length); + PACK_STRUCT_FLD_8(u8_t flags); + PACK_STRUCT_FIELD(u32_t valid_lifetime); + PACK_STRUCT_FIELD(u32_t preferred_lifetime); + PACK_STRUCT_FLD_8(u8_t reserved2[3]); + PACK_STRUCT_FLD_8(u8_t site_prefix_length); + PACK_STRUCT_FLD_S(ip6_addr_p_t prefix); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Redirected header option. */ +#define ND6_OPTION_TYPE_REDIR_HDR (0x04) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct redirected_header_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t reserved[6]); + /* Portion of redirected packet follows. */ + /* PACK_STRUCT_FLD_8(u8_t redirected[8]); */ +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** MTU option. */ +#define ND6_OPTION_TYPE_MTU (0x05) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct mtu_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FIELD(u16_t reserved); + PACK_STRUCT_FIELD(u32_t mtu); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Route information option. */ +#define ND6_OPTION_TYPE_ROUTE_INFO (24) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct route_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FLD_8(u8_t prefix_length); + PACK_STRUCT_FLD_8(u8_t preference); + PACK_STRUCT_FIELD(u32_t route_lifetime); + PACK_STRUCT_FLD_S(ip6_addr_p_t prefix); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/** Recursive DNS Server Option. */ +#if LWIP_ND6_RDNSS_MAX_DNS_SERVERS +#define LWIP_RDNSS_OPTION_MAX_SERVERS LWIP_ND6_RDNSS_MAX_DNS_SERVERS +#else +#define LWIP_RDNSS_OPTION_MAX_SERVERS 1 +#endif +#define ND6_OPTION_TYPE_RDNSS (25) +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct rdnss_option { + PACK_STRUCT_FLD_8(u8_t type); + PACK_STRUCT_FLD_8(u8_t length); + PACK_STRUCT_FIELD(u16_t reserved); + PACK_STRUCT_FIELD(u32_t lifetime); + PACK_STRUCT_FLD_S(ip6_addr_p_t rdnss_address[LWIP_RDNSS_OPTION_MAX_SERVERS]); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_ND6_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/tcp.h b/tools/sdk/include/lwip/lwip/prot/tcp.h new file mode 100644 index 00000000..67fe7b9e --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/tcp.h @@ -0,0 +1,97 @@ +/** + * @file + * TCP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_TCP_H +#define LWIP_HDR_PROT_TCP_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Length of the TCP header, excluding options. */ +#define TCP_HLEN 20 + +/* Fields are (of course) in network byte order. + * Some fields are converted to host byte order in tcp_input(). + */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct tcp_hdr { + PACK_STRUCT_FIELD(u16_t src); + PACK_STRUCT_FIELD(u16_t dest); + PACK_STRUCT_FIELD(u32_t seqno); + PACK_STRUCT_FIELD(u32_t ackno); + PACK_STRUCT_FIELD(u16_t _hdrlen_rsvd_flags); + PACK_STRUCT_FIELD(u16_t wnd); + PACK_STRUCT_FIELD(u16_t chksum); + PACK_STRUCT_FIELD(u16_t urgp); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +/* TCP header flags bits */ +#define TCP_FIN 0x01U +#define TCP_SYN 0x02U +#define TCP_RST 0x04U +#define TCP_PSH 0x08U +#define TCP_ACK 0x10U +#define TCP_URG 0x20U +#define TCP_ECE 0x40U +#define TCP_CWR 0x80U +/* Valid TCP header flags */ +#define TCP_FLAGS 0x3fU + +#define TCPH_HDRLEN(phdr) ((u16_t)(lwip_ntohs((phdr)->_hdrlen_rsvd_flags) >> 12)) +#define TCPH_FLAGS(phdr) ((u16_t)(lwip_ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS)) + +#define TCPH_HDRLEN_SET(phdr, len) (phdr)->_hdrlen_rsvd_flags = lwip_htons(((len) << 12) | TCPH_FLAGS(phdr)) +#define TCPH_FLAGS_SET(phdr, flags) (phdr)->_hdrlen_rsvd_flags = (((phdr)->_hdrlen_rsvd_flags & PP_HTONS(~TCP_FLAGS)) | lwip_htons(flags)) +#define TCPH_HDRLEN_FLAGS_SET(phdr, len, flags) (phdr)->_hdrlen_rsvd_flags = (u16_t)(lwip_htons((u16_t)((len) << 12) | (flags))) + +#define TCPH_SET_FLAG(phdr, flags ) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags | lwip_htons(flags)) +#define TCPH_UNSET_FLAG(phdr, flags) (phdr)->_hdrlen_rsvd_flags = ((phdr)->_hdrlen_rsvd_flags & ~lwip_htons(flags)) + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_TCP_H */ diff --git a/tools/sdk/include/lwip/lwip/prot/udp.h b/tools/sdk/include/lwip/lwip/prot/udp.h new file mode 100644 index 00000000..664f19a3 --- /dev/null +++ b/tools/sdk/include/lwip/lwip/prot/udp.h @@ -0,0 +1,68 @@ +/** + * @file + * UDP protocol definitions + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef LWIP_HDR_PROT_UDP_H +#define LWIP_HDR_PROT_UDP_H + +#include "lwip/arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define UDP_HLEN 8 + +/* Fields are (of course) in network byte order. */ +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/bpstruct.h" +#endif +PACK_STRUCT_BEGIN +struct udp_hdr { + PACK_STRUCT_FIELD(u16_t src); + PACK_STRUCT_FIELD(u16_t dest); /* src/dest UDP ports */ + PACK_STRUCT_FIELD(u16_t len); + PACK_STRUCT_FIELD(u16_t chksum); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END +#ifdef PACK_STRUCT_USE_INCLUDES +# include "arch/epstruct.h" +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_HDR_PROT_UDP_H */ diff --git a/tools/sdk/include/lwip/lwip/raw.h b/tools/sdk/include/lwip/lwip/raw.h index 474fdc15..30aa1471 100644 --- a/tools/sdk/include/lwip/lwip/raw.h +++ b/tools/sdk/include/lwip/lwip/raw.h @@ -1,3 +1,9 @@ +/** + * @file + * raw API (to be used from TCPIP thread)\n + * See also @ref raw_raw + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -61,6 +67,7 @@ struct raw_pcb; typedef u8_t (*raw_recv_fn)(void *arg, struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *addr); +/** the RAW protocol control block */ struct raw_pcb { /* Common members of all PCB types */ IP_PCB; @@ -97,6 +104,8 @@ void raw_recv (struct raw_pcb *pcb, raw_recv_fn recv, void *re u8_t raw_input (struct pbuf *p, struct netif *inp); #define raw_init() /* Compatibility define, no init needed. */ +void raw_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr); + /* for compatibility with older implementation */ #define raw_new_ip6(proto) raw_new_ip_type(IPADDR_TYPE_V6, proto) diff --git a/tools/sdk/include/lwip/lwip/sio.h b/tools/sdk/include/lwip/lwip/sio.h index 09cf799a..7643e195 100644 --- a/tools/sdk/include/lwip/lwip/sio.h +++ b/tools/sdk/include/lwip/lwip/sio.h @@ -36,6 +36,7 @@ #define SIO_H #include "lwip/arch.h" +#include "lwip/opt.h" #ifdef __cplusplus extern "C" { diff --git a/tools/sdk/include/lwip/lwip/snmp.h b/tools/sdk/include/lwip/lwip/snmp.h index 07368cc6..8704d0b4 100644 --- a/tools/sdk/include/lwip/lwip/snmp.h +++ b/tools/sdk/include/lwip/lwip/snmp.h @@ -1,7 +1,6 @@ /** * @file - * MIB2 callback functions called from throughout the stack to integrate a MIB2 - * into lwIP (together with MIB2_STATS). + * SNMP support API for implementing netifs and statitics for MIB2 */ /* @@ -48,9 +47,15 @@ extern "C" { struct udp_pcb; struct netif; +/** + * @defgroup netif_mib2 MIB2 statistics + * @ingroup netif + */ + /* MIB2 statistics functions */ #if MIB2_STATS /* don't build if not configured for use in lwipopts.h */ /** + * @ingroup netif_mib2 * @see RFC1213, "MIB-II, 6. Definitions" */ enum snmp_ifType { @@ -88,18 +93,31 @@ enum snmp_ifType { snmp_ifType_frame_relay }; -/* This macro has a precision of ~49 days because sys_now returns u32_t. #define your own if you want ~490 days. */ +/** This macro has a precision of ~49 days because sys_now returns u32_t. \#define your own if you want ~490 days. */ #ifndef MIB2_COPY_SYSUPTIME_TO #define MIB2_COPY_SYSUPTIME_TO(ptrToVal) (*(ptrToVal) = (sys_now() / 10)) #endif +/** + * @ingroup netif_mib2 + * Increment stats member for SNMP MIB2 stats (struct stats_mib2_netif_ctrs) + */ #define MIB2_STATS_NETIF_INC(n, x) do { ++(n)->mib2_counters.x; } while(0) +/** + * @ingroup netif_mib2 + * Add value to stats member for SNMP MIB2 stats (struct stats_mib2_netif_ctrs) + */ #define MIB2_STATS_NETIF_ADD(n, x, val) do { (n)->mib2_counters.x += (val); } while(0) +/** + * @ingroup netif_mib2 + * Init MIB2 statistic counters in netif + * @param netif Netif to init + * @param type one of enum @ref snmp_ifType + * @param speed your link speed here (units: bits per second) + */ #define MIB2_INIT_NETIF(netif, type, speed) do { \ - /* use "snmp_ifType" enum from snmp_mib2.h for "type", snmp_ifType_ethernet_csmacd by example */ \ (netif)->link_type = (type); \ - /* your link speed here (units: bits per second) */ \ (netif)->link_speed = (speed);\ (netif)->ts = 0; \ (netif)->mib2_counters.ifinoctets = 0; \ diff --git a/tools/sdk/include/lwip/lwip/sockets.h b/tools/sdk/include/lwip/lwip/sockets.h index e9ebff65..eff3b42e 100644 --- a/tools/sdk/include/lwip/lwip/sockets.h +++ b/tools/sdk/include/lwip/lwip/sockets.h @@ -1,3 +1,8 @@ +/** + * @file + * Socket API (to be used from non-TCPIP threads) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -38,12 +43,10 @@ #if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */ -#include /* for size_t */ -#include /* for FD_ZERO */ - #include "lwip/ip_addr.h" #include "lwip/err.h" #include "lwip/inet.h" +#include "lwip/errno.h" #ifdef __cplusplus extern "C" { @@ -191,6 +194,7 @@ struct msghdr { #define SO_CONTIMEO 0x1009 /* Unimplemented: connect timeout */ #define SO_NO_CHECK 0x100a /* don't create UDP checksum */ + /* * Structure used for manipulating linger option. */ @@ -250,11 +254,6 @@ struct linger { #define TCP_KEEPIDLE 0x03 /* set pcb->keep_idle - Same as TCP_KEEPALIVE, but use seconds for get/setsockopt */ #define TCP_KEEPINTVL 0x04 /* set pcb->keep_intvl - Use seconds for get/setsockopt */ #define TCP_KEEPCNT 0x05 /* set pcb->keep_cnt - Use number of probes sent for get/setsockopt */ -#if ESP_PER_SOC_TCP_WND -#define TCP_WINDOW 0x06 /* set pcb->per_soc_tcp_wnd */ -#define TCP_SNDBUF 0x07 /* set pcb->per_soc_tcp_snd_buf */ -#endif - #endif /* LWIP_TCP */ #if LWIP_IPV6 @@ -264,6 +263,7 @@ struct linger { #define IPV6_CHECKSUM 7 /* RFC3542: calculate and insert the ICMPv6 checksum for raw sockets. */ #define IPV6_V6ONLY 27 /* RFC3493: boolean control to restrict AF_INET6 sockets to IPv6 communications only. */ +#if ESP_LWIP #if LWIP_IPV6_MLD /* Socket options for IPV6 multicast, uses the MLD interface to manage group memberships. RFC2133. */ #define IPV6_MULTICAST_IF 0x300 @@ -283,6 +283,7 @@ typedef struct ip6_mreq { #define IPV6_LEAVE_GROUP IPV6_DROP_MEMBERSHIP #endif /* LWIP_IPV6_MLD */ +#endif #endif /* LWIP_IPV6 */ @@ -466,8 +467,6 @@ void lwip_socket_thread_init(void); /* LWIP_NETCONN_SEM_PER_THREAD==1: initializ void lwip_socket_thread_cleanup(void); /* LWIP_NETCONN_SEM_PER_THREAD==1: destroy thread-local semaphore */ #if LWIP_COMPAT_SOCKETS == 2 - - /* This helps code parsers/code completion by not having the COMPAT functions as defines */ #define lwip_accept accept #define lwip_bind bind @@ -541,6 +540,7 @@ int lwip_setsockopt_r (int s, int level, int optname, const void *optval, sockle int lwip_close_r(int s); int lwip_connect_r(int s, const struct sockaddr *name, socklen_t namelen); int lwip_listen_r(int s, int backlog); +int lwip_recvmsg_r(int s, struct msghdr *message, int flags); int lwip_recv_r(int s, void *mem, size_t len, int flags); int lwip_read_r(int s, void *mem, size_t len); int lwip_recvfrom_r(int s, void *mem, size_t len, int flags, @@ -577,6 +577,8 @@ static inline int connect(int s,const struct sockaddr *name,socklen_t namelen) { return lwip_connect_r(s,name,namelen); } static inline int listen(int s,int backlog) { return lwip_listen_r(s,backlog); } +static inline int recvmsg(int sockfd, struct msghdr *msg, int flags) +{ return lwip_recvmsg_r(sockfd, msg, flags); } static inline int recv(int s,void *mem,size_t len,int flags) { return lwip_recv_r(s,mem,len,flags); } static inline int recvfrom(int s,void *mem,size_t len,int flags,struct sockaddr *from,socklen_t *fromlen) @@ -609,71 +611,106 @@ static inline int fcntl(int s,int cmd,int val) { return lwip_fcntl_r(s,cmd,val); } static inline int ioctl(int s,long cmd,void *argp) { return lwip_ioctl_r(s,cmd,argp); } -#endif /* { RETURN LWIP_POSIX_SOCKETS_IO_NAMES */ +#endif /* LWIP_POSIX_SOCKETS_IO_NAMES */ #else -static inline int accept(int s,struct sockaddr *addr,socklen_t *addrlen) -{ return lwip_accept(s,addr,addrlen); } -static inline int bind(int s,const struct sockaddr *name,socklen_t namelen) -{ return lwip_bind(s,name,namelen); } -static inline int shutdown(int s,int how) -{ return lwip_shutdown(s,how); } -static inline int getpeername(int s,struct sockaddr *name,socklen_t *namelen) -{ return lwip_getpeername(s,name,namelen); } -static inline int getsockname(int s,struct sockaddr *name,socklen_t *namelen) -{ return lwip_getsockname(s,name,namelen); } -static inline int setsockopt(int s,int level,int optname,const void *opval,socklen_t optlen) -{ return lwip_setsockopt(s,level,optname,opval,optlen); } -static inline int getsockopt(int s,int level,int optname,void *opval,socklen_t *optlen) -{ return lwip_getsockopt(s,level,optname,opval,optlen); } -static inline int closesocket(int s) -{ return lwip_close(s); } -static inline int connect(int s,const struct sockaddr *name,socklen_t namelen) -{ return lwip_connect(s,name,namelen); } -static inline int listen(int s,int backlog) -{ return lwip_listen(s,backlog); } -static inline int recv(int s,void *mem,size_t len,int flags) -{ return lwip_recv(s,mem,len,flags); } -static inline int recvfrom(int s,void *mem,size_t len,int flags,struct sockaddr *from,socklen_t *fromlen) -{ return lwip_recvfrom(s,mem,len,flags,from,fromlen); } -static inline int send(int s,const void *dataptr,size_t size,int flags) -{ return lwip_send(s,dataptr,size,flags); } -static inline int sendmsg(int s,const struct msghdr *message,int flags) -{ return lwip_sendmsg(s,message,flags); } -static inline int sendto(int s,const void *dataptr,size_t size,int flags,const struct sockaddr *to,socklen_t tolen) -{ return lwip_sendto(s,dataptr,size,flags,to,tolen); } -static inline int socket(int domain,int type,int protocol) -{ return lwip_socket(domain,type,protocol); } -#ifndef ESP_HAS_SELECT -static inline int select(int maxfdp1,fd_set t*readset,fd_set *writeset,fd_set *exceptset,struct timeval *timeout) -{ return lwip_select(maxfdp1,readset,writeset,exceptset,timeout); } -#endif /* ESP_HAS_SELECT */ -static inline int ioctlsocket(int s,long cmd,void *argp) -{ return lwip_ioctl(s,cmd,argp); } +/** @ingroup socket */ +#define accept(s,addr,addrlen) lwip_accept(s,addr,addrlen) +/** @ingroup socket */ +#define bind(s,name,namelen) lwip_bind(s,name,namelen) +/** @ingroup socket */ +#define shutdown(s,how) lwip_shutdown(s,how) +/** @ingroup socket */ +#define getpeername(s,name,namelen) lwip_getpeername(s,name,namelen) +/** @ingroup socket */ +#define getsockname(s,name,namelen) lwip_getsockname(s,name,namelen) +/** @ingroup socket */ +#define setsockopt(s,level,optname,opval,optlen) lwip_setsockopt(s,level,optname,opval,optlen) +/** @ingroup socket */ +#define getsockopt(s,level,optname,opval,optlen) lwip_getsockopt(s,level,optname,opval,optlen) +/** @ingroup socket */ +#define closesocket(s) lwip_close(s) +/** @ingroup socket */ +#define connect(s,name,namelen) lwip_connect(s,name,namelen) +/** @ingroup socket */ +#define listen(s,backlog) lwip_listen(s,backlog) +/** @ingroup socket */ +#define recv(s,mem,len,flags) lwip_recv(s,mem,len,flags) +/** @ingroup socket */ +#define recvfrom(s,mem,len,flags,from,fromlen) lwip_recvfrom(s,mem,len,flags,from,fromlen) +/** @ingroup socket */ +#define send(s,dataptr,size,flags) lwip_send(s,dataptr,size,flags) +/** @ingroup socket */ +#define sendmsg(s,message,flags) lwip_sendmsg(s,message,flags) +/** @ingroup socket */ +#define sendto(s,dataptr,size,flags,to,tolen) lwip_sendto(s,dataptr,size,flags,to,tolen) +/** @ingroup socket */ +#define socket(domain,type,protocol) lwip_socket(domain,type,protocol) +/** @ingroup socket */ +#define select(maxfdp1,readset,writeset,exceptset,timeout) lwip_select(maxfdp1,readset,writeset,exceptset,timeout) +/** @ingroup socket */ +#define ioctlsocket(s,cmd,argp) lwip_ioctl(s,cmd,argp) #if LWIP_POSIX_SOCKETS_IO_NAMES -static inline int read(int s,void *mem,size_t len) -{ return lwip_read(s,mem,len); } -static inline int write(int s,const void *dataptr,size_t len) -{ return lwip_write(s,dataptr,len); } -static inline int writev(int s,const struct iovec *iov,int iovcnt) -{ return lwip_writev(s,iov,iovcnt); } -static inline int close(int s) -{ return lwip_close(s); } -static inline int fcntl(int s,long cmd,void *val) -{ return lwip_fcntl(s,cmd,val); } -static inline int ioctl(int s,int cmd,int argp) -{ return lwip_ioctl(s,cmd,argp); } +/** @ingroup socket */ +#define read(s,mem,len) lwip_read(s,mem,len) +/** @ingroup socket */ +#define write(s,dataptr,len) lwip_write(s,dataptr,len) +/** @ingroup socket */ +#define writev(s,iov,iovcnt) lwip_writev(s,iov,iovcnt) +/** @ingroup socket */ +#define close(s) lwip_close(s) +/** @ingroup socket */ +#define fcntl(s,cmd,val) lwip_fcntl(s,cmd,val) +/** @ingroup socket */ +#define ioctl(s,cmd,argp) lwip_ioctl(s,cmd,argp) #endif /* LWIP_POSIX_SOCKETS_IO_NAMES */ -#endif /* ESP_THREAD_SAFE */ +#endif /* ESP_THREAD_SAFE */ #endif /* LWIP_COMPAT_SOCKETS != 2 */ +#if ESP_LWIP #if LWIP_IPV4 && LWIP_IPV6 +#define lwip_inet_ntop(af,src,dst,size) \ + (((af) == AF_INET6) ? ip6addr_ntoa_r((const ip6_addr_t*)(src),(dst),(size)) \ + : (((af) == AF_INET) ? ip4addr_ntoa_r((const ip4_addr_t*)(src),(dst),(size)) : NULL)) +#define lwip_inet_pton(af,src,dst) \ + (((af) == AF_INET6) ? ip6addr_aton((src),(ip6_addr_t*)(dst)) \ + : (((af) == AF_INET) ? ip4addr_aton((src),(ip4_addr_t*)(dst)) : 0)) +#elif LWIP_IPV4 /* LWIP_IPV4 && LWIP_IPV6 */ +#define lwip_inet_ntop(af,src,dst,size) \ + (((af) == AF_INET) ? ip4addr_ntoa_r((const ip4_addr_t*)(src),(dst),(size)) : NULL) +#define lwip_inet_pton(af,src,dst) \ + (((af) == AF_INET) ? ip4addr_aton((src),(ip4_addr_t*)(dst)) : 0) +#else /* LWIP_IPV4 && LWIP_IPV6 */ +#define lwip_inet_ntop(af,src,dst,size) \ + (((af) == AF_INET6) ? ip6addr_ntoa_r((const ip6_addr_t*)(src),(dst),(size)) : NULL) +#define lwip_inet_pton(af,src,dst) \ + (((af) == AF_INET6) ? ip6addr_aton((src),(ip6_addr_t*)(dst)) : 0) +#endif /* LWIP_IPV4 && LWIP_IPV6 */ + +#if LWIP_COMPAT_SOCKET_INET == 1 +/* Some libraries have problems with inet_... being macros, so please use this define + to declare normal functions */ +static inline const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) +{ lwip_inet_ntop(af, src, dst, size); return dst; } +static inline int inet_pton(int af, const char *src, void *dst) +{ lwip_inet_pton(af, src, dst); return 1; } +#else +/* By default fall back to original inet_... macros */ +# define inet_ntop(a,b,c,d) lwip_inet_ntop(a,b,c,d) +# define inet_pton(a,b,c) lwip_inet_pton(a,b,c) +#endif /* LWIP_COMPAT_SOCKET_INET */ + +#else /* ESP_LWIP*/ + +#if LWIP_IPV4 && LWIP_IPV6 +/** @ingroup socket */ #define inet_ntop(af,src,dst,size) \ (((af) == AF_INET6) ? ip6addr_ntoa_r((const ip6_addr_t*)(src),(dst),(size)) \ : (((af) == AF_INET) ? ip4addr_ntoa_r((const ip4_addr_t*)(src),(dst),(size)) : NULL)) +/** @ingroup socket */ #define inet_pton(af,src,dst) \ (((af) == AF_INET6) ? ip6addr_aton((src),(ip6_addr_t*)(dst)) \ : (((af) == AF_INET) ? ip4addr_aton((src),(ip4_addr_t*)(dst)) : 0)) @@ -689,6 +726,7 @@ static inline int ioctl(int s,int cmd,int argp) (((af) == AF_INET6) ? ip6addr_aton((src),(ip6_addr_t*)(dst)) : 0) #endif /* LWIP_IPV4 && LWIP_IPV6 */ +#endif /* ESP_LWIP */ #endif /* LWIP_COMPAT_SOCKETS */ #ifdef __cplusplus diff --git a/tools/sdk/include/lwip/lwip/stats.h b/tools/sdk/include/lwip/lwip/stats.h index a4c700b2..e883383f 100644 --- a/tools/sdk/include/lwip/lwip/stats.h +++ b/tools/sdk/include/lwip/lwip/stats.h @@ -1,3 +1,8 @@ +/** + * @file + * Statistics API (to be used from TCPIP thread) + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -55,6 +60,7 @@ extern "C" { #define STAT_COUNTER_F U16_F #endif +/** Protocol related stats */ struct stats_proto { STAT_COUNTER xmit; /* Transmitted packets. */ STAT_COUNTER recv; /* Received packets. */ @@ -70,6 +76,7 @@ struct stats_proto { STAT_COUNTER cachehit; }; +/** IGMP stats */ struct stats_igmp { STAT_COUNTER xmit; /* Transmitted packets. */ STAT_COUNTER recv; /* Received packets. */ @@ -87,10 +94,11 @@ struct stats_igmp { STAT_COUNTER tx_report; /* Sent reports. */ }; +/** Memory stats */ struct stats_mem { -#ifdef LWIP_DEBUG +#if defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY const char *name; -#endif /* LWIP_DEBUG */ +#endif /* defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY */ STAT_COUNTER err; mem_size_t avail; mem_size_t used; @@ -98,18 +106,21 @@ struct stats_mem { STAT_COUNTER illegal; }; +/** System element stats */ struct stats_syselem { STAT_COUNTER used; STAT_COUNTER max; STAT_COUNTER err; }; +/** System stats */ struct stats_sys { struct stats_syselem sem; struct stats_syselem mutex; struct stats_syselem mbox; }; +/** SNMP MIB2 stats */ struct stats_mib2 { /* IP */ u32_t ipinhdrerrors; @@ -168,51 +179,56 @@ struct stats_mib2 { u32_t icmpoutechoreps; }; +/** + * @ingroup netif_mib2 + * SNMP MIB2 interface stats + */ struct stats_mib2_netif_ctrs { - /* The total number of octets received on the interface, including framing characters */ + /** The total number of octets received on the interface, including framing characters */ u32_t ifinoctets; - /* The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were + /** The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were * not addressed to a multicast or broadcast address at this sub-layer */ u32_t ifinucastpkts; - /* The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were + /** The number of packets, delivered by this sub-layer to a higher (sub-)layer, which were * addressed to a multicast or broadcast address at this sub-layer */ u32_t ifinnucastpkts; - /* The number of inbound packets which were chosen to be discarded even though no errors had - * been detected to prevent their being deliverable to a higher-layer protocol. One possible + /** The number of inbound packets which were chosen to be discarded even though no errors had + * been detected to prevent their being deliverable to a higher-layer protocol. One possible * reason for discarding such a packet could be to free up buffer space */ u32_t ifindiscards; - /* For packet-oriented interfaces, the number of inbound packets that contained errors + /** For packet-oriented interfaces, the number of inbound packets that contained errors * preventing them from being deliverable to a higher-layer protocol. For character- - * oriented or fixed-length interfaces, the number of inbound transmission units that + * oriented or fixed-length interfaces, the number of inbound transmission units that * contained errors preventing them from being deliverable to a higher-layer protocol. */ u32_t ifinerrors; - /* For packet-oriented interfaces, the number of packets received via the interface which + /** For packet-oriented interfaces, the number of packets received via the interface which * were discarded because of an unknown or unsupported protocol. For character-oriented * or fixed-length interfaces that support protocol multiplexing the number of transmission * units received via the interface which were discarded because of an unknown or unsupported * protocol. For any interface that does not support protocol multiplexing, this counter will * always be 0 */ u32_t ifinunknownprotos; - /* The total number of octets transmitted out of the interface, including framing characters. */ + /** The total number of octets transmitted out of the interface, including framing characters. */ u32_t ifoutoctets; - /* The total number of packets that higher-level protocols requested be transmitted, and + /** The total number of packets that higher-level protocols requested be transmitted, and * which were not addressed to a multicast or broadcast address at this sub-layer, including * those that were discarded or not sent. */ u32_t ifoutucastpkts; - /* The total number of packets that higher-level protocols requested be transmitted, and which + /** The total number of packets that higher-level protocols requested be transmitted, and which * were addressed to a multicast or broadcast address at this sub-layer, including * those that were discarded or not sent. */ u32_t ifoutnucastpkts; - /* The number of outbound packets which were chosen to be discarded even though no errors had + /** The number of outbound packets which were chosen to be discarded even though no errors had * been detected to prevent their being transmitted. One possible reason for discarding * such a packet could be to free up buffer space. */ u32_t ifoutdiscards; - /* For packet-oriented interfaces, the number of outbound packets that could not be transmitted + /** For packet-oriented interfaces, the number of outbound packets that could not be transmitted * because of errors. For character-oriented or fixed-length interfaces, the number of outbound * transmission units that could not be transmitted because of errors. */ u32_t ifouterrors; }; +#if ESP_STATS_DROP struct stats_esp { /* mbox post fail stats */ u32_t rx_rawmbox_post_fail; @@ -229,66 +245,88 @@ struct stats_esp { u32_t wlanif_input_pbuf_fail; u32_t wlanif_outut_pbuf_fail; }; +#endif +/** lwIP stats container */ struct stats_ { #if LINK_STATS + /** Link level */ struct stats_proto link; #endif #if ETHARP_STATS + /** ARP */ struct stats_proto etharp; #endif #if IPFRAG_STATS + /** Fragmentation */ struct stats_proto ip_frag; #endif #if IP_STATS + /** IP */ struct stats_proto ip; #endif #if ICMP_STATS + /** ICMP */ struct stats_proto icmp; #endif #if IGMP_STATS + /** IGMP */ struct stats_igmp igmp; #endif #if UDP_STATS + /** UDP */ struct stats_proto udp; #endif #if TCP_STATS + /** TCP */ struct stats_proto tcp; #endif #if MEM_STATS + /** Heap */ struct stats_mem mem; #endif #if MEMP_STATS - struct stats_mem memp[MEMP_MAX]; + /** Internal memory pools */ + struct stats_mem *memp[MEMP_MAX]; #endif #if SYS_STATS + /** System */ struct stats_sys sys; #endif #if IP6_STATS + /** IPv6 */ struct stats_proto ip6; #endif #if ICMP6_STATS + /** ICMP6 */ struct stats_proto icmp6; #endif #if IP6_FRAG_STATS + /** IPv6 fragmentation */ struct stats_proto ip6_frag; #endif #if MLD6_STATS + /** Multicast listener discovery */ struct stats_igmp mld6; #endif #if ND6_STATS + /** Neighbor discovery */ struct stats_proto nd6; #endif #if MIB2_STATS + /** SNMP MIB2 */ struct stats_mib2 mib2; #endif + #if ESP_STATS_DROP struct stats_esp esp; #endif }; +/** Global variable containing lwIP internal statistics. Add this to your debugger's watchlist. */ extern struct stats_ lwip_stats; +/** Init statistics */ void stats_init(void); #define STATS_INC(x) ++lwip_stats.x @@ -372,9 +410,9 @@ void stats_init(void); #if MEM_STATS #define MEM_STATS_AVAIL(x, y) lwip_stats.mem.x = y -#define MEM_STATS_INC(x) STATS_INC(mem.x) -#define MEM_STATS_INC_USED(x, y) STATS_INC_USED(mem, y) -#define MEM_STATS_DEC_USED(x, y) lwip_stats.mem.x -= y +#define MEM_STATS_INC(x) SYS_ARCH_INC(lwip_stats.mem.x, 1) +#define MEM_STATS_INC_USED(x, y) SYS_ARCH_INC(lwip_stats.mem.x, y) +#define MEM_STATS_DEC_USED(x, y) SYS_ARCH_DEC(lwip_stats.mem.x, y) #define MEM_STATS_DISPLAY() stats_display_mem(&lwip_stats.mem, "HEAP") #else #define MEM_STATS_AVAIL(x, y) @@ -384,18 +422,12 @@ void stats_init(void); #define MEM_STATS_DISPLAY() #endif -#if MEMP_STATS -#define MEMP_STATS_AVAIL(x, i, y) lwip_stats.memp[i].x = y -#define MEMP_STATS_INC(x, i) STATS_INC(memp[i].x) -#define MEMP_STATS_DEC(x, i) STATS_DEC(memp[i].x) -#define MEMP_STATS_INC_USED(x, i) STATS_INC_USED(memp[i], 1) -#define MEMP_STATS_DISPLAY(i) stats_display_memp(&lwip_stats.memp[i], i) -#define MEMP_STATS_GET(x, i) STATS_GET(memp[i].x) -#else -#define MEMP_STATS_AVAIL(x, i, y) -#define MEMP_STATS_INC(x, i) + #if MEMP_STATS +#define MEMP_STATS_DEC(x, i) STATS_DEC(memp[i]->x) +#define MEMP_STATS_DISPLAY(i) stats_display_memp(lwip_stats.memp[i], i) +#define MEMP_STATS_GET(x, i) STATS_GET(memp[i]->x) + #else #define MEMP_STATS_DEC(x, i) -#define MEMP_STATS_INC_USED(x, i) #define MEMP_STATS_DISPLAY(i) #define MEMP_STATS_GET(x, i) 0 #endif @@ -474,7 +506,10 @@ void stats_display_igmp(struct stats_igmp *igmp, const char *name); void stats_display_mem(struct stats_mem *mem, const char *name); void stats_display_memp(struct stats_mem *mem, int index); void stats_display_sys(struct stats_sys *sys); +#if ESP_STATS_DROP void stats_display_esp(struct stats_esp *esp); +#endif + #else /* LWIP_STATS_DISPLAY */ #define stats_display() #define stats_display_proto(proto, name) @@ -482,7 +517,10 @@ void stats_display_esp(struct stats_esp *esp); #define stats_display_mem(mem, name) #define stats_display_memp(mem, index) #define stats_display_sys(sys) +#if ESP_STATS_DROP #define stats_display_esp(esp) +#endif + #endif /* LWIP_STATS_DISPLAY */ #ifdef __cplusplus diff --git a/tools/sdk/include/lwip/lwip/sys.h b/tools/sdk/include/lwip/lwip/sys.h index 67729e3b..f229e407 100644 --- a/tools/sdk/include/lwip/lwip/sys.h +++ b/tools/sdk/include/lwip/lwip/sys.h @@ -1,3 +1,8 @@ +/** + * @file + * OS abstraction layer + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -27,8 +32,8 @@ * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels - * */ + #ifndef LWIP_HDR_SYS_H #define LWIP_HDR_SYS_H @@ -115,134 +120,215 @@ typedef void (*lwip_thread_fn)(void *arg); #else /* LWIP_COMPAT_MUTEX */ -/** Create a new mutex +/** + * @ingroup sys_mutex + * Create a new mutex. + * Note that mutexes are expected to not be taken recursively by the lwIP code, + * so both implementation types (recursive or non-recursive) should work. * @param mutex pointer to the mutex to create - * @return a new mutex */ + * @return ERR_OK if successful, another err_t otherwise + */ err_t sys_mutex_new(sys_mutex_t *mutex); -/** Lock a mutex - * @param mutex the mutex to lock */ +/** + * @ingroup sys_mutex + * Lock a mutex + * @param mutex the mutex to lock + */ void sys_mutex_lock(sys_mutex_t *mutex); -/** Unlock a mutex - * @param mutex the mutex to unlock */ +/** + * @ingroup sys_mutex + * Unlock a mutex + * @param mutex the mutex to unlock + */ void sys_mutex_unlock(sys_mutex_t *mutex); -/** Delete a semaphore - * @param mutex the mutex to delete */ +/** + * @ingroup sys_mutex + * Delete a semaphore + * @param mutex the mutex to delete + */ void sys_mutex_free(sys_mutex_t *mutex); #ifndef sys_mutex_valid -/** Check if a mutex is valid/allocated: return 1 for valid, 0 for invalid */ +/** + * @ingroup sys_mutex + * Check if a mutex is valid/allocated: return 1 for valid, 0 for invalid + */ int sys_mutex_valid(sys_mutex_t *mutex); #endif #ifndef sys_mutex_set_invalid -/** Set a mutex invalid so that sys_mutex_valid returns 0 */ +/** + * @ingroup sys_mutex + * Set a mutex invalid so that sys_mutex_valid returns 0 + */ void sys_mutex_set_invalid(sys_mutex_t *mutex); #endif #endif /* LWIP_COMPAT_MUTEX */ /* Semaphore functions: */ -/** Create a new semaphore +/** + * @ingroup sys_sem + * Create a new semaphore * @param sem pointer to the semaphore to create * @param count initial count of the semaphore - * @return ERR_OK if successful, another err_t otherwise */ + * @return ERR_OK if successful, another err_t otherwise + */ err_t sys_sem_new(sys_sem_t *sem, u8_t count); -/** Signals a semaphore - * @param sem the semaphore to signal */ +/** + * @ingroup sys_sem + * Signals a semaphore + * @param sem the semaphore to signal + */ void sys_sem_signal(sys_sem_t *sem); + +#if ESP_LWIP /** Signals a semaphore (ISR version) * @param sem the semaphore to signal * @return non-zero if a higher priority task has been woken */ int sys_sem_signal_isr(sys_sem_t *sem); -/** Wait for a semaphore for the specified timeout +#endif + +/** + * @ingroup sys_sem + * Wait for a semaphore for the specified timeout * @param sem the semaphore to wait for * @param timeout timeout in milliseconds to wait (0 = wait forever) * @return time (in milliseconds) waited for the semaphore - * or SYS_ARCH_TIMEOUT on timeout */ + * or SYS_ARCH_TIMEOUT on timeout + */ u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout); -/** Delete a semaphore - * @param sem semaphore to delete */ +/** + * @ingroup sys_sem + * Delete a semaphore + * @param sem semaphore to delete + */ void sys_sem_free(sys_sem_t *sem); /** Wait for a semaphore - forever/no timeout */ #define sys_sem_wait(sem) sys_arch_sem_wait(sem, 0) #ifndef sys_sem_valid -/** Check if a semaphore is valid/allocated: return 1 for valid, 0 for invalid */ +/** + * @ingroup sys_sem + * Check if a semaphore is valid/allocated: return 1 for valid, 0 for invalid + */ int sys_sem_valid(sys_sem_t *sem); #endif #ifndef sys_sem_set_invalid -/** Set a semaphore invalid so that sys_sem_valid returns 0 */ +/** + * @ingroup sys_sem + * Set a semaphore invalid so that sys_sem_valid returns 0 + */ void sys_sem_set_invalid(sys_sem_t *sem); #endif #ifndef sys_sem_valid_val -/** Same as sys_sem_valid() but taking a value, not a pointer */ +/** + * Same as sys_sem_valid() but taking a value, not a pointer + */ #define sys_sem_valid_val(sem) sys_sem_valid(&(sem)) #endif #ifndef sys_sem_set_invalid_val -/** Same as sys_sem_set_invalid() but taking a value, not a pointer */ +/** + * Same as sys_sem_set_invalid() but taking a value, not a pointer + */ #define sys_sem_set_invalid_val(sem) sys_sem_set_invalid(&(sem)) #endif -/* Time functions. */ #ifndef sys_msleep +/** + * @ingroup sys_misc + * Sleep for specified number of ms + */ void sys_msleep(u32_t ms); /* only has a (close to) 1 ms resolution. */ #endif /* Mailbox functions. */ -/** Create a new mbox of specified size +/** + * @ingroup sys_mbox + * Create a new mbox of specified size * @param mbox pointer to the mbox to create * @param size (minimum) number of messages in this mbox - * @return ERR_OK if successful, another err_t otherwise */ + * @return ERR_OK if successful, another err_t otherwise + */ err_t sys_mbox_new(sys_mbox_t *mbox, int size); -/** Post a message to an mbox - may not fail +/** + * @ingroup sys_mbox + * Post a message to an mbox - may not fail * -> blocks if full, only used from tasks not from ISR * @param mbox mbox to posts the message - * @param msg message to post (ATTENTION: can be NULL) */ + * @param msg message to post (ATTENTION: can be NULL) + */ void sys_mbox_post(sys_mbox_t *mbox, void *msg); -/** Try to post a message to an mbox - may fail if full or ISR +/** + * @ingroup sys_mbox + * Try to post a message to an mbox - may fail if full or ISR * @param mbox mbox to posts the message - * @param msg message to post (ATTENTION: can be NULL) */ + * @param msg message to post (ATTENTION: can be NULL) + */ err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg); -/** Wait for a new message to arrive in the mbox +/** + * @ingroup sys_mbox + * Wait for a new message to arrive in the mbox * @param mbox mbox to get a message from * @param msg pointer where the message is stored * @param timeout maximum time (in milliseconds) to wait for a message (0 = wait forever) * @return time (in milliseconds) waited for a message, may be 0 if not waited or SYS_ARCH_TIMEOUT on timeout - * The returned time has to be accurate to prevent timer jitter! */ + * The returned time has to be accurate to prevent timer jitter! + */ u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout); /* Allow port to override with a macro, e.g. special timeout for sys_arch_mbox_fetch() */ #ifndef sys_arch_mbox_tryfetch -/** Wait for a new message to arrive in the mbox +/** + * @ingroup sys_mbox + * Wait for a new message to arrive in the mbox * @param mbox mbox to get a message from * @param msg pointer where the message is stored * @return 0 (milliseconds) if a message has been received - * or SYS_MBOX_EMPTY if the mailbox is empty */ + * or SYS_MBOX_EMPTY if the mailbox is empty + */ u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg); #endif -/** For now, we map straight to sys_arch implementation. */ +/** + * For now, we map straight to sys_arch implementation. + */ #define sys_mbox_tryfetch(mbox, msg) sys_arch_mbox_tryfetch(mbox, msg) -/** Delete an mbox - * @param mbox mbox to delete */ +/** + * @ingroup sys_mbox + * Delete an mbox + * @param mbox mbox to delete + */ void sys_mbox_free(sys_mbox_t *mbox); #define sys_mbox_fetch(mbox, msg) sys_arch_mbox_fetch(mbox, msg, 0) #ifndef sys_mbox_valid -/** Check if an mbox is valid/allocated: return 1 for valid, 0 for invalid */ +/** + * @ingroup sys_mbox + * Check if an mbox is valid/allocated: return 1 for valid, 0 for invalid + */ int sys_mbox_valid(sys_mbox_t *mbox); #endif #ifndef sys_mbox_set_invalid -/** Set an mbox invalid so that sys_mbox_valid returns 0 */ +/** + * @ingroup sys_mbox + * Set an mbox invalid so that sys_mbox_valid returns 0 + */ void sys_mbox_set_invalid(sys_mbox_t *mbox); #endif #ifndef sys_mbox_valid_val -/** Same as sys_mbox_valid() but taking a value, not a pointer */ +/** + * Same as sys_mbox_valid() but taking a value, not a pointer + */ #define sys_mbox_valid_val(mbox) sys_mbox_valid(&(mbox)) #endif #ifndef sys_mbox_set_invalid_val -/** Same as sys_mbox_set_invalid() but taking a value, not a pointer */ +/** + * Same as sys_mbox_set_invalid() but taking a value, not a pointer + */ #define sys_mbox_set_invalid_val(mbox) sys_mbox_set_invalid(&(mbox)) #endif -/** The only thread function: +/** + * @ingroup sys_misc + * The only thread function: * Creates a new thread * ATTENTION: although this function returns a value, it MUST NOT FAIL (ports have to assert this!) * @param name human-readable name for the thread (used for debugging purposes) @@ -258,12 +344,17 @@ sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, void sys_init(void); #ifndef sys_jiffies -/** Ticks/jiffies since power up. */ +/** + * Ticks/jiffies since power up. + */ u32_t sys_jiffies(void); #endif -/** Returns the current time in milliseconds, - * may be the same as sys_jiffies or at least based on it. */ +/** + * @ingroup sys_time + * Returns the current time in milliseconds, + * may be the same as sys_jiffies or at least based on it. + */ u32_t sys_now(void); /* Critical Region Protection */ @@ -279,13 +370,17 @@ u32_t sys_now(void); */ #if SYS_LIGHTWEIGHT_PROT -/** SYS_ARCH_DECL_PROTECT +/** + * @ingroup sys_prot + * SYS_ARCH_DECL_PROTECT * declare a protection variable. This macro will default to defining a variable of * type sys_prot_t. If a particular port needs a different implementation, then * this macro may be defined in sys_arch.h. */ #define SYS_ARCH_DECL_PROTECT(lev) sys_prot_t lev -/** SYS_ARCH_PROTECT +/** + * @ingroup sys_prot + * SYS_ARCH_PROTECT * Perform a "fast" protect. This could be implemented by * disabling interrupts for an embedded system or by using a semaphore or * mutex. The implementation should allow calling SYS_ARCH_PROTECT when @@ -295,7 +390,9 @@ u32_t sys_now(void); * different implementation, then this macro may be defined in sys_arch.h */ #define SYS_ARCH_PROTECT(lev) lev = sys_arch_protect() -/** SYS_ARCH_UNPROTECT +/** + * @ingroup sys_prot + * SYS_ARCH_UNPROTECT * Perform a "fast" set of the protection level to "lev". This could be * implemented by setting the interrupt level to "lev" within the MACRO or by * using a semaphore or mutex. This macro will default to calling the diff --git a/tools/sdk/include/lwip/lwip/tcp.h b/tools/sdk/include/lwip/lwip/tcp.h index f7a46b2e..30dbf147 100644 --- a/tools/sdk/include/lwip/lwip/tcp.h +++ b/tools/sdk/include/lwip/lwip/tcp.h @@ -1,3 +1,9 @@ +/** + * @file + * TCP API (to be used from TCPIP thread)\n + * See also @ref tcp_raw + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -117,7 +123,7 @@ typedef void (*tcp_err_fn)(void *arg, err_t err); * * @param arg Additional argument to pass to the callback function (@see tcp_arg()) * @param tpcb The connection pcb which is connected - * @param err An unused error code, always ERR_OK currently ;-) TODO! + * @param err An unused error code, always ERR_OK currently ;-) @todo! * Only return ERR_ABRT if you have called tcp_abort from within the * callback function! * @@ -129,15 +135,19 @@ typedef err_t (*tcp_connected_fn)(void *arg, struct tcp_pcb *tpcb, err_t err); #define RCV_WND_SCALE(pcb, wnd) (((wnd) >> (pcb)->rcv_scale)) #define SND_WND_SCALE(pcb, wnd) (((wnd) << (pcb)->snd_scale)) #define TCPWND16(x) ((u16_t)LWIP_MIN((x), 0xFFFF)) -#define TCP_WND_MAX(pcb) ((tcpwnd_size_t)(((pcb)->flags & TF_WND_SCALE) ? TCP_WND(pcb) : TCPWND16(TCP_WND(pcb)))) +#define TCP_WND_MAX(pcb) ((tcpwnd_size_t)(((pcb)->flags & TF_WND_SCALE) ? TCP_WND : TCPWND16(TCP_WND))) typedef u32_t tcpwnd_size_t; -typedef u16_t tcpflags_t; #else #define RCV_WND_SCALE(pcb, wnd) (wnd) #define SND_WND_SCALE(pcb, wnd) (wnd) #define TCPWND16(x) (x) -#define TCP_WND_MAX(pcb) TCP_WND(pcb) +#define TCP_WND_MAX(pcb) TCP_WND typedef u16_t tcpwnd_size_t; +#endif + +#if LWIP_WND_SCALE || TCP_LISTEN_BACKLOG || LWIP_TCP_TIMESTAMPS +typedef u16_t tcpflags_t; +#else typedef u8_t tcpflags_t; #endif @@ -155,34 +165,38 @@ enum tcp_state { TIME_WAIT = 10 }; -#if LWIP_CALLBACK_API - /* Function to call when a listener has been connected. - * @param arg user-supplied argument (tcp_pcb.callback_arg) - * @param pcb a new tcp_pcb that now is connected - * @param err an error argument (TODO: that is current always ERR_OK?) - * @return ERR_OK: accept the new connection, - * any other err_t aborts the new connection - */ -#define DEF_ACCEPT_CALLBACK tcp_accept_fn accept; -#else /* LWIP_CALLBACK_API */ -#define DEF_ACCEPT_CALLBACK -#endif /* LWIP_CALLBACK_API */ - /** * members common to struct tcp_pcb and struct tcp_listen_pcb */ #define TCP_PCB_COMMON(type) \ type *next; /* for the linked list */ \ void *callback_arg; \ - /* the accept callback for listen- and normal pcbs, if LWIP_CALLBACK_API */ \ - DEF_ACCEPT_CALLBACK \ enum tcp_state state; /* TCP state */ \ u8_t prio; \ /* ports are in host byte order */ \ u16_t local_port -/* the TCP protocol control block */ +/** the TCP protocol control block for listening pcbs */ +struct tcp_pcb_listen { +/** Common members of all PCB types */ + IP_PCB; +/** Protocol specific PCB members */ + TCP_PCB_COMMON(struct tcp_pcb_listen); + +#if LWIP_CALLBACK_API + /* Function to call when a listener has been connected. */ + tcp_accept_fn accept; +#endif /* LWIP_CALLBACK_API */ + +#if TCP_LISTEN_BACKLOG + u8_t backlog; + u8_t accepts_pending; +#endif /* TCP_LISTEN_BACKLOG */ +}; + + +/** the TCP protocol control block */ struct tcp_pcb { /** common PCB members */ IP_PCB; @@ -196,13 +210,19 @@ struct tcp_pcb { #define TF_ACK_DELAY 0x01U /* Delayed ACK. */ #define TF_ACK_NOW 0x02U /* Immediate ACK. */ #define TF_INFR 0x04U /* In fast recovery. */ -#define TF_TIMESTAMP 0x08U /* Timestamp option enabled */ +#define TF_CLOSEPEND 0x08U /* If this is set, tcp_close failed to enqueue the FIN (retried in tcp_tmr) */ #define TF_RXCLOSED 0x10U /* rx closed by tcp_shutdown */ #define TF_FIN 0x20U /* Connection was closed locally (FIN segment enqueued). */ #define TF_NODELAY 0x40U /* Disable Nagle algorithm */ #define TF_NAGLEMEMERR 0x80U /* nagle enabled, memerr, try to output to prevent delayed ACK to happen */ #if LWIP_WND_SCALE #define TF_WND_SCALE 0x0100U /* Window Scale option enabled */ +#endif +#if TCP_LISTEN_BACKLOG +#define TF_BACKLOGPEND 0x0200U /* If this is set, a connection pcb has increased the backlog on its listener */ +#endif +#if LWIP_TCP_TIMESTAMPS +#define TF_TIMESTAMP 0x0400U /* Timestamp option enabled */ #endif /* the rest of the fields are in host byte order @@ -236,11 +256,6 @@ struct tcp_pcb { u8_t dupacks; u32_t lastack; /* Highest acknowledged seqno. */ -#if ESP_PER_SOC_TCP_WND - tcpwnd_size_t per_soc_tcp_wnd; /* per tcp socket tcp window size */ - tcpwnd_size_t per_soc_tcp_snd_buf; /* per tcp socket tcp send buffer size */ -#endif - /* congestion avoidance/control variables */ tcpwnd_size_t cwnd; tcpwnd_size_t ssthresh; @@ -253,8 +268,6 @@ struct tcp_pcb { tcpwnd_size_t snd_wnd; /* sender window */ tcpwnd_size_t snd_wnd_max; /* the maximum sender window announced by the remote host */ - tcpwnd_size_t acked; - tcpwnd_size_t snd_buf; /* Available buffer space for sending (in bytes). */ #define TCP_SNDQUEUELEN_OVERFLOW (0xffffU-3) u16_t snd_queuelen; /* Number of pbufs currently in the send buffer. */ @@ -273,6 +286,10 @@ struct tcp_pcb { struct pbuf *refused_data; /* Data previously received but not yet taken by upper layer */ +#if LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG + struct tcp_pcb_listen* listener; +#endif /* LWIP_CALLBACK_API || TCP_LISTEN_BACKLOG */ + #if LWIP_CALLBACK_API /* Function to be called when more send buffer space is available. */ tcp_sent_fn sent; @@ -333,18 +350,6 @@ struct tcp_pcb { #define ESP_STATS_TCP_PCB(pcb) #endif -struct tcp_pcb_listen { -/* Common members of all PCB types */ - IP_PCB; -/* Protocol specific PCB members */ - TCP_PCB_COMMON(struct tcp_pcb_listen); - -#if TCP_LISTEN_BACKLOG - u8_t backlog; - u8_t accepts_pending; -#endif /* TCP_LISTEN_BACKLOG */ -}; - #if LWIP_EVENT_API enum lwip_event { @@ -369,30 +374,40 @@ struct tcp_pcb * tcp_new (void); struct tcp_pcb * tcp_new_ip_type (u8_t type); void tcp_arg (struct tcp_pcb *pcb, void *arg); -void tcp_accept (struct tcp_pcb *pcb, tcp_accept_fn accept); +#if LWIP_CALLBACK_API void tcp_recv (struct tcp_pcb *pcb, tcp_recv_fn recv); void tcp_sent (struct tcp_pcb *pcb, tcp_sent_fn sent); -void tcp_poll (struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval); void tcp_err (struct tcp_pcb *pcb, tcp_err_fn err); +void tcp_accept (struct tcp_pcb *pcb, tcp_accept_fn accept); +#endif /* LWIP_CALLBACK_API */ +void tcp_poll (struct tcp_pcb *pcb, tcp_poll_fn poll, u8_t interval); +#if LWIP_TCP_TIMESTAMPS #define tcp_mss(pcb) (((pcb)->flags & TF_TIMESTAMP) ? ((pcb)->mss - 12) : (pcb)->mss) +#else /* LWIP_TCP_TIMESTAMPS */ +#define tcp_mss(pcb) ((pcb)->mss) +#endif /* LWIP_TCP_TIMESTAMPS */ #define tcp_sndbuf(pcb) (TCPWND16((pcb)->snd_buf)) #define tcp_sndqueuelen(pcb) ((pcb)->snd_queuelen) +/** @ingroup tcp_raw */ #define tcp_nagle_disable(pcb) ((pcb)->flags |= TF_NODELAY) +/** @ingroup tcp_raw */ #define tcp_nagle_enable(pcb) ((pcb)->flags = (tcpflags_t)((pcb)->flags & ~TF_NODELAY)) +/** @ingroup tcp_raw */ #define tcp_nagle_disabled(pcb) (((pcb)->flags & TF_NODELAY) != 0) #if TCP_LISTEN_BACKLOG -#define tcp_accepted(pcb) do { \ - LWIP_ASSERT("pcb->state == LISTEN (called for wrong pcb?)", pcb->state == LISTEN); \ - (((struct tcp_pcb_listen *)(pcb))->accepts_pending--); } while(0) #define tcp_backlog_set(pcb, new_backlog) do { \ LWIP_ASSERT("pcb->state == LISTEN (called for wrong pcb?)", (pcb)->state == LISTEN); \ ((struct tcp_pcb_listen *)(pcb))->backlog = ((new_backlog) ? (new_backlog) : 1); } while(0) +void tcp_backlog_delayed(struct tcp_pcb* pcb); +void tcp_backlog_accepted(struct tcp_pcb* pcb); #else /* TCP_LISTEN_BACKLOG */ -#define tcp_accepted(pcb) LWIP_ASSERT("pcb->state == LISTEN (called for wrong pcb?)", \ - (pcb)->state == LISTEN) +#define tcp_backlog_set(pcb, new_backlog) +#define tcp_backlog_delayed(pcb) +#define tcp_backlog_accepted(pcb) #endif /* TCP_LISTEN_BACKLOG */ +#define tcp_accepted(pcb) /* compatibility define, not needed any more */ void tcp_recved (struct tcp_pcb *pcb, u16_t len); err_t tcp_bind (struct tcp_pcb *pcb, const ip_addr_t *ipaddr, @@ -400,7 +415,9 @@ err_t tcp_bind (struct tcp_pcb *pcb, const ip_addr_t *ipaddr, err_t tcp_connect (struct tcp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port, tcp_connected_fn connected); +struct tcp_pcb * tcp_listen_with_backlog_and_err(struct tcp_pcb *pcb, u8_t backlog, err_t *err); struct tcp_pcb * tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog); +/** @ingroup tcp_raw */ #define tcp_listen(pcb) tcp_listen_with_backlog(pcb, TCP_DEFAULT_LISTEN_BACKLOG) void tcp_abort (struct tcp_pcb *pcb); @@ -428,10 +445,6 @@ const char* tcp_debug_state_str(enum tcp_state s); /* for compatibility with older implementation */ #define tcp_new_ip6() tcp_new_ip_type(IPADDR_TYPE_V6) -#if ESP_PER_SOC_TCP_WND -#define PER_SOC_WND(pcb) (pcb->per_soc_wnd) -#endif - #ifdef __cplusplus } #endif diff --git a/tools/sdk/include/lwip/lwip/tcpip.h b/tools/sdk/include/lwip/lwip/tcpip.h index c1235865..f2f6b469 100644 --- a/tools/sdk/include/lwip/lwip/tcpip.h +++ b/tools/sdk/include/lwip/lwip/tcpip.h @@ -1,3 +1,8 @@ +/** + * @file + * Functions to sync with TCPIP thread + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -37,13 +42,25 @@ #if !NO_SYS /* don't build if not configured for use in lwipopts.h */ #include "lwip/err.h" -#include "lwip/timers.h" +#include "lwip/timeouts.h" #include "lwip/netif.h" #ifdef __cplusplus extern "C" { #endif +#if LWIP_TCPIP_CORE_LOCKING +/** The global semaphore to lock the stack. */ +extern sys_mutex_t lock_tcpip_core; +/** Lock lwIP core mutex (needs @ref LWIP_TCPIP_CORE_LOCKING 1) */ +#define LOCK_TCPIP_CORE() sys_mutex_lock(&lock_tcpip_core) +/** Unlock lwIP core mutex (needs @ref LWIP_TCPIP_CORE_LOCKING 1) */ +#define UNLOCK_TCPIP_CORE() sys_mutex_unlock(&lock_tcpip_core) +#else /* LWIP_TCPIP_CORE_LOCKING */ +#define LOCK_TCPIP_CORE() +#define UNLOCK_TCPIP_CORE() +#endif /* LWIP_TCPIP_CORE_LOCKING */ + struct pbuf; struct netif; @@ -61,6 +78,10 @@ err_t tcpip_inpkt(struct pbuf *p, struct netif *inp, netif_input_fn input_fn); err_t tcpip_input(struct pbuf *p, struct netif *inp); err_t tcpip_callback_with_block(tcpip_callback_fn function, void *ctx, u8_t block); +/** + * @ingroup lwip_os + * @see tcpip_callback_with_block + */ #define tcpip_callback(f, ctx) tcpip_callback_with_block(f, ctx, 1) struct tcpip_callback_msg* tcpip_callbackmsg_new(tcpip_callback_fn function, void *ctx); @@ -71,10 +92,10 @@ err_t tcpip_trycallback(struct tcpip_callback_msg* msg); err_t pbuf_free_callback(struct pbuf *p); err_t mem_free_callback(void *m); -#if LWIP_TCPIP_TIMEOUT +#if LWIP_TCPIP_TIMEOUT && LWIP_TIMERS err_t tcpip_timeout(u32_t msecs, sys_timeout_handler h, void *arg); err_t tcpip_untimeout(sys_timeout_handler h, void *arg); -#endif /* LWIP_TCPIP_TIMEOUT */ +#endif /* LWIP_TCPIP_TIMEOUT && LWIP_TIMERS */ #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwip/timers.h b/tools/sdk/include/lwip/lwip/timeouts.h similarity index 80% rename from tools/sdk/include/lwip/lwip/timers.h rename to tools/sdk/include/lwip/lwip/timeouts.h index d735392d..c9b93aa0 100644 --- a/tools/sdk/include/lwip/lwip/timers.h +++ b/tools/sdk/include/lwip/lwip/timeouts.h @@ -1,3 +1,8 @@ +/** + * @file + * Timer implementations + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -30,16 +35,10 @@ * Simon Goldschmidt * */ -#ifndef LWIP_HDR_TIMERS_H -#define LWIP_HDR_TIMERS_H +#ifndef LWIP_HDR_TIMEOUTS_H +#define LWIP_HDR_TIMEOUTS_H #include "lwip/opt.h" - -/* Timers are not supported when NO_SYS==1 and NO_SYS_NO_TIMERS==1 */ -#define LWIP_TIMERS (!NO_SYS || (NO_SYS && !NO_SYS_NO_TIMERS)) - -#if LWIP_TIMERS - #include "lwip/err.h" #if !NO_SYS #include "lwip/sys.h" @@ -57,6 +56,26 @@ extern "C" { #endif /* LWIP_DEBUG*/ #endif +/** Function prototype for a stack-internal timer function that has to be + * called at a defined interval */ +typedef void (* lwip_cyclic_timer_handler)(void); + +/** This struct contains information about a stack-internal timer function + that has to be called at a defined interval */ +struct lwip_cyclic_timer { + u32_t interval_ms; + lwip_cyclic_timer_handler handler; +#if LWIP_DEBUG_TIMERNAMES + const char* handler_name; +#endif /* LWIP_DEBUG_TIMERNAMES */ +}; + +/** This array contains all stack-internal cyclic timers. To get the number of + * timers, use LWIP_ARRAYSIZE() */ +extern const struct lwip_cyclic_timer lwip_cyclic_timers[]; + +#if LWIP_TIMERS + /** Function prototype for a timeout callback function. Register such a function * using sys_timeout(). * @@ -84,18 +103,19 @@ void sys_timeout(u32_t msecs, sys_timeout_handler handler, void *arg); #endif /* LWIP_DEBUG_TIMERNAMES */ void sys_untimeout(sys_timeout_handler handler, void *arg); +void sys_restart_timeouts(void); #if NO_SYS void sys_check_timeouts(void); -void sys_restart_timeouts(void); u32_t sys_timeouts_sleeptime(void); #else /* NO_SYS */ void sys_timeouts_mbox_fetch(sys_mbox_t *mbox, void **msg); #endif /* NO_SYS */ +#endif /* LWIP_TIMERS */ + #ifdef __cplusplus } #endif -#endif /* LWIP_TIMERS */ -#endif /* LWIP_HDR_TIMERS_H */ +#endif /* LWIP_HDR_TIMEOUTS_H */ diff --git a/tools/sdk/include/lwip/lwip/udp.h b/tools/sdk/include/lwip/lwip/udp.h index c2f6ed9d..b679a82d 100644 --- a/tools/sdk/include/lwip/lwip/udp.h +++ b/tools/sdk/include/lwip/lwip/udp.h @@ -1,3 +1,9 @@ +/** + * @file + * UDP API (to be used from TCPIP thread)\n + * See also @ref udp_raw + */ + /* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. @@ -41,29 +47,12 @@ #include "lwip/ip_addr.h" #include "lwip/ip.h" #include "lwip/ip6_addr.h" +#include "lwip/prot/udp.h" #ifdef __cplusplus extern "C" { #endif -#define UDP_HLEN 8 - -/* Fields are (of course) in network byte order. */ -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct udp_hdr { - PACK_STRUCT_FIELD(u16_t src); - PACK_STRUCT_FIELD(u16_t dest); /* src/dest UDP ports */ - PACK_STRUCT_FIELD(u16_t len); - PACK_STRUCT_FIELD(u16_t chksum); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - #define UDP_FLAGS_NOCHKSUM 0x01U #define UDP_FLAGS_UDPLITE 0x02U #define UDP_FLAGS_CONNECTED 0x04U @@ -88,8 +77,9 @@ struct udp_pcb; typedef void (*udp_recv_fn)(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port); +/** the UDP protocol control block */ struct udp_pcb { -/* Common members of all PCB types */ +/** Common members of all PCB types */ IP_PCB; /* Protocol specific PCB members */ @@ -174,10 +164,12 @@ void udp_init (void); #define udp_set_multicast_ttl(pcb, value) do { (pcb)->mcast_ttl = value; } while(0) #define udp_get_multicast_ttl(pcb) ((pcb)->mcast_ttl) +#if ESP_LWIP #if LWIP_IPV6_MLD #define udp_set_multicast_netif_ip6addr(pcb, ip6addr) ip_addr_copy_from_ip6((pcb)->multicast_ip, *(ip6addr)) #define udp_get_multicast_netif_ip6addr(pcb) ip_2_ip6(&(pcb)->multicast_ip) #endif +#endif #endif /* LWIP_MULTICAST_TX_OPTIONS */ @@ -187,9 +179,7 @@ void udp_debug_print(struct udp_hdr *udphdr); #define udp_debug_print(udphdr) #endif -#if LWIP_IPV4 -void udp_netif_ipv4_addr_changed(const ip4_addr_t* old_addr, const ip4_addr_t* new_addr); -#endif /* LWIP_IPV4 */ +void udp_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr); #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/lwipopts.h b/tools/sdk/include/lwip/lwipopts.h index 8f1dd44f..53b59860 100644 --- a/tools/sdk/include/lwip/lwipopts.h +++ b/tools/sdk/include/lwip/lwipopts.h @@ -44,6 +44,8 @@ #include "esp_system.h" #include "sdkconfig.h" +#include "netif/dhcp_state.h" + /* Enable all Espressif-only options */ /* @@ -220,6 +222,19 @@ */ #define DHCP_DOES_ARP_CHECK CONFIG_LWIP_DHCP_DOES_ARP_CHECK + +/** + * CONFIG_LWIP_DHCP_RESTORE_LAST_IP==1: Last valid IP address obtained from DHCP server + * is restored after reset/power-up. + */ +#if CONFIG_LWIP_DHCP_RESTORE_LAST_IP + +#define LWIP_DHCP_IP_ADDR_RESTORE() dhcp_ip_addr_restore(netif) +#define LWIP_DHCP_IP_ADDR_STORE() dhcp_ip_addr_store(netif) +#define LWIP_DHCP_IP_ADDR_ERASE() dhcp_ip_addr_erase(esp_netif[tcpip_if]) + +#endif + /* ------------------------------------ ---------- AUTOIP options ---------- @@ -626,7 +641,6 @@ --------------------------------------- */ #define LWIP_HOOK_IP4_ROUTE_SRC ip4_route_src_hook - /* --------------------------------------- ---------- Debugging options ---------- @@ -720,7 +734,7 @@ #define ESP_LWIP 1 #define ESP_LWIP_ARP 1 -#define ESP_PER_SOC_TCP_WND 1 +#define ESP_PER_SOC_TCP_WND 0 #define ESP_THREAD_SAFE 1 #define ESP_THREAD_SAFE_DEBUG LWIP_DBG_OFF #define ESP_DHCP 1 @@ -735,9 +749,12 @@ #define ESP_STATS_DROP CONFIG_LWIP_STATS #define ESP_STATS_TCP 0 #define ESP_DHCP_TIMER 1 +#define ESP_DHCPS_TIMER 1 #define ESP_LWIP_LOGI(...) ESP_LOGI("lwip", __VA_ARGS__) #define ESP_PING 1 #define ESP_HAS_SELECT 1 +#define ESP_AUTO_RECV 1 +#define ESP_GRATUITOUS_ARP CONFIG_ESP_GRATUITOUS_ARP #if CONFIG_LWIP_IRAM_OPTIMIZATION #define ESP_IRAM_ATTR IRAM_ATTR @@ -745,9 +762,6 @@ #define ESP_IRAM_ATTR #endif -#define TCP_WND_DEFAULT CONFIG_TCP_WND_DEFAULT -#define TCP_SND_BUF_DEFAULT CONFIG_TCP_SND_BUF_DEFAULT - #if ESP_PERF #define DBG_PERF_PATH_SET(dir, point) #define DBG_PERF_FILTER_LEN 1000 @@ -772,9 +786,18 @@ enum { #define DBG_PERF_FILTER_LEN 1000 #endif +#define TCP_SND_BUF CONFIG_TCP_SND_BUF_DEFAULT +#define TCP_WND CONFIG_TCP_WND_DEFAULT + #if ESP_PER_SOC_TCP_WND +#define TCP_WND_DEFAULT CONFIG_TCP_WND_DEFAULT +#define TCP_SND_BUF_DEFAULT CONFIG_TCP_SND_BUF_DEFAULT #define TCP_WND(pcb) (pcb->per_soc_tcp_wnd) #define TCP_SND_BUF(pcb) (pcb->per_soc_tcp_snd_buf) +#define TCP_SND_QUEUELEN(pcb) ((4 * (TCP_SND_BUF((pcb))) + (TCP_MSS - 1))/(TCP_MSS)) +#define TCP_SNDLOWAT(pcb) LWIP_MIN(LWIP_MAX(((TCP_SND_BUF((pcb)))/2), (2 * TCP_MSS) + 1), (TCP_SND_BUF((pcb))) - 1) +#define TCP_SNDQUEUELOWAT(pcb) LWIP_MAX(((TCP_SND_QUEUELEN((pcb)))/2), 5) +#define TCP_WND_UPDATE_THRESHOLD(pcb) LWIP_MIN((TCP_WND((pcb)) / 4), (TCP_MSS * 4)) #endif /** diff --git a/tools/sdk/include/lwip/netdb.h b/tools/sdk/include/lwip/netdb.h index 12d4c7f5..363154f6 100644 --- a/tools/sdk/include/lwip/netdb.h +++ b/tools/sdk/include/lwip/netdb.h @@ -31,3 +31,10 @@ */ #include "lwip/netdb.h" + +#ifdef ESP_PLATFORM +int getnameinfo(const struct sockaddr *addr, socklen_t addrlen, + char *host, socklen_t hostlen, + char *serv, socklen_t servlen, int flags); + +#endif diff --git a/tools/sdk/include/lwip/netif/dhcp_state.h b/tools/sdk/include/lwip/netif/dhcp_state.h new file mode 100644 index 00000000..ffea1164 --- /dev/null +++ b/tools/sdk/include/lwip/netif/dhcp_state.h @@ -0,0 +1,33 @@ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +#ifndef _DHCP_STATE_H_ +#define _DHCP_STATE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +bool dhcp_ip_addr_restore(void *netif); + +void dhcp_ip_addr_store(void *netif); + +void dhcp_ip_addr_erase(void *netif); + +#ifdef __cplusplus +} +#endif + +#endif /* _DHCP_STATE_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/lwip/netif/etharp.h b/tools/sdk/include/lwip/netif/etharp.h index 3e25c389..b536fd28 100644 --- a/tools/sdk/include/lwip/netif/etharp.h +++ b/tools/sdk/include/lwip/netif/etharp.h @@ -1,147 +1,3 @@ -/* - * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * Copyright (c) 2003-2004 Leon Woestenberg - * Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT - * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING - * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY - * OF SUCH DAMAGE. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Adam Dunkels - * - */ - -#ifndef LWIP_HDR_NETIF_ETHARP_H -#define LWIP_HDR_NETIF_ETHARP_H - -#include "lwip/opt.h" - -#if LWIP_ARP || LWIP_ETHERNET /* don't build if not configured for use in lwipopts.h */ - -#include "lwip/pbuf.h" -#include "lwip/ip4_addr.h" -#include "lwip/netif.h" -#include "lwip/ip4.h" +/* ARP has been moved to core/ipv4, provide this #include for compatibility only */ +#include "lwip/etharp.h" #include "netif/ethernet.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#if LWIP_IPV4 && LWIP_ARP /* don't build if not configured for use in lwipopts.h */ - -#ifndef ETHARP_HWADDR_LEN -#define ETHARP_HWADDR_LEN ETH_HWADDR_LEN -#endif - -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -/** the ARP message, see RFC 826 ("Packet format") */ -struct etharp_hdr { - PACK_STRUCT_FIELD(u16_t hwtype); - PACK_STRUCT_FIELD(u16_t proto); - PACK_STRUCT_FLD_8(u8_t hwlen); - PACK_STRUCT_FLD_8(u8_t protolen); - PACK_STRUCT_FIELD(u16_t opcode); - PACK_STRUCT_FLD_S(struct eth_addr shwaddr); - PACK_STRUCT_FLD_S(struct ip4_addr2 sipaddr); - PACK_STRUCT_FLD_S(struct eth_addr dhwaddr); - PACK_STRUCT_FLD_S(struct ip4_addr2 dipaddr); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define SIZEOF_ETHARP_HDR 28 - -#define SIZEOF_ETHARP_PACKET (SIZEOF_ETH_HDR + SIZEOF_ETHARP_HDR) -#if ETHARP_SUPPORT_VLAN && defined(LWIP_HOOK_VLAN_SET) -#define SIZEOF_ETHARP_PACKET_TX (SIZEOF_ETHARP_PACKET + SIZEOF_VLAN_HDR) -#else /* ETHARP_SUPPORT_VLAN && defined(LWIP_HOOK_VLAN_SET) */ -#define SIZEOF_ETHARP_PACKET_TX SIZEOF_ETHARP_PACKET -#endif /* ETHARP_SUPPORT_VLAN && defined(LWIP_HOOK_VLAN_SET) */ - -/** 1 seconds period */ -#define ARP_TMR_INTERVAL 1000 - -/** ARP message types (opcodes) */ -#define ARP_REQUEST 1 -#define ARP_REPLY 2 - -#if ARP_QUEUEING -/** struct for queueing outgoing packets for unknown address - * defined here to be accessed by memp.h - */ -struct etharp_q_entry { - struct etharp_q_entry *next; - struct pbuf *p; -}; -#endif /* ARP_QUEUEING */ - -#define etharp_init() /* Compatibility define, no init needed. */ -void etharp_tmr(void); -s8_t etharp_find_addr(struct netif *netif, const ip4_addr_t *ipaddr, - struct eth_addr **eth_ret, const ip4_addr_t **ip_ret); -u8_t etharp_get_entry(u8_t i, ip4_addr_t **ipaddr, struct netif **netif, struct eth_addr **eth_ret); -err_t etharp_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr); -err_t etharp_query(struct netif *netif, const ip4_addr_t *ipaddr, struct pbuf *q); -err_t etharp_request(struct netif *netif, const ip4_addr_t *ipaddr); -/** For Ethernet network interfaces, we might want to send "gratuitous ARP"; - * this is an ARP packet sent by a node in order to spontaneously cause other - * nodes to update an entry in their ARP cache. - * From RFC 3220 "IP Mobility Support for IPv4" section 4.6. */ -#define etharp_gratuitous(netif) etharp_request((netif), netif_ip4_addr(netif)) -void etharp_cleanup_netif(struct netif *netif); - -#if ETHARP_SUPPORT_STATIC_ENTRIES -err_t etharp_add_static_entry(const ip4_addr_t *ipaddr, struct eth_addr *ethaddr); -err_t etharp_remove_static_entry(const ip4_addr_t *ipaddr); -#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */ - -#if LWIP_AUTOIP -err_t etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr, - const struct eth_addr *ethdst_addr, - const struct eth_addr *hwsrc_addr, const ip4_addr_t *ipsrc_addr, - const struct eth_addr *hwdst_addr, const ip4_addr_t *ipdst_addr, - const u16_t opcode); -#endif /* LWIP_AUTOIP */ - -#endif /* LWIP_IPV4 && LWIP_ARP */ - -void etharp_arp_input(struct netif *netif, struct eth_addr *ethaddr, struct pbuf *p); - -#if ETHARP_TRUST_IP_MAC -void etharp_ip_input(struct netif *netif, struct pbuf *p); -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* LWIP_ARP || LWIP_ETHERNET */ - -#endif /* LWIP_HDR_NETIF_ETHARP_H */ diff --git a/tools/sdk/include/lwip/netif/ethernet.h b/tools/sdk/include/lwip/netif/ethernet.h index 17623e4a..49649cbf 100644 --- a/tools/sdk/include/lwip/netif/ethernet.h +++ b/tools/sdk/include/lwip/netif/ethernet.h @@ -1,3 +1,9 @@ +/** + * @file + * Ethernet input function - handles INCOMING ethernet level traffic + * To be used in most low-level netif implementations + */ + /* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * Copyright (c) 2003-2004 Leon Woestenberg @@ -39,111 +45,12 @@ #include "lwip/pbuf.h" #include "lwip/netif.h" +#include "lwip/prot/ethernet.h" #ifdef __cplusplus extern "C" { #endif -#ifndef ETH_HWADDR_LEN -#ifdef ETHARP_HWADDR_LEN -#define ETH_HWADDR_LEN ETHARP_HWADDR_LEN /* compatibility mode */ -#else -#define ETH_HWADDR_LEN 6 -#endif -#endif - -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -struct eth_addr { - PACK_STRUCT_FLD_8(u8_t addr[ETH_HWADDR_LEN]); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -/** Ethernet header */ -struct eth_hdr { -#if ETH_PAD_SIZE - PACK_STRUCT_FLD_8(u8_t padding[ETH_PAD_SIZE]); -#endif - PACK_STRUCT_FLD_S(struct eth_addr dest); - PACK_STRUCT_FLD_S(struct eth_addr src); - PACK_STRUCT_FIELD(u16_t type); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define SIZEOF_ETH_HDR (14 + ETH_PAD_SIZE) - -#if ETHARP_SUPPORT_VLAN - -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/bpstruct.h" -#endif -PACK_STRUCT_BEGIN -/** VLAN header inserted between ethernet header and payload - * if 'type' in ethernet header is ETHTYPE_VLAN. - * See IEEE802.Q */ -struct eth_vlan_hdr { - PACK_STRUCT_FIELD(u16_t prio_vid); - PACK_STRUCT_FIELD(u16_t tpid); -} PACK_STRUCT_STRUCT; -PACK_STRUCT_END -#ifdef PACK_STRUCT_USE_INCLUDES -# include "arch/epstruct.h" -#endif - -#define SIZEOF_VLAN_HDR 4 -#define VLAN_ID(vlan_hdr) (htons((vlan_hdr)->prio_vid) & 0xFFF) - -#endif /* ETHARP_SUPPORT_VLAN */ - -/* A list of often ethtypes (although lwIP does not use all of them): */ -#define ETHTYPE_IP 0x0800U /* Internet protocol v4 */ -#define ETHTYPE_ARP 0x0806U /* Address resolution protocol */ -#define ETHTYPE_WOL 0x0842U /* Wake on lan */ -#define ETHTYPE_VLAN 0x8100U /* Virtual local area network */ -#define ETHTYPE_IPV6 0x86DDU /* Internet protocol v6 */ -#define ETHTYPE_PPPOEDISC 0x8863U /* PPP Over Ethernet Discovery Stage */ -#define ETHTYPE_PPPOE 0x8864U /* PPP Over Ethernet Session Stage */ -#define ETHTYPE_JUMBO 0x8870U /* Jumbo Frames */ -#define ETHTYPE_PROFINET 0x8892U /* Process field network */ -#define ETHTYPE_ETHERCAT 0x88A4U /* Ethernet for control automation technology */ -#define ETHTYPE_LLDP 0x88CCU /* Link layer discovery protocol */ -#define ETHTYPE_SERCOS 0x88CDU /* Serial real-time communication system */ -#define ETHTYPE_PTP 0x88F7U /* Precision time protocol */ -#define ETHTYPE_QINQ 0x9100U /* Q-in-Q, 802.1ad */ - -/** The 24-bit IANA IPv4-multicast OUI is 01-00-5e: */ -#define LL_IP4_MULTICAST_ADDR_0 0x01 -#define LL_IP4_MULTICAST_ADDR_1 0x00 -#define LL_IP4_MULTICAST_ADDR_2 0x5e - -/** IPv6 multicast uses this prefix */ -#define LL_IP6_MULTICAST_ADDR_0 0x33 -#define LL_IP6_MULTICAST_ADDR_1 0x33 - -/** MEMCPY-like macro to copy to/from struct eth_addr's that are local variables - * or known to be 32-bit aligned within the protocol header. */ -#ifndef ETHADDR32_COPY -#define ETHADDR32_COPY(dst, src) SMEMCPY(dst, src, ETH_HWADDR_LEN) -#endif - -/** MEMCPY-like macro to copy to/from struct eth_addr's that are no local - * variables and known to be 16-bit aligned within the protocol header. */ -#ifndef ETHADDR16_COPY -#define ETHADDR16_COPY(dst, src) SMEMCPY(dst, src, ETH_HWADDR_LEN) -#endif - #if LWIP_ARP || LWIP_ETHERNET /** Define this to 1 and define LWIP_ARP_FILTER_NETIF_FN(pbuf, netif, type) @@ -157,8 +64,7 @@ PACK_STRUCT_END #endif err_t ethernet_input(struct pbuf *p, struct netif *netif); - -#define eth_addr_cmp(addr1, addr2) (memcmp((addr1)->addr, (addr2)->addr, ETH_HWADDR_LEN) == 0) +err_t ethernet_output(struct netif* netif, struct pbuf* p, const struct eth_addr* src, const struct eth_addr* dst, u16_t eth_type); extern const struct eth_addr ethbroadcast, ethzero; diff --git a/tools/sdk/include/lwip/netif/lowpan6.h b/tools/sdk/include/lwip/netif/lowpan6.h index 21552938..4174644b 100644 --- a/tools/sdk/include/lwip/netif/lowpan6.h +++ b/tools/sdk/include/lwip/netif/lowpan6.h @@ -73,7 +73,9 @@ err_t lowpan6_if_init(struct netif *netif); /* pan_id in network byte order. */ err_t lowpan6_set_pan_id(u16_t pan_id); +#if !NO_SYS err_t tcpip_6lowpan_input(struct pbuf *p, struct netif *inp); +#endif /* !NO_SYS */ #ifdef __cplusplus } diff --git a/tools/sdk/include/lwip/netif/lowpan6_opts.h b/tools/sdk/include/lwip/netif/lowpan6_opts.h index 6a769575..fb93ea05 100644 --- a/tools/sdk/include/lwip/netif/lowpan6_opts.h +++ b/tools/sdk/include/lwip/netif/lowpan6_opts.h @@ -1,3 +1,8 @@ +/** + * @file + * 6LowPAN options list + */ + /* * Copyright (c) 2015 Inico Technologies Ltd. * All rights reserved. diff --git a/tools/sdk/include/lwip/netif/ppp/ccp.h b/tools/sdk/include/lwip/netif/ppp/ccp.h index a8eab9c0..14dd6596 100644 --- a/tools/sdk/include/lwip/netif/ppp/ccp.h +++ b/tools/sdk/include/lwip/netif/ppp/ccp.h @@ -30,7 +30,7 @@ * $Id: ccp.h,v 1.12 2004/11/04 10:02:26 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && CCP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef CCP_H diff --git a/tools/sdk/include/lwip/netif/ppp/chap-md5.h b/tools/sdk/include/lwip/netif/ppp/chap-md5.h index a05a157d..eb0269fe 100644 --- a/tools/sdk/include/lwip/netif/ppp/chap-md5.h +++ b/tools/sdk/include/lwip/netif/ppp/chap-md5.h @@ -28,7 +28,7 @@ * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && CHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ extern const struct chap_digest_type md5_digest; diff --git a/tools/sdk/include/lwip/netif/ppp/chap-new.h b/tools/sdk/include/lwip/netif/ppp/chap-new.h index 9b7c0487..64eae322 100644 --- a/tools/sdk/include/lwip/netif/ppp/chap-new.h +++ b/tools/sdk/include/lwip/netif/ppp/chap-new.h @@ -28,7 +28,7 @@ * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && CHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef CHAP_H diff --git a/tools/sdk/include/lwip/netif/ppp/chap_ms.h b/tools/sdk/include/lwip/netif/ppp/chap_ms.h index 709bb899..07952911 100644 --- a/tools/sdk/include/lwip/netif/ppp/chap_ms.h +++ b/tools/sdk/include/lwip/netif/ppp/chap_ms.h @@ -30,15 +30,15 @@ * $Id: chap_ms.h,v 1.13 2004/11/15 22:13:26 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && MSCHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ -#ifndef __CHAPMS_INCLUDE__ +#ifndef CHAPMS_INCLUDE +#define CHAPMS_INCLUDE extern const struct chap_digest_type chapms_digest; extern const struct chap_digest_type chapms2_digest; -#define __CHAPMS_INCLUDE__ -#endif /* __CHAPMS_INCLUDE__ */ +#endif /* CHAPMS_INCLUDE */ #endif /* PPP_SUPPORT && MSCHAP_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/eap.h b/tools/sdk/include/lwip/netif/ppp/eap.h index 7dfd6763..3ee9aaf8 100644 --- a/tools/sdk/include/lwip/netif/ppp/eap.h +++ b/tools/sdk/include/lwip/netif/ppp/eap.h @@ -20,7 +20,7 @@ * $Id: eap.h,v 1.2 2003/06/11 23:56:26 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && EAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef PPP_EAP_H @@ -148,12 +148,12 @@ typedef struct eap_state { /* * Timeouts. */ -#if 0 /* moved to opt.h */ +#if 0 /* moved to ppp_opts.h */ #define EAP_DEFTIMEOUT 3 /* Timeout (seconds) for rexmit */ #define EAP_DEFTRANSMITS 10 /* max # times to transmit */ #define EAP_DEFREQTIME 20 /* Time to wait for peer request */ #define EAP_DEFALLOWREQ 20 /* max # times to accept requests */ -#endif /* moved to opt.h */ +#endif /* moved to ppp_opts.h */ void eap_authwithpeer(ppp_pcb *pcb, const char *localname); void eap_authpeer(ppp_pcb *pcb, const char *localname); diff --git a/tools/sdk/include/lwip/netif/ppp/ecp.h b/tools/sdk/include/lwip/netif/ppp/ecp.h index cba6678e..5cdce29d 100644 --- a/tools/sdk/include/lwip/netif/ppp/ecp.h +++ b/tools/sdk/include/lwip/netif/ppp/ecp.h @@ -31,7 +31,7 @@ * $Id: ecp.h,v 1.2 2003/01/10 07:12:36 fcusack Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && ECP_SUPPORT /* don't build if not configured for use in lwipopts.h */ typedef struct ecp_options { diff --git a/tools/sdk/include/lwip/netif/ppp/eui64.h b/tools/sdk/include/lwip/netif/ppp/eui64.h index dffb5e41..20ac22ee 100644 --- a/tools/sdk/include/lwip/netif/ppp/eui64.h +++ b/tools/sdk/include/lwip/netif/ppp/eui64.h @@ -35,14 +35,14 @@ * $Id: eui64.h,v 1.6 2002/12/04 23:03:32 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPP_IPV6_SUPPORT /* don't build if not configured for use in lwipopts.h */ -#ifndef __EUI64_H__ -#define __EUI64_H__ +#ifndef EUI64_H +#define EUI64_H /* - * TODO: + * @todo: * * Maybe this should be done by processing struct in6_addr directly... */ @@ -84,11 +84,11 @@ typedef union #define eui64_set32(e, l) do { \ (e).e32[0] = 0; \ - (e).e32[1] = htonl(l); \ + (e).e32[1] = lwip_htonl(l); \ } while (0) #define eui64_setlo32(e, l) eui64_set32(e, l) char *eui64_ntoa(eui64_t); /* Returns ascii representation of id */ -#endif /* __EUI64_H__ */ +#endif /* EUI64_H */ #endif /* PPP_SUPPORT && PPP_IPV6_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/fsm.h b/tools/sdk/include/lwip/netif/ppp/fsm.h index fc0a4b10..b6915d3b 100644 --- a/tools/sdk/include/lwip/netif/ppp/fsm.h +++ b/tools/sdk/include/lwip/netif/ppp/fsm.h @@ -42,7 +42,7 @@ * $Id: fsm.h,v 1.10 2004/11/13 02:28:15 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef FSM_H @@ -150,12 +150,12 @@ typedef struct fsm_callbacks { /* * Timeouts. */ -#if 0 /* moved to opt.h */ +#if 0 /* moved to ppp_opts.h */ #define DEFTIMEOUT 3 /* Timeout time in seconds */ #define DEFMAXTERMREQS 2 /* Maximum Terminate-Request transmissions */ #define DEFMAXCONFREQS 10 /* Maximum Configure-Request transmissions */ #define DEFMAXNAKLOOPS 5 /* Maximum number of nak loops */ -#endif /* moved to opt.h */ +#endif /* moved to ppp_opts.h */ /* diff --git a/tools/sdk/include/lwip/netif/ppp/ipcp.h b/tools/sdk/include/lwip/netif/ppp/ipcp.h index 298f8dc6..45f46b31 100644 --- a/tools/sdk/include/lwip/netif/ppp/ipcp.h +++ b/tools/sdk/include/lwip/netif/ppp/ipcp.h @@ -42,7 +42,7 @@ * $Id: ipcp.h,v 1.14 2002/12/04 23:03:32 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPP_IPV4_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef IPCP_H diff --git a/tools/sdk/include/lwip/netif/ppp/ipv6cp.h b/tools/sdk/include/lwip/netif/ppp/ipv6cp.h index 540a7d18..07d1ae31 100644 --- a/tools/sdk/include/lwip/netif/ppp/ipv6cp.h +++ b/tools/sdk/include/lwip/netif/ppp/ipv6cp.h @@ -138,7 +138,7 @@ * $Id: ipv6cp.h,v 1.7 2002/12/04 23:03:32 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPP_IPV6_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef IPV6CP_H diff --git a/tools/sdk/include/lwip/netif/ppp/lcp.h b/tools/sdk/include/lwip/netif/ppp/lcp.h index 04970699..12e2a05f 100644 --- a/tools/sdk/include/lwip/netif/ppp/lcp.h +++ b/tools/sdk/include/lwip/netif/ppp/lcp.h @@ -42,7 +42,7 @@ * $Id: lcp.h,v 1.20 2004/11/14 22:53:42 carlsonj Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef LCP_H @@ -90,11 +90,11 @@ /* Value used as data for CI_CALLBACK option */ #define CBCP_OPT 6 /* Use callback control protocol */ -#if 0 /* moved to opt.h */ +#if 0 /* moved to ppp_opts.h */ #define DEFMRU 1500 /* Try for this */ #define MINMRU 128 /* No MRUs below this */ #define MAXMRU 16384 /* Normally limit MRU to this */ -#endif /* moved to opt.h */ +#endif /* moved to ppp_opts.h */ /* An endpoint discriminator, used with multilink. */ #define MAX_ENDP_LEN 20 /* maximum length of discriminator value */ @@ -110,7 +110,9 @@ struct epdisc { typedef struct lcp_options { unsigned int passive :1; /* Don't die if we don't get a response */ unsigned int silent :1; /* Wait for the other end to start first */ +#if 0 /* UNUSED */ unsigned int restart :1; /* Restart vs. exit after close */ +#endif /* UNUSED */ unsigned int neg_mru :1; /* Negotiate the MRU? */ unsigned int neg_asyncmap :1; /* Negotiate the async map? */ #if PAP_SUPPORT @@ -159,11 +161,11 @@ void lcp_sprotrej(ppp_pcb *pcb, u_char *p, int len); /* send protocol reject extern const struct protent lcp_protent; -#if 0 /* moved to opt.h */ +#if 0 /* moved to ppp_opts.h */ /* Default number of times we receive our magic number from the peer before deciding the link is looped-back. */ #define DEFLOOPBACKFAIL 10 -#endif /* moved to opt.h */ +#endif /* moved to ppp_opts.h */ #endif /* LCP_H */ #endif /* PPP_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/magic.h b/tools/sdk/include/lwip/netif/ppp/magic.h index 678ff724..a2a9b530 100644 --- a/tools/sdk/include/lwip/netif/ppp/magic.h +++ b/tools/sdk/include/lwip/netif/ppp/magic.h @@ -74,7 +74,7 @@ * Extracted from avos. *****************************************************************************/ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef MAGIC_H diff --git a/tools/sdk/include/lwip/netif/ppp/mppe.h b/tools/sdk/include/lwip/netif/ppp/mppe.h index 93086955..1ae8a5d9 100644 --- a/tools/sdk/include/lwip/netif/ppp/mppe.h +++ b/tools/sdk/include/lwip/netif/ppp/mppe.h @@ -33,17 +33,13 @@ * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && MPPE_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef MPPE_H #define MPPE_H -#if LWIP_INCLUDED_POLARSSL_ARC4 -#include "netif/ppp/polarssl/arc4.h" -#else -#include "polarssl/arc4.h" -#endif +#include "netif/ppp/pppcrypt.h" #define MPPE_PAD 4 /* MPPE growth per frame */ #define MPPE_MAX_KEY_LEN 16 /* largest key length (128-bit) */ @@ -63,7 +59,7 @@ * This is not nice ... the alternative is a bitfield struct though. * And unfortunately, we cannot share the same bits for the option * names above since C and H are the same bit. We could do a u_int32 - * but then we have to do a htonl() all the time and/or we still need + * but then we have to do a lwip_htonl() all the time and/or we still need * to know which octet is which. */ #define MPPE_C_BIT 0x01 /* MPPC */ @@ -152,7 +148,7 @@ static const u8_t mppe_sha1_pad2[SHA1_PAD_SIZE] = { * State for an MPPE (de)compressor. */ typedef struct ppp_mppe_state { - arc4_context arc4; + lwip_arc4_context arc4; u8_t master_key[MPPE_MAX_KEY_LEN]; u8_t session_key[MPPE_MAX_KEY_LEN]; u8_t keylen; /* key length in bytes */ diff --git a/tools/sdk/include/lwip/netif/ppp/polarssl/arc4.h b/tools/sdk/include/lwip/netif/ppp/polarssl/arc4.h index 95d9b34a..4af724cd 100644 --- a/tools/sdk/include/lwip/netif/ppp/polarssl/arc4.h +++ b/tools/sdk/include/lwip/netif/ppp/polarssl/arc4.h @@ -33,7 +33,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_INCLUDED_POLARSSL_ARC4 #ifndef LWIP_INCLUDED_POLARSSL_ARC4_H diff --git a/tools/sdk/include/lwip/netif/ppp/polarssl/des.h b/tools/sdk/include/lwip/netif/ppp/polarssl/des.h index d0858bd8..e893890e 100644 --- a/tools/sdk/include/lwip/netif/ppp/polarssl/des.h +++ b/tools/sdk/include/lwip/netif/ppp/polarssl/des.h @@ -33,7 +33,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_INCLUDED_POLARSSL_DES #ifndef LWIP_INCLUDED_POLARSSL_DES_H diff --git a/tools/sdk/include/lwip/netif/ppp/polarssl/md4.h b/tools/sdk/include/lwip/netif/ppp/polarssl/md4.h index a382f85a..57044568 100644 --- a/tools/sdk/include/lwip/netif/ppp/polarssl/md4.h +++ b/tools/sdk/include/lwip/netif/ppp/polarssl/md4.h @@ -33,7 +33,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_INCLUDED_POLARSSL_MD4 #ifndef LWIP_INCLUDED_POLARSSL_MD4_H diff --git a/tools/sdk/include/lwip/netif/ppp/polarssl/md5.h b/tools/sdk/include/lwip/netif/ppp/polarssl/md5.h index a299d98c..12440118 100644 --- a/tools/sdk/include/lwip/netif/ppp/polarssl/md5.h +++ b/tools/sdk/include/lwip/netif/ppp/polarssl/md5.h @@ -33,7 +33,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_INCLUDED_POLARSSL_MD5 #ifndef LWIP_INCLUDED_POLARSSL_MD5_H diff --git a/tools/sdk/include/lwip/netif/ppp/polarssl/sha1.h b/tools/sdk/include/lwip/netif/ppp/polarssl/sha1.h index 56d947c2..a4c53e07 100644 --- a/tools/sdk/include/lwip/netif/ppp/polarssl/sha1.h +++ b/tools/sdk/include/lwip/netif/ppp/polarssl/sha1.h @@ -33,7 +33,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_INCLUDED_POLARSSL_SHA1 #ifndef LWIP_INCLUDED_POLARSSL_SHA1_H diff --git a/tools/sdk/include/lwip/netif/ppp/ppp.h b/tools/sdk/include/lwip/netif/ppp/ppp.h index 4a502054..d9ea097e 100644 --- a/tools/sdk/include/lwip/netif/ppp/ppp.h +++ b/tools/sdk/include/lwip/netif/ppp/ppp.h @@ -31,7 +31,7 @@ * Original derived from BSD codes. *****************************************************************************/ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef PPP_H @@ -42,13 +42,12 @@ #include "lwip/mem.h" #include "lwip/netif.h" #include "lwip/sys.h" -#include "lwip/sio.h" -#include "lwip/timers.h" +#include "lwip/timeouts.h" #if PPP_IPV6_SUPPORT #include "lwip/ip6_addr.h" #endif /* PPP_IPV6_SUPPORT */ -/* Disable non-working or rarely used PPP feature, so rarely that we don't want to bloat opt.h with them */ +/* Disable non-working or rarely used PPP feature, so rarely that we don't want to bloat ppp_opts.h with them */ #ifndef PPP_OPTIONS #define PPP_OPTIONS 0 #endif @@ -111,18 +110,18 @@ * Values for phase. */ #define PPP_PHASE_DEAD 0 -#define PPP_PHASE_INITIALIZE 1 -#define PPP_PHASE_SERIALCONN 2 -#define PPP_PHASE_DORMANT 3 -#define PPP_PHASE_ESTABLISH 4 -#define PPP_PHASE_AUTHENTICATE 5 -#define PPP_PHASE_CALLBACK 6 -#define PPP_PHASE_NETWORK 7 -#define PPP_PHASE_RUNNING 8 -#define PPP_PHASE_TERMINATE 9 -#define PPP_PHASE_DISCONNECT 10 -#define PPP_PHASE_HOLDOFF 11 -#define PPP_PHASE_MASTER 12 +#define PPP_PHASE_MASTER 1 +#define PPP_PHASE_HOLDOFF 2 +#define PPP_PHASE_INITIALIZE 3 +#define PPP_PHASE_SERIALCONN 4 +#define PPP_PHASE_DORMANT 5 +#define PPP_PHASE_ESTABLISH 6 +#define PPP_PHASE_AUTHENTICATE 7 +#define PPP_PHASE_CALLBACK 8 +#define PPP_PHASE_NETWORK 9 +#define PPP_PHASE_RUNNING 10 +#define PPP_PHASE_TERMINATE 11 +#define PPP_PHASE_DISCONNECT 12 /* Error codes. */ #define PPPERR_NONE 0 /* No error. */ @@ -311,7 +310,6 @@ struct ppp_addrs { * PPP interface control block. */ struct ppp_pcb_s { - /* -- below are data that will NOT be cleared between two sessions */ ppp_settings settings; const struct link_callbacks *link_cb; void *link_ctx_cb; @@ -321,18 +319,12 @@ struct ppp_pcb_s { #endif /* PPP_NOTIFY_PHASE */ void *ctx_cb; /* Callbacks optional pointer */ struct netif *netif; /* PPP interface */ - - /* -- below are data that will be cleared between two sessions */ - - /* - * phase must be the first member of cleared members, because it is used to know - * which part must not be cleared. - */ u8_t phase; /* where the link is at */ u8_t err_code; /* Code indicating why interface is down. */ /* flags */ #if PPP_IPV4_SUPPORT + unsigned int ask_for_local :1; /* request our address from peer */ unsigned int ipcp_is_open :1; /* haven't called np_finished() */ unsigned int ipcp_is_up :1; /* have called ipcp_up() */ unsigned int if4_up :1; /* True when the IPv4 interface is up. */ @@ -432,7 +424,13 @@ struct ppp_pcb_s { ************************/ /* - * Set auth helper, optional, you can either fill ppp_pcb->settings. + * WARNING: For multi-threads environment, all ppp_set_* functions most + * only be called while the PPP is in the dead phase (i.e. disconnected). + */ + +#if PPP_AUTH_SUPPORT +/* + * Set PPP authentication. * * Warning: Using PPPAUTHTYPE_ANY might have security consequences. * RFC 1994 says: @@ -452,6 +450,7 @@ struct ppp_pcb_s { * circumstances, then distinct user names SHOULD be employed, each of * which identifies exactly one authentication method. * + * Default is none auth type, unset (NULL) user and passwd. */ #define PPPAUTHTYPE_NONE 0x00 #define PPPAUTHTYPE_PAP 0x01 @@ -462,6 +461,127 @@ struct ppp_pcb_s { #define PPPAUTHTYPE_ANY 0xff void ppp_set_auth(ppp_pcb *pcb, u8_t authtype, const char *user, const char *passwd); +/* + * If set, peer is required to authenticate. This is mostly necessary for PPP server support. + * + * Default is false. + */ +#define ppp_set_auth_required(ppp, boolval) (ppp->settings.auth_required = boolval) +#endif /* PPP_AUTH_SUPPORT */ + +#if PPP_IPV4_SUPPORT +/* + * Set PPP interface "our" and "his" IPv4 addresses. This is mostly necessary for PPP server + * support but it can also be used on a PPP link where each side choose its own IP address. + * + * Default is unset (0.0.0.0). + */ +#define ppp_set_ipcp_ouraddr(ppp, addr) do { ppp->ipcp_wantoptions.ouraddr = ip4_addr_get_u32(addr); \ + ppp->ask_for_local = ppp->ipcp_wantoptions.ouraddr != 0; } while(0) +#define ppp_set_ipcp_hisaddr(ppp, addr) (ppp->ipcp_wantoptions.hisaddr = ip4_addr_get_u32(addr)) +#if LWIP_DNS +/* + * Set DNS server addresses that are sent if the peer asks for them. This is mostly necessary + * for PPP server support. + * + * Default is unset (0.0.0.0). + */ +#define ppp_set_ipcp_dnsaddr(ppp, index, addr) (ppp->ipcp_allowoptions.dnsaddr[index] = ip4_addr_get_u32(addr)) + +/* + * If set, we ask the peer for up to 2 DNS server addresses. Received DNS server addresses are + * registered using the dns_setserver() function. + * + * Default is false. + */ +#define ppp_set_usepeerdns(ppp, boolval) (ppp->settings.usepeerdns = boolval) +#endif /* LWIP_DNS */ +#endif /* PPP_IPV4_SUPPORT */ + +#if MPPE_SUPPORT +/* Disable MPPE (Microsoft Point to Point Encryption). This parameter is exclusive. */ +#define PPP_MPPE_DISABLE 0x00 +/* Require the use of MPPE (Microsoft Point to Point Encryption). */ +#define PPP_MPPE_ENABLE 0x01 +/* Allow MPPE to use stateful mode. Stateless mode is still attempted first. */ +#define PPP_MPPE_ALLOW_STATEFUL 0x02 +/* Refuse the use of MPPE with 40-bit encryption. Conflict with PPP_MPPE_REFUSE_128. */ +#define PPP_MPPE_REFUSE_40 0x04 +/* Refuse the use of MPPE with 128-bit encryption. Conflict with PPP_MPPE_REFUSE_40. */ +#define PPP_MPPE_REFUSE_128 0x08 +/* + * Set MPPE configuration + * + * Default is disabled. + */ +void ppp_set_mppe(ppp_pcb *pcb, u8_t flags); +#endif /* MPPE_SUPPORT */ + +/* + * Wait for up to intval milliseconds for a valid PPP packet from the peer. + * At the end of this time, or when a valid PPP packet is received from the + * peer, we commence negotiation by sending our first LCP packet. + * + * Default is 0. + */ +#define ppp_set_listen_time(ppp, intval) (ppp->settings.listen_time = intval) + +/* + * If set, we will attempt to initiate a connection but if no reply is received from + * the peer, we will then just wait passively for a valid LCP packet from the peer. + * + * Default is false. + */ +#define ppp_set_passive(ppp, boolval) (ppp->lcp_wantoptions.passive = boolval) + +/* + * If set, we will not transmit LCP packets to initiate a connection until a valid + * LCP packet is received from the peer. This is what we usually call the server mode. + * + * Default is false. + */ +#define ppp_set_silent(ppp, boolval) (ppp->lcp_wantoptions.silent = boolval) + +/* + * If set, enable protocol field compression negotiation in both the receive and + * the transmit direction. + * + * Default is true. + */ +#define ppp_set_neg_pcomp(ppp, boolval) (ppp->lcp_wantoptions.neg_pcompression = \ + ppp->lcp_allowoptions.neg_pcompression = boolval) + +/* + * If set, enable Address/Control compression in both the receive and the transmit + * direction. + * + * Default is true. + */ +#define ppp_set_neg_accomp(ppp, boolval) (ppp->lcp_wantoptions.neg_accompression = \ + ppp->lcp_allowoptions.neg_accompression = boolval) + +/* + * If set, enable asyncmap negotiation. Otherwise forcing all control characters to + * be escaped for both the transmit and the receive direction. + * + * Default is true. + */ +#define ppp_set_neg_asyncmap(ppp, boolval) (ppp->lcp_wantoptions.neg_asyncmap = \ + ppp->lcp_allowoptions.neg_asyncmap = boolval) + +/* + * This option sets the Async-Control-Character-Map (ACCM) for this end of the link. + * The ACCM is a set of 32 bits, one for each of the ASCII control characters with + * values from 0 to 31, where a 1 bit indicates that the corresponding control + * character should not be used in PPP packets sent to this system. The map is + * an unsigned 32 bits integer where the least significant bit (00000001) represents + * character 0 and the most significant bit (80000000) represents character 31. + * We will then ask the peer to send these characters as a 2-byte escape sequence. + * + * Default is 0. + */ +#define ppp_set_asyncmap(ppp, intval) (ppp->lcp_wantoptions.asyncmap = intval) + /* * Set a PPP interface as the default network interface * (used to output all packets for which no specific route is found). @@ -498,13 +618,10 @@ err_t ppp_connect(ppp_pcb *pcb, u16_t holdoff); * * This can only be called if PPP is in the dead phase. * - * Local and remote interface IP addresses, as well as DNS are - * provided through a previously filled struct ppp_addrs. - * * If this port connects to a modem, the modem connection must be * established before calling this. */ -err_t ppp_listen(ppp_pcb *pcb, struct ppp_addrs *addrs); +err_t ppp_listen(ppp_pcb *pcb); #endif /* PPP_SERVER */ /* diff --git a/tools/sdk/include/lwip/netif/ppp/ppp_impl.h b/tools/sdk/include/lwip/netif/ppp/ppp_impl.h index 324f4b05..1d4c7742 100644 --- a/tools/sdk/include/lwip/netif/ppp/ppp_impl.h +++ b/tools/sdk/include/lwip/netif/ppp/ppp_impl.h @@ -33,7 +33,7 @@ #ifndef LWIP_HDR_PPP_IMPL_H #define LWIP_HDR_PPP_IMPL_H -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ @@ -48,7 +48,7 @@ #include "lwip/netif.h" #include "lwip/def.h" -#include "lwip/timers.h" +#include "lwip/timeouts.h" #include "ppp.h" #include "pppdebug.h" @@ -138,10 +138,10 @@ */ struct link_callbacks { /* Start a connection (e.g. Initiate discovery phase) */ - err_t (*connect) (ppp_pcb *pcb, void *ctx); + void (*connect) (ppp_pcb *pcb, void *ctx); #if PPP_SERVER /* Listen for an incoming connection (Passive mode) */ - err_t (*listen) (ppp_pcb *pcb, void *ctx, struct ppp_addrs *addrs); + void (*listen) (ppp_pcb *pcb, void *ctx); #endif /* PPP_SERVER */ /* End a connection (i.e. initiate disconnect phase) */ void (*disconnect) (ppp_pcb *pcb, void *ctx); @@ -378,6 +378,7 @@ struct pppd_stats { * PPP private functions */ + /* * Functions called from lwIP core. */ @@ -385,7 +386,6 @@ struct pppd_stats { /* initialize the PPP subsystem */ int ppp_init(void); - /* * Functions called from PPP link protocols. */ @@ -394,9 +394,6 @@ int ppp_init(void); ppp_pcb *ppp_new(struct netif *pppif, const struct link_callbacks *callbacks, void *link_ctx_cb, ppp_link_status_cb_fn link_status_cb, void *ctx_cb); -/* Set a PPP PCB to its initial state */ -void ppp_clear(ppp_pcb *pcb); - /* Initiate LCP open request */ void ppp_start(ppp_pcb *pcb); @@ -623,7 +620,7 @@ void ppp_warn(const char *fmt, ...); /* log a warning message */ void ppp_error(const char *fmt, ...); /* log an error message */ void ppp_fatal(const char *fmt, ...); /* log an error message and die(1) */ #if PRINTPKT_SUPPORT -void ppp_dump_packet(const char *tag, unsigned char *p, int len); +void ppp_dump_packet(ppp_pcb *pcb, const char *tag, unsigned char *p, int len); /* dump packet to debug log if interesting */ #endif /* PRINTPKT_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/ppp_opts.h b/tools/sdk/include/lwip/netif/ppp/ppp_opts.h new file mode 100644 index 00000000..fa79c090 --- /dev/null +++ b/tools/sdk/include/lwip/netif/ppp/ppp_opts.h @@ -0,0 +1,593 @@ +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#ifndef LWIP_PPP_OPTS_H +#define LWIP_PPP_OPTS_H + +#include "lwip/opt.h" + +/** + * PPP_SUPPORT==1: Enable PPP. + */ +#ifndef PPP_SUPPORT +#define PPP_SUPPORT 0 +#endif + +/** + * PPPOE_SUPPORT==1: Enable PPP Over Ethernet + */ +#ifndef PPPOE_SUPPORT +#define PPPOE_SUPPORT 0 +#endif + +/** + * PPPOL2TP_SUPPORT==1: Enable PPP Over L2TP + */ +#ifndef PPPOL2TP_SUPPORT +#define PPPOL2TP_SUPPORT 0 +#endif + +/** + * PPPOL2TP_AUTH_SUPPORT==1: Enable PPP Over L2TP Auth (enable MD5 support) + */ +#ifndef PPPOL2TP_AUTH_SUPPORT +#define PPPOL2TP_AUTH_SUPPORT PPPOL2TP_SUPPORT +#endif + +/** + * PPPOS_SUPPORT==1: Enable PPP Over Serial + */ +#ifndef PPPOS_SUPPORT +#define PPPOS_SUPPORT PPP_SUPPORT +#endif + +/** + * LWIP_PPP_API==1: Enable PPP API (in pppapi.c) + */ +#ifndef LWIP_PPP_API +#define LWIP_PPP_API (PPP_SUPPORT && (NO_SYS == 0)) +#endif + +/** + * MEMP_NUM_PPP_PCB: the number of simultaneously active PPP + * connections (requires the PPP_SUPPORT option) + */ +#ifndef MEMP_NUM_PPP_PCB +#define MEMP_NUM_PPP_PCB 1 +#endif + +#if PPP_SUPPORT + +/** + * MEMP_NUM_PPPOS_INTERFACES: the number of concurrently active PPPoS + * interfaces (only used with PPPOS_SUPPORT==1) + */ +#ifndef MEMP_NUM_PPPOS_INTERFACES +#define MEMP_NUM_PPPOS_INTERFACES MEMP_NUM_PPP_PCB +#endif + +/** + * MEMP_NUM_PPPOE_INTERFACES: the number of concurrently active PPPoE + * interfaces (only used with PPPOE_SUPPORT==1) + */ +#ifndef MEMP_NUM_PPPOE_INTERFACES +#define MEMP_NUM_PPPOE_INTERFACES 1 +#endif + +/** + * MEMP_NUM_PPPOL2TP_INTERFACES: the number of concurrently active PPPoL2TP + * interfaces (only used with PPPOL2TP_SUPPORT==1) + */ +#ifndef MEMP_NUM_PPPOL2TP_INTERFACES +#define MEMP_NUM_PPPOL2TP_INTERFACES 1 +#endif + +/** + * MEMP_NUM_PPP_API_MSG: Number of concurrent PPP API messages (in pppapi.c) + */ +#ifndef MEMP_NUM_PPP_API_MSG +#define MEMP_NUM_PPP_API_MSG 5 +#endif + +/** + * PPP_DEBUG: Enable debugging for PPP. + */ +#ifndef PPP_DEBUG +#define PPP_DEBUG LWIP_DBG_OFF +#endif + +/** + * PPP_INPROC_IRQ_SAFE==1 call pppos_input() using tcpip_callback(). + * + * Please read the "PPPoS input path" chapter in the PPP documentation about this option. + */ +#ifndef PPP_INPROC_IRQ_SAFE +#define PPP_INPROC_IRQ_SAFE 0 +#endif + +/** + * PRINTPKT_SUPPORT==1: Enable PPP print packet support + * + * Mandatory for debugging, it displays exchanged packet content in debug trace. + */ +#ifndef PRINTPKT_SUPPORT +#define PRINTPKT_SUPPORT 0 +#endif + +/** + * PPP_IPV4_SUPPORT==1: Enable PPP IPv4 support + */ +#ifndef PPP_IPV4_SUPPORT +#define PPP_IPV4_SUPPORT (LWIP_IPV4) +#endif + +/** + * PPP_IPV6_SUPPORT==1: Enable PPP IPv6 support + */ +#ifndef PPP_IPV6_SUPPORT +#define PPP_IPV6_SUPPORT (LWIP_IPV6) +#endif + +/** + * PPP_NOTIFY_PHASE==1: Support PPP notify phase support + * + * PPP notify phase support allows you to set a callback which is + * called on change of the internal PPP state machine. + * + * This can be used for example to set a LED pattern depending on the + * current phase of the PPP session. + */ +#ifndef PPP_NOTIFY_PHASE +#define PPP_NOTIFY_PHASE 0 +#endif + +/** + * pbuf_type PPP is using for LCP, PAP, CHAP, EAP, CCP, IPCP and IP6CP packets. + * + * Memory allocated must be single buffered for PPP to works, it requires pbuf + * that are not going to be chained when allocated. This requires setting + * PBUF_POOL_BUFSIZE to at least 512 bytes, which is quite huge for small systems. + * + * Setting PPP_USE_PBUF_RAM to 1 makes PPP use memory from heap where continuous + * buffers are required, allowing you to use a smaller PBUF_POOL_BUFSIZE. + */ +#ifndef PPP_USE_PBUF_RAM +#define PPP_USE_PBUF_RAM 0 +#endif + +/** + * PPP_FCS_TABLE: Keep a 256*2 byte table to speed up FCS calculation for PPPoS + */ +#ifndef PPP_FCS_TABLE +#define PPP_FCS_TABLE 1 +#endif + +/** + * PAP_SUPPORT==1: Support PAP. + */ +#ifndef PAP_SUPPORT +#define PAP_SUPPORT 0 +#endif + +/** + * CHAP_SUPPORT==1: Support CHAP. + */ +#ifndef CHAP_SUPPORT +#define CHAP_SUPPORT 0 +#endif + +/** + * MSCHAP_SUPPORT==1: Support MSCHAP. + */ +#ifndef MSCHAP_SUPPORT +#define MSCHAP_SUPPORT 0 +#endif +#if MSCHAP_SUPPORT +/* MSCHAP requires CHAP support */ +#undef CHAP_SUPPORT +#define CHAP_SUPPORT 1 +#endif /* MSCHAP_SUPPORT */ + +/** + * EAP_SUPPORT==1: Support EAP. + */ +#ifndef EAP_SUPPORT +#define EAP_SUPPORT 0 +#endif + +/** + * CCP_SUPPORT==1: Support CCP. + */ +#ifndef CCP_SUPPORT +#define CCP_SUPPORT 0 +#endif + +/** + * MPPE_SUPPORT==1: Support MPPE. + */ +#ifndef MPPE_SUPPORT +#define MPPE_SUPPORT 0 +#endif +#if MPPE_SUPPORT +/* MPPE requires CCP support */ +#undef CCP_SUPPORT +#define CCP_SUPPORT 1 +/* MPPE requires MSCHAP support */ +#undef MSCHAP_SUPPORT +#define MSCHAP_SUPPORT 1 +/* MSCHAP requires CHAP support */ +#undef CHAP_SUPPORT +#define CHAP_SUPPORT 1 +#endif /* MPPE_SUPPORT */ + +/** + * CBCP_SUPPORT==1: Support CBCP. CURRENTLY NOT SUPPORTED! DO NOT SET! + */ +#ifndef CBCP_SUPPORT +#define CBCP_SUPPORT 0 +#endif + +/** + * ECP_SUPPORT==1: Support ECP. CURRENTLY NOT SUPPORTED! DO NOT SET! + */ +#ifndef ECP_SUPPORT +#define ECP_SUPPORT 0 +#endif + +/** + * DEMAND_SUPPORT==1: Support dial on demand. CURRENTLY NOT SUPPORTED! DO NOT SET! + */ +#ifndef DEMAND_SUPPORT +#define DEMAND_SUPPORT 0 +#endif + +/** + * LQR_SUPPORT==1: Support Link Quality Report. Do nothing except exchanging some LCP packets. + */ +#ifndef LQR_SUPPORT +#define LQR_SUPPORT 0 +#endif + +/** + * PPP_SERVER==1: Enable PPP server support (waiting for incoming PPP session). + * + * Currently only supported for PPPoS. + */ +#ifndef PPP_SERVER +#define PPP_SERVER 0 +#endif + +#if PPP_SERVER +/* + * PPP_OUR_NAME: Our name for authentication purposes + */ +#ifndef PPP_OUR_NAME +#define PPP_OUR_NAME "lwIP" +#endif +#endif /* PPP_SERVER */ + +/** + * VJ_SUPPORT==1: Support VJ header compression. + */ +#ifndef VJ_SUPPORT +#define VJ_SUPPORT 1 +#endif +/* VJ compression is only supported for TCP over IPv4 over PPPoS. */ +#if !PPPOS_SUPPORT || !PPP_IPV4_SUPPORT || !LWIP_TCP +#undef VJ_SUPPORT +#define VJ_SUPPORT 0 +#endif /* !PPPOS_SUPPORT */ + +/** + * PPP_MD5_RANDM==1: Use MD5 for better randomness. + * Enabled by default if CHAP, EAP, or L2TP AUTH support is enabled. + */ +#ifndef PPP_MD5_RANDM +#define PPP_MD5_RANDM (CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT) +#endif + +/** + * PolarSSL embedded library + * + * + * lwIP contains some files fetched from the latest BSD release of + * the PolarSSL project (PolarSSL 0.10.1-bsd) for ciphers and encryption + * methods we need for lwIP PPP support. + * + * The PolarSSL files were cleaned to contain only the necessary struct + * fields and functions needed for lwIP. + * + * The PolarSSL API was not changed at all, so if you are already using + * PolarSSL you can choose to skip the compilation of the included PolarSSL + * library into lwIP. + * + * If you are not using the embedded copy you must include external + * libraries into your arch/cc.h port file. + * + * Beware of the stack requirements which can be a lot larger if you are not + * using our cleaned PolarSSL library. + */ + +/** + * LWIP_USE_EXTERNAL_POLARSSL: Use external PolarSSL library + */ +#ifndef LWIP_USE_EXTERNAL_POLARSSL +#define LWIP_USE_EXTERNAL_POLARSSL 0 +#endif + +/** + * LWIP_USE_EXTERNAL_MBEDTLS: Use external mbed TLS library + */ +#ifndef LWIP_USE_EXTERNAL_MBEDTLS +#define LWIP_USE_EXTERNAL_MBEDTLS 0 +#endif + +/* + * PPP Timeouts + */ + +/** + * FSM_DEFTIMEOUT: Timeout time in seconds + */ +#ifndef FSM_DEFTIMEOUT +#define FSM_DEFTIMEOUT 6 +#endif + +/** + * FSM_DEFMAXTERMREQS: Maximum Terminate-Request transmissions + */ +#ifndef FSM_DEFMAXTERMREQS +#define FSM_DEFMAXTERMREQS 2 +#endif + +/** + * FSM_DEFMAXCONFREQS: Maximum Configure-Request transmissions + */ +#ifndef FSM_DEFMAXCONFREQS +#define FSM_DEFMAXCONFREQS 10 +#endif + +/** + * FSM_DEFMAXNAKLOOPS: Maximum number of nak loops + */ +#ifndef FSM_DEFMAXNAKLOOPS +#define FSM_DEFMAXNAKLOOPS 5 +#endif + +/** + * UPAP_DEFTIMEOUT: Timeout (seconds) for retransmitting req + */ +#ifndef UPAP_DEFTIMEOUT +#define UPAP_DEFTIMEOUT 6 +#endif + +/** + * UPAP_DEFTRANSMITS: Maximum number of auth-reqs to send + */ +#ifndef UPAP_DEFTRANSMITS +#define UPAP_DEFTRANSMITS 10 +#endif + +#if PPP_SERVER +/** + * UPAP_DEFREQTIME: Time to wait for auth-req from peer + */ +#ifndef UPAP_DEFREQTIME +#define UPAP_DEFREQTIME 30 +#endif +#endif /* PPP_SERVER */ + +/** + * CHAP_DEFTIMEOUT: Timeout (seconds) for retransmitting req + */ +#ifndef CHAP_DEFTIMEOUT +#define CHAP_DEFTIMEOUT 6 +#endif + +/** + * CHAP_DEFTRANSMITS: max # times to send challenge + */ +#ifndef CHAP_DEFTRANSMITS +#define CHAP_DEFTRANSMITS 10 +#endif + +#if PPP_SERVER +/** + * CHAP_DEFRECHALLENGETIME: If this option is > 0, rechallenge the peer every n seconds + */ +#ifndef CHAP_DEFRECHALLENGETIME +#define CHAP_DEFRECHALLENGETIME 0 +#endif +#endif /* PPP_SERVER */ + +/** + * EAP_DEFREQTIME: Time to wait for peer request + */ +#ifndef EAP_DEFREQTIME +#define EAP_DEFREQTIME 6 +#endif + +/** + * EAP_DEFALLOWREQ: max # times to accept requests + */ +#ifndef EAP_DEFALLOWREQ +#define EAP_DEFALLOWREQ 10 +#endif + +#if PPP_SERVER +/** + * EAP_DEFTIMEOUT: Timeout (seconds) for rexmit + */ +#ifndef EAP_DEFTIMEOUT +#define EAP_DEFTIMEOUT 6 +#endif + +/** + * EAP_DEFTRANSMITS: max # times to transmit + */ +#ifndef EAP_DEFTRANSMITS +#define EAP_DEFTRANSMITS 10 +#endif +#endif /* PPP_SERVER */ + +/** + * LCP_DEFLOOPBACKFAIL: Default number of times we receive our magic number from the peer + * before deciding the link is looped-back. + */ +#ifndef LCP_DEFLOOPBACKFAIL +#define LCP_DEFLOOPBACKFAIL 10 +#endif + +/** + * LCP_ECHOINTERVAL: Interval in seconds between keepalive echo requests, 0 to disable. + */ +#ifndef LCP_ECHOINTERVAL +#define LCP_ECHOINTERVAL 0 +#endif + +/** + * LCP_MAXECHOFAILS: Number of unanswered echo requests before failure. + */ +#ifndef LCP_MAXECHOFAILS +#define LCP_MAXECHOFAILS 3 +#endif + +/** + * PPP_MAXIDLEFLAG: Max Xmit idle time (in ms) before resend flag char. + */ +#ifndef PPP_MAXIDLEFLAG +#define PPP_MAXIDLEFLAG 100 +#endif + +/** + * PPP Packet sizes + */ + +/** + * PPP_MRU: Default MRU + */ +#ifndef PPP_MRU +#define PPP_MRU 1500 +#endif + +/** + * PPP_DEFMRU: Default MRU to try + */ +#ifndef PPP_DEFMRU +#define PPP_DEFMRU 1500 +#endif + +/** + * PPP_MAXMRU: Normally limit MRU to this (pppd default = 16384) + */ +#ifndef PPP_MAXMRU +#define PPP_MAXMRU 1500 +#endif + +/** + * PPP_MINMRU: No MRUs below this + */ +#ifndef PPP_MINMRU +#define PPP_MINMRU 128 +#endif + +/** + * PPPOL2TP_DEFMRU: Default MTU and MRU for L2TP + * Default = 1500 - PPPoE(6) - PPP Protocol(2) - IPv4 header(20) - UDP Header(8) + * - L2TP Header(6) - HDLC Header(2) - PPP Protocol(2) - MPPE Header(2) - PPP Protocol(2) + */ +#if PPPOL2TP_SUPPORT +#ifndef PPPOL2TP_DEFMRU +#define PPPOL2TP_DEFMRU 1450 +#endif +#endif /* PPPOL2TP_SUPPORT */ + +/** + * MAXNAMELEN: max length of hostname or name for auth + */ +#ifndef MAXNAMELEN +#define MAXNAMELEN 256 +#endif + +/** + * MAXSECRETLEN: max length of password or secret + */ +#ifndef MAXSECRETLEN +#define MAXSECRETLEN 256 +#endif + +/* ------------------------------------------------------------------------- */ + +/* + * Build triggers for embedded PolarSSL + */ +#if !LWIP_USE_EXTERNAL_POLARSSL && !LWIP_USE_EXTERNAL_MBEDTLS + +/* CHAP, EAP, L2TP AUTH and MD5 Random require MD5 support */ +#if CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM +#define LWIP_INCLUDED_POLARSSL_MD5 1 +#endif /* CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM */ + +#if MSCHAP_SUPPORT + +/* MSCHAP require MD4 support */ +#define LWIP_INCLUDED_POLARSSL_MD4 1 +/* MSCHAP require SHA1 support */ +#define LWIP_INCLUDED_POLARSSL_SHA1 1 +/* MSCHAP require DES support */ +#define LWIP_INCLUDED_POLARSSL_DES 1 + +/* MS-CHAP support is required for MPPE */ +#if MPPE_SUPPORT +/* MPPE require ARC4 support */ +#define LWIP_INCLUDED_POLARSSL_ARC4 1 +#endif /* MPPE_SUPPORT */ + +#endif /* MSCHAP_SUPPORT */ + +#endif /* !LWIP_USE_EXTERNAL_POLARSSL && !LWIP_USE_EXTERNAL_MBEDTLS */ + +/* Default value if unset */ +#ifndef LWIP_INCLUDED_POLARSSL_MD4 +#define LWIP_INCLUDED_POLARSSL_MD4 0 +#endif /* LWIP_INCLUDED_POLARSSL_MD4 */ +#ifndef LWIP_INCLUDED_POLARSSL_MD5 +#define LWIP_INCLUDED_POLARSSL_MD5 0 +#endif /* LWIP_INCLUDED_POLARSSL_MD5 */ +#ifndef LWIP_INCLUDED_POLARSSL_SHA1 +#define LWIP_INCLUDED_POLARSSL_SHA1 0 +#endif /* LWIP_INCLUDED_POLARSSL_SHA1 */ +#ifndef LWIP_INCLUDED_POLARSSL_DES +#define LWIP_INCLUDED_POLARSSL_DES 0 +#endif /* LWIP_INCLUDED_POLARSSL_DES */ +#ifndef LWIP_INCLUDED_POLARSSL_ARC4 +#define LWIP_INCLUDED_POLARSSL_ARC4 0 +#endif /* LWIP_INCLUDED_POLARSSL_ARC4 */ + +#endif /* PPP_SUPPORT */ + +#endif /* LWIP_PPP_OPTS_H */ diff --git a/tools/sdk/include/lwip/lwip/pppapi.h b/tools/sdk/include/lwip/netif/ppp/pppapi.h similarity index 90% rename from tools/sdk/include/lwip/lwip/pppapi.h rename to tools/sdk/include/lwip/netif/ppp/pppapi.h index 3ddf3daf..9bda2a8c 100644 --- a/tools/sdk/include/lwip/lwip/pppapi.h +++ b/tools/sdk/include/lwip/netif/ppp/pppapi.h @@ -25,10 +25,10 @@ * */ -#ifndef __LWIP_PPPAPI_H__ -#define __LWIP_PPPAPI_H__ +#ifndef LWIP_PPPAPI_H +#define LWIP_PPPAPI_H -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if LWIP_PPP_API /* don't build if not configured for use in lwipopts.h */ @@ -47,11 +47,13 @@ extern "C" { struct pppapi_msg_msg { ppp_pcb *ppp; union { +#if ESP_LWIP struct { u8_t authtype; const char *user; const char *passwd; } setauth; +#endif #if PPP_NOTIFY_PHASE struct { ppp_notify_phase_cb_fn notify_phase_cb; @@ -79,7 +81,7 @@ struct pppapi_msg_msg { struct { struct netif *pppif; struct netif *netif; - ip_addr_t *ipaddr; + API_MSG_M_DEF_C(ip_addr_t, ipaddr); u16_t port; #if PPPOL2TP_AUTH_SUPPORT const u8_t *secret; @@ -92,11 +94,6 @@ struct pppapi_msg_msg { struct { u16_t holdoff; } connect; -#if PPP_SERVER - struct { - struct ppp_addrs *addrs; - } listen; -#endif /* PPP_SERVER */ struct { u8_t nocarrier; } close; @@ -108,15 +105,17 @@ struct pppapi_msg_msg { }; struct pppapi_msg { - struct tcpip_api_call call; + struct tcpip_api_call_data call; struct pppapi_msg_msg msg; }; /* API for application */ -void pppapi_set_default(ppp_pcb *pcb); +err_t pppapi_set_default(ppp_pcb *pcb); +#if ESP_LWIP void pppapi_set_auth(ppp_pcb *pcb, u8_t authtype, const char *user, const char *passwd); +#endif #if PPP_NOTIFY_PHASE -void pppapi_set_notify_phase_callback(ppp_pcb *pcb, ppp_notify_phase_cb_fn notify_phase_cb); +err_t pppapi_set_notify_phase_callback(ppp_pcb *pcb, ppp_notify_phase_cb_fn notify_phase_cb); #endif /* PPP_NOTIFY_PHASE */ #if PPPOS_SUPPORT ppp_pcb *pppapi_pppos_create(struct netif *pppif, pppos_output_cb_fn output_cb, ppp_link_status_cb_fn link_status_cb, void *ctx_cb); @@ -133,7 +132,7 @@ ppp_pcb *pppapi_pppol2tp_create(struct netif *pppif, struct netif *netif, ip_add #endif /* PPPOL2TP_SUPPORT */ err_t pppapi_connect(ppp_pcb *pcb, u16_t holdoff); #if PPP_SERVER -err_t pppapi_listen(ppp_pcb *pcb, struct ppp_addrs *addrs); +err_t pppapi_listen(ppp_pcb *pcb); #endif /* PPP_SERVER */ err_t pppapi_close(ppp_pcb *pcb, u8_t nocarrier); err_t pppapi_free(ppp_pcb *pcb); @@ -145,4 +144,4 @@ err_t pppapi_ioctl(ppp_pcb *pcb, u8_t cmd, void *arg); #endif /* LWIP_PPP_API */ -#endif /* __LWIP_PPPAPI_H__ */ +#endif /* LWIP_PPPAPI_H */ diff --git a/tools/sdk/include/lwip/netif/ppp/pppcrypt.h b/tools/sdk/include/lwip/netif/ppp/pppcrypt.h index ef2e87de..a7b2099f 100644 --- a/tools/sdk/include/lwip/netif/ppp/pppcrypt.h +++ b/tools/sdk/include/lwip/netif/ppp/pppcrypt.h @@ -30,14 +30,107 @@ * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include "lwip/opt.h" -#if PPP_SUPPORT && MSCHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ +#include "netif/ppp/ppp_opts.h" +#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ + +/* This header file is included in all PPP modules needing hashes and/or ciphers */ #ifndef PPPCRYPT_H #define PPPCRYPT_H +/* + * If included PolarSSL copy is not used, user is expected to include + * external libraries in arch/cc.h (which is included by lwip/arch.h). + */ +#include "lwip/arch.h" + +/* + * Map hashes and ciphers functions to PolarSSL + */ +#if !LWIP_USE_EXTERNAL_MBEDTLS + +#include "netif/ppp/polarssl/md4.h" +#define lwip_md4_context md4_context +#define lwip_md4_init(context) +#define lwip_md4_starts md4_starts +#define lwip_md4_update md4_update +#define lwip_md4_finish md4_finish +#define lwip_md4_free(context) + +#include "netif/ppp/polarssl/md5.h" +#define lwip_md5_context md5_context +#define lwip_md5_init(context) +#define lwip_md5_starts md5_starts +#define lwip_md5_update md5_update +#define lwip_md5_finish md5_finish +#define lwip_md5_free(context) + +#include "netif/ppp/polarssl/sha1.h" +#define lwip_sha1_context sha1_context +#define lwip_sha1_init(context) +#define lwip_sha1_starts sha1_starts +#define lwip_sha1_update sha1_update +#define lwip_sha1_finish sha1_finish +#define lwip_sha1_free(context) + +#include "netif/ppp/polarssl/des.h" +#define lwip_des_context des_context +#define lwip_des_init(context) +#define lwip_des_setkey_enc des_setkey_enc +#define lwip_des_crypt_ecb des_crypt_ecb +#define lwip_des_free(context) + +#include "netif/ppp/polarssl/arc4.h" +#define lwip_arc4_context arc4_context +#define lwip_arc4_init(context) +#define lwip_arc4_setup arc4_setup +#define lwip_arc4_crypt arc4_crypt +#define lwip_arc4_free(context) + +#endif /* !LWIP_USE_EXTERNAL_MBEDTLS */ + +/* + * Map hashes and ciphers functions to mbed TLS + */ +#if LWIP_USE_EXTERNAL_MBEDTLS + +#define lwip_md4_context mbedtls_md4_context +#define lwip_md4_init mbedtls_md4_init +#define lwip_md4_starts mbedtls_md4_starts +#define lwip_md4_update mbedtls_md4_update +#define lwip_md4_finish mbedtls_md4_finish +#define lwip_md4_free mbedtls_md4_free + +#define lwip_md5_context mbedtls_md5_context +#define lwip_md5_init mbedtls_md5_init +#define lwip_md5_starts mbedtls_md5_starts +#define lwip_md5_update mbedtls_md5_update +#define lwip_md5_finish mbedtls_md5_finish +#define lwip_md5_free mbedtls_md5_free + +#define lwip_sha1_context mbedtls_sha1_context +#define lwip_sha1_init mbedtls_sha1_init +#define lwip_sha1_starts mbedtls_sha1_starts +#define lwip_sha1_update mbedtls_sha1_update +#define lwip_sha1_finish mbedtls_sha1_finish +#define lwip_sha1_free mbedtls_sha1_free + +#define lwip_des_context mbedtls_des_context +#define lwip_des_init mbedtls_des_init +#define lwip_des_setkey_enc mbedtls_des_setkey_enc +#define lwip_des_crypt_ecb mbedtls_des_crypt_ecb +#define lwip_des_free mbedtls_des_free + +#define lwip_arc4_context mbedtls_arc4_context +#define lwip_arc4_init mbedtls_arc4_init +#define lwip_arc4_setup mbedtls_arc4_setup +#define lwip_arc4_crypt(context, buffer, length) mbedtls_arc4_crypt(context, length, buffer, buffer) +#define lwip_arc4_free mbedtls_arc4_free + +#endif /* LWIP_USE_EXTERNAL_MBEDTLS */ + void pppcrypt_56_to_64_bit_key(u_char *key, u_char *des_key); #endif /* PPPCRYPT_H */ -#endif /* PPP_SUPPORT && MSCHAP_SUPPORT */ +#endif /* PPP_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/pppdebug.h b/tools/sdk/include/lwip/netif/ppp/pppdebug.h index e35c8e09..7ead0459 100644 --- a/tools/sdk/include/lwip/netif/ppp/pppdebug.h +++ b/tools/sdk/include/lwip/netif/ppp/pppdebug.h @@ -34,7 +34,7 @@ ***************************************************************************** */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef PPPDEBUG_H diff --git a/tools/sdk/include/lwip/netif/ppp/pppoe.h b/tools/sdk/include/lwip/netif/ppp/pppoe.h index b1dd2fd9..9f8f2892 100644 --- a/tools/sdk/include/lwip/netif/ppp/pppoe.h +++ b/tools/sdk/include/lwip/netif/ppp/pppoe.h @@ -67,14 +67,14 @@ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPPOE_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef PPP_OE_H #define PPP_OE_H #include "ppp.h" -#include "netif/etharp.h" +#include "lwip/etharp.h" #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" diff --git a/tools/sdk/include/lwip/netif/ppp/pppol2tp.h b/tools/sdk/include/lwip/netif/ppp/pppol2tp.h index 097b4d18..f03950e6 100644 --- a/tools/sdk/include/lwip/netif/ppp/pppol2tp.h +++ b/tools/sdk/include/lwip/netif/ppp/pppol2tp.h @@ -31,11 +31,11 @@ * */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPPOL2TP_SUPPORT /* don't build if not configured for use in lwipopts.h */ -#ifndef PPPOL2TP_H_ -#define PPPOL2TP_H_ +#ifndef PPPOL2TP_H +#define PPPOL2TP_H #include "ppp.h" @@ -193,9 +193,9 @@ struct pppol2tp_pcb_s { /* Create a new L2TP session. */ ppp_pcb *pppol2tp_create(struct netif *pppif, - struct netif *netif, ip_addr_t *ipaddr, u16_t port, + struct netif *netif, const ip_addr_t *ipaddr, u16_t port, const u8_t *secret, u8_t secret_len, ppp_link_status_cb_fn link_status_cb, void *ctx_cb); -#endif /* PPPOL2TP_H_ */ +#endif /* PPPOL2TP_H */ #endif /* PPP_SUPPORT && PPPOL2TP_SUPPORT */ diff --git a/tools/sdk/include/lwip/netif/ppp/pppos.h b/tools/sdk/include/lwip/netif/ppp/pppos.h index 39b2b7d0..d924a9fc 100644 --- a/tools/sdk/include/lwip/netif/ppp/pppos.h +++ b/tools/sdk/include/lwip/netif/ppp/pppos.h @@ -31,14 +31,13 @@ * */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PPPOS_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef PPPOS_H #define PPPOS_H #include "lwip/sys.h" -#include "lwip/sio.h" #include "ppp.h" #include "vj.h" diff --git a/tools/sdk/include/lwip/netif/ppp/upap.h b/tools/sdk/include/lwip/netif/ppp/upap.h index bb9309bd..7da792ec 100644 --- a/tools/sdk/include/lwip/netif/ppp/upap.h +++ b/tools/sdk/include/lwip/netif/ppp/upap.h @@ -42,7 +42,7 @@ * $Id: upap.h,v 1.8 2002/12/04 23:03:33 paulus Exp $ */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && PAP_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef UPAP_H @@ -88,10 +88,10 @@ /* * Timeouts. */ -#if 0 /* moved to opt.h */ +#if 0 /* moved to ppp_opts.h */ #define UPAP_DEFTIMEOUT 3 /* Timeout (seconds) for retransmitting req */ #define UPAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */ -#endif /* moved to opt.h */ +#endif /* moved to ppp_opts.h */ /* * Each interface is described by upap structure. diff --git a/tools/sdk/include/lwip/netif/ppp/vj.h b/tools/sdk/include/lwip/netif/ppp/vj.h index f2e1f8b4..7f389c84 100644 --- a/tools/sdk/include/lwip/netif/ppp/vj.h +++ b/tools/sdk/include/lwip/netif/ppp/vj.h @@ -22,7 +22,7 @@ * - Initial distribution. */ -#include "lwip/opt.h" +#include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT && VJ_SUPPORT /* don't build if not configured for use in lwipopts.h */ #ifndef VJ_H diff --git a/tools/sdk/include/lwip/netif/slipif.h b/tools/sdk/include/lwip/netif/slipif.h index d164d448..65ba31f8 100644 --- a/tools/sdk/include/lwip/netif/slipif.h +++ b/tools/sdk/include/lwip/netif/slipif.h @@ -1,3 +1,9 @@ +/** + * @file + * + * SLIP netif API + */ + /* * Copyright (c) 2001, Swedish Institute of Computer Science. * All rights reserved. diff --git a/tools/sdk/include/lwip/perf.h b/tools/sdk/include/lwip/perf.h new file mode 100644 index 00000000..089facac --- /dev/null +++ b/tools/sdk/include/lwip/perf.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __PERF_H__ +#define __PERF_H__ + +#define PERF_START /* null definition */ +#define PERF_STOP(x) /* null definition */ + +#endif /* __PERF_H__ */ diff --git a/tools/sdk/include/lwip/ping/esp_ping.h b/tools/sdk/include/lwip/ping/esp_ping.h new file mode 100644 index 00000000..d83c5b36 --- /dev/null +++ b/tools/sdk/include/lwip/ping/esp_ping.h @@ -0,0 +1,106 @@ +// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef ESP_PING_H_ +#define ESP_PING_H_ + +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_ERR_PING_BASE 0x6000 + +#define ESP_ERR_PING_INVALID_PARAMS ESP_ERR_PING_BASE + 0x01 +#define ESP_ERR_PING_NO_MEM ESP_ERR_PING_BASE + 0x02 + +#define ESP_PING_CHECK_OPTLEN(optlen, opttype) do { if ((optlen) < sizeof(opttype)) { return ESP_ERR_PING_INVALID_PARAMS; }}while(0) + +typedef struct _ping_found { + uint32_t resp_time; + uint32_t timeout_count; + uint32_t send_count; + uint32_t recv_count; + uint32_t err_count; + uint32_t bytes; + uint32_t total_bytes; + uint32_t total_time; + uint32_t min_time; + uint32_t max_time; + int8_t ping_err; +} esp_ping_found; + +typedef enum { + PING_TARGET_IP_ADDRESS = 50, /**< target IP address */ + PING_TARGET_IP_ADDRESS_COUNT = 51, /**< target IP address total counter */ + PING_TARGET_RCV_TIMEO = 52, /**< receive timeout in milliseconds */ + PING_TARGET_DELAY_TIME = 53, /**< delay time in milliseconds */ + PING_TARGET_ID = 54, /**< identifier */ + PING_TARGET_RES_FN = 55, /**< ping result callback function */ + PING_TARGET_RES_RESET = 56 /**< ping result statistic reset */ +} ping_target_id_t; + +typedef enum { + PING_RES_TIMEOUT = 0, + PING_RES_OK = 1, + PING_RES_FINISH = 2, +} ping_res_t; + +typedef void (* esp_ping_found_fn)(ping_target_id_t found_id, esp_ping_found *found_val); + +/** + * @brief Set PING function option + * + * @param[in] opt_id: option index, 50 for IP, 51 for COUNT, 52 for RCV TIMEOUT, 53 for DELAY TIME, 54 for ID + * @param[in] opt_val: option parameter + * @param[in] opt_len: option length + * + * @return + * - ESP_OK + * - ESP_ERR_PING_INVALID_PARAMS + */ +esp_err_t esp_ping_set_target(ping_target_id_t opt_id, void *opt_val, uint32_t opt_len); + +/** + * @brief Get PING function option + * + * @param[in] opt_id: option index, 50 for IP, 51 for COUNT, 52 for RCV TIMEOUT, 53 for DELAY TIME, 54 for ID + * @param[in] opt_val: option parameter + * @param[in] opt_len: option length + * + * @return + * - ESP_OK + * - ESP_ERR_PING_INVALID_PARAMS + */ +esp_err_t esp_ping_get_target(ping_target_id_t opt_id, void *opt_val, uint32_t opt_len); + +/** + * @brief Get PING function result action + * + * @param[in] res_val: ping function action, 1 for successful, 0 for fail. + * res_len: response bytes + * res_time: response time + * + * @return + * - ESP_OK + * - ESP_ERR_PING_INVALID_PARAMS + */ +esp_err_t esp_ping_result(uint8_t res_val, uint16_t res_len, uint32_t res_time); + +#ifdef __cplusplus +} +#endif + +#endif /* ESP_PING_H_ */ diff --git a/tools/sdk/include/lwip/ping/ping.h b/tools/sdk/include/lwip/ping/ping.h new file mode 100644 index 00000000..6e8eb24b --- /dev/null +++ b/tools/sdk/include/lwip/ping/ping.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#ifndef LWIP_PING_H +#define LWIP_PING_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * PING_USE_SOCKETS: Set to 1 to use sockets, otherwise the raw api is used + */ +#ifndef PING_USE_SOCKETS +#define PING_USE_SOCKETS LWIP_SOCKET +#endif + + +int ping_init(void); + +#ifdef ESP_PING +void ping_deinit(void); +#endif + +#if !PING_USE_SOCKETS +void ping_send_now(void); +#endif /* !PING_USE_SOCKETS */ + +#ifdef __cplusplus +} +#endif + +#endif /* LWIP_PING_H */ diff --git a/tools/sdk/include/lwip/posix/errno.h b/tools/sdk/include/lwip/posix/errno.h new file mode 100644 index 00000000..5917c75e --- /dev/null +++ b/tools/sdk/include/lwip/posix/errno.h @@ -0,0 +1,33 @@ +/** + * @file + * This file is a posix wrapper for lwip/errno.h. + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/errno.h" diff --git a/tools/sdk/include/lwip/posix/netdb.h b/tools/sdk/include/lwip/posix/netdb.h new file mode 100644 index 00000000..363154f6 --- /dev/null +++ b/tools/sdk/include/lwip/posix/netdb.h @@ -0,0 +1,40 @@ +/** + * @file + * This file is a posix wrapper for lwip/netdb.h. + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/netdb.h" + +#ifdef ESP_PLATFORM +int getnameinfo(const struct sockaddr *addr, socklen_t addrlen, + char *host, socklen_t hostlen, + char *serv, socklen_t servlen, int flags); + +#endif diff --git a/tools/sdk/include/lwip/posix/sys/socket.h b/tools/sdk/include/lwip/posix/sys/socket.h new file mode 100644 index 00000000..0ed9baf3 --- /dev/null +++ b/tools/sdk/include/lwip/posix/sys/socket.h @@ -0,0 +1,33 @@ +/** + * @file + * This file is a posix wrapper for lwip/sockets.h. + */ + +/* + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/sockets.h" diff --git a/tools/sdk/include/lwip/sys_arch.h b/tools/sdk/include/lwip/sys_arch.h new file mode 100644 index 00000000..b13d7d1f --- /dev/null +++ b/tools/sdk/include/lwip/sys_arch.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#ifndef __SYS_ARCH_H__ +#define __SYS_ARCH_H__ + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/semphr.h" +#include "arch/vfs_lwip.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef xSemaphoreHandle sys_sem_t; +typedef xSemaphoreHandle sys_mutex_t; +typedef xTaskHandle sys_thread_t; + +typedef struct sys_mbox_s { + xQueueHandle os_mbox; + sys_mutex_t lock; + uint8_t alive; +}* sys_mbox_t; + + +#define LWIP_COMPAT_MUTEX 0 + +#if !LWIP_COMPAT_MUTEX +#define sys_mutex_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define sys_mutex_set_invalid( x ) ( ( *x ) = NULL ) +#endif + +#define sys_mbox_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define sys_mbox_set_invalid( x ) ( ( *x ) = NULL ) + +#define sys_sem_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define sys_sem_set_invalid( x ) ( ( *x ) = NULL ) + +void sys_delay_ms(uint32_t ms); +sys_sem_t* sys_thread_sem_init(void); +void sys_thread_sem_deinit(void); +sys_sem_t* sys_thread_sem_get(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __SYS_ARCH_H__ */ + diff --git a/tools/sdk/include/lwip/vfs_lwip.h b/tools/sdk/include/lwip/vfs_lwip.h new file mode 100644 index 00000000..1957304b --- /dev/null +++ b/tools/sdk/include/lwip/vfs_lwip.h @@ -0,0 +1,23 @@ +// Copyright 2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifdef __cplusplus +extern "C" { +#endif + +void esp_vfs_lwip_sockets_register(); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/mbedtls/CMakeLists.txt b/tools/sdk/include/mbedtls/CMakeLists.txt index 985a3530..1b581a54 100644 --- a/tools/sdk/include/mbedtls/CMakeLists.txt +++ b/tools/sdk/include/mbedtls/CMakeLists.txt @@ -9,3 +9,8 @@ if(INSTALL_MBEDTLS_HEADERS) PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ) endif(INSTALL_MBEDTLS_HEADERS) + +# Make config.h available in an out-of-source build. ssl-opt.sh requires it. +if (NOT ${CMAKE_CURRENT_BINARY_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) + link_to_source(mbedtls) +endif() diff --git a/tools/sdk/include/mbedtls/mbedtls/aes.h b/tools/sdk/include/mbedtls/mbedtls/aes.h index e0fc238d..f6603d59 100644 --- a/tools/sdk/include/mbedtls/mbedtls/aes.h +++ b/tools/sdk/include/mbedtls/mbedtls/aes.h @@ -13,6 +13,11 @@ * ISO/IEC 18033-2:2006: Information technology -- Security * techniques -- Encryption algorithms -- Part 2: Asymmetric * ciphers. + * + * The AES-XTS block mode is standardized by NIST SP 800-38E + * + * and described in detail by IEEE P1619 + * . */ /* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. @@ -53,7 +58,8 @@ #define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */ #define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */ -/* Error codes in range 0x0023-0x0025 */ +/* Error codes in range 0x0021-0x0025 */ +#define MBEDTLS_ERR_AES_BAD_INPUT_DATA -0x0021 /**< Invalid input data. */ #define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE -0x0023 /**< Feature not available. For example, an unsupported AES key size. */ #define MBEDTLS_ERR_AES_HW_ACCEL_FAILED -0x0025 /**< AES hardware accelerator failed. */ @@ -88,6 +94,19 @@ typedef struct } mbedtls_aes_context; +#if defined(MBEDTLS_CIPHER_MODE_XTS) +/** + * \brief The AES XTS context-type definition. + */ +typedef struct +{ + mbedtls_aes_context crypt; /*!< The AES context to use for AES block + encryption or decryption. */ + mbedtls_aes_context tweak; /*!< The AES context used for tweak + computation. */ +} mbedtls_aes_xts_context; +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + #else /* MBEDTLS_AES_ALT */ #include "aes_alt.h" #endif /* MBEDTLS_AES_ALT */ @@ -109,6 +128,25 @@ void mbedtls_aes_init( mbedtls_aes_context *ctx ); */ void mbedtls_aes_free( mbedtls_aes_context *ctx ); +#if defined(MBEDTLS_CIPHER_MODE_XTS) +/** + * \brief This function initializes the specified AES XTS context. + * + * It must be the first API called before using + * the context. + * + * \param ctx The AES XTS context to initialize. + */ +void mbedtls_aes_xts_init( mbedtls_aes_xts_context *ctx ); + +/** + * \brief This function releases and clears the specified AES XTS context. + * + * \param ctx The AES XTS context to clear. + */ +void mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx ); +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + /** * \brief This function sets the encryption key. * @@ -141,6 +179,44 @@ int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key, int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits ); +#if defined(MBEDTLS_CIPHER_MODE_XTS) +/** + * \brief This function prepares an XTS context for encryption and + * sets the encryption key. + * + * \param ctx The AES XTS context to which the key should be bound. + * \param key The encryption key. This is comprised of the XTS key1 + * concatenated with the XTS key2. + * \param keybits The size of \p key passed in bits. Valid options are: + *
  • 256 bits (each of key1 and key2 is a 128-bit key)
  • + *
  • 512 bits (each of key1 and key2 is a 256-bit key)
+ * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. + */ +int mbedtls_aes_xts_setkey_enc( mbedtls_aes_xts_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function prepares an XTS context for decryption and + * sets the decryption key. + * + * \param ctx The AES XTS context to which the key should be bound. + * \param key The decryption key. This is comprised of the XTS key1 + * concatenated with the XTS key2. + * \param keybits The size of \p key passed in bits. Valid options are: + *
  • 256 bits (each of key1 and key2 is a 128-bit key)
  • + *
  • 512 bits (each of key1 and key2 is a 256-bit key)
+ * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. + */ +int mbedtls_aes_xts_setkey_dec( mbedtls_aes_xts_context *ctx, + const unsigned char *key, + unsigned int keybits ); +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + /** * \brief This function performs an AES single-block encryption or * decryption operation. @@ -212,6 +288,49 @@ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_CBC */ +#if defined(MBEDTLS_CIPHER_MODE_XTS) +/** + * \brief This function performs an AES-XTS encryption or decryption + * operation for an entire XTS data unit. + * + * AES-XTS encrypts or decrypts blocks based on their location as + * defined by a data unit number. The data unit number must be + * provided by \p data_unit. + * + * NIST SP 800-38E limits the maximum size of a data unit to 2^20 + * AES blocks. If the data unit is larger than this, this function + * returns #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH. + * + * \param ctx The AES XTS context to use for AES XTS operations. + * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or + * #MBEDTLS_AES_DECRYPT. + * \param length The length of a data unit in bytes. This can be any + * length between 16 bytes and 2^24 bytes inclusive + * (between 1 and 2^20 block cipher blocks). + * \param data_unit The address of the data unit encoded as an array of 16 + * bytes in little-endian format. For disk encryption, this + * is typically the index of the block device sector that + * contains the data. + * \param input The buffer holding the input data (which is an entire + * data unit). This function reads \p length bytes from \p + * input. + * \param output The buffer holding the output data (which is an entire + * data unit). This function writes \p length bytes to \p + * output. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH if \p length is + * smaller than an AES block in size (16 bytes) or if \p + * length is larger than 2^20 blocks (16 MiB). + */ +int mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx, + int mode, + size_t length, + const unsigned char data_unit[16], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_XTS */ + #if defined(MBEDTLS_CIPHER_MODE_CFB) /** * \brief This function performs an AES-CFB128 encryption or decryption @@ -295,6 +414,56 @@ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx, unsigned char *output ); #endif /*MBEDTLS_CIPHER_MODE_CFB */ +#if defined(MBEDTLS_CIPHER_MODE_OFB) +/** + * \brief This function performs an AES-OFB (Output Feedback Mode) + * encryption or decryption operation. + * + * For OFB, you must set up the context with + * mbedtls_aes_setkey_enc(), regardless of whether you are + * performing an encryption or decryption operation. This is + * because OFB mode uses the same key schedule for encryption and + * decryption. + * + * The OFB operation is identical for encryption or decryption, + * therefore no operation mode needs to be specified. + * + * \note Upon exit, the content of iv, the Initialisation Vector, is + * updated so that you can call the same function again on the next + * block(s) of data and get the same result as if it was encrypted + * in one call. This allows a "streaming" usage, by initialising + * iv_off to 0 before the first call, and preserving its value + * between calls. + * + * For non-streaming use, the iv should be initialised on each call + * to a unique value, and iv_off set to 0 on each call. + * + * If you need to retain the contents of the initialisation vector, + * you must either save it manually or use the cipher module + * instead. + * + * \warning For the OFB mode, the initialisation vector must be unique + * every encryption operation. Reuse of an initialisation vector + * will compromise security. + * + * \param ctx The AES context to use for encryption or decryption. + * \param length The length of the input data. + * \param iv_off The offset in IV (updated after use). + * \param iv The initialization vector (updated after use). + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. + */ +int mbedtls_aes_crypt_ofb( mbedtls_aes_context *ctx, + size_t length, + size_t *iv_off, + unsigned char iv[16], + const unsigned char *input, + unsigned char *output ); + +#endif /* MBEDTLS_CIPHER_MODE_OFB */ + #if defined(MBEDTLS_CIPHER_MODE_CTR) /** * \brief This function performs an AES-CTR encryption or decryption @@ -309,7 +478,49 @@ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx, * must use the context initialized with mbedtls_aes_setkey_enc() * for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT. * - * \warning You must keep the maximum use of your counter in mind. + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 12 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 12 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**96 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. An alternative is to generate random nonces, but this + * limits the number of messages that can be securely encrypted: + * for example, with 96-bit random nonces, you should not encrypt + * more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that an AES block is 16 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. * * \param ctx The AES context to use for encryption or decryption. * \param length The length of the input data. diff --git a/tools/sdk/include/mbedtls/mbedtls/aria.h b/tools/sdk/include/mbedtls/mbedtls/aria.h new file mode 100644 index 00000000..bae0621b --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/aria.h @@ -0,0 +1,331 @@ +/** + * \file aria.h + * + * \brief ARIA block cipher + * + * The ARIA algorithm is a symmetric block cipher that can encrypt and + * decrypt information. It is defined by the Korean Agency for + * Technology and Standards (KATS) in KS X 1213:2004 (in + * Korean, but see http://210.104.33.10/ARIA/index-e.html in English) + * and also described by the IETF in RFC 5794. + */ +/* Copyright (C) 2006-2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_ARIA_H +#define MBEDTLS_ARIA_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#define MBEDTLS_ARIA_ENCRYPT 1 /**< ARIA encryption. */ +#define MBEDTLS_ARIA_DECRYPT 0 /**< ARIA decryption. */ + +#define MBEDTLS_ARIA_BLOCKSIZE 16 /**< ARIA block size in bytes. */ +#define MBEDTLS_ARIA_MAX_ROUNDS 16 /**< Maxiumum number of rounds in ARIA. */ +#define MBEDTLS_ARIA_MAX_KEYSIZE 32 /**< Maximum size of an ARIA key in bytes. */ + +#define MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH -0x005C /**< Invalid key length. */ +#define MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH -0x005E /**< Invalid data input length. */ +#define MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE -0x005A /**< Feature not available. For example, an unsupported ARIA key size. */ +#define MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED -0x0058 /**< ARIA hardware accelerator failed. */ + +#if !defined(MBEDTLS_ARIA_ALT) +// Regular implementation +// + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief The ARIA context-type definition. + */ +typedef struct +{ + unsigned char nr; /*!< The number of rounds (12, 14 or 16) */ + /*! The ARIA round keys. */ + uint32_t rk[MBEDTLS_ARIA_MAX_ROUNDS + 1][MBEDTLS_ARIA_BLOCKSIZE / 4]; +} +mbedtls_aria_context; + +#else /* MBEDTLS_ARIA_ALT */ +#include "aria_alt.h" +#endif /* MBEDTLS_ARIA_ALT */ + +/** + * \brief This function initializes the specified ARIA context. + * + * It must be the first API called before using + * the context. + * + * \param ctx The ARIA context to initialize. + */ +void mbedtls_aria_init( mbedtls_aria_context *ctx ); + +/** + * \brief This function releases and clears the specified ARIA context. + * + * \param ctx The ARIA context to clear. + */ +void mbedtls_aria_free( mbedtls_aria_context *ctx ); + +/** + * \brief This function sets the encryption key. + * + * \param ctx The ARIA context to which the key should be bound. + * \param key The encryption key. + * \param keybits The size of data passed in bits. Valid options are: + *
  • 128 bits
  • + *
  • 192 bits
  • + *
  • 256 bits
+ * + * \return \c 0 on success or #MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH + * on failure. + */ +int mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function sets the decryption key. + * + * \param ctx The ARIA context to which the key should be bound. + * \param key The decryption key. + * \param keybits The size of data passed. Valid options are: + *
  • 128 bits
  • + *
  • 192 bits
  • + *
  • 256 bits
+ * + * \return \c 0 on success, or #MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH on failure. + */ +int mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx, + const unsigned char *key, + unsigned int keybits ); + +/** + * \brief This function performs an ARIA single-block encryption or + * decryption operation. + * + * It performs encryption or decryption (depending on whether + * the key was set for encryption on decryption) on the input + * data buffer defined in the \p input parameter. + * + * mbedtls_aria_init(), and either mbedtls_aria_setkey_enc() or + * mbedtls_aria_setkey_dec() must be called before the first + * call to this API with the same context. + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param input The 16-Byte buffer holding the input data. + * \param output The 16-Byte buffer holding the output data. + + * \return \c 0 on success. + */ +int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx, + const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE], + unsigned char output[MBEDTLS_ARIA_BLOCKSIZE] ); + +#if defined(MBEDTLS_CIPHER_MODE_CBC) +/** + * \brief This function performs an ARIA-CBC encryption or decryption operation + * on full blocks. + * + * It performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer defined in + * the \p input parameter. + * + * It can be called as many times as needed, until all the input + * data is processed. mbedtls_aria_init(), and either + * mbedtls_aria_setkey_enc() or mbedtls_aria_setkey_dec() must be called + * before the first call to this API with the same context. + * + * \note This function operates on aligned blocks, that is, the input size + * must be a multiple of the ARIA block size of 16 Bytes. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the IV, you should + * either save it manually or use the cipher module instead. + * + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param mode The ARIA operation: #MBEDTLS_ARIA_ENCRYPT or + * #MBEDTLS_ARIA_DECRYPT. + * \param length The length of the input data in Bytes. This must be a + * multiple of the block size (16 Bytes). + * \param iv Initialization vector (updated after use). + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success, or #MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH + * on failure. + */ +int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx, + int mode, + size_t length, + unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CBC */ + +#if defined(MBEDTLS_CIPHER_MODE_CFB) +/** + * \brief This function performs an ARIA-CFB128 encryption or decryption + * operation. + * + * It performs the operation defined in the \p mode + * parameter (encrypt or decrypt), on the input data buffer + * defined in the \p input parameter. + * + * For CFB, you must set up the context with mbedtls_aria_setkey_enc(), + * regardless of whether you are performing an encryption or decryption + * operation, that is, regardless of the \p mode parameter. This is + * because CFB mode uses the same key schedule for encryption and + * decryption. + * + * \note Upon exit, the content of the IV is updated so that you can + * call the same function again on the next + * block(s) of data and get the same result as if it was + * encrypted in one call. This allows a "streaming" usage. + * If you need to retain the contents of the + * IV, you must either save it manually or use the cipher + * module instead. + * + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param mode The ARIA operation: #MBEDTLS_ARIA_ENCRYPT or + * #MBEDTLS_ARIA_DECRYPT. + * \param length The length of the input data. + * \param iv_off The offset in IV (updated after use). + * \param iv The initialization vector (updated after use). + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. + */ +int mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx, + int mode, + size_t length, + size_t *iv_off, + unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CFB */ + +#if defined(MBEDTLS_CIPHER_MODE_CTR) +/** + * \brief This function performs an ARIA-CTR encryption or decryption + * operation. + * + * This function performs the operation defined in the \p mode + * parameter (encrypt/decrypt), on the input data buffer + * defined in the \p input parameter. + * + * Due to the nature of CTR, you must use the same key schedule + * for both encryption and decryption operations. Therefore, you + * must use the context initialized with mbedtls_aria_setkey_enc() + * for both #MBEDTLS_ARIA_ENCRYPT and #MBEDTLS_ARIA_DECRYPT. + * + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 12 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 12 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**96 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. An alternative is to generate random nonces, but this + * limits the number of messages that can be securely encrypted: + * for example, with 96-bit random nonces, you should not encrypt + * more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that an ARIA block is 16 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. + * + * \param ctx The ARIA context to use for encryption or decryption. + * \param length The length of the input data. + * \param nc_off The offset in the current \p stream_block, for + * resuming within the current cipher stream. The + * offset pointer should be 0 at the start of a stream. + * \param nonce_counter The 128-bit nonce and counter. + * \param stream_block The saved stream block for resuming. This is + * overwritten by the function. + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * + * \return \c 0 on success. + */ +int mbedtls_aria_crypt_ctr( mbedtls_aria_context *ctx, + size_t length, + size_t *nc_off, + unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE], + unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE], + const unsigned char *input, + unsigned char *output ); +#endif /* MBEDTLS_CIPHER_MODE_CTR */ + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief Checkup routine. + * + * \return \c 0 on success, or \c 1 on failure. + */ +int mbedtls_aria_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* aria.h */ diff --git a/tools/sdk/include/mbedtls/mbedtls/blowfish.h b/tools/sdk/include/mbedtls/mbedtls/blowfish.h index 22479be5..985faa43 100644 --- a/tools/sdk/include/mbedtls/mbedtls/blowfish.h +++ b/tools/sdk/include/mbedtls/mbedtls/blowfish.h @@ -174,7 +174,46 @@ int mbedtls_blowfish_crypt_cfb64( mbedtls_blowfish_context *ctx, /** * \brief Blowfish-CTR buffer encryption/decryption * - * Warning: You have to keep the maximum use of your counter in mind! + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**64 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 4 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 4 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**32 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. + * + * Note that for both stategies, sizes are measured in blocks and + * that a Blowfish block is 8 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. * * \param ctx Blowfish context * \param length The length of the data diff --git a/tools/sdk/include/mbedtls/mbedtls/bn_mul.h b/tools/sdk/include/mbedtls/mbedtls/bn_mul.h index 354c1cc1..b587317d 100644 --- a/tools/sdk/include/mbedtls/mbedtls/bn_mul.h +++ b/tools/sdk/include/mbedtls/mbedtls/bn_mul.h @@ -49,7 +49,14 @@ /* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */ #if defined(__GNUC__) && \ ( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 ) -#if defined(__i386__) + +/* + * Disable use of the i386 assembly code below if option -O0, to disable all + * compiler optimisations, is passed, detected with __OPTIMIZE__ + * This is done as the number of registers used in the assembly code doesn't + * work with the -O0 option. + */ +#if defined(__i386__) && defined(__OPTIMIZE__) #define MULADDC_INIT \ asm( \ @@ -142,7 +149,7 @@ "movl %%esi, %3 \n\t" \ : "=m" (t), "=m" (c), "=m" (d), "=m" (s) \ : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \ - : "eax", "ecx", "edx", "esi", "edi" \ + : "eax", "ebx", "ecx", "edx", "esi", "edi" \ ); #else @@ -154,7 +161,7 @@ "movl %%esi, %3 \n\t" \ : "=m" (t), "=m" (c), "=m" (d), "=m" (s) \ : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \ - : "eax", "ecx", "edx", "esi", "edi" \ + : "eax", "ebx", "ecx", "edx", "esi", "edi" \ ); #endif /* SSE2 */ #endif /* i386 */ @@ -521,7 +528,7 @@ "swi r3, %2 \n\t" \ : "=m" (c), "=m" (d), "=m" (s) \ : "m" (s), "m" (d), "m" (c), "m" (b) \ - : "r3", "r4" "r5", "r6", "r7", "r8", \ + : "r3", "r4", "r5", "r6", "r7", "r8", \ "r9", "r10", "r11", "r12", "r13" \ ); diff --git a/tools/sdk/include/mbedtls/mbedtls/camellia.h b/tools/sdk/include/mbedtls/mbedtls/camellia.h index f0466bfd..7e4721af 100644 --- a/tools/sdk/include/mbedtls/mbedtls/camellia.h +++ b/tools/sdk/include/mbedtls/mbedtls/camellia.h @@ -187,12 +187,54 @@ int mbedtls_camellia_crypt_cfb128( mbedtls_camellia_context *ctx, /** * \brief CAMELLIA-CTR buffer encryption/decryption * - * Warning: You have to keep the maximum use of your counter in mind! - * * Note: Due to the nature of CTR you should use the same key schedule for * both encryption and decryption. So a context initialized with * mbedtls_camellia_setkey_enc() for both MBEDTLS_CAMELLIA_ENCRYPT and MBEDTLS_CAMELLIA_DECRYPT. * + * \warning You must never reuse a nonce value with the same key. Doing so + * would void the encryption for the two messages encrypted with + * the same nonce and key. + * + * There are two common strategies for managing nonces with CTR: + * + * 1. You can handle everything as a single message processed over + * successive calls to this function. In that case, you want to + * set \p nonce_counter and \p nc_off to 0 for the first call, and + * then preserve the values of \p nonce_counter, \p nc_off and \p + * stream_block across calls to this function as they will be + * updated by this function. + * + * With this strategy, you must not encrypt more than 2**128 + * blocks of data with the same key. + * + * 2. You can encrypt separate messages by dividing the \p + * nonce_counter buffer in two areas: the first one used for a + * per-message nonce, handled by yourself, and the second one + * updated by this function internally. + * + * For example, you might reserve the first 12 bytes for the + * per-message nonce, and the last 4 bytes for internal use. In that + * case, before calling this function on a new message you need to + * set the first 12 bytes of \p nonce_counter to your chosen nonce + * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p + * stream_block to be ignored). That way, you can encrypt at most + * 2**96 messages of up to 2**32 blocks each with the same key. + * + * The per-message nonce (or information sufficient to reconstruct + * it) needs to be communicated with the ciphertext and must be unique. + * The recommended way to ensure uniqueness is to use a message + * counter. An alternative is to generate random nonces, but this + * limits the number of messages that can be securely encrypted: + * for example, with 96-bit random nonces, you should not encrypt + * more than 2**32 messages with the same key. + * + * Note that for both stategies, sizes are measured in blocks and + * that a CAMELLIA block is 16 bytes. + * + * \warning Upon return, \p stream_block contains sensitive data. Its + * content must not be written to insecure storage and should be + * securely discarded as soon as it's no longer needed. + * * \param ctx CAMELLIA context * \param length The length of the data * \param nc_off The offset in the current stream_block (for resuming diff --git a/tools/sdk/include/mbedtls/mbedtls/ccm.h b/tools/sdk/include/mbedtls/mbedtls/ccm.h index 8585ce5e..5d727e7c 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ccm.h +++ b/tools/sdk/include/mbedtls/mbedtls/ccm.h @@ -14,6 +14,18 @@ *
  • Nonce - A unique value that is assigned to the payload and the * associated data.
  • * + * Definition of CCM: + * http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf + * RFC 3610 "Counter with CBC-MAC (CCM)" + * + * Related: + * RFC 5116 "An Interface and Algorithms for Authenticated Encryption" + * + * Definition of CCM*: + * IEEE 802.15.4 - IEEE Standard for Local and metropolitan area networks + * Integer representation is fixed most-significant-octet-first order and + * the representation of octets is most-significant-bit-first order. This is + * consistent with RFC 3610. */ /* * Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved @@ -102,7 +114,6 @@ void mbedtls_ccm_free( mbedtls_ccm_context *ctx ); /** * \brief This function encrypts a buffer using CCM. * - * * \note The tag is written to a separate buffer. To concatenate * the \p tag with the \p output, as done in RFC-3610: * Counter with CBC-MAC (CCM), use @@ -112,15 +123,17 @@ void mbedtls_ccm_free( mbedtls_ccm_context *ctx ); * \param ctx The CCM context to use for encryption. * \param length The length of the input data in Bytes. * \param iv Initialization vector (nonce). - * \param iv_len The length of the IV in Bytes: 7, 8, 9, 10, 11, 12, or 13. + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. * \param add The additional data field. * \param add_len The length of additional data in Bytes. * Must be less than 2^16 - 2^8. * \param input The buffer holding the input data. * \param output The buffer holding the output data. * Must be at least \p length Bytes wide. - * \param tag The buffer holding the tag. - * \param tag_len The length of the tag to generate in Bytes: + * \param tag The buffer holding the authentication field. + * \param tag_len The length of the authentication field to generate in Bytes: * 4, 6, 8, 10, 12, 14 or 16. * * \return \c 0 on success. @@ -133,21 +146,64 @@ int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length, unsigned char *tag, size_t tag_len ); /** - * \brief This function performs a CCM authenticated decryption of a - * buffer. + * \brief This function encrypts a buffer using CCM*. * - * \param ctx The CCM context to use for decryption. + * \note The tag is written to a separate buffer. To concatenate + * the \p tag with the \p output, as done in RFC-3610: + * Counter with CBC-MAC (CCM), use + * \p tag = \p output + \p length, and make sure that the + * output buffer is at least \p length + \p tag_len wide. + * + * \note When using this function in a variable tag length context, + * the tag length has to be encoded into the \p iv passed to + * this function. + * + * \param ctx The CCM context to use for encryption. * \param length The length of the input data in Bytes. - * \param iv Initialization vector. - * \param iv_len The length of the IV in Bytes: 7, 8, 9, 10, 11, 12, or 13. + * \param iv Initialization vector (nonce). + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. * \param add The additional data field. * \param add_len The length of additional data in Bytes. * Must be less than 2^16 - 2^8. * \param input The buffer holding the input data. * \param output The buffer holding the output data. * Must be at least \p length Bytes wide. - * \param tag The buffer holding the tag. - * \param tag_len The length of the tag in Bytes. + * \param tag The buffer holding the authentication field. + * \param tag_len The length of the authentication field to generate in Bytes: + * 0, 4, 6, 8, 10, 12, 14 or 16. + * + * \warning Passing 0 as \p tag_len means that the message is no + * longer authenticated. + * + * \return \c 0 on success. + * \return A CCM or cipher-specific error code on failure. + */ +int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length, + const unsigned char *iv, size_t iv_len, + const unsigned char *add, size_t add_len, + const unsigned char *input, unsigned char *output, + unsigned char *tag, size_t tag_len ); + +/** + * \brief This function performs a CCM authenticated decryption of a + * buffer. + * + * \param ctx The CCM context to use for decryption. + * \param length The length of the input data in Bytes. + * \param iv Initialization vector (nonce). + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. + * \param add The additional data field. + * \param add_len The length of additional data in Bytes. + * Must be less than 2^16 - 2^8. + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * Must be at least \p length Bytes wide. + * \param tag The buffer holding the authentication field. + * \param tag_len The length of the authentication field in Bytes. * 4, 6, 8, 10, 12, 14 or 16. * * \return \c 0 on success. This indicates that the message is authentic. @@ -160,6 +216,43 @@ int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, const unsigned char *input, unsigned char *output, const unsigned char *tag, size_t tag_len ); +/** + * \brief This function performs a CCM* authenticated decryption of a + * buffer. + * + * \note When using this function in a variable tag length context, + * the tag length has to be decoded from \p iv and passed to + * this function as \p tag_len. (\p tag needs to be adjusted + * accordingly.) + * + * \param ctx The CCM context to use for decryption. + * \param length The length of the input data in Bytes. + * \param iv Initialization vector (nonce). + * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12, + * or 13. The length L of the message length field is + * 15 - \p iv_len. + * \param add The additional data field. + * \param add_len The length of additional data in Bytes. + * Must be less than 2^16 - 2^8. + * \param input The buffer holding the input data. + * \param output The buffer holding the output data. + * Must be at least \p length Bytes wide. + * \param tag The buffer holding the authentication field. + * \param tag_len The length of the authentication field in Bytes. + * 0, 4, 6, 8, 10, 12, 14 or 16. + * + * \warning Passing 0 as \p tag_len means that the message is no + * longer authenticated. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match. + * \return A cipher-specific error code on calculation failure. + */ +int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length, + const unsigned char *iv, size_t iv_len, + const unsigned char *add, size_t add_len, + const unsigned char *input, unsigned char *output, + const unsigned char *tag, size_t tag_len ); #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) /** diff --git a/tools/sdk/include/mbedtls/mbedtls/chacha20.h b/tools/sdk/include/mbedtls/mbedtls/chacha20.h new file mode 100644 index 00000000..47bd7d38 --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/chacha20.h @@ -0,0 +1,212 @@ +/** + * \file chacha20.h + * + * \brief This file contains ChaCha20 definitions and functions. + * + * ChaCha20 is a stream cipher that can encrypt and decrypt + * information. ChaCha was created by Daniel Bernstein as a variant of + * its Salsa cipher https://cr.yp.to/chacha/chacha-20080128.pdf + * ChaCha20 is the variant with 20 rounds, that was also standardized + * in RFC 7539. + * + * \author Daniel King + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CHACHA20_H +#define MBEDTLS_CHACHA20_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#define MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA -0x0051 /**< Invalid input parameter(s). */ +#define MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE -0x0053 /**< Feature not available. For example, s part of the API is not implemented. */ +#define MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED -0x0055 /**< Chacha20 hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_CHACHA20_ALT) + +typedef struct +{ + uint32_t state[16]; /*! The state (before round operations). */ + uint8_t keystream8[64]; /*! Leftover keystream bytes. */ + size_t keystream_bytes_used; /*! Number of keystream bytes already used. */ +} +mbedtls_chacha20_context; + +#else /* MBEDTLS_CHACHA20_ALT */ +#include "chacha20_alt.h" +#endif /* MBEDTLS_CHACHA20_ALT */ + +/** + * \brief This function initializes the specified ChaCha20 context. + * + * It must be the first API called before using + * the context. + * + * It is usually followed by calls to + * \c mbedtls_chacha20_setkey() and + * \c mbedtls_chacha20_starts(), then one or more calls to + * to \c mbedtls_chacha20_update(), and finally to + * \c mbedtls_chacha20_free(). + * + * \param ctx The ChaCha20 context to initialize. + */ +void mbedtls_chacha20_init( mbedtls_chacha20_context *ctx ); + +/** + * \brief This function releases and clears the specified ChaCha20 context. + * + * \param ctx The ChaCha20 context to clear. + */ +void mbedtls_chacha20_free( mbedtls_chacha20_context *ctx ); + +/** + * \brief This function sets the encryption/decryption key. + * + * \note After using this function, you must also call + * \c mbedtls_chacha20_starts() to set a nonce before you + * start encrypting/decrypting data with + * \c mbedtls_chacha_update(). + * + * \param ctx The ChaCha20 context to which the key should be bound. + * \param key The encryption/decryption key. Must be 32 bytes in length. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or key is NULL. + */ +int mbedtls_chacha20_setkey( mbedtls_chacha20_context *ctx, + const unsigned char key[32] ); + +/** + * \brief This function sets the nonce and initial counter value. + * + * \note A ChaCha20 context can be re-used with the same key by + * calling this function to change the nonce. + * + * \warning You must never use the same nonce twice with the same key. + * This would void any confidentiality guarantees for the + * messages encrypted with the same nonce and key. + * + * \param ctx The ChaCha20 context to which the nonce should be bound. + * \param nonce The nonce. Must be 12 bytes in size. + * \param counter The initial counter value. This is usually 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or nonce is + * NULL. + */ +int mbedtls_chacha20_starts( mbedtls_chacha20_context* ctx, + const unsigned char nonce[12], + uint32_t counter ); + +/** + * \brief This function encrypts or decrypts data. + * + * Since ChaCha20 is a stream cipher, the same operation is + * used for encrypting and decrypting data. + * + * \note The \p input and \p output pointers must either be equal or + * point to non-overlapping buffers. + * + * \note \c mbedtls_chacha20_setkey() and + * \c mbedtls_chacha20_starts() must be called at least once + * to setup the context before this function can be called. + * + * \note This function can be called multiple times in a row in + * order to encrypt of decrypt data piecewise with the same + * key and nonce. + * + * \param ctx The ChaCha20 context to use for encryption or decryption. + * \param size The length of the input data in bytes. + * \param input The buffer holding the input data. + * This pointer can be NULL if size == 0. + * \param output The buffer holding the output data. + * Must be able to hold \p size bytes. + * This pointer can be NULL if size == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if the ctx, input, or + * output pointers are NULL. + */ +int mbedtls_chacha20_update( mbedtls_chacha20_context *ctx, + size_t size, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function encrypts or decrypts data with ChaCha20 and + * the given key and nonce. + * + * Since ChaCha20 is a stream cipher, the same operation is + * used for encrypting and decrypting data. + * + * \warning You must never use the same (key, nonce) pair more than + * once. This would void any confidentiality guarantees for + * the messages encrypted with the same nonce and key. + * + * \note The \p input and \p output pointers must either be equal or + * point to non-overlapping buffers. + * + * \param key The encryption/decryption key. Must be 32 bytes in length. + * \param nonce The nonce. Must be 12 bytes in size. + * \param counter The initial counter value. This is usually 0. + * \param size The length of the input data in bytes. + * \param input The buffer holding the input data. + * This pointer can be NULL if size == 0. + * \param output The buffer holding the output data. + * Must be able to hold \p size bytes. + * This pointer can be NULL if size == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if key, nonce, input, + * or output is NULL. + */ +int mbedtls_chacha20_crypt( const unsigned char key[32], + const unsigned char nonce[12], + uint32_t counter, + size_t size, + const unsigned char* input, + unsigned char* output ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief The ChaCha20 checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_chacha20_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_CHACHA20_H */ diff --git a/tools/sdk/include/mbedtls/mbedtls/chachapoly.h b/tools/sdk/include/mbedtls/mbedtls/chachapoly.h new file mode 100644 index 00000000..42b2b230 --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/chachapoly.h @@ -0,0 +1,355 @@ +/** + * \file chachapoly.h + * + * \brief This file contains the AEAD-ChaCha20-Poly1305 definitions and + * functions. + * + * ChaCha20-Poly1305 is an algorithm for Authenticated Encryption + * with Associated Data (AEAD) that can be used to encrypt and + * authenticate data. It is based on ChaCha20 and Poly1305 by Daniel + * Bernstein and was standardized in RFC 7539. + * + * \author Daniel King + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_CHACHAPOLY_H +#define MBEDTLS_CHACHAPOLY_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +/* for shared error codes */ +#include "poly1305.h" + +#define MBEDTLS_ERR_CHACHAPOLY_BAD_STATE -0x0054 /**< The requested operation is not permitted in the current state. */ +#define MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED -0x0056 /**< Authenticated decryption failed: data was not authentic. */ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum +{ + MBEDTLS_CHACHAPOLY_ENCRYPT, /**< The mode value for performing encryption. */ + MBEDTLS_CHACHAPOLY_DECRYPT /**< The mode value for performing decryption. */ +} +mbedtls_chachapoly_mode_t; + +#if !defined(MBEDTLS_CHACHAPOLY_ALT) + +#include "chacha20.h" + +typedef struct +{ + mbedtls_chacha20_context chacha20_ctx; /**< The ChaCha20 context. */ + mbedtls_poly1305_context poly1305_ctx; /**< The Poly1305 context. */ + uint64_t aad_len; /**< The length (bytes) of the Additional Authenticated Data. */ + uint64_t ciphertext_len; /**< The length (bytes) of the ciphertext. */ + int state; /**< The current state of the context. */ + mbedtls_chachapoly_mode_t mode; /**< Cipher mode (encrypt or decrypt). */ +} +mbedtls_chachapoly_context; + +#else /* !MBEDTLS_CHACHAPOLY_ALT */ +#include "chachapoly_alt.h" +#endif /* !MBEDTLS_CHACHAPOLY_ALT */ + +/** + * \brief This function initializes the specified ChaCha20-Poly1305 context. + * + * It must be the first API called before using + * the context. It must be followed by a call to + * \c mbedtls_chachapoly_setkey() before any operation can be + * done, and to \c mbedtls_chachapoly_free() once all + * operations with that context have been finished. + * + * In order to encrypt or decrypt full messages at once, for + * each message you should make a single call to + * \c mbedtls_chachapoly_crypt_and_tag() or + * \c mbedtls_chachapoly_auth_decrypt(). + * + * In order to encrypt messages piecewise, for each + * message you should make a call to + * \c mbedtls_chachapoly_starts(), then 0 or more calls to + * \c mbedtls_chachapoly_update_aad(), then 0 or more calls to + * \c mbedtls_chachapoly_update(), then one call to + * \c mbedtls_chachapoly_finish(). + * + * \warning Decryption with the piecewise API is discouraged! Always + * use \c mbedtls_chachapoly_auth_decrypt() when possible! + * + * If however this is not possible because the data is too + * large to fit in memory, you need to: + * + * - call \c mbedtls_chachapoly_starts() and (if needed) + * \c mbedtls_chachapoly_update_aad() as above, + * - call \c mbedtls_chachapoly_update() multiple times and + * ensure its output (the plaintext) is NOT used in any other + * way than placing it in temporary storage at this point, + * - call \c mbedtls_chachapoly_finish() to compute the + * authentication tag and compared it in constant time to the + * tag received with the ciphertext. + * + * If the tags are not equal, you must immediately discard + * all previous outputs of \c mbedtls_chachapoly_update(), + * otherwise you can now safely use the plaintext. + * + * \param ctx The ChachaPoly context to initialize. + */ +void mbedtls_chachapoly_init( mbedtls_chachapoly_context *ctx ); + +/** + * \brief This function releases and clears the specified ChaCha20-Poly1305 context. + * + * \param ctx The ChachaPoly context to clear. + */ +void mbedtls_chachapoly_free( mbedtls_chachapoly_context *ctx ); + +/** + * \brief This function sets the ChaCha20-Poly1305 symmetric encryption key. + * + * \param ctx The ChaCha20-Poly1305 context to which the key should be + * bound. + * \param key The 256-bit (32 bytes) key. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if \p ctx or \p key are NULL. + */ +int mbedtls_chachapoly_setkey( mbedtls_chachapoly_context *ctx, + const unsigned char key[32] ); + +/** + * \brief This function starts a ChaCha20-Poly1305 encryption or + * decryption operation. + * + * \warning You must never use the same nonce twice with the same key. + * This would void any confidentiality and authenticity + * guarantees for the messages encrypted with the same nonce + * and key. + * + * \note If the context is being used for AAD only (no data to + * encrypt or decrypt) then \p mode can be set to any value. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \param ctx The ChaCha20-Poly1305 context. + * \param nonce The nonce/IV to use for the message. Must be 12 bytes. + * \param mode The operation to perform: #MBEDTLS_CHACHAPOLY_ENCRYPT or + * #MBEDTLS_CHACHAPOLY_DECRYPT (discouraged, see warning). + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if \p ctx or \p mac are NULL. + */ +int mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx, + const unsigned char nonce[12], + mbedtls_chachapoly_mode_t mode ); + +/** + * \brief This function feeds additional data to be authenticated + * into an ongoing ChaCha20-Poly1305 operation. + * + * The Additional Authenticated Data (AAD), also called + * Associated Data (AD) is only authenticated but not + * encrypted nor included in the encrypted output. It is + * usually transmitted separately from the ciphertext or + * computed locally by each party. + * + * \note This function is called before data is encrypted/decrypted. + * I.e. call this function to process the AAD before calling + * \c mbedtls_chachapoly_update(). + * + * You may call this function multiple times to process + * an arbitrary amount of AAD. It is permitted to call + * this function 0 times, if no AAD is used. + * + * This function cannot be called any more if data has + * been processed by \c mbedtls_chachapoly_update(), + * or if the context has been finished. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \param ctx The ChaCha20-Poly1305 context to use. + * \param aad_len The length (in bytes) of the AAD. The length has no + * restrictions. + * \param aad Buffer containing the AAD. + * This pointer can be NULL if aad_len == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if \p ctx or \p aad are NULL. + * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE + * if the operations has not been started or has been + * finished, or if the AAD has been finished. + */ +int mbedtls_chachapoly_update_aad( mbedtls_chachapoly_context *ctx, + const unsigned char *aad, + size_t aad_len ); + +/** + * \brief Thus function feeds data to be encrypted or decrypted + * into an on-going ChaCha20-Poly1305 + * operation. + * + * The direction (encryption or decryption) depends on the + * mode that was given when calling + * \c mbedtls_chachapoly_starts(). + * + * You may call this function multiple times to process + * an arbitrary amount of data. It is permitted to call + * this function 0 times, if no data is to be encrypted + * or decrypted. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \param ctx The ChaCha20-Poly1305 context to use. + * \param len The length (in bytes) of the data to encrypt or decrypt. + * \param input The buffer containing the data to encrypt or decrypt. + * This pointer can be NULL if len == 0. + * \param output The buffer to where the encrypted or decrypted data is written. + * Must be able to hold \p len bytes. + * This pointer can be NULL if len == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if \p ctx, \p input, or \p output are NULL. + * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE + * if the operation has not been started or has been + * finished. + */ +int mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx, + size_t len, + const unsigned char *input, + unsigned char *output ); + +/** + * \brief This function finished the ChaCha20-Poly1305 operation and + * generates the MAC (authentication tag). + * + * \param ctx The ChaCha20-Poly1305 context to use. + * \param mac The buffer to where the 128-bit (16 bytes) MAC is written. + * + * \warning Decryption with the piecewise API is discouraged, see the + * warning on \c mbedtls_chachapoly_init(). + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if \p ctx or \p mac are NULL. + * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE + * if the operation has not been started or has been + * finished. + */ +int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx, + unsigned char mac[16] ); + +/** + * \brief This function performs a complete ChaCha20-Poly1305 + * authenticated encryption with the previously-set key. + * + * \note Before using this function, you must set the key with + * \c mbedtls_chachapoly_setkey(). + * + * \warning You must never use the same nonce twice with the same key. + * This would void any confidentiality and authenticity + * guarantees for the messages encrypted with the same nonce + * and key. + * + * \param ctx The ChaCha20-Poly1305 context to use (holds the key). + * \param length The length (in bytes) of the data to encrypt or decrypt. + * \param nonce The 96-bit (12 bytes) nonce/IV to use. + * \param aad The buffer containing the additional authenticated data (AAD). + * This pointer can be NULL if aad_len == 0. + * \param aad_len The length (in bytes) of the AAD data to process. + * \param input The buffer containing the data to encrypt or decrypt. + * This pointer can be NULL if ilen == 0. + * \param output The buffer to where the encrypted or decrypted data is written. + * This pointer can be NULL if ilen == 0. + * \param tag The buffer to where the computed 128-bit (16 bytes) MAC is written. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if one or more of the required parameters are NULL. + */ +int mbedtls_chachapoly_encrypt_and_tag( mbedtls_chachapoly_context *ctx, + size_t length, + const unsigned char nonce[12], + const unsigned char *aad, + size_t aad_len, + const unsigned char *input, + unsigned char *output, + unsigned char tag[16] ); + +/** + * \brief This function performs a complete ChaCha20-Poly1305 + * authenticated decryption with the previously-set key. + * + * \note Before using this function, you must set the key with + * \c mbedtls_chachapoly_setkey(). + * + * \param ctx The ChaCha20-Poly1305 context to use (holds the key). + * \param length The length (in bytes) of the data to decrypt. + * \param nonce The 96-bit (12 bytes) nonce/IV to use. + * \param aad The buffer containing the additional authenticated data (AAD). + * This pointer can be NULL if aad_len == 0. + * \param aad_len The length (in bytes) of the AAD data to process. + * \param tag The buffer holding the authentication tag. + * \param input The buffer containing the data to decrypt. + * This pointer can be NULL if ilen == 0. + * \param output The buffer to where the decrypted data is written. + * This pointer can be NULL if ilen == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if one or more of the required parameters are NULL. + * \return #MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED + * if the data was not authentic. + */ +int mbedtls_chachapoly_auth_decrypt( mbedtls_chachapoly_context *ctx, + size_t length, + const unsigned char nonce[12], + const unsigned char *aad, + size_t aad_len, + const unsigned char tag[16], + const unsigned char *input, + unsigned char *output ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief The ChaCha20-Poly1305 checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_chachapoly_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_CHACHAPOLY_H */ diff --git a/tools/sdk/include/mbedtls/mbedtls/check_config.h b/tools/sdk/include/mbedtls/mbedtls/check_config.h index be803329..9e6bb8a4 100644 --- a/tools/sdk/include/mbedtls/mbedtls/check_config.h +++ b/tools/sdk/include/mbedtls/mbedtls/check_config.h @@ -4,7 +4,7 @@ * \brief Consistency checks for configuration options */ /* - * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -87,6 +87,11 @@ #error "MBEDTLS_CMAC_C defined, but not all prerequisites" #endif +#if defined(MBEDTLS_NIST_KW_C) && \ + ( !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CIPHER_C) ) +#error "MBEDTLS_NIST_KW_C defined, but not all prerequisites" +#endif + #if defined(MBEDTLS_ECDH_C) && !defined(MBEDTLS_ECP_C) #error "MBEDTLS_ECDH_C defined, but not all prerequisites" #endif @@ -191,6 +196,10 @@ #error "MBEDTLS_HAVEGE_C defined, but not all prerequisites" #endif +#if defined(MBEDTLS_HKDF_C) && !defined(MBEDTLS_MD_C) +#error "MBEDTLS_HKDF_C defined, but not all prerequisites" +#endif + #if defined(MBEDTLS_HMAC_DRBG_C) && !defined(MBEDTLS_MD_C) #error "MBEDTLS_HMAC_DRBG_C defined, but not all prerequisites" #endif diff --git a/tools/sdk/include/mbedtls/mbedtls/cipher.h b/tools/sdk/include/mbedtls/mbedtls/cipher.h index 3ee2ab7d..ea0ce983 100644 --- a/tools/sdk/include/mbedtls/mbedtls/cipher.h +++ b/tools/sdk/include/mbedtls/mbedtls/cipher.h @@ -37,7 +37,7 @@ #include -#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) +#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) || defined(MBEDTLS_CHACHAPOLY_C) #define MBEDTLS_CIPHER_MODE_AEAD #endif @@ -45,7 +45,7 @@ #define MBEDTLS_CIPHER_MODE_WITH_PADDING #endif -#if defined(MBEDTLS_ARC4_C) +#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) #define MBEDTLS_CIPHER_MODE_STREAM #endif @@ -86,6 +86,8 @@ typedef enum { MBEDTLS_CIPHER_ID_CAMELLIA, /**< The Camellia cipher. */ MBEDTLS_CIPHER_ID_BLOWFISH, /**< The Blowfish cipher. */ MBEDTLS_CIPHER_ID_ARC4, /**< The RC4 cipher. */ + MBEDTLS_CIPHER_ID_ARIA, /**< The Aria cipher. */ + MBEDTLS_CIPHER_ID_CHACHA20, /**< The ChaCha20 cipher. */ } mbedtls_cipher_id_t; /** @@ -145,6 +147,31 @@ typedef enum { MBEDTLS_CIPHER_CAMELLIA_128_CCM, /**< Camellia cipher with 128-bit CCM mode. */ MBEDTLS_CIPHER_CAMELLIA_192_CCM, /**< Camellia cipher with 192-bit CCM mode. */ MBEDTLS_CIPHER_CAMELLIA_256_CCM, /**< Camellia cipher with 256-bit CCM mode. */ + MBEDTLS_CIPHER_ARIA_128_ECB, /**< Aria cipher with 128-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_192_ECB, /**< Aria cipher with 192-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_256_ECB, /**< Aria cipher with 256-bit key and ECB mode. */ + MBEDTLS_CIPHER_ARIA_128_CBC, /**< Aria cipher with 128-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_192_CBC, /**< Aria cipher with 192-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_256_CBC, /**< Aria cipher with 256-bit key and CBC mode. */ + MBEDTLS_CIPHER_ARIA_128_CFB128, /**< Aria cipher with 128-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_192_CFB128, /**< Aria cipher with 192-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_256_CFB128, /**< Aria cipher with 256-bit key and CFB-128 mode. */ + MBEDTLS_CIPHER_ARIA_128_CTR, /**< Aria cipher with 128-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_192_CTR, /**< Aria cipher with 192-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_256_CTR, /**< Aria cipher with 256-bit key and CTR mode. */ + MBEDTLS_CIPHER_ARIA_128_GCM, /**< Aria cipher with 128-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_192_GCM, /**< Aria cipher with 192-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_256_GCM, /**< Aria cipher with 256-bit key and GCM mode. */ + MBEDTLS_CIPHER_ARIA_128_CCM, /**< Aria cipher with 128-bit key and CCM mode. */ + MBEDTLS_CIPHER_ARIA_192_CCM, /**< Aria cipher with 192-bit key and CCM mode. */ + MBEDTLS_CIPHER_ARIA_256_CCM, /**< Aria cipher with 256-bit key and CCM mode. */ + MBEDTLS_CIPHER_AES_128_OFB, /**< AES 128-bit cipher in OFB mode. */ + MBEDTLS_CIPHER_AES_192_OFB, /**< AES 192-bit cipher in OFB mode. */ + MBEDTLS_CIPHER_AES_256_OFB, /**< AES 256-bit cipher in OFB mode. */ + MBEDTLS_CIPHER_AES_128_XTS, /**< AES 128-bit cipher in XTS block mode. */ + MBEDTLS_CIPHER_AES_256_XTS, /**< AES 256-bit cipher in XTS block mode. */ + MBEDTLS_CIPHER_CHACHA20, /**< ChaCha20 stream cipher. */ + MBEDTLS_CIPHER_CHACHA20_POLY1305, /**< ChaCha20-Poly1305 AEAD cipher. */ } mbedtls_cipher_type_t; /** Supported cipher modes. */ @@ -153,11 +180,13 @@ typedef enum { MBEDTLS_MODE_ECB, /**< The ECB cipher mode. */ MBEDTLS_MODE_CBC, /**< The CBC cipher mode. */ MBEDTLS_MODE_CFB, /**< The CFB cipher mode. */ - MBEDTLS_MODE_OFB, /**< The OFB cipher mode - unsupported. */ + MBEDTLS_MODE_OFB, /**< The OFB cipher mode. */ MBEDTLS_MODE_CTR, /**< The CTR cipher mode. */ MBEDTLS_MODE_GCM, /**< The GCM cipher mode. */ MBEDTLS_MODE_STREAM, /**< The stream cipher mode. */ MBEDTLS_MODE_CCM, /**< The CCM cipher mode. */ + MBEDTLS_MODE_XTS, /**< The XTS cipher mode. */ + MBEDTLS_MODE_CHACHAPOLY, /**< The ChaCha-Poly cipher mode. */ } mbedtls_cipher_mode_t; /** Supported cipher padding types. */ @@ -273,7 +302,8 @@ typedef struct { /** Number of Bytes that have not been processed yet. */ size_t unprocessed_len; - /** Current IV or NONCE_COUNTER for CTR-mode. */ + /** Current IV or NONCE_COUNTER for CTR-mode, data unit (or sector) number + * for XTS-mode. */ unsigned char iv[MBEDTLS_MAX_IV_LENGTH]; /** IV size in Bytes, for ciphers with variable-length IVs. */ @@ -560,11 +590,11 @@ int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx, */ int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx ); -#if defined(MBEDTLS_GCM_C) +#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C) /** * \brief This function adds additional data for AEAD ciphers. - * Only supported with GCM. Must be called - * exactly once, after mbedtls_cipher_reset(). + * Currently supported with GCM and ChaCha20+Poly1305. + * Must be called exactly once, after mbedtls_cipher_reset(). * * \param ctx The generic cipher context. * \param ad The additional data to use. @@ -575,7 +605,7 @@ int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx ); */ int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx, const unsigned char *ad, size_t ad_len ); -#endif /* MBEDTLS_GCM_C */ +#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */ /** * \brief The generic cipher update function. It encrypts or @@ -633,10 +663,10 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx, unsigned char *output, size_t *olen ); -#if defined(MBEDTLS_GCM_C) +#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C) /** * \brief This function writes a tag for AEAD ciphers. - * Only supported with GCM. + * Currently supported with GCM and ChaCha20+Poly1305. * Must be called after mbedtls_cipher_finish(). * * \param ctx The generic cipher context. @@ -651,7 +681,7 @@ int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx, /** * \brief This function checks the tag for AEAD ciphers. - * Only supported with GCM. + * Currently supported with GCM and ChaCha20+Poly1305. * Must be called after mbedtls_cipher_finish(). * * \param ctx The generic cipher context. @@ -663,7 +693,7 @@ int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx, */ int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx, const unsigned char *tag, size_t tag_len ); -#endif /* MBEDTLS_GCM_C */ +#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */ /** * \brief The generic all-in-one encryption/decryption function, diff --git a/tools/sdk/include/mbedtls/mbedtls/cipher_internal.h b/tools/sdk/include/mbedtls/mbedtls/cipher_internal.h index 969ff9cc..c6def0be 100644 --- a/tools/sdk/include/mbedtls/mbedtls/cipher_internal.h +++ b/tools/sdk/include/mbedtls/mbedtls/cipher_internal.h @@ -64,6 +64,14 @@ struct mbedtls_cipher_base_t unsigned char *output ); #endif +#if defined(MBEDTLS_CIPHER_MODE_OFB) + /** Encrypt using OFB (Full length) */ + int (*ofb_func)( void *ctx, size_t length, size_t *iv_off, + unsigned char *iv, + const unsigned char *input, + unsigned char *output ); +#endif + #if defined(MBEDTLS_CIPHER_MODE_CTR) /** Encrypt using CTR */ int (*ctr_func)( void *ctx, size_t length, size_t *nc_off, @@ -71,6 +79,13 @@ struct mbedtls_cipher_base_t const unsigned char *input, unsigned char *output ); #endif +#if defined(MBEDTLS_CIPHER_MODE_XTS) + /** Encrypt or decrypt using XTS. */ + int (*xts_func)( void *ctx, mbedtls_operation_t mode, size_t length, + const unsigned char data_unit[16], + const unsigned char *input, unsigned char *output ); +#endif + #if defined(MBEDTLS_CIPHER_MODE_STREAM) /** Encrypt using STREAM */ int (*stream_func)( void *ctx, size_t length, diff --git a/tools/sdk/include/mbedtls/mbedtls/cmac.h b/tools/sdk/include/mbedtls/mbedtls/cmac.h index 913c05f8..a4fd5525 100644 --- a/tools/sdk/include/mbedtls/mbedtls/cmac.h +++ b/tools/sdk/include/mbedtls/mbedtls/cmac.h @@ -28,7 +28,7 @@ #ifndef MBEDTLS_CMAC_H #define MBEDTLS_CMAC_H -#include "mbedtls/cipher.h" +#include "cipher.h" #ifdef __cplusplus extern "C" { diff --git a/tools/sdk/include/mbedtls/mbedtls/compat-1.3.h b/tools/sdk/include/mbedtls/mbedtls/compat-1.3.h index 600a0f15..213b6914 100644 --- a/tools/sdk/include/mbedtls/mbedtls/compat-1.3.h +++ b/tools/sdk/include/mbedtls/mbedtls/compat-1.3.h @@ -1378,7 +1378,8 @@ #define SSL_ANTI_REPLAY_ENABLED MBEDTLS_SSL_ANTI_REPLAY_ENABLED #define SSL_ARC4_DISABLED MBEDTLS_SSL_ARC4_DISABLED #define SSL_ARC4_ENABLED MBEDTLS_SSL_ARC4_ENABLED -#define SSL_BUFFER_LEN MBEDTLS_SSL_BUFFER_LEN +#define SSL_BUFFER_LEN ( ( ( MBEDTLS_SSL_IN_BUFFER_LEN ) < ( MBEDTLS_SSL_OUT_BUFFER_LEN ) ) \ + ? ( MBEDTLS_SSL_IN_BUFFER_LEN ) : ( MBEDTLS_SSL_OUT_BUFFER_LEN ) ) #define SSL_CACHE_DEFAULT_MAX_ENTRIES MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES #define SSL_CACHE_DEFAULT_TIMEOUT MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT #define SSL_CBC_RECORD_SPLITTING_DISABLED MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED diff --git a/tools/sdk/include/mbedtls/mbedtls/config.h b/tools/sdk/include/mbedtls/mbedtls/config.h index 9585e692..70820be5 100644 --- a/tools/sdk/include/mbedtls/mbedtls/config.h +++ b/tools/sdk/include/mbedtls/mbedtls/config.h @@ -8,7 +8,7 @@ * memory footprint. */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -48,10 +48,14 @@ * Requires support for asm() in compiler. * * Used in: + * library/aria.c * library/timing.c - * library/padlock.c * include/mbedtls/bn_mul.h * + * Required by: + * MBEDTLS_AESNI_C + * MBEDTLS_PADLOCK_C + * * Comment to disable the use of assembly code. */ #define MBEDTLS_HAVE_ASM @@ -84,6 +88,28 @@ */ //#define MBEDTLS_NO_UDBL_DIVISION +/** + * \def MBEDTLS_NO_64BIT_MULTIPLICATION + * + * The platform lacks support for 32x32 -> 64-bit multiplication. + * + * Used in: + * library/poly1305.c + * + * Some parts of the library may use multiplication of two unsigned 32-bit + * operands with a 64-bit result in order to speed up computations. On some + * platforms, this is not available in hardware and has to be implemented in + * software, usually in a library provided by the toolchain. + * + * Sometimes it is not desirable to have to link to that library. This option + * removes the dependency of that library on platforms that lack a hardware + * 64-bit multiplier by embedding a software implementation in Mbed TLS. + * + * Note that depending on the compiler, this may decrease performance compared + * to using the library function provided by the toolchain. + */ +//#define MBEDTLS_NO_64BIT_MULTIPLICATION + /** * \def MBEDTLS_HAVE_SSE2 * @@ -271,23 +297,29 @@ */ //#define MBEDTLS_AES_ALT //#define MBEDTLS_ARC4_ALT +//#define MBEDTLS_ARIA_ALT //#define MBEDTLS_BLOWFISH_ALT //#define MBEDTLS_CAMELLIA_ALT //#define MBEDTLS_CCM_ALT +//#define MBEDTLS_CHACHA20_ALT +//#define MBEDTLS_CHACHAPOLY_ALT //#define MBEDTLS_CMAC_ALT //#define MBEDTLS_DES_ALT //#define MBEDTLS_DHM_ALT //#define MBEDTLS_ECJPAKE_ALT //#define MBEDTLS_GCM_ALT +//#define MBEDTLS_NIST_KW_ALT //#define MBEDTLS_MD2_ALT //#define MBEDTLS_MD4_ALT //#define MBEDTLS_MD5_ALT +//#define MBEDTLS_POLY1305_ALT //#define MBEDTLS_RIPEMD160_ALT //#define MBEDTLS_RSA_ALT //#define MBEDTLS_SHA1_ALT //#define MBEDTLS_SHA256_ALT //#define MBEDTLS_SHA512_ALT //#define MBEDTLS_XTEA_ALT + /* * When replacing the elliptic curve module, pleace consider, that it is * implemented with two .c files: @@ -509,6 +541,20 @@ */ #define MBEDTLS_CIPHER_MODE_CTR +/** + * \def MBEDTLS_CIPHER_MODE_OFB + * + * Enable Output Feedback mode (OFB) for symmetric ciphers. + */ +#define MBEDTLS_CIPHER_MODE_OFB + +/** + * \def MBEDTLS_CIPHER_MODE_XTS + * + * Enable Xor-encrypt-xor with ciphertext stealing mode (XTS) for AES. + */ +#define MBEDTLS_CIPHER_MODE_XTS + /** * \def MBEDTLS_CIPHER_NULL_CIPHER * @@ -1128,6 +1174,17 @@ */ #define MBEDTLS_SSL_ALL_ALERT_MESSAGES +/** + * \def MBEDTLS_SSL_ASYNC_PRIVATE + * + * Enable asynchronous external private key operations in SSL. This allows + * you to configure an SSL connection to call an external cryptographic + * module to perform private key operations instead of performing the + * operation inside the library. + * + */ +//#define MBEDTLS_SSL_ASYNC_PRIVATE + /** * \def MBEDTLS_SSL_DEBUG_ALL * @@ -1617,7 +1674,7 @@ * Enable the AES block cipher. * * Module: library/aes.c - * Caller: library/ssl_tls.c + * Caller: library/cipher.c * library/pem.c * library/ctr_drbg.c * @@ -1692,7 +1749,7 @@ * Enable the ARCFOUR stream cipher. * * Module: library/arc4.c - * Caller: library/ssl_tls.c + * Caller: library/cipher.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): @@ -1786,7 +1843,7 @@ * Enable the Camellia block cipher. * * Module: library/camellia.c - * Caller: library/ssl_tls.c + * Caller: library/cipher.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): @@ -1835,6 +1892,58 @@ */ #define MBEDTLS_CAMELLIA_C +/** + * \def MBEDTLS_ARIA_C + * + * Enable the ARIA block cipher. + * + * Module: library/aria.c + * Caller: library/cipher.c + * + * This module enables the following ciphersuites (if other requisites are + * enabled as well): + * + * MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 + * MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 + * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 + * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 + * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 + */ +//#define MBEDTLS_ARIA_C + /** * \def MBEDTLS_CCM_C * @@ -1861,6 +1970,26 @@ */ #define MBEDTLS_CERTS_C +/** + * \def MBEDTLS_CHACHA20_C + * + * Enable the ChaCha20 stream cipher. + * + * Module: library/chacha20.c + */ +#define MBEDTLS_CHACHA20_C + +/** + * \def MBEDTLS_CHACHAPOLY_C + * + * Enable the ChaCha20-Poly1305 AEAD algorithm. + * + * Module: library/chachapoly.c + * + * This module requires: MBEDTLS_CHACHA20_C, MBEDTLS_POLY1305_C + */ +#define MBEDTLS_CHACHAPOLY_C + /** * \def MBEDTLS_CIPHER_C * @@ -1921,7 +2050,7 @@ * * Module: library/des.c * Caller: library/pem.c - * library/ssl_tls.c + * library/cipher.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): @@ -2091,6 +2220,21 @@ */ //#define MBEDTLS_HAVEGE_C +/** + * \def MBEDTLS_HKDF_C + * + * Enable the HKDF algorithm (RFC 5869). + * + * Module: library/hkdf.c + * Caller: + * + * Requires: MBEDTLS_MD_C + * + * This module adds support for the Hashed Message Authentication Code + * (HMAC)-based key derivation function (HKDF). + */ +#define MBEDTLS_HKDF_C + /** * \def MBEDTLS_HMAC_DRBG_C * @@ -2105,6 +2249,19 @@ */ #define MBEDTLS_HMAC_DRBG_C +/** + * \def MBEDTLS_NIST_KW_C + * + * Enable the Key Wrapping mode for 128-bit block ciphers, + * as defined in NIST SP 800-38F. Only KW and KWP modes + * are supported. At the moment, only AES is approved by NIST. + * + * Module: library/nist_kw.c + * + * Requires: MBEDTLS_AES_C and MBEDTLS_CIPHER_C + */ +//#define MBEDTLS_NIST_KW_C + /** * \def MBEDTLS_MD_C * @@ -2388,6 +2545,16 @@ */ #define MBEDTLS_PLATFORM_C +/** + * \def MBEDTLS_POLY1305_C + * + * Enable the Poly1305 MAC algorithm. + * + * Module: library/poly1305.c + * Caller: library/chachapoly.c + */ +#define MBEDTLS_POLY1305_C + /** * \def MBEDTLS_RIPEMD160_C * @@ -2798,7 +2965,51 @@ //#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /**< Maximum entries in cache */ /* SSL options */ -//#define MBEDTLS_SSL_MAX_CONTENT_LEN 16384 /**< Maxium fragment length in bytes, determines the size of each of the two internal I/O buffers */ + +/** \def MBEDTLS_SSL_MAX_CONTENT_LEN + * + * Maximum fragment length in bytes. + * + * Determines the size of both the incoming and outgoing TLS I/O buffers. + * + * Uncommenting MBEDTLS_SSL_IN_CONTENT_LEN and/or MBEDTLS_SSL_OUT_CONTENT_LEN + * will override this length by setting maximum incoming and/or outgoing + * fragment length, respectively. + */ +//#define MBEDTLS_SSL_MAX_CONTENT_LEN 16384 + +/** \def MBEDTLS_SSL_IN_CONTENT_LEN + * + * Maximum incoming fragment length in bytes. + * + * Uncomment to set the size of the inward TLS buffer independently of the + * outward buffer. + */ +//#define MBEDTLS_SSL_IN_CONTENT_LEN 16384 + +/** \def MBEDTLS_SSL_OUT_CONTENT_LEN + * + * Maximum outgoing fragment length in bytes. + * + * Uncomment to set the size of the outward TLS buffer independently of the + * inward buffer. + * + * It is possible to save RAM by setting a smaller outward buffer, while keeping + * the default inward 16384 byte buffer to conform to the TLS specification. + * + * The minimum required outward buffer size is determined by the handshake + * protocol's usage. Handshaking will fail if the outward buffer is too small. + * The specific size requirement depends on the configured ciphers and any + * certificate data which is sent during the handshake. + * + * For absolute minimum RAM usage, it's best to enable + * MBEDTLS_SSL_MAX_FRAGMENT_LENGTH and reduce MBEDTLS_SSL_MAX_CONTENT_LEN. This + * reduces both incoming and outgoing buffer sizes. However this is only + * guaranteed if the other end of the connection also supports the TLS + * max_fragment_len extension. Otherwise the connection may fail. + */ +//#define MBEDTLS_SSL_OUT_CONTENT_LEN 16384 + //#define MBEDTLS_SSL_DEFAULT_TICKET_LIFETIME 86400 /**< Lifetime of session tickets (if enabled) */ //#define MBEDTLS_PSK_MAX_LEN 32 /**< Max size of TLS pre-shared keys, in bytes (default 256 bits) */ //#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */ @@ -2852,10 +3063,30 @@ */ #define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE +/** + * Uncomment the macro to let mbed TLS use your alternate implementation of + * mbedtls_platform_zeroize(). This replaces the default implementation in + * platform_util.c. + * + * mbedtls_platform_zeroize() is a widely used function across the library to + * zero a block of memory. The implementation is expected to be secure in the + * sense that it has been written to prevent the compiler from removing calls + * to mbedtls_platform_zeroize() as part of redundant code elimination + * optimizations. However, it is difficult to guarantee that calls to + * mbedtls_platform_zeroize() will not be optimized by the compiler as older + * versions of the C language standards do not provide a secure implementation + * of memset(). Therefore, MBEDTLS_PLATFORM_ZEROIZE_ALT enables users to + * configure their own implementation of mbedtls_platform_zeroize(), for + * example by using directives specific to their compiler, features from newer + * C standards (e.g using memset_s() in C11) or calling a secure memset() from + * their system (e.g explicit_bzero() in BSD). + */ +//#define MBEDTLS_PLATFORM_ZEROIZE_ALT + /* \} name SECTION: Customisation configuration options */ /* Target and application specific configurations */ -//#define YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE "mbedtls/target_config.h" +//#define YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE "target_config.h" #if defined(TARGET_LIKE_MBED) && defined(YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE) #include YOTTA_CFG_MBEDTLS_TARGET_CONFIG_FILE diff --git a/tools/sdk/include/mbedtls/mbedtls/ctr_drbg.h b/tools/sdk/include/mbedtls/mbedtls/ctr_drbg.h index dcbc0479..3835d729 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ctr_drbg.h +++ b/tools/sdk/include/mbedtls/mbedtls/ctr_drbg.h @@ -36,7 +36,7 @@ #include "aes.h" #if defined(MBEDTLS_THREADING_C) -#include "mbedtls/threading.h" +#include "threading.h" #endif #define MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED -0x0034 /**< The entropy source failed. */ diff --git a/tools/sdk/include/mbedtls/mbedtls/dhm.h b/tools/sdk/include/mbedtls/mbedtls/dhm.h index f848e221..75317a8e 100644 --- a/tools/sdk/include/mbedtls/mbedtls/dhm.h +++ b/tools/sdk/include/mbedtls/mbedtls/dhm.h @@ -1,12 +1,12 @@ /** * \file dhm.h * - * \brief This file contains Diffie-Hellman-Merkle (DHM) key exchange + * \brief This file contains Diffie-Hellman-Merkle (DHM) key exchange * definitions and functions. * * Diffie-Hellman-Merkle (DHM) key exchange is defined in - * RFC-2631: Diffie-Hellman Key Agreement Method and - * Public-Key Cryptography Standards (PKCS) #3: Diffie + * RFC-2631: Diffie-Hellman Key Agreement Method and + * Public-Key Cryptography Standards (PKCS) #3: Diffie * Hellman Key Agreement Standard. * * RFC-3526: More Modular Exponential (MODP) Diffie-Hellman groups for diff --git a/tools/sdk/include/mbedtls/mbedtls/ecdh.h b/tools/sdk/include/mbedtls/mbedtls/ecdh.h index 922f029d..5fdf55a8 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ecdh.h +++ b/tools/sdk/include/mbedtls/mbedtls/ecdh.h @@ -2,8 +2,8 @@ * \file ecdh.h * * \brief This file contains ECDH definitions and functions. - * - * The Elliptic Curve Diffie-Hellman (ECDH) protocol is an anonymous + * + * The Elliptic Curve Diffie-Hellman (ECDH) protocol is an anonymous * key agreement protocol allowing two parties to establish a shared * secret over an insecure channel. Each party must have an * elliptic-curve public–private key pair. diff --git a/tools/sdk/include/mbedtls/mbedtls/ecp_internal.h b/tools/sdk/include/mbedtls/mbedtls/ecp_internal.h index 8a6d517e..18040697 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ecp_internal.h +++ b/tools/sdk/include/mbedtls/mbedtls/ecp_internal.h @@ -48,7 +48,7 @@ * [6] Digital Signature Standard (DSS), FIPS 186-4. * * - * [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer + * [7] Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer * Security (TLS), RFC 4492. * * diff --git a/tools/sdk/include/mbedtls/mbedtls/entropy.h b/tools/sdk/include/mbedtls/mbedtls/entropy.h index fcb4d025..a5cb05a5 100644 --- a/tools/sdk/include/mbedtls/mbedtls/entropy.h +++ b/tools/sdk/include/mbedtls/mbedtls/entropy.h @@ -166,7 +166,7 @@ void mbedtls_entropy_free( mbedtls_entropy_context *ctx ); * \param threshold Minimum required from source before entropy is released * ( with mbedtls_entropy_func() ) (in bytes) * \param strong MBEDTLS_ENTROPY_SOURCE_STRONG or - * MBEDTSL_ENTROPY_SOURCE_WEAK. + * MBEDTLS_ENTROPY_SOURCE_WEAK. * At least one strong source needs to be added. * Weaker sources (such as the cycle counter) can be used as * a complement. diff --git a/tools/sdk/include/mbedtls/mbedtls/error.h b/tools/sdk/include/mbedtls/mbedtls/error.h index 8b4d3a87..6b82d4fb 100644 --- a/tools/sdk/include/mbedtls/mbedtls/error.h +++ b/tools/sdk/include/mbedtls/mbedtls/error.h @@ -4,7 +4,7 @@ * \brief Error to string translation */ /* - * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * Copyright (C) 2006-2018, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may @@ -53,7 +53,7 @@ * GCM 3 0x0012-0x0014 0x0013-0x0013 * BLOWFISH 3 0x0016-0x0018 0x0017-0x0017 * THREADING 3 0x001A-0x001E - * AES 4 0x0020-0x0022 0x0023-0x0025 + * AES 5 0x0020-0x0022 0x0021-0x0025 * CAMELLIA 3 0x0024-0x0026 0x0027-0x0027 * XTEA 2 0x0028-0x0028 0x0029-0x0029 * BASE64 2 0x002A-0x002C @@ -62,7 +62,8 @@ * DES 2 0x0032-0x0032 0x0033-0x0033 * CTR_DBRG 4 0x0034-0x003A * ENTROPY 3 0x003C-0x0040 0x003D-0x003F - * NET 11 0x0042-0x0052 0x0043-0x0045 + * NET 13 0x0042-0x0052 0x0043-0x0049 + * ARIA 4 0x0058-0x005E * ASN1 7 0x0060-0x006C * CMAC 1 0x007A-0x007A * PBKDF2 1 0x007C-0x007C @@ -76,6 +77,9 @@ * SHA1 1 0x0035-0x0035 * SHA256 1 0x0037-0x0037 * SHA512 1 0x0039-0x0039 + * CHACHA20 3 0x0051-0x0055 + * POLY1305 3 0x0057-0x005B + * CHACHAPOLY 2 0x0054-0x0056 * * High-level module nr (3 bits - 0x0...-0x7...) * Name ID Nr of Errors @@ -88,8 +92,9 @@ * RSA 4 11 * ECP 4 9 (Started from top) * MD 5 5 + * HKDF 5 1 (Started from top) * CIPHER 6 8 - * SSL 6 17 (Started from top) + * SSL 6 22 (Started from top) * SSL 7 31 * * Module dependent error code (5 bits 0x.00.-0x.F8.) diff --git a/tools/sdk/include/mbedtls/mbedtls/gcm.h b/tools/sdk/include/mbedtls/mbedtls/gcm.h index 3c220331..87535ab9 100644 --- a/tools/sdk/include/mbedtls/mbedtls/gcm.h +++ b/tools/sdk/include/mbedtls/mbedtls/gcm.h @@ -113,21 +113,41 @@ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx, * the same as input buffer. If the buffers overlap, the output * buffer must trail at least 8 Bytes behind the input buffer. * + * \warning When this function performs a decryption, it outputs the + * authentication tag and does not verify that the data is + * authentic. You should use this function to perform encryption + * only. For decryption, use mbedtls_gcm_auth_decrypt() instead. + * * \param ctx The GCM context to use for encryption or decryption. - * \param mode The operation to perform: #MBEDTLS_GCM_ENCRYPT or - * #MBEDTLS_GCM_DECRYPT. - * \param length The length of the input data. This must be a multiple of - * 16 except in the last call before mbedtls_gcm_finish(). + * \param mode The operation to perform: + * - #MBEDTLS_GCM_ENCRYPT to perform authenticated encryption. + * The ciphertext is written to \p output and the + * authentication tag is written to \p tag. + * - #MBEDTLS_GCM_DECRYPT to perform decryption. + * The plaintext is written to \p output and the + * authentication tag is written to \p tag. + * Note that this mode is not recommended, because it does + * not verify the authenticity of the data. For this reason, + * you should use mbedtls_gcm_auth_decrypt() instead of + * calling this function in decryption mode. + * \param length The length of the input data, which is equal to the length + * of the output data. * \param iv The initialization vector. * \param iv_len The length of the IV. * \param add The buffer holding the additional data. * \param add_len The length of the additional data. - * \param input The buffer holding the input data. - * \param output The buffer for holding the output data. + * \param input The buffer holding the input data. Its size is \b length. + * \param output The buffer for holding the output data. It must have room + * for \b length bytes. * \param tag_len The length of the tag to generate. * \param tag The buffer for holding the tag. * - * \return \c 0 on success. + * \return \c 0 if the encryption or decryption was performed + * successfully. Note that in #MBEDTLS_GCM_DECRYPT mode, + * this does not indicate that the data is authentic. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid. + * \return #MBEDTLS_ERR_GCM_HW_ACCEL_FAILED or a cipher-specific + * error code if the encryption or decryption failed. */ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, int mode, @@ -150,19 +170,23 @@ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, * must trail at least 8 Bytes behind the input buffer. * * \param ctx The GCM context. - * \param length The length of the input data. This must be a multiple - * of 16 except in the last call before mbedtls_gcm_finish(). + * \param length The length of the ciphertext to decrypt, which is also + * the length of the decrypted plaintext. * \param iv The initialization vector. * \param iv_len The length of the IV. * \param add The buffer holding the additional data. * \param add_len The length of the additional data. - * \param tag The buffer holding the tag. - * \param tag_len The length of the tag. - * \param input The buffer holding the input data. - * \param output The buffer for holding the output data. + * \param tag The buffer holding the tag to verify. + * \param tag_len The length of the tag to verify. + * \param input The buffer holding the ciphertext. Its size is \b length. + * \param output The buffer for holding the decrypted plaintext. It must + * have room for \b length bytes. * - * \return 0 if successful and authenticated. - * \return #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match. + * \return \c 0 if successful and authenticated. + * \return #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match. + * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths are not valid. + * \return #MBEDTLS_ERR_GCM_HW_ACCEL_FAILED or a cipher-specific + * error code if the decryption failed. */ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, size_t length, diff --git a/tools/sdk/include/mbedtls/mbedtls/hkdf.h b/tools/sdk/include/mbedtls/mbedtls/hkdf.h new file mode 100644 index 00000000..6833e727 --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/hkdf.h @@ -0,0 +1,125 @@ +/** + * \file hkdf.h + * + * \brief This file contains the HKDF interface. + * + * The HMAC-based Extract-and-Expand Key Derivation Function (HKDF) is + * specified by RFC 5869. + */ +/* + * Copyright (C) 2016-2018, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_HKDF_H +#define MBEDTLS_HKDF_H + +#include "md.h" + +/** + * \name HKDF Error codes + * \{ + */ +#define MBEDTLS_ERR_HKDF_BAD_INPUT_DATA -0x5F80 /**< Bad input parameters to function. */ +/* \} name */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief This is the HMAC-based Extract-and-Expand Key Derivation Function + * (HKDF). + * + * \param md A hash function; md.size denotes the length of the hash + * function output in bytes. + * \param salt An optional salt value (a non-secret random value); + * if the salt is not provided, a string of all zeros of + * md.size length is used as the salt. + * \param salt_len The length in bytes of the optional \p salt. + * \param ikm The input keying material. + * \param ikm_len The length in bytes of \p ikm. + * \param info An optional context and application specific information + * string. This can be a zero-length string. + * \param info_len The length of \p info in bytes. + * \param okm The output keying material of \p okm_len bytes. + * \param okm_len The length of the output keying material in bytes. This + * must be less than or equal to 255 * md.size bytes. + * + * \return 0 on success. + * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid. + * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying + * MD layer. + */ +int mbedtls_hkdf( const mbedtls_md_info_t *md, const unsigned char *salt, + size_t salt_len, const unsigned char *ikm, size_t ikm_len, + const unsigned char *info, size_t info_len, + unsigned char *okm, size_t okm_len ); + +/** + * \brief Take the input keying material \p ikm and extract from it a + * fixed-length pseudorandom key \p prk. + * + * \param md A hash function; md.size denotes the length of the + * hash function output in bytes. + * \param salt An optional salt value (a non-secret random value); + * if the salt is not provided, a string of all zeros + * of md.size length is used as the salt. + * \param salt_len The length in bytes of the optional \p salt. + * \param ikm The input keying material. + * \param ikm_len The length in bytes of \p ikm. + * \param[out] prk A pseudorandom key of at least md.size bytes. + * + * \return 0 on success. + * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid. + * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying + * MD layer. + */ +int mbedtls_hkdf_extract( const mbedtls_md_info_t *md, + const unsigned char *salt, size_t salt_len, + const unsigned char *ikm, size_t ikm_len, + unsigned char *prk ); + +/** + * \brief Expand the supplied \p prk into several additional pseudorandom + * keys, which is the output of the HKDF. + * + * \param md A hash function; md.size denotes the length of the hash + * function output in bytes. + * \param prk A pseudorandom key of at least md.size bytes. \p prk is usually, + * the output from the HKDF extract step. + * \param prk_len The length in bytes of \p prk. + * \param info An optional context and application specific information + * string. This can be a zero-length string. + * \param info_len The length of \p info in bytes. + * \param okm The output keying material of \p okm_len bytes. + * \param okm_len The length of the output keying material in bytes. This + * must be less than or equal to 255 * md.size bytes. + * + * \return 0 on success. + * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid. + * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying + * MD layer. + */ +int mbedtls_hkdf_expand( const mbedtls_md_info_t *md, const unsigned char *prk, + size_t prk_len, const unsigned char *info, + size_t info_len, unsigned char *okm, size_t okm_len ); + +#ifdef __cplusplus +} +#endif + +#endif /* hkdf.h */ diff --git a/tools/sdk/include/mbedtls/mbedtls/hmac_drbg.h b/tools/sdk/include/mbedtls/mbedtls/hmac_drbg.h index e0821cf7..2608de85 100644 --- a/tools/sdk/include/mbedtls/mbedtls/hmac_drbg.h +++ b/tools/sdk/include/mbedtls/mbedtls/hmac_drbg.h @@ -27,7 +27,7 @@ #include "md.h" #if defined(MBEDTLS_THREADING_C) -#include "mbedtls/threading.h" +#include "threading.h" #endif /* diff --git a/tools/sdk/include/mbedtls/mbedtls/net.h b/tools/sdk/include/mbedtls/mbedtls/net.h index 28ae8217..6c13b53f 100644 --- a/tools/sdk/include/mbedtls/mbedtls/net.h +++ b/tools/sdk/include/mbedtls/mbedtls/net.h @@ -1,7 +1,7 @@ /** * \file net.h * - * \brief Deprecated header file that includes mbedtls/net_sockets.h + * \brief Deprecated header file that includes net_sockets.h * * \deprecated Superseded by mbedtls/net_sockets.h */ @@ -25,7 +25,7 @@ */ #if !defined(MBEDTLS_DEPRECATED_REMOVED) -#include "mbedtls/net_sockets.h" +#include "net_sockets.h" #if defined(MBEDTLS_DEPRECATED_WARNING) #warning "Deprecated header file: Superseded by mbedtls/net_sockets.h" #endif /* MBEDTLS_DEPRECATED_WARNING */ diff --git a/tools/sdk/include/mbedtls/mbedtls/net_sockets.h b/tools/sdk/include/mbedtls/mbedtls/net_sockets.h index 0f9b31eb..9f07eeb4 100644 --- a/tools/sdk/include/mbedtls/mbedtls/net_sockets.h +++ b/tools/sdk/include/mbedtls/mbedtls/net_sockets.h @@ -1,7 +1,23 @@ /** * \file net_sockets.h * - * \brief Network communication functions + * \brief Network sockets abstraction layer to integrate Mbed TLS into a + * BSD-style sockets API. + * + * The network sockets module provides an example integration of the + * Mbed TLS library into a BSD sockets implementation. The module is + * intended to be an example of how Mbed TLS can be integrated into a + * networking stack, as well as to be Mbed TLS's network integration + * for its supported platforms. + * + * The module is intended only to be used with the Mbed TLS library and + * is not intended to be used by third party application software + * directly. + * + * The supported platforms are as follows: + * * Microsoft Windows and Windows CE + * * POSIX/Unix platforms including Linux, OS X + * */ /* * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved diff --git a/tools/sdk/include/mbedtls/mbedtls/nist_kw.h b/tools/sdk/include/mbedtls/mbedtls/nist_kw.h new file mode 100644 index 00000000..5a0f656a --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/nist_kw.h @@ -0,0 +1,178 @@ +/** + * \file nist_kw.h + * + * \brief This file provides an API for key wrapping (KW) and key wrapping with + * padding (KWP) as defined in NIST SP 800-38F. + * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf + * + * Key wrapping specifies a deterministic authenticated-encryption mode + * of operation, according to NIST SP 800-38F: Recommendation for + * Block Cipher Modes of Operation: Methods for Key Wrapping. Its + * purpose is to protect cryptographic keys. + * + * Its equivalent is RFC 3394 for KW, and RFC 5649 for KWP. + * https://tools.ietf.org/html/rfc3394 + * https://tools.ietf.org/html/rfc5649 + * + */ +/* + * Copyright (C) 2018, Arm Limited (or its affiliates), All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_NIST_KW_H +#define MBEDTLS_NIST_KW_H + +#include "cipher.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum +{ + MBEDTLS_KW_MODE_KW = 0, + MBEDTLS_KW_MODE_KWP = 1 +} mbedtls_nist_kw_mode_t; + +#if !defined(MBEDTLS_NIST_KW_ALT) +// Regular implementation +// + +/** + * \brief The key wrapping context-type definition. The key wrapping context is passed + * to the APIs called. + * + * \note The definition of this type may change in future library versions. + * Don't make any assumptions on this context! + */ +typedef struct { + mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ +} mbedtls_nist_kw_context; + +#else /* MBEDTLS_NIST_key wrapping_ALT */ +#include "nist_kw_alt.h" +#endif /* MBEDTLS_NIST_KW_ALT */ + +/** + * \brief This function initializes the specified key wrapping context + * to make references valid and prepare the context + * for mbedtls_nist_kw_setkey() or mbedtls_nist_kw_free(). + * + * \param ctx The key wrapping context to initialize. + * + */ +void mbedtls_nist_kw_init( mbedtls_nist_kw_context *ctx ); + +/** + * \brief This function initializes the key wrapping context set in the + * \p ctx parameter and sets the encryption key. + * + * \param ctx The key wrapping context. + * \param cipher The 128-bit block cipher to use. Only AES is supported. + * \param key The Key Encryption Key (KEK). + * \param keybits The KEK size in bits. This must be acceptable by the cipher. + * \param is_wrap Specify whether the operation within the context is wrapping or unwrapping + * + * \return \c 0 on success. + * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for any invalid input. + * \return \c MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE for 128-bit block ciphers + * which are not supported. + * \return cipher-specific error code on failure of the underlying cipher. + */ +int mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx, + mbedtls_cipher_id_t cipher, + const unsigned char *key, + unsigned int keybits, + const int is_wrap ); + +/** + * \brief This function releases and clears the specified key wrapping context + * and underlying cipher sub-context. + * + * \param ctx The key wrapping context to clear. + */ +void mbedtls_nist_kw_free( mbedtls_nist_kw_context *ctx ); + +/** + * \brief This function encrypts a buffer using key wrapping. + * + * \param ctx The key wrapping context to use for encryption. + * \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP) + * \param input The buffer holding the input data. + * \param in_len The length of the input data in Bytes. + * The input uses units of 8 Bytes called semiblocks. + *
    • For KW mode: a multiple of 8 bytes between 16 and 2^57-8 inclusive.
    • + *
    • For KWP mode: any length between 1 and 2^32-1 inclusive.
    + * \param[out] output The buffer holding the output data. + *
    • For KW mode: Must be at least 8 bytes larger than \p in_len.
    • + *
    • For KWP mode: Must be at least 8 bytes larger rounded up to a multiple of + * 8 bytes for KWP (15 bytes at most).
    + * \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure. + * \param[in] out_size The capacity of the output buffer. + * + * \return \c 0 on success. + * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length. + * \return cipher-specific error code on failure of the underlying cipher. + */ +int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode, + const unsigned char *input, size_t in_len, + unsigned char *output, size_t* out_len, size_t out_size ); + +/** + * \brief This function decrypts a buffer using key wrapping. + * + * \param ctx The key wrapping context to use for decryption. + * \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP) + * \param input The buffer holding the input data. + * \param in_len The length of the input data in Bytes. + * The input uses units of 8 Bytes called semiblocks. + * The input must be a multiple of semiblocks. + *
    • For KW mode: a multiple of 8 bytes between 24 and 2^57 inclusive.
    • + *
    • For KWP mode: a multiple of 8 bytes between 16 and 2^32 inclusive.
    + * \param[out] output The buffer holding the output data. + * The output buffer's minimal length is 8 bytes shorter than \p in_len. + * \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure. + * For KWP mode, the length could be up to 15 bytes shorter than \p in_len, + * depending on how much padding was added to the data. + * \param[in] out_size The capacity of the output buffer. + * + * \return \c 0 on success. + * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length. + * \return \c MBEDTLS_ERR_CIPHER_AUTH_FAILED for verification failure of the ciphertext. + * \return cipher-specific error code on failure of the underlying cipher. + */ +int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode, + const unsigned char *input, size_t in_len, + unsigned char *output, size_t* out_len, size_t out_size); + + +#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) +/** + * \brief The key wrapping checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_nist_kw_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_NIST_KW_H */ diff --git a/tools/sdk/include/mbedtls/mbedtls/oid.h b/tools/sdk/include/mbedtls/mbedtls/oid.h index 408645ec..f8255484 100644 --- a/tools/sdk/include/mbedtls/mbedtls/oid.h +++ b/tools/sdk/include/mbedtls/mbedtls/oid.h @@ -97,6 +97,8 @@ /* ISO arc for standard certificate and CRL extensions */ #define MBEDTLS_OID_ID_CE MBEDTLS_OID_ISO_CCITT_DS "\x1D" /**< id-ce OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 29} */ +#define MBEDTLS_OID_NIST_ALG MBEDTLS_OID_GOV "\x03\x04" /** { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) */ + /** * Private Internet Extensions * { iso(1) identified-organization(3) dod(6) internet(1) @@ -219,12 +221,12 @@ #define MBEDTLS_OID_DIGEST_ALG_MD4 MBEDTLS_OID_RSA_COMPANY "\x02\x04" /**< id-mbedtls_md4 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 4 } */ #define MBEDTLS_OID_DIGEST_ALG_MD5 MBEDTLS_OID_RSA_COMPANY "\x02\x05" /**< id-mbedtls_md5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 5 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA1 MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_SHA1 /**< id-mbedtls_sha1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } */ -#define MBEDTLS_OID_DIGEST_ALG_SHA224 MBEDTLS_OID_GOV "\x03\x04\x02\x04" /**< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */ -#define MBEDTLS_OID_DIGEST_ALG_SHA256 MBEDTLS_OID_GOV "\x03\x04\x02\x01" /**< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */ +#define MBEDTLS_OID_DIGEST_ALG_SHA224 MBEDTLS_OID_NIST_ALG "\x02\x04" /**< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */ +#define MBEDTLS_OID_DIGEST_ALG_SHA256 MBEDTLS_OID_NIST_ALG "\x02\x01" /**< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */ -#define MBEDTLS_OID_DIGEST_ALG_SHA384 MBEDTLS_OID_GOV "\x03\x04\x02\x02" /**< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */ +#define MBEDTLS_OID_DIGEST_ALG_SHA384 MBEDTLS_OID_NIST_ALG "\x02\x02" /**< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */ -#define MBEDTLS_OID_DIGEST_ALG_SHA512 MBEDTLS_OID_GOV "\x03\x04\x02\x03" /**< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */ +#define MBEDTLS_OID_DIGEST_ALG_SHA512 MBEDTLS_OID_NIST_ALG "\x02\x03" /**< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */ #define MBEDTLS_OID_HMAC_SHA1 MBEDTLS_OID_RSA_COMPANY "\x02\x07" /**< id-hmacWithSHA1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 7 } */ @@ -241,7 +243,20 @@ */ #define MBEDTLS_OID_DES_CBC MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_ALG "\x07" /**< desCBC OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 7 } */ #define MBEDTLS_OID_DES_EDE3_CBC MBEDTLS_OID_RSA_COMPANY "\x03\x07" /**< des-ede3-cbc OBJECT IDENTIFIER ::= { iso(1) member-body(2) -- us(840) rsadsi(113549) encryptionAlgorithm(3) 7 } */ +#define MBEDTLS_OID_AES MBEDTLS_OID_NIST_ALG "\x01" /** aes OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) 1 } */ +/* + * Key Wrapping algorithms + */ +/* + * RFC 5649 + */ +#define MBEDTLS_OID_AES128_KW MBEDTLS_OID_AES "\x05" /** id-aes128-wrap OBJECT IDENTIFIER ::= { aes 5 } */ +#define MBEDTLS_OID_AES128_KWP MBEDTLS_OID_AES "\x08" /** id-aes128-wrap-pad OBJECT IDENTIFIER ::= { aes 8 } */ +#define MBEDTLS_OID_AES192_KW MBEDTLS_OID_AES "\x19" /** id-aes192-wrap OBJECT IDENTIFIER ::= { aes 25 } */ +#define MBEDTLS_OID_AES192_KWP MBEDTLS_OID_AES "\x1c" /** id-aes192-wrap-pad OBJECT IDENTIFIER ::= { aes 28 } */ +#define MBEDTLS_OID_AES256_KW MBEDTLS_OID_AES "\x2d" /** id-aes256-wrap OBJECT IDENTIFIER ::= { aes 45 } */ +#define MBEDTLS_OID_AES256_KWP MBEDTLS_OID_AES "\x30" /** id-aes256-wrap-pad OBJECT IDENTIFIER ::= { aes 48 } */ /* * PKCS#5 OIDs */ diff --git a/tools/sdk/include/mbedtls/mbedtls/platform.h b/tools/sdk/include/mbedtls/mbedtls/platform.h index d50b266b..624cc642 100644 --- a/tools/sdk/include/mbedtls/mbedtls/platform.h +++ b/tools/sdk/include/mbedtls/mbedtls/platform.h @@ -9,7 +9,7 @@ * system services, making the library easier to port and embed. * Application developers and users of the library can provide their own * implementations of these functions, or implementations specific to - * their platform, which can be statically linked to the library or + * their platform, which can be statically linked to the library or * dynamically configured at runtime. */ /* @@ -40,7 +40,7 @@ #endif #if defined(MBEDTLS_HAVE_TIME) -#include "mbedtls/platform_time.h" +#include "platform_time.h" #endif #ifdef __cplusplus @@ -121,8 +121,8 @@ extern "C" { #else /* For size_t */ #include -extern void * (*mbedtls_calloc)( size_t n, size_t size ); -extern void (*mbedtls_free)( void *ptr ); +extern void *mbedtls_calloc( size_t n, size_t size ); +extern void mbedtls_free( void *ptr ); /** * \brief This function dynamically sets the memory-management @@ -223,7 +223,7 @@ int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n, #if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) #define mbedtls_snprintf MBEDTLS_PLATFORM_SNPRINTF_MACRO #else -#define mbedtls_snprintf snprintf +#define mbedtls_snprintf MBEDTLS_PLATFORM_STD_SNPRINTF #endif /* MBEDTLS_PLATFORM_SNPRINTF_MACRO */ #endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */ @@ -331,7 +331,7 @@ mbedtls_platform_context; * \note This function should be called before any other library functions. * * Its implementation is platform-specific, and unless - * platform-specific code is provided, it does nothing. + * platform-specific code is provided, it does nothing. * * \note The usage and necessity of this function is dependent on the platform. * diff --git a/tools/sdk/include/mbedtls/mbedtls/platform_util.h b/tools/sdk/include/mbedtls/mbedtls/platform_util.h new file mode 100644 index 00000000..84f0732e --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/platform_util.h @@ -0,0 +1,62 @@ +/** + * \file platform_util.h + * + * \brief Common and shared functions used by multiple modules in the Mbed TLS + * library. + */ +/* + * Copyright (C) 2018, Arm Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ +#ifndef MBEDTLS_PLATFORM_UTIL_H +#define MBEDTLS_PLATFORM_UTIL_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Securely zeroize a buffer + * + * The function is meant to wipe the data contained in a buffer so + * that it can no longer be recovered even if the program memory + * is later compromised. Call this function on sensitive data + * stored on the stack before returning from a function, and on + * sensitive data stored on the heap before freeing the heap + * object. + * + * It is extremely difficult to guarantee that calls to + * mbedtls_platform_zeroize() are not removed by aggressive + * compiler optimizations in a portable way. For this reason, Mbed + * TLS provides the configuration option + * MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure + * mbedtls_platform_zeroize() to use a suitable implementation for + * their platform and needs + * + * \param buf Buffer to be zeroized + * \param len Length of the buffer in bytes + * + */ +void mbedtls_platform_zeroize( void *buf, size_t len ); + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_PLATFORM_UTIL_H */ diff --git a/tools/sdk/include/mbedtls/mbedtls/poly1305.h b/tools/sdk/include/mbedtls/mbedtls/poly1305.h new file mode 100644 index 00000000..54b50abc --- /dev/null +++ b/tools/sdk/include/mbedtls/mbedtls/poly1305.h @@ -0,0 +1,181 @@ +/** + * \file poly1305.h + * + * \brief This file contains Poly1305 definitions and functions. + * + * Poly1305 is a one-time message authenticator that can be used to + * authenticate messages. Poly1305-AES was created by Daniel + * Bernstein https://cr.yp.to/mac/poly1305-20050329.pdf The generic + * Poly1305 algorithm (not tied to AES) was also standardized in RFC + * 7539. + * + * \author Daniel King + */ + +/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#ifndef MBEDTLS_POLY1305_H +#define MBEDTLS_POLY1305_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include +#include + +#define MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA -0x0057 /**< Invalid input parameter(s). */ +#define MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE -0x0059 /**< Feature not available. For example, s part of the API is not implemented. */ +#define MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED -0x005B /**< Poly1305 hardware accelerator failed. */ + +#ifdef __cplusplus +extern "C" { +#endif + +#if !defined(MBEDTLS_POLY1305_ALT) + +typedef struct +{ + uint32_t r[4]; /** The value for 'r' (low 128 bits of the key). */ + uint32_t s[4]; /** The value for 's' (high 128 bits of the key). */ + uint32_t acc[5]; /** The accumulator number. */ + uint8_t queue[16]; /** The current partial block of data. */ + size_t queue_len; /** The number of bytes stored in 'queue'. */ +} +mbedtls_poly1305_context; + +#else /* MBEDTLS_POLY1305_ALT */ +#include "poly1305_alt.h" +#endif /* MBEDTLS_POLY1305_ALT */ + +/** + * \brief This function initializes the specified Poly1305 context. + * + * It must be the first API called before using + * the context. + * + * It is usually followed by a call to + * \c mbedtls_poly1305_starts(), then one or more calls to + * \c mbedtls_poly1305_update(), then one call to + * \c mbedtls_poly1305_finish(), then finally + * \c mbedtls_poly1305_free(). + * + * \param ctx The Poly1305 context to initialize. + */ +void mbedtls_poly1305_init( mbedtls_poly1305_context *ctx ); + +/** + * \brief This function releases and clears the specified Poly1305 context. + * + * \param ctx The Poly1305 context to clear. + */ +void mbedtls_poly1305_free( mbedtls_poly1305_context *ctx ); + +/** + * \brief This function sets the one-time authentication key. + * + * \warning The key must be unique and unpredictable for each + * invocation of Poly1305. + * + * \param ctx The Poly1305 context to which the key should be bound. + * \param key The buffer containing the 256-bit key. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if ctx or key are NULL. + */ +int mbedtls_poly1305_starts( mbedtls_poly1305_context *ctx, + const unsigned char key[32] ); + +/** + * \brief This functions feeds an input buffer into an ongoing + * Poly1305 computation. + * + * It is called between \c mbedtls_cipher_poly1305_starts() and + * \c mbedtls_cipher_poly1305_finish(). + * It can be called repeatedly to process a stream of data. + * + * \param ctx The Poly1305 context to use for the Poly1305 operation. + * \param ilen The length of the input data (in bytes). Any value is accepted. + * \param input The buffer holding the input data. + * This pointer can be NULL if ilen == 0. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if ctx or input are NULL. + */ +int mbedtls_poly1305_update( mbedtls_poly1305_context *ctx, + const unsigned char *input, + size_t ilen ); + +/** + * \brief This function generates the Poly1305 Message + * Authentication Code (MAC). + * + * \param ctx The Poly1305 context to use for the Poly1305 operation. + * \param mac The buffer to where the MAC is written. Must be big enough + * to hold the 16-byte MAC. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if ctx or mac are NULL. + */ +int mbedtls_poly1305_finish( mbedtls_poly1305_context *ctx, + unsigned char mac[16] ); + +/** + * \brief This function calculates the Poly1305 MAC of the input + * buffer with the provided key. + * + * \warning The key must be unique and unpredictable for each + * invocation of Poly1305. + * + * \param key The buffer containing the 256-bit key. + * \param ilen The length of the input data (in bytes). Any value is accepted. + * \param input The buffer holding the input data. + * This pointer can be NULL if ilen == 0. + * \param mac The buffer to where the MAC is written. Must be big enough + * to hold the 16-byte MAC. + * + * \return \c 0 on success. + * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA + * if key, input, or mac are NULL. + */ +int mbedtls_poly1305_mac( const unsigned char key[32], + const unsigned char *input, + size_t ilen, + unsigned char mac[16] ); + +#if defined(MBEDTLS_SELF_TEST) +/** + * \brief The Poly1305 checkup routine. + * + * \return \c 0 on success. + * \return \c 1 on failure. + */ +int mbedtls_poly1305_self_test( int verbose ); +#endif /* MBEDTLS_SELF_TEST */ + +#ifdef __cplusplus +} +#endif + +#endif /* MBEDTLS_POLY1305_H */ diff --git a/tools/sdk/include/mbedtls/mbedtls/rsa.h b/tools/sdk/include/mbedtls/mbedtls/rsa.h index df6e3e55..19eb2ee7 100644 --- a/tools/sdk/include/mbedtls/mbedtls/rsa.h +++ b/tools/sdk/include/mbedtls/mbedtls/rsa.h @@ -5,7 +5,7 @@ * * The RSA public-key cryptosystem is defined in Public-Key * Cryptography Standards (PKCS) #1 v1.5: RSA Encryption - * and Public-Key Cryptography Standards (PKCS) #1 v2.1: + * and Public-Key Cryptography Standards (PKCS) #1 v2.1: * RSA Cryptography Specifications. * */ @@ -781,7 +781,7 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx, * \param olen The length of the plaintext. * \param input The buffer holding the encrypted data. * \param output The buffer to hold the plaintext. - * \param output_max_len The maximum length of the output buffer. + * \param output_max_len The maximum length of the output buffer. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure. diff --git a/tools/sdk/include/mbedtls/mbedtls/sha1.h b/tools/sdk/include/mbedtls/mbedtls/sha1.h index 8f805fb4..65a124c9 100644 --- a/tools/sdk/include/mbedtls/mbedtls/sha1.h +++ b/tools/sdk/include/mbedtls/mbedtls/sha1.h @@ -3,7 +3,7 @@ * * \brief This file contains SHA-1 definitions and functions. * - * The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined in + * The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined in * FIPS 180-4: Secure Hash Standard (SHS). * * \warning SHA-1 is considered a weak message digest and its use constitutes diff --git a/tools/sdk/include/mbedtls/mbedtls/ssl.h b/tools/sdk/include/mbedtls/mbedtls/ssl.h index bb9c02db..2d511a8e 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ssl.h +++ b/tools/sdk/include/mbedtls/mbedtls/ssl.h @@ -62,7 +62,7 @@ #endif #if defined(MBEDTLS_HAVE_TIME) -#include "mbedtls/platform_time.h" +#include "platform_time.h" #endif /* @@ -120,6 +120,7 @@ #define MBEDTLS_ERR_SSL_NON_FATAL -0x6680 /**< The alert message received indicates a non-fatal error. */ #define MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH -0x6600 /**< Couldn't set the hash for verifying CertificateVerify */ #define MBEDTLS_ERR_SSL_CONTINUE_PROCESSING -0x6580 /**< Internal-only message signaling that further message-processing should be done */ +#define MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS -0x6500 /**< The asynchronous operation is not completed yet. */ /* * Various constants @@ -219,7 +220,7 @@ #endif /* - * Maxium fragment length in bytes, + * Maximum fragment length in bytes, * determines the size of each of the two internal I/O buffers. * * Note: the RFC defines the default size of SSL / TLS messages. If you @@ -233,6 +234,14 @@ #define MBEDTLS_SSL_MAX_CONTENT_LEN 16384 /**< Size of the input / output buffer */ #endif +#if !defined(MBEDTLS_SSL_IN_CONTENT_LEN) +#define MBEDTLS_SSL_IN_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN +#endif + +#if !defined(MBEDTLS_SSL_OUT_CONTENT_LEN) +#define MBEDTLS_SSL_OUT_CONTENT_LEN MBEDTLS_SSL_MAX_CONTENT_LEN +#endif + /* \} name SECTION: Module settings */ /* @@ -536,7 +545,6 @@ typedef void mbedtls_ssl_set_timer_t( void * ctx, */ typedef int mbedtls_ssl_get_timer_t( void * ctx ); - /* Defined below */ typedef struct mbedtls_ssl_session mbedtls_ssl_session; typedef struct mbedtls_ssl_context mbedtls_ssl_context; @@ -553,6 +561,218 @@ typedef struct mbedtls_ssl_key_cert mbedtls_ssl_key_cert; typedef struct mbedtls_ssl_flight_item mbedtls_ssl_flight_item; #endif +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) +#if defined(MBEDTLS_X509_CRT_PARSE_C) +/** + * \brief Callback type: start external signature operation. + * + * This callback is called during an SSL handshake to start + * a signature decryption operation using an + * external processor. The parameter \p cert contains + * the public key; it is up to the callback function to + * determine how to access the associated private key. + * + * This function typically sends or enqueues a request, and + * does not wait for the operation to complete. This allows + * the handshake step to be non-blocking. + * + * The parameters \p ssl and \p cert are guaranteed to remain + * valid throughout the handshake. On the other hand, this + * function must save the contents of \p hash if the value + * is needed for later processing, because the \p hash buffer + * is no longer valid after this function returns. + * + * This function may call mbedtls_ssl_set_async_operation_data() + * to store an operation context for later retrieval + * by the resume or cancel callback. + * + * \note For RSA signatures, this function must produce output + * that is consistent with PKCS#1 v1.5 in the same way as + * mbedtls_rsa_pkcs1_sign(). Before the private key operation, + * apply the padding steps described in RFC 8017, section 9.2 + * "EMSA-PKCS1-v1_5" as follows. + * - If \p md_alg is #MBEDTLS_MD_NONE, apply the PKCS#1 v1.5 + * encoding, treating \p hash as the DigestInfo to be + * padded. In other words, apply EMSA-PKCS1-v1_5 starting + * from step 3, with `T = hash` and `tLen = hash_len`. + * - If `md_alg != MBEDTLS_MD_NONE`, apply the PKCS#1 v1.5 + * encoding, treating \p hash as the hash to be encoded and + * padded. In other words, apply EMSA-PKCS1-v1_5 starting + * from step 2, with `digestAlgorithm` obtained by calling + * mbedtls_oid_get_oid_by_md() on \p md_alg. + * + * \note For ECDSA signatures, the output format is the DER encoding + * `Ecdsa-Sig-Value` defined in + * [RFC 4492 section 5.4](https://tools.ietf.org/html/rfc4492#section-5.4). + * + * \param ssl The SSL connection instance. It should not be + * modified other than via + * mbedtls_ssl_set_async_operation_data(). + * \param cert Certificate containing the public key. + * In simple cases, this is one of the pointers passed to + * mbedtls_ssl_conf_own_cert() when configuring the SSL + * connection. However, if other callbacks are used, this + * property may not hold. For example, if an SNI callback + * is registered with mbedtls_ssl_conf_sni(), then + * this callback determines what certificate is used. + * \param md_alg Hash algorithm. + * \param hash Buffer containing the hash. This buffer is + * no longer valid when the function returns. + * \param hash_len Size of the \c hash buffer in bytes. + * + * \return 0 if the operation was started successfully and the SSL + * stack should call the resume callback immediately. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation + * was started successfully and the SSL stack should return + * immediately without calling the resume callback yet. + * \return #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external + * processor does not support this key. The SSL stack will + * use the private key object instead. + * \return Any other error indicates a fatal failure and is + * propagated up the call chain. The callback should + * use \c MBEDTLS_ERR_PK_xxx error codes, and must not + * use \c MBEDTLS_ERR_SSL_xxx error codes except as + * directed in the documentation of this callback. + */ +typedef int mbedtls_ssl_async_sign_t( mbedtls_ssl_context *ssl, + mbedtls_x509_crt *cert, + mbedtls_md_type_t md_alg, + const unsigned char *hash, + size_t hash_len ); + +/** + * \brief Callback type: start external decryption operation. + * + * This callback is called during an SSL handshake to start + * an RSA decryption operation using an + * external processor. The parameter \p cert contains + * the public key; it is up to the callback function to + * determine how to access the associated private key. + * + * This function typically sends or enqueues a request, and + * does not wait for the operation to complete. This allows + * the handshake step to be non-blocking. + * + * The parameters \p ssl and \p cert are guaranteed to remain + * valid throughout the handshake. On the other hand, this + * function must save the contents of \p input if the value + * is needed for later processing, because the \p input buffer + * is no longer valid after this function returns. + * + * This function may call mbedtls_ssl_set_async_operation_data() + * to store an operation context for later retrieval + * by the resume or cancel callback. + * + * \warning RSA decryption as used in TLS is subject to a potential + * timing side channel attack first discovered by Bleichenbacher + * in 1998. This attack can be remotely exploitable + * in practice. To avoid this attack, you must ensure that + * if the callback performs an RSA decryption, the time it + * takes to execute and return the result does not depend + * on whether the RSA decryption succeeded or reported + * invalid padding. + * + * \param ssl The SSL connection instance. It should not be + * modified other than via + * mbedtls_ssl_set_async_operation_data(). + * \param cert Certificate containing the public key. + * In simple cases, this is one of the pointers passed to + * mbedtls_ssl_conf_own_cert() when configuring the SSL + * connection. However, if other callbacks are used, this + * property may not hold. For example, if an SNI callback + * is registered with mbedtls_ssl_conf_sni(), then + * this callback determines what certificate is used. + * \param input Buffer containing the input ciphertext. This buffer + * is no longer valid when the function returns. + * \param input_len Size of the \p input buffer in bytes. + * + * \return 0 if the operation was started successfully and the SSL + * stack should call the resume callback immediately. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation + * was started successfully and the SSL stack should return + * immediately without calling the resume callback yet. + * \return #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external + * processor does not support this key. The SSL stack will + * use the private key object instead. + * \return Any other error indicates a fatal failure and is + * propagated up the call chain. The callback should + * use \c MBEDTLS_ERR_PK_xxx error codes, and must not + * use \c MBEDTLS_ERR_SSL_xxx error codes except as + * directed in the documentation of this callback. + */ +typedef int mbedtls_ssl_async_decrypt_t( mbedtls_ssl_context *ssl, + mbedtls_x509_crt *cert, + const unsigned char *input, + size_t input_len ); +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + +/** + * \brief Callback type: resume external operation. + * + * This callback is called during an SSL handshake to resume + * an external operation started by the + * ::mbedtls_ssl_async_sign_t or + * ::mbedtls_ssl_async_decrypt_t callback. + * + * This function typically checks the status of a pending + * request or causes the request queue to make progress, and + * does not wait for the operation to complete. This allows + * the handshake step to be non-blocking. + * + * This function may call mbedtls_ssl_get_async_operation_data() + * to retrieve an operation context set by the start callback. + * It may call mbedtls_ssl_set_async_operation_data() to modify + * this context. + * + * Note that when this function returns a status other than + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, it must free any + * resources associated with the operation. + * + * \param ssl The SSL connection instance. It should not be + * modified other than via + * mbedtls_ssl_set_async_operation_data(). + * \param output Buffer containing the output (signature or decrypted + * data) on success. + * \param output_len On success, number of bytes written to \p output. + * \param output_size Size of the \p output buffer in bytes. + * + * \return 0 if output of the operation is available in the + * \p output buffer. + * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation + * is still in progress. Subsequent requests for progress + * on the SSL connection will call the resume callback + * again. + * \return Any other error means that the operation is aborted. + * The SSL handshake is aborted. The callback should + * use \c MBEDTLS_ERR_PK_xxx error codes, and must not + * use \c MBEDTLS_ERR_SSL_xxx error codes except as + * directed in the documentation of this callback. + */ +typedef int mbedtls_ssl_async_resume_t( mbedtls_ssl_context *ssl, + unsigned char *output, + size_t *output_len, + size_t output_size ); + +/** + * \brief Callback type: cancel external operation. + * + * This callback is called if an SSL connection is closed + * while an asynchronous operation is in progress. Note that + * this callback is not called if the + * ::mbedtls_ssl_async_resume_t callback has run and has + * returned a value other than + * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, since in that case + * the asynchronous operation has already completed. + * + * This function may call mbedtls_ssl_get_async_operation_data() + * to retrieve an operation context set by the start callback. + * + * \param ssl The SSL connection instance. It should not be + * modified. + */ +typedef void mbedtls_ssl_async_cancel_t( mbedtls_ssl_context *ssl ); +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + /* * This structure is used for storing current session data. */ @@ -669,6 +889,16 @@ struct mbedtls_ssl_config mbedtls_x509_crl *ca_crl; /*!< trusted CAs CRLs */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) +#if defined(MBEDTLS_X509_CRT_PARSE_C) + mbedtls_ssl_async_sign_t *f_async_sign_start; /*!< start asynchronous signature operation */ + mbedtls_ssl_async_decrypt_t *f_async_decrypt_start; /*!< start asynchronous decryption operation */ +#endif /* MBEDTLS_X509_CRT_PARSE_C */ + mbedtls_ssl_async_resume_t *f_async_resume; /*!< resume asynchronous operation */ + mbedtls_ssl_async_cancel_t *f_async_cancel; /*!< cancel asynchronous operation */ + void *p_async_config_data; /*!< Configuration data set by mbedtls_ssl_conf_async_private_cb(). */ +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) const int *sig_hashes; /*!< allowed signature hashes */ #endif @@ -946,14 +1176,6 @@ extern int (*mbedtls_ssl_hw_record_read)(mbedtls_ssl_context *ssl); extern int (*mbedtls_ssl_hw_record_finish)(mbedtls_ssl_context *ssl); #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ -/** - * \brief Returns the list of ciphersuites supported by the SSL/TLS module. - * - * \return a statically allocated array of ciphersuites, the last - * entry is 0. - */ -const int *mbedtls_ssl_list_ciphersuites( void ); - /** * \brief Return the name of the ciphersuite associated with the * given ID @@ -1315,6 +1537,85 @@ void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf, void *p_export_keys ); #endif /* MBEDTLS_SSL_EXPORT_KEYS */ +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) +/** + * \brief Configure asynchronous private key operation callbacks. + * + * \param conf SSL configuration context + * \param f_async_sign Callback to start a signature operation. See + * the description of ::mbedtls_ssl_async_sign_t + * for more information. This may be \c NULL if the + * external processor does not support any signature + * operation; in this case the private key object + * associated with the certificate will be used. + * \param f_async_decrypt Callback to start a decryption operation. See + * the description of ::mbedtls_ssl_async_decrypt_t + * for more information. This may be \c NULL if the + * external processor does not support any decryption + * operation; in this case the private key object + * associated with the certificate will be used. + * \param f_async_resume Callback to resume an asynchronous operation. See + * the description of ::mbedtls_ssl_async_resume_t + * for more information. This may not be \c NULL unless + * \p f_async_sign and \p f_async_decrypt are both + * \c NULL. + * \param f_async_cancel Callback to cancel an asynchronous operation. See + * the description of ::mbedtls_ssl_async_cancel_t + * for more information. This may be \c NULL if + * no cleanup is needed. + * \param config_data A pointer to configuration data which can be + * retrieved with + * mbedtls_ssl_conf_get_async_config_data(). The + * library stores this value without dereferencing it. + */ +void mbedtls_ssl_conf_async_private_cb( mbedtls_ssl_config *conf, + mbedtls_ssl_async_sign_t *f_async_sign, + mbedtls_ssl_async_decrypt_t *f_async_decrypt, + mbedtls_ssl_async_resume_t *f_async_resume, + mbedtls_ssl_async_cancel_t *f_async_cancel, + void *config_data ); + +/** + * \brief Retrieve the configuration data set by + * mbedtls_ssl_conf_async_private_cb(). + * + * \param conf SSL configuration context + * \return The configuration data set by + * mbedtls_ssl_conf_async_private_cb(). + */ +void *mbedtls_ssl_conf_get_async_config_data( const mbedtls_ssl_config *conf ); + +/** + * \brief Retrieve the asynchronous operation user context. + * + * \note This function may only be called while a handshake + * is in progress. + * + * \param ssl The SSL context to access. + * + * \return The asynchronous operation user context that was last + * set during the current handshake. If + * mbedtls_ssl_set_async_operation_data() has not yet been + * called during the current handshake, this function returns + * \c NULL. + */ +void *mbedtls_ssl_get_async_operation_data( const mbedtls_ssl_context *ssl ); + +/** + * \brief Retrieve the asynchronous operation user context. + * + * \note This function may only be called while a handshake + * is in progress. + * + * \param ssl The SSL context to access. + * \param ctx The new value of the asynchronous operation user context. + * Call mbedtls_ssl_get_async_operation_data() later during the + * same handshake to retrieve this value. + */ +void mbedtls_ssl_set_async_operation_data( mbedtls_ssl_context *ssl, + void *ctx ); +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + /** * \brief Callback type: generate a cookie * @@ -1854,21 +2155,21 @@ void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf, #if defined(MBEDTLS_X509_CRT_PARSE_C) /** - * \brief Set or reset the hostname to check against the received - * server certificate. It sets the ServerName TLS extension, + * \brief Set or reset the hostname to check against the received + * server certificate. It sets the ServerName TLS extension, * too, if that extension is enabled. (client-side only) * * \param ssl SSL context * \param hostname the server hostname, may be NULL to clear hostname - + * \note Maximum hostname length MBEDTLS_SSL_MAX_HOST_NAME_LEN. * - * \return 0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on - * allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on + * \return 0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on + * allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on * too long input hostname. * * Hostname set to the one provided on success (cleared - * when NULL). On allocation failure hostname is cleared. + * when NULL). On allocation failure hostname is cleared. * On too long input failure, old hostname is unchanged. */ int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname ); @@ -2125,7 +2426,8 @@ void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf, #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) /** * \brief Set the maximum fragment length to emit and/or negotiate - * (Default: MBEDTLS_SSL_MAX_CONTENT_LEN, usually 2^14 bytes) + * (Default: the smaller of MBEDTLS_SSL_IN_CONTENT_LEN and + * MBEDTLS_SSL_OUT_CONTENT_LEN, usually 2^14 bytes) * (Server: set maximum fragment length to emit, * usually negotiated by the client during handshake * (Client: set maximum fragment length to emit *and* @@ -2444,7 +2746,6 @@ const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ss * \brief Save session in order to resume it later (client-side only) * Session data is copied to presented session structure. * - * \warning Currently, peer certificate is lost in the operation. * * \param ssl SSL context * \param session session context @@ -2452,7 +2753,18 @@ const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ss * \return 0 if successful, * MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed, * MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used server-side or - * arguments are otherwise invalid + * arguments are otherwise invalid. + * + * \note Only the server certificate is copied, and not the full chain, + * so you should not attempt to validate the certificate again + * by calling \c mbedtls_x509_crt_verify() on it. + * Instead, you should use the results from the verification + * in the original handshake by calling \c mbedtls_ssl_get_verify_result() + * after loading the session again into a new SSL context + * using \c mbedtls_ssl_set_session(). + * + * \note Once the session object is not needed anymore, you should + * free it by calling \c mbedtls_ssl_session_free(). * * \sa mbedtls_ssl_set_session() */ @@ -2614,17 +2926,19 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) * or MBEDTLS_ERR_SSL_WANT_WRITE or MBEDTLS_ERR_SSL_WANT_READ, * or another negative error code. * - * \note If this function returns something other than a positive value - * or MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using - * the SSL context for reading or writing, and either free it or - * call \c mbedtls_ssl_session_reset() on it before re-using it - * for a new connection; the current connection must be closed. + * \note If this function returns something other than 0, a positive + * value or MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop + * using the SSL context for reading or writing, and either + * free it or call \c mbedtls_ssl_session_reset() on it before + * re-using it for a new connection; the current connection + * must be closed. * * \note When this function returns MBEDTLS_ERR_SSL_WANT_WRITE/READ, * it must be called later with the *same* arguments, - * until it returns a positive value. When the function returns - * MBEDTLS_ERR_SSL_WANT_WRITE there may be some partial - * data in the output buffer, however this is not yet sent. + * until it returns a value greater that or equal to 0. When + * the function returns MBEDTLS_ERR_SSL_WANT_WRITE there may be + * some partial data in the output buffer, however this is not + * yet sent. * * \note If the requested length is greater than the maximum * fragment length (either the built-in limit or the one set @@ -2633,6 +2947,9 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) * - with DTLS, MBEDTLS_ERR_SSL_BAD_INPUT_DATA is returned. * \c mbedtls_ssl_get_max_frag_len() may be used to query the * active maximum fragment length. + * + * \note Attempting to write 0 bytes will result in an empty TLS + * application record being sent. */ int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ); @@ -2725,6 +3042,9 @@ void mbedtls_ssl_session_init( mbedtls_ssl_session *session ); * \brief Free referenced items in an SSL session including the * peer certificate and clear memory * + * \note A session object can be freed even if the SSL context + * that was used to retrieve the session is still in use. + * * \param session SSL session */ void mbedtls_ssl_session_free( mbedtls_ssl_session *session ); diff --git a/tools/sdk/include/mbedtls/mbedtls/ssl_ciphersuites.h b/tools/sdk/include/mbedtls/mbedtls/ssl_ciphersuites.h index 545468a5..cda8b483 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ssl_ciphersuites.h +++ b/tools/sdk/include/mbedtls/mbedtls/ssl_ciphersuites.h @@ -169,6 +169,45 @@ extern "C" { #define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256 0xC03A /**< Weak! No SSL3! */ #define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384 0xC03B /**< Weak! No SSL3! */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 0xC03C /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 0xC03D /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC044 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC045 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC048 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC049 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC04A /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC04B /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC04C /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC04D /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 0xC04E /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 0xC04F /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 0xC050 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 0xC051 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC052 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC053 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05C /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05D /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05E /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05F /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC060 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC061 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 0xC062 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 0xC063 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 0xC064 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 0xC065 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC066 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC067 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 0xC068 /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 0xC069 /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 0xC06A /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 0xC06B /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 0xC06C /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 0xC06D /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 0xC06E /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 0xC06F /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC070 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC071 /**< TLS 1.2 */ + #define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC072 /**< Not in SSL3! */ #define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0xC073 /**< Not in SSL3! */ #define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC074 /**< Not in SSL3! */ @@ -232,6 +271,15 @@ extern "C" { #define MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 0xC0FF /**< experimental */ +/* RFC 7905 */ +#define MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA /**< TLS 1.2 */ +#define MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAB /**< TLS 1.2 */ +#define MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAC /**< TLS 1.2 */ +#define MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAD /**< TLS 1.2 */ +#define MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAE /**< TLS 1.2 */ + /* Reminder: update mbedtls_ssl_premaster_secret when adding a new key exchange. * Reminder: update MBEDTLS_KEY_EXCHANGE__xxx below */ @@ -267,7 +315,7 @@ typedef enum { defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \ - defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) + defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) #define MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED #endif diff --git a/tools/sdk/include/mbedtls/mbedtls/ssl_internal.h b/tools/sdk/include/mbedtls/mbedtls/ssl_internal.h index 60b431a0..d214703d 100644 --- a/tools/sdk/include/mbedtls/mbedtls/ssl_internal.h +++ b/tools/sdk/include/mbedtls/mbedtls/ssl_internal.h @@ -143,32 +143,73 @@ #define MBEDTLS_SSL_PADDING_ADD 0 #endif -#define MBEDTLS_SSL_PAYLOAD_LEN ( MBEDTLS_SSL_MAX_CONTENT_LEN \ - + MBEDTLS_SSL_COMPRESSION_ADD \ - + MBEDTLS_MAX_IV_LENGTH \ - + MBEDTLS_SSL_MAC_ADD \ - + MBEDTLS_SSL_PADDING_ADD \ - ) +#define MBEDTLS_SSL_PAYLOAD_OVERHEAD ( MBEDTLS_SSL_COMPRESSION_ADD + \ + MBEDTLS_MAX_IV_LENGTH + \ + MBEDTLS_SSL_MAC_ADD + \ + MBEDTLS_SSL_PADDING_ADD \ + ) + +#define MBEDTLS_SSL_IN_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \ + ( MBEDTLS_SSL_IN_CONTENT_LEN ) ) + +#define MBEDTLS_SSL_OUT_PAYLOAD_LEN ( MBEDTLS_SSL_PAYLOAD_OVERHEAD + \ + ( MBEDTLS_SSL_OUT_CONTENT_LEN ) ) + +/* Maximum length we can advertise as our max content length for + RFC 6066 max_fragment_length extension negotiation purposes + (the lesser of both sizes, if they are unequal.) + */ +#define MBEDTLS_TLS_EXT_ADV_CONTENT_LEN ( \ + (MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_OUT_CONTENT_LEN) \ + ? ( MBEDTLS_SSL_OUT_CONTENT_LEN ) \ + : ( MBEDTLS_SSL_IN_CONTENT_LEN ) \ + ) /* * Check that we obey the standard's message size bounds */ #if MBEDTLS_SSL_MAX_CONTENT_LEN > 16384 -#error Bad configuration - record content too large. +#error "Bad configuration - record content too large." #endif -#if MBEDTLS_SSL_PAYLOAD_LEN > 16384 + 2048 -#error Bad configuration - protected record payload too large. +#if MBEDTLS_SSL_IN_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN +#error "Bad configuration - incoming record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN." #endif +#if MBEDTLS_SSL_OUT_CONTENT_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN +#error "Bad configuration - outgoing record content should not be larger than MBEDTLS_SSL_MAX_CONTENT_LEN." +#endif + +#if MBEDTLS_SSL_IN_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048 +#error "Bad configuration - incoming protected record payload too large." +#endif + +#if MBEDTLS_SSL_OUT_PAYLOAD_LEN > MBEDTLS_SSL_MAX_CONTENT_LEN + 2048 +#error "Bad configuration - outgoing protected record payload too large." +#endif + +/* Calculate buffer sizes */ + /* Note: Even though the TLS record header is only 5 bytes long, we're internally using 8 bytes to store the implicit sequence number. */ #define MBEDTLS_SSL_HEADER_LEN 13 -#define MBEDTLS_SSL_BUFFER_LEN \ - ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_PAYLOAD_LEN ) ) +#define MBEDTLS_SSL_IN_BUFFER_LEN \ + ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_IN_PAYLOAD_LEN ) ) + +#define MBEDTLS_SSL_OUT_BUFFER_LEN \ + ( ( MBEDTLS_SSL_HEADER_LEN ) + ( MBEDTLS_SSL_OUT_PAYLOAD_LEN ) ) + +#ifdef MBEDTLS_ZLIB_SUPPORT +/* Compression buffer holds both IN and OUT buffers, so should be size of the larger */ +#define MBEDTLS_SSL_COMPRESS_BUFFER_LEN ( \ + ( MBEDTLS_SSL_IN_BUFFER_LEN > MBEDTLS_SSL_OUT_BUFFER_LEN ) \ + ? MBEDTLS_SSL_IN_BUFFER_LEN \ + : MBEDTLS_SSL_OUT_BUFFER_LEN \ + ) +#endif /* * TLS extension flags (for extensions with outgoing ServerHello content @@ -243,6 +284,7 @@ struct mbedtls_ssl_handshake_params mbedtls_x509_crl *sni_ca_crl; /*!< trusted CAs CRLs from SNI */ #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #endif /* MBEDTLS_X509_CRT_PARSE_C */ + #if defined(MBEDTLS_SSL_PROTO_DTLS) unsigned int out_msg_seq; /*!< Outgoing handshake sequence number */ unsigned int in_msg_seq; /*!< Incoming handshake sequence number */ @@ -307,6 +349,19 @@ struct mbedtls_ssl_handshake_params #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) int extended_ms; /*!< use Extended Master Secret? */ #endif + +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) + unsigned int async_in_progress : 1; /*!< an asynchronous operation is in progress */ +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ + +#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) + /** Asynchronous operation context. This field is meant for use by the + * asynchronous operation callbacks (mbedtls_ssl_config::f_async_sign_start, + * mbedtls_ssl_config::f_async_decrypt_start, + * mbedtls_ssl_config::f_async_resume, mbedtls_ssl_config::f_async_cancel). + * The library does not use it internally. */ + void *user_async_ctx; +#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ }; /* @@ -410,9 +465,9 @@ void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform ); * \brief Free referenced items in an SSL handshake context and clear * memory * - * \param handshake SSL handshake context + * \param ssl SSL context */ -void mbedtls_ssl_handshake_free( mbedtls_ssl_handshake_params *handshake ); +void mbedtls_ssl_handshake_free( mbedtls_ssl_context *ssl ); int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl ); int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl ); @@ -630,7 +685,13 @@ static inline int mbedtls_ssl_safer_memcmp( const void *a, const void *b, size_t volatile unsigned char diff = 0; for( i = 0; i < n; i++ ) - diff |= A[i] ^ B[i]; + { + /* Read volatile data in order before computing diff. + * This avoids IAR compiler warning: + * 'the order of volatile accesses is undefined ..' */ + unsigned char x = A[i], y = B[i]; + diff |= x ^ y; + } return( diff ); } @@ -646,9 +707,9 @@ int mbedtls_ssl_get_key_exchange_md_ssl_tls( mbedtls_ssl_context *ssl, #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) int mbedtls_ssl_get_key_exchange_md_tls1_2( mbedtls_ssl_context *ssl, - unsigned char *output, - unsigned char *data, size_t data_len, - mbedtls_md_type_t md_alg ); + unsigned char *hash, size_t *hashlen, + unsigned char *data, size_t data_len, + mbedtls_md_type_t md_alg ); #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ diff --git a/tools/sdk/include/mbedtls/mbedtls/threading.h b/tools/sdk/include/mbedtls/mbedtls/threading.h index aeea5d0e..c25daa5c 100644 --- a/tools/sdk/include/mbedtls/mbedtls/threading.h +++ b/tools/sdk/include/mbedtls/mbedtls/threading.h @@ -99,9 +99,6 @@ extern int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t *mutex ); #if defined(MBEDTLS_FS_IO) extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex; #endif -#if defined(MBEDTLS_HAVE_TIME_DATE) -extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex; -#endif #endif /* MBEDTLS_THREADING_C */ #ifdef __cplusplus diff --git a/tools/sdk/include/mbedtls/mbedtls/version.h b/tools/sdk/include/mbedtls/mbedtls/version.h index aa52ce21..eaf25d90 100644 --- a/tools/sdk/include/mbedtls/mbedtls/version.h +++ b/tools/sdk/include/mbedtls/mbedtls/version.h @@ -39,7 +39,7 @@ * Major, Minor, Patchlevel */ #define MBEDTLS_VERSION_MAJOR 2 -#define MBEDTLS_VERSION_MINOR 9 +#define MBEDTLS_VERSION_MINOR 12 #define MBEDTLS_VERSION_PATCH 0 /** @@ -47,9 +47,9 @@ * MMNNPP00 * Major version | Minor version | Patch version */ -#define MBEDTLS_VERSION_NUMBER 0x02090000 -#define MBEDTLS_VERSION_STRING "2.9.0" -#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.9.0" +#define MBEDTLS_VERSION_NUMBER 0x020C0000 +#define MBEDTLS_VERSION_STRING "2.12.0" +#define MBEDTLS_VERSION_STRING_FULL "mbed TLS 2.12.0" #if defined(MBEDTLS_VERSION_C) diff --git a/tools/sdk/include/mbedtls_port/mbedtls/esp_config.h b/tools/sdk/include/mbedtls_port/mbedtls/esp_config.h index c81bf1a0..561ff723 100644 --- a/tools/sdk/include/mbedtls_port/mbedtls/esp_config.h +++ b/tools/sdk/include/mbedtls_port/mbedtls/esp_config.h @@ -114,7 +114,9 @@ * * Enable this layer to allow use of alternative memory allocators. */ -//#define MBEDTLS_PLATFORM_MEMORY +#ifdef CONFIG_MBEDTLS_PLATFORM_MEMORY +#define MBEDTLS_PLATFORM_MEMORY +#endif /** * \def MBEDTLS_PLATFORM_NO_STD_FUNCTIONS diff --git a/tools/sdk/include/newlib/errno.h b/tools/sdk/include/newlib/errno.h index 7cc2ca86..85fb2e15 100644 --- a/tools/sdk/include/newlib/errno.h +++ b/tools/sdk/include/newlib/errno.h @@ -1,11 +1,39 @@ -#ifndef __ERRNO_H__ -#define __ERRNO_H__ -#ifndef __error_t_defined -typedef int error_t; -#define __error_t_defined 1 +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#ifndef _ESP_PLATFORM_ERRNO_H_ +#define _ESP_PLATFORM_ERRNO_H_ + +#include_next "errno.h" + +// +// Possibly define some missing errors +// +#ifndef ESHUTDOWN +#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ #endif -#include +#ifndef EAI_SOCKTYPE +#define EAI_SOCKTYPE 10 /* ai_socktype not supported */ +#endif -#endif /* !__ERRNO_H__ */ +#ifndef EAI_AGAIN +#define EAI_AGAIN 2 /* temporary failure in name resolution */ +#endif + +#ifndef EAI_BADFLAGS +#define EAI_BADFLAGS 3 /* invalid value for ai_flags */ +#endif + +#endif // _ESP_PLATFORM_ERRNO_H_ diff --git a/tools/sdk/include/newlib/net/if.h b/tools/sdk/include/newlib/net/if.h new file mode 100644 index 00000000..8760bb15 --- /dev/null +++ b/tools/sdk/include/newlib/net/if.h @@ -0,0 +1,45 @@ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#ifndef _ESP_PLATFORM_NET_IF_H_ +#define _ESP_PLATFORM_NET_IF_H_ + +#define MSG_DONTROUTE 0x4 /* send without using routing tables */ +#define SOCK_SEQPACKET 5 /* sequenced packet stream */ +#define MSG_EOR 0x8 /* data completes record */ +#define SOCK_SEQPACKET 5 /* sequenced packet stream */ +#define SOMAXCONN 128 + +#define IF_NAMESIZE 16 + +#define IPV6_UNICAST_HOPS 4 /* int; IP6 hops */ + +#define NI_MAXHOST 1025 +#define NI_MAXSERV 32 +#define NI_NUMERICSERV 0x00000008 +#define NI_DGRAM 0x00000010 + + +struct ipv6_mreq { + struct in6_addr ipv6mr_multiaddr; + unsigned int ipv6mr_interface; +}; + +typedef u32_t socklen_t; + + +unsigned int if_nametoindex(const char *ifname); + +char *if_indextoname(unsigned int ifindex, char *ifname); + +#endif // _ESP_PLATFORM_NET_IF_H_ diff --git a/tools/sdk/include/newlib/pthread.h b/tools/sdk/include/newlib/pthread.h index db1f9c1c..4515fb00 100644 --- a/tools/sdk/include/newlib/pthread.h +++ b/tools/sdk/include/newlib/pthread.h @@ -1,431 +1,33 @@ -/* pthread.h - * - * Written by Joel Sherrill . - * - * COPYRIGHT (c) 1989-2013. - * On-Line Applications Research Corporation (OAR). - * - * Permission to use, copy, modify, and distribute this software for any - * purpose without fee is hereby granted, provided that this entire notice - * is included in all copies of any software which is or includes a copy - * or modification of this software. - * - * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED - * WARRANTY. IN PARTICULAR, THE AUTHOR MAKES NO REPRESENTATION - * OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY OF THIS - * SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. - * - * $Id$ - */ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#ifndef __ESP_PLATFORM_PTHREAD_H__ +#define __ESP_PLATFORM_PTHREAD_H__ -#ifndef __PTHREAD_h -#define __PTHREAD_h +#include +#include +#include_next #ifdef __cplusplus extern "C" { #endif -#include - -#if defined(_POSIX_THREADS) - -#include -#include -#include -#include - -struct _pthread_cleanup_context { - void (*_routine)(void *); - void *_arg; - int _canceltype; - struct _pthread_cleanup_context *_previous; -}; - -/* Register Fork Handlers */ -int _EXFUN(pthread_atfork,(void (*prepare)(void), void (*parent)(void), - void (*child)(void))); - -/* Mutex Initialization Attributes, P1003.1c/Draft 10, p. 81 */ - -int _EXFUN(pthread_mutexattr_init, (pthread_mutexattr_t *__attr)); -int _EXFUN(pthread_mutexattr_destroy, (pthread_mutexattr_t *__attr)); -int _EXFUN(pthread_mutexattr_getpshared, - (_CONST pthread_mutexattr_t *__attr, int *__pshared)); -int _EXFUN(pthread_mutexattr_setpshared, - (pthread_mutexattr_t *__attr, int __pshared)); - -#if defined(_UNIX98_THREAD_MUTEX_ATTRIBUTES) - -/* Single UNIX Specification 2 Mutex Attributes types */ - -int _EXFUN(pthread_mutexattr_gettype, - (_CONST pthread_mutexattr_t *__attr, int *__kind)); -int _EXFUN(pthread_mutexattr_settype, - (pthread_mutexattr_t *__attr, int __kind)); - -#endif - -/* Initializing and Destroying a Mutex, P1003.1c/Draft 10, p. 87 */ - -int _EXFUN(pthread_mutex_init, - (pthread_mutex_t *__mutex, _CONST pthread_mutexattr_t *__attr)); -int _EXFUN(pthread_mutex_destroy, (pthread_mutex_t *__mutex)); - -/* This is used to statically initialize a pthread_mutex_t. Example: - - pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; - */ - -#define PTHREAD_MUTEX_INITIALIZER ((pthread_mutex_t) 0xFFFFFFFF) - -/* Locking and Unlocking a Mutex, P1003.1c/Draft 10, p. 93 - NOTE: P1003.4b/D8 adds pthread_mutex_timedlock(), p. 29 */ - -int _EXFUN(pthread_mutex_lock, (pthread_mutex_t *__mutex)); -int _EXFUN(pthread_mutex_trylock, (pthread_mutex_t *__mutex)); -int _EXFUN(pthread_mutex_unlock, (pthread_mutex_t *__mutex)); - -#if defined(_POSIX_TIMEOUTS) - -int _EXFUN(pthread_mutex_timedlock, - (pthread_mutex_t *__mutex, _CONST struct timespec *__timeout)); - -#endif /* _POSIX_TIMEOUTS */ - -/* Condition Variable Initialization Attributes, P1003.1c/Draft 10, p. 96 */ - -int _EXFUN(pthread_condattr_init, (pthread_condattr_t *__attr)); -int _EXFUN(pthread_condattr_destroy, (pthread_condattr_t *__attr)); -int _EXFUN(pthread_condattr_getpshared, - (_CONST pthread_condattr_t *__attr, int *__pshared)); -int _EXFUN(pthread_condattr_setpshared, - (pthread_condattr_t *__attr, int __pshared)); - -/* Initializing and Destroying a Condition Variable, P1003.1c/Draft 10, p. 87 */ - -int _EXFUN(pthread_cond_init, - (pthread_cond_t *__cond, _CONST pthread_condattr_t *__attr)); -int _EXFUN(pthread_cond_destroy, (pthread_cond_t *__mutex)); - -/* This is used to statically initialize a pthread_cond_t. Example: - - pthread_cond_t cond = PTHREAD_COND_INITIALIZER; - */ - -#define PTHREAD_COND_INITIALIZER ((pthread_cond_t) 0xFFFFFFFF) - -/* Broadcasting and Signaling a Condition, P1003.1c/Draft 10, p. 101 */ - -int _EXFUN(pthread_cond_signal, (pthread_cond_t *__cond)); -int _EXFUN(pthread_cond_broadcast, (pthread_cond_t *__cond)); - -/* Waiting on a Condition, P1003.1c/Draft 10, p. 105 */ - -int _EXFUN(pthread_cond_wait, - (pthread_cond_t *__cond, pthread_mutex_t *__mutex)); - -int _EXFUN(pthread_cond_timedwait, - (pthread_cond_t *__cond, pthread_mutex_t *__mutex, - _CONST struct timespec *__abstime)); - -#if defined(_POSIX_THREAD_PRIORITY_SCHEDULING) - -/* Thread Creation Scheduling Attributes, P1003.1c/Draft 10, p. 120 */ - -int _EXFUN(pthread_attr_setscope, - (pthread_attr_t *__attr, int __contentionscope)); -int _EXFUN(pthread_attr_getscope, - (_CONST pthread_attr_t *__attr, int *__contentionscope)); -int _EXFUN(pthread_attr_setinheritsched, - (pthread_attr_t *__attr, int __inheritsched)); -int _EXFUN(pthread_attr_getinheritsched, - (_CONST pthread_attr_t *__attr, int *__inheritsched)); -int _EXFUN(pthread_attr_setschedpolicy, - (pthread_attr_t *__attr, int __policy)); -int _EXFUN(pthread_attr_getschedpolicy, - (_CONST pthread_attr_t *__attr, int *__policy)); - -#endif /* defined(_POSIX_THREAD_PRIORITY_SCHEDULING) */ - -int _EXFUN(pthread_attr_setschedparam, - (pthread_attr_t *__attr, _CONST struct sched_param *__param)); -int _EXFUN(pthread_attr_getschedparam, - (_CONST pthread_attr_t *__attr, struct sched_param *__param)); - -#if defined(_POSIX_THREAD_PRIORITY_SCHEDULING) - -/* Dynamic Thread Scheduling Parameters Access, P1003.1c/Draft 10, p. 124 */ - -int _EXFUN(pthread_getschedparam, - (pthread_t __pthread, int *__policy, struct sched_param *__param)); -int _EXFUN(pthread_setschedparam, - (pthread_t __pthread, int __policy, struct sched_param *__param)); - -#endif /* defined(_POSIX_THREAD_PRIORITY_SCHEDULING) */ - -#if defined(_POSIX_THREAD_PRIO_INHERIT) || defined(_POSIX_THREAD_PRIO_PROTECT) - -/* Mutex Initialization Scheduling Attributes, P1003.1c/Draft 10, p. 128 */ - -int _EXFUN(pthread_mutexattr_setprotocol, - (pthread_mutexattr_t *__attr, int __protocol)); -int _EXFUN(pthread_mutexattr_getprotocol, - (_CONST pthread_mutexattr_t *__attr, int *__protocol)); -int _EXFUN(pthread_mutexattr_setprioceiling, - (pthread_mutexattr_t *__attr, int __prioceiling)); -int _EXFUN(pthread_mutexattr_getprioceiling, - (_CONST pthread_mutexattr_t *__attr, int *__prioceiling)); - -#endif /* _POSIX_THREAD_PRIO_INHERIT || _POSIX_THREAD_PRIO_PROTECT */ - -#if defined(_POSIX_THREAD_PRIO_PROTECT) - -/* Change the Priority Ceiling of a Mutex, P1003.1c/Draft 10, p. 131 */ - -int _EXFUN(pthread_mutex_setprioceiling, - (pthread_mutex_t *__mutex, int __prioceiling, int *__old_ceiling)); -int _EXFUN(pthread_mutex_getprioceiling, - (pthread_mutex_t *__mutex, int *__prioceiling)); - -#endif /* _POSIX_THREAD_PRIO_PROTECT */ - -/* Thread Creation Attributes, P1003.1c/Draft 10, p, 140 */ - -int _EXFUN(pthread_attr_init, (pthread_attr_t *__attr)); -int _EXFUN(pthread_attr_destroy, (pthread_attr_t *__attr)); -int _EXFUN(pthread_attr_setstack, (pthread_attr_t *attr, - void *__stackaddr, size_t __stacksize)); -int _EXFUN(pthread_attr_getstack, (_CONST pthread_attr_t *attr, - void **__stackaddr, size_t *__stacksize)); -int _EXFUN(pthread_attr_getstacksize, - (_CONST pthread_attr_t *__attr, size_t *__stacksize)); -int _EXFUN(pthread_attr_setstacksize, - (pthread_attr_t *__attr, size_t __stacksize)); -int _EXFUN(pthread_attr_getstackaddr, - (_CONST pthread_attr_t *__attr, void **__stackaddr)); -int _EXFUN(pthread_attr_setstackaddr, - (pthread_attr_t *__attr, void *__stackaddr)); -int _EXFUN(pthread_attr_getdetachstate, - (_CONST pthread_attr_t *__attr, int *__detachstate)); -int _EXFUN(pthread_attr_setdetachstate, - (pthread_attr_t *__attr, int __detachstate)); -int _EXFUN(pthread_attr_getguardsize, - (_CONST pthread_attr_t *__attr, size_t *__guardsize)); -int _EXFUN(pthread_attr_setguardsize, - (pthread_attr_t *__attr, size_t __guardsize)); - -/* POSIX thread APIs beyond the POSIX standard but provided - * in GNU/Linux. They may be provided by other OSes for - * compatibility. - */ -#if defined(__GNU_VISIBLE) -#if defined(__rtems__) -int _EXFUN(pthread_attr_setaffinity_np, - (pthread_attr_t *__attr, size_t __cpusetsize, - const cpu_set_t *__cpuset)); -int _EXFUN(pthread_attr_getaffinity_np, - (const pthread_attr_t *__attr, size_t __cpusetsize, - cpu_set_t *__cpuset)); - -int _EXFUN(pthread_setaffinity_np, - (pthread_t __id, size_t __cpusetsize, const cpu_set_t *__cpuset)); -int _EXFUN(pthread_getaffinity_np, - (const pthread_t __id, size_t __cpusetsize, cpu_set_t *__cpuset)); - -int _EXFUN(pthread_getattr_np, - (pthread_t __id, pthread_attr_t *__attr)); -#endif /* defined(__rtems__) */ -#endif /* defined(__GNU_VISIBLE) */ - -/* Thread Creation, P1003.1c/Draft 10, p. 144 */ - -int _EXFUN(pthread_create, - (pthread_t *__pthread, _CONST pthread_attr_t *__attr, - void *(*__start_routine)( void * ), void *__arg)); - -/* Wait for Thread Termination, P1003.1c/Draft 10, p. 147 */ - -int _EXFUN(pthread_join, (pthread_t __pthread, void **__value_ptr)); - -/* Detaching a Thread, P1003.1c/Draft 10, p. 149 */ - -int _EXFUN(pthread_detach, (pthread_t __pthread)); - -/* Thread Termination, p1003.1c/Draft 10, p. 150 */ - -void _EXFUN(pthread_exit, (void *__value_ptr)); - -/* Get Calling Thread's ID, p1003.1c/Draft 10, p. XXX */ - -pthread_t _EXFUN(pthread_self, (void)); - -/* Compare Thread IDs, p1003.1c/Draft 10, p. 153 */ - -int _EXFUN(pthread_equal, (pthread_t __t1, pthread_t __t2)); - -/* Dynamic Package Initialization */ - -/* This is used to statically initialize a pthread_once_t. Example: - - pthread_once_t once = PTHREAD_ONCE_INIT; - - NOTE: This is named inconsistently -- it should be INITIALIZER. */ - -#define PTHREAD_ONCE_INIT { 1, 0 } /* is initialized and not run */ - -int _EXFUN(pthread_once, - (pthread_once_t *__once_control, void (*__init_routine)(void))); - -/* Thread-Specific Data Key Create, P1003.1c/Draft 10, p. 163 */ - -int _EXFUN(pthread_key_create, - (pthread_key_t *__key, void (*__destructor)( void * ))); - -/* Thread-Specific Data Management, P1003.1c/Draft 10, p. 165 */ - -int _EXFUN(pthread_setspecific, - (pthread_key_t __key, _CONST void *__value)); -void * _EXFUN(pthread_getspecific, (pthread_key_t __key)); - -/* Thread-Specific Data Key Deletion, P1003.1c/Draft 10, p. 167 */ - -int _EXFUN(pthread_key_delete, (pthread_key_t __key)); - -/* Execution of a Thread, P1003.1c/Draft 10, p. 181 */ - -#define PTHREAD_CANCEL_ENABLE 0 -#define PTHREAD_CANCEL_DISABLE 1 - -#define PTHREAD_CANCEL_DEFERRED 0 -#define PTHREAD_CANCEL_ASYNCHRONOUS 1 - -#define PTHREAD_CANCELED ((void *) -1) - -int _EXFUN(pthread_cancel, (pthread_t __pthread)); - -/* Setting Cancelability State, P1003.1c/Draft 10, p. 183 */ - -int _EXFUN(pthread_setcancelstate, (int __state, int *__oldstate)); -int _EXFUN(pthread_setcanceltype, (int __type, int *__oldtype)); -void _EXFUN(pthread_testcancel, (void)); - -/* Establishing Cancellation Handlers, P1003.1c/Draft 10, p. 184 */ - -void _EXFUN(_pthread_cleanup_push, - (struct _pthread_cleanup_context *_context, - void (*_routine)(void *), void *_arg)); - -void _EXFUN(_pthread_cleanup_pop, - (struct _pthread_cleanup_context *_context, - int _execute)); - -/* It is intentional to open and close the scope in two different macros */ -#define pthread_cleanup_push(_routine, _arg) \ - do { \ - struct _pthread_cleanup_context _pthread_clup_ctx; \ - _pthread_cleanup_push(&_pthread_clup_ctx, (_routine), (_arg)) - -#define pthread_cleanup_pop(_execute) \ - _pthread_cleanup_pop(&_pthread_clup_ctx, (_execute)); \ - } while (0) - -#if defined(_GNU_SOURCE) -void _EXFUN(_pthread_cleanup_push_defer, - (struct _pthread_cleanup_context *_context, - void (*_routine)(void *), void *_arg)); - -void _EXFUN(_pthread_cleanup_pop_restore, - (struct _pthread_cleanup_context *_context, - int _execute)); - -/* It is intentional to open and close the scope in two different macros */ -#define pthread_cleanup_push_defer_np(_routine, _arg) \ - do { \ - struct _pthread_cleanup_context _pthread_clup_ctx; \ - _pthread_cleanup_push_defer(&_pthread_clup_ctx, (_routine), (_arg)) - -#define pthread_cleanup_pop_restore_np(_execute) \ - _pthread_cleanup_pop_restore(&_pthread_clup_ctx, (_execute)); \ - } while (0) -#endif /* defined(_GNU_SOURCE) */ - -#if defined(_POSIX_THREAD_CPUTIME) - -/* Accessing a Thread CPU-time Clock, P1003.4b/D8, p. 58 */ - -int _EXFUN(pthread_getcpuclockid, - (pthread_t __pthread_id, clockid_t *__clock_id)); - -#endif /* defined(_POSIX_THREAD_CPUTIME) */ - - -#endif /* defined(_POSIX_THREADS) */ - -#if defined(_POSIX_BARRIERS) - -int _EXFUN(pthread_barrierattr_init, (pthread_barrierattr_t *__attr)); -int _EXFUN(pthread_barrierattr_destroy, (pthread_barrierattr_t *__attr)); -int _EXFUN(pthread_barrierattr_getpshared, - (_CONST pthread_barrierattr_t *__attr, int *__pshared)); -int _EXFUN(pthread_barrierattr_setpshared, - (pthread_barrierattr_t *__attr, int __pshared)); - -#define PTHREAD_BARRIER_SERIAL_THREAD -1 - -int _EXFUN(pthread_barrier_init, - (pthread_barrier_t *__barrier, - _CONST pthread_barrierattr_t *__attr, unsigned __count)); -int _EXFUN(pthread_barrier_destroy, (pthread_barrier_t *__barrier)); -int _EXFUN(pthread_barrier_wait,(pthread_barrier_t *__barrier)); - -#endif /* defined(_POSIX_BARRIERS) */ - -#if defined(_POSIX_SPIN_LOCKS) - -int _EXFUN(pthread_spin_init, - (pthread_spinlock_t *__spinlock, int __pshared)); -int _EXFUN(pthread_spin_destroy, (pthread_spinlock_t *__spinlock)); -int _EXFUN(pthread_spin_lock, (pthread_spinlock_t *__spinlock)); -int _EXFUN(pthread_spin_trylock, (pthread_spinlock_t *__spinlock)); -int _EXFUN(pthread_spin_unlock, (pthread_spinlock_t *__spinlock)); - -#endif /* defined(_POSIX_SPIN_LOCKS) */ - -#if defined(_POSIX_READER_WRITER_LOCKS) - -/* This is used to statically initialize a pthread_rwlock_t. Example: - - pthread_mutex_t mutex = PTHREAD_RWLOCK_INITIALIZER; - */ - -#define PTHREAD_RWLOCK_INITIALIZER ((pthread_rwlock_t) 0xFFFFFFFF) - -int _EXFUN(pthread_rwlockattr_init, (pthread_rwlockattr_t *__attr)); -int _EXFUN(pthread_rwlockattr_destroy, (pthread_rwlockattr_t *__attr)); -int _EXFUN(pthread_rwlockattr_getpshared, - (_CONST pthread_rwlockattr_t *__attr, int *__pshared)); -int _EXFUN(pthread_rwlockattr_setpshared, - (pthread_rwlockattr_t *__attr, int __pshared)); - -int _EXFUN(pthread_rwlock_init, - (pthread_rwlock_t *__rwlock, _CONST pthread_rwlockattr_t *__attr)); -int _EXFUN(pthread_rwlock_destroy, (pthread_rwlock_t *__rwlock)); -int _EXFUN(pthread_rwlock_rdlock,(pthread_rwlock_t *__rwlock)); -int _EXFUN(pthread_rwlock_tryrdlock,(pthread_rwlock_t *__rwlock)); -int _EXFUN(pthread_rwlock_timedrdlock, - (pthread_rwlock_t *__rwlock, _CONST struct timespec *__abstime)); -int _EXFUN(pthread_rwlock_unlock,(pthread_rwlock_t *__rwlock)); -int _EXFUN(pthread_rwlock_wrlock,(pthread_rwlock_t *__rwlock)); -int _EXFUN(pthread_rwlock_trywrlock,(pthread_rwlock_t *__rwlock)); -int _EXFUN(pthread_rwlock_timedwrlock, - (pthread_rwlock_t *__rwlock, _CONST struct timespec *__abstime)); - -#endif /* defined(_POSIX_READER_WRITER_LOCKS) */ +int pthread_condattr_getclock(const pthread_condattr_t * attr, clockid_t * clock_id); +int pthread_condattr_setclock(pthread_condattr_t *attr, clockid_t clock_id); #ifdef __cplusplus } #endif -#endif -/* end of include file */ +#endif // __ESP_PLATFORM_PTHREAD_H__ diff --git a/tools/sdk/include/newlib/sys/poll.h b/tools/sdk/include/newlib/sys/poll.h new file mode 100644 index 00000000..6e006734 --- /dev/null +++ b/tools/sdk/include/newlib/sys/poll.h @@ -0,0 +1,32 @@ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#ifndef _ESP_PLATFORM_SYS_POLL_H_ +#define _ESP_PLATFORM_SYS_POLL_H_ + +#define POLLIN 0x0001 /* any readable data available */ +#define POLLOUT 0x0004 /* file descriptor is writeable */ +#define POLLPRI 0x0002 /* OOB/Urgent readable data */ +#define POLLERR 0x0008 /* some poll error occurred */ +#define POLLHUP 0x0010 /* file descriptor was "hung up" */ + +struct pollfd { + int fd; /* The descriptor. */ + short events; /* The event(s) is/are specified here. */ + short revents; /* Events found are returned here. */ +}; + +typedef unsigned int nfds_t; +int poll(struct pollfd *fds, nfds_t nfds, int timeout); + +#endif // _ESP_PLATFORM_SYS_POLL_H_ diff --git a/tools/sdk/include/newlib/sys/random.h b/tools/sdk/include/newlib/sys/random.h new file mode 100644 index 00000000..afbf4dfd --- /dev/null +++ b/tools/sdk/include/newlib/sys/random.h @@ -0,0 +1,30 @@ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef __SYS_RANDOM__ +#define __SYS_RANDOM__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +ssize_t getrandom(void *buf, size_t buflen, unsigned int flags); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif //__SYS_RANDOM__ diff --git a/tools/sdk/include/newlib/sys/reent.h b/tools/sdk/include/newlib/sys/reent.h index ee409618..b35595a7 100644 --- a/tools/sdk/include/newlib/sys/reent.h +++ b/tools/sdk/include/newlib/sys/reent.h @@ -402,7 +402,7 @@ struct _reent char *_asctime_buf; /* signal info */ - void (**(_sig_func))(int); + void (**_sig_func)(int); # ifndef _REENT_GLOBAL_ATEXIT /* atexit stuff */ diff --git a/tools/sdk/include/newlib/sys/termios.h b/tools/sdk/include/newlib/sys/termios.h new file mode 100644 index 00000000..fd0eb5ca --- /dev/null +++ b/tools/sdk/include/newlib/sys/termios.h @@ -0,0 +1,296 @@ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// This header file is based on the termios header of +// "The Single UNIX (r) Specification, Version 2, Copyright (c) 1997 The Open Group". + +#ifndef __ESP_SYS_TERMIOS_H__ +#define __ESP_SYS_TERMIOS_H__ + +// ESP-IDF NOTE: This header provides only a compatibility layer for macros and functions defined in sys/termios.h. +// Not everything has a defined meaning for ESP-IDF (e.g. process leader IDs) and therefore are likely to be stubbed +// in actual implementations. + + +#include +#include +#include "sdkconfig.h" + +#ifdef CONFIG_SUPPORT_TERMIOS + +// subscripts for the array c_cc: +#define VEOF 0 /** EOF character */ +#define VEOL 1 /** EOL character */ +#define VERASE 2 /** ERASE character */ +#define VINTR 3 /** INTR character */ +#define VKILL 4 /** KILL character */ +#define VMIN 5 /** MIN value */ +#define VQUIT 6 /** QUIT character */ +#define VSTART 7 /** START character */ +#define VSTOP 8 /** STOP character */ +#define VSUSP 9 /** SUSP character */ +#define VTIME 10 /** TIME value */ +#define NCCS (VTIME + 1) /** Size of the array c_cc for control characters */ + +// input modes for use as flags in the c_iflag field +#define BRKINT (1u << 0) /** Signal interrupt on break. */ +#define ICRNL (1u << 1) /** Map CR to NL on input. */ +#define IGNBRK (1u << 2) /** Ignore break condition. */ +#define IGNCR (1u << 3) /** Ignore CR. */ +#define IGNPAR (1u << 4) /** Ignore characters with parity errors. */ +#define INLCR (1u << 5) /** Map NL to CR on input. */ +#define INPCK (1u << 6) /** Enable input parity check. */ +#define ISTRIP (1u << 7) /** Strip character. */ +#define IUCLC (1u << 8) /** Map upper-case to lower-case on input (LEGACY). */ +#define IXANY (1u << 9) /** Enable any character to restart output. */ +#define IXOFF (1u << 10) /** Enable start/stop input control. */ +#define IXON (1u << 11) /** Enable start/stop output control. */ +#define PARMRK (1u << 12) /** Mark parity errors. */ + +// output Modes for use as flags in the c_oflag field +#define OPOST (1u << 0) /** Post-process output */ +#define OLCUC (1u << 1) /** Map lower-case to upper-case on output (LEGACY). */ +#define ONLCR (1u << 2) /** Map NL to CR-NL on output. */ +#define OCRNL (1u << 3) /** Map CR to NL on output. */ +#define ONOCR (1u << 4) /** No CR output at column 0. */ +#define ONLRET (1u << 5) /** NL performs CR function. */ +#define OFILL (1u << 6) /** Use fill characters for delay. */ +#define NLDLY (1u << 7) /** Select newline delays: */ +#define NL0 (0u << 7) /** Newline character type 0. */ +#define NL1 (1u << 7) /** Newline character type 1. */ +#define CRDLY (3u << 8) /** Select carriage-return delays: */ +#define CR0 (0u << 8) /** Carriage-return delay type 0. */ +#define CR1 (1u << 8) /** Carriage-return delay type 1. */ +#define CR2 (2u << 8) /** Carriage-return delay type 2. */ +#define CR3 (3u << 8) /** Carriage-return delay type 3. */ +#define TABDLY (3u << 10) /** Select horizontal-tab delays: */ +#define TAB0 (0u << 10) /** Horizontal-tab delay type 0. */ +#define TAB1 (1u << 10) /** Horizontal-tab delay type 1. */ +#define TAB2 (2u << 10) /** Horizontal-tab delay type 2. */ +#define TAB3 (3u << 10) /** Expand tabs to spaces. */ +#define BSDLY (1u << 12) /** Select backspace delays: */ +#define BS0 (0u << 12) /** Backspace-delay type 0. */ +#define BS1 (1u << 12) /** Backspace-delay type 1. */ +#define VTDLY (1u << 13) /** Select vertical-tab delays: */ +#define VT0 (0u << 13) /** Vertical-tab delay type 0. */ +#define VT1 (1u << 13) /** Vertical-tab delay type 1. */ +#define FFDLY (1u << 14) /** Select form-feed delays: */ +#define FF0 (0u << 14) /** Form-feed delay type 0. */ +#define FF1 (1u << 14) /** Form-feed delay type 1. */ + +// Baud Rate Selection. Valid values for objects of type speed_t: +// CBAUD range B0 - B38400 +#define B0 0 /** Hang up */ +#define B50 1 +#define B75 2 +#define B110 3 +#define B134 4 +#define B150 5 +#define B200 6 +#define B300 7 +#define B600 8 +#define B1200 9 +#define B1800 10 +#define B2400 11 +#define B4800 12 +#define B9600 13 +#define B19200 14 +#define B38400 15 +// CBAUDEX range B57600 - B4000000 +#define B57600 16 +#define B115200 17 +#define B230400 18 +#define B460800 19 +#define B500000 20 +#define B576000 21 +#define B921600 22 +#define B1000000 23 +#define B1152000 24 +#define B1500000 25 +#define B2000000 26 +#define B2500000 27 +#define B3000000 28 +#define B3500000 29 +#define B4000000 30 + +// Control Modes for the c_cflag field: +#define CSIZE (3u << 0) /* Character size: */ +#define CS5 (0u << 0) /** 5 bits. */ +#define CS6 (1u << 0) /** 6 bits. */ +#define CS7 (2u << 0) /** 7 bits. */ +#define CS8 (3u << 0) /** 8 bits. */ +#define CSTOPB (1u << 2) /** Send two stop bits, else one. */ +#define CREAD (1u << 3) /** Enable receiver. */ +#define PARENB (1u << 4) /** Parity enable. */ +#define PARODD (1u << 5) /** Odd parity, else even. */ +#define HUPCL (1u << 6) /** Hang up on last close. */ +#define CLOCAL (1u << 7) /** Ignore modem status lines. */ +#define CBAUD (1u << 8) /** Use baud rates defined by B0-B38400 macros. */ +#define CBAUDEX (1u << 9) /** Use baud rates defined by B57600-B4000000 macros. */ +#define BOTHER (1u << 10) /** Use custom baud rates */ + +// Local Modes for c_lflag field: +#define ECHO (1u << 0) /** Enable echo. */ +#define ECHOE (1u << 1) /** Echo erase character as error-correcting backspace. */ +#define ECHOK (1u << 2) /** Echo KILL. */ +#define ECHONL (1u << 3) /** Echo NL. */ +#define ICANON (1u << 4) /** Canonical input (erase and kill processing). */ +#define IEXTEN (1u << 5) /** Enable extended input character processing. */ +#define ISIG (1u << 6) /** Enable signals. */ +#define NOFLSH (1u << 7) /** Disable flush after interrupt or quit. */ +#define TOSTOP (1u << 8) /** Send SIGTTOU for background output. */ +#define XCASE (1u << 9) /** Canonical upper/lower presentation (LEGACY). */ + +// Attribute Selection constants for use with tcsetattr(): +#define TCSANOW 0 /** Change attributes immediately. */ +#define TCSADRAIN 1 /** Change attributes when output has drained. */ +#define TCSAFLUSH 2 /** Change attributes when output has drained; also flush pending input. */ + +// Line Control constants for use with tcflush(): +#define TCIFLUSH 0 /** Flush pending input. Flush untransmitted output. */ +#define TCIOFLUSH 1 /** Flush both pending input and untransmitted output. */ +#define TCOFLUSH 2 /** Flush untransmitted output. */ + +// constants for use with tcflow(): +#define TCIOFF 0 /** Transmit a STOP character, intended to suspend input data. */ +#define TCION 1 /** Transmit a START character, intended to restart input data. */ +#define TCOOFF 2 /** Suspend output. */ +#define TCOON 3 /** Restart output. */ + +typedef uint8_t cc_t; +typedef uint32_t speed_t; +typedef uint16_t tcflag_t; + +struct termios +{ + tcflag_t c_iflag; /** Input modes */ + tcflag_t c_oflag; /** Output modes */ + tcflag_t c_cflag; /** Control modes */ + tcflag_t c_lflag; /** Local modes */ + cc_t c_cc[NCCS]; /** Control characters */ + speed_t c_ispeed; /** input baud rate */ + speed_t c_ospeed; /** output baud rate */ +}; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Extracts the input baud rate from the input structure exactly (without interpretation). + * + * @param p input termios structure + * @return input baud rate + */ +speed_t cfgetispeed(const struct termios *p); + +/** + * @brief Extracts the output baud rate from the input structure exactly (without interpretation). + * + * @param p input termios structure + * @return output baud rate + */ +speed_t cfgetospeed(const struct termios *p); + +/** + * @brief Set input baud rate in the termios structure + * + * There is no effect in hardware until a subsequent call of tcsetattr(). + * + * @param p input termios structure + * @param sp input baud rate + * @return 0 when successful, -1 otherwise with errno set + */ +int cfsetispeed(struct termios *p, speed_t sp); + +/** + * @brief Set output baud rate in the termios structure + * + * There is no effect in hardware until a subsequent call of tcsetattr(). + * + * @param p input termios structure + * @param sp output baud rate + * @return 0 when successful, -1 otherwise with errno set + */ +int cfsetospeed(struct termios *p, speed_t sp); + +/** + * @brief Wait for transmission of output + * + * @param fd file descriptor of the terminal + * @return 0 when successful, -1 otherwise with errno set + */ +int tcdrain(int fd); + +/** + * @brief Suspend or restart the transmission or reception of data + * + * @param fd file descriptor of the terminal + * @param action selects actions to do + * @return 0 when successful, -1 otherwise with errno set + */ +int tcflow(int fd, int action); + +/** + * @brief Flush non-transmitted output data and non-read input data + * + * @param fd file descriptor of the terminal + * @param select selects what should be flushed + * @return 0 when successful, -1 otherwise with errno set + */ +int tcflush(int fd, int select); + +/** + * @brief Gets the parameters of the terminal + * + * @param fd file descriptor of the terminal + * @param p output termios structure + * @return 0 when successful, -1 otherwise with errno set + */ +int tcgetattr(int fd, struct termios *p); + +/** + * @brief Get process group ID for session leader for controlling terminal + * + * @param fd file descriptor of the terminal + * @return process group ID when successful, -1 otherwise with errno set + */ +pid_t tcgetsid(int fd); + +/** + * @brief Send a break for a specific duration + * + * @param fd file descriptor of the terminal + * @param duration duration of break + * @return 0 when successful, -1 otherwise with errno set + */ +int tcsendbreak(int fd, int duration); + +/** + * @brief Sets the parameters of the terminal + * + * @param fd file descriptor of the terminal + * @param optional_actions optional actions + * @param p input termios structure + * @return 0 when successful, -1 otherwise with errno set + */ +int tcsetattr(int fd, int optional_actions, const struct termios *p); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // CONFIG_SUPPORT_TERMIOS + +#endif //__ESP_SYS_TERMIOS_H__ diff --git a/tools/sdk/include/newlib/sys/uio.h b/tools/sdk/include/newlib/sys/uio.h new file mode 100644 index 00000000..ede27b23 --- /dev/null +++ b/tools/sdk/include/newlib/sys/uio.h @@ -0,0 +1,21 @@ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#ifndef _ESP_PLATFORM_SYS_UIO_H_ +#define _ESP_PLATFORM_SYS_UIO_H_ + +int writev(int s, const struct iovec *iov, int iovcnt); + +ssize_t readv(int fd, const struct iovec *iov, int iovcnt); + +#endif // _ESP_PLATFORM_SYS_UIO_H_ diff --git a/tools/sdk/include/newlib/sys/un.h b/tools/sdk/include/newlib/sys/un.h new file mode 100644 index 00000000..a99b1832 --- /dev/null +++ b/tools/sdk/include/newlib/sys/un.h @@ -0,0 +1,24 @@ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#ifndef _ESP_PLATFORM_SYS_UN_H_ +#define _ESP_PLATFORM_SYS_UN_H_ + +#define AF_UNIX 1 /* local to host (pipes) */ + +struct sockaddr_un { + short sun_family; /*AF_UNIX*/ + char sun_path[108]; /*path name */ +}; + +#endif // _ESP_PLATFORM_SYS_UN_H_ diff --git a/tools/sdk/include/newlib/sys/unistd.h b/tools/sdk/include/newlib/sys/unistd.h index e76c84b9..e09b68be 100644 --- a/tools/sdk/include/newlib/sys/unistd.h +++ b/tools/sdk/include/newlib/sys/unistd.h @@ -23,6 +23,7 @@ extern "C" { #include_next int _EXFUN(truncate, (const char *, off_t __length)); +int _EXFUN(gethostname, (char *__name, size_t __len)); #ifdef __cplusplus } diff --git a/tools/sdk/include/newlib/time.h b/tools/sdk/include/newlib/time.h index d7b6612d..954d824d 100644 --- a/tools/sdk/include/newlib/time.h +++ b/tools/sdk/include/newlib/time.h @@ -1,291 +1,35 @@ -/* - * time.h - * - * Struct and function declarations for dealing with time. - */ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. -#ifndef _TIME_H_ -#define _TIME_H_ -#include "_ansi.h" -#include - -#define __need_size_t -#define __need_NULL -#include - -/* Get _CLOCKS_PER_SEC_ */ -#include - -#ifndef _CLOCKS_PER_SEC_ -#define _CLOCKS_PER_SEC_ 1000 -#endif - -#define CLOCKS_PER_SEC _CLOCKS_PER_SEC_ -#define CLK_TCK CLOCKS_PER_SEC - -#include - -_BEGIN_STD_C - -struct tm -{ - int tm_sec; - int tm_min; - int tm_hour; - int tm_mday; - int tm_mon; - int tm_year; - int tm_wday; - int tm_yday; - int tm_isdst; -#ifdef __TM_GMTOFF - long __TM_GMTOFF; -#endif -#ifdef __TM_ZONE - const char *__TM_ZONE; -#endif -}; - -clock_t _EXFUN(clock, (void)); -double _EXFUN(difftime, (time_t _time2, time_t _time1)); -time_t _EXFUN(mktime, (struct tm *_timeptr)); -time_t _EXFUN(time, (time_t *_timer)); -#ifndef _REENT_ONLY -char *_EXFUN(asctime, (const struct tm *_tblock)); -char *_EXFUN(ctime, (const time_t *_time)); -struct tm *_EXFUN(gmtime, (const time_t *_timer)); -struct tm *_EXFUN(localtime,(const time_t *_timer)); -#endif -size_t _EXFUN(strftime, (char *__restrict _s, - size_t _maxsize, const char *__restrict _fmt, - const struct tm *__restrict _t)); - -char *_EXFUN(asctime_r, (const struct tm *__restrict, - char *__restrict)); -char *_EXFUN(ctime_r, (const time_t *, char *)); -struct tm *_EXFUN(gmtime_r, (const time_t *__restrict, - struct tm *__restrict)); -struct tm *_EXFUN(localtime_r, (const time_t *__restrict, - struct tm *__restrict)); - -_END_STD_C +#ifndef _ESP_TIME_H +#define _ESP_TIME_H #ifdef __cplusplus extern "C" { #endif +#include_next -#ifndef __STRICT_ANSI__ -char *_EXFUN(strptime, (const char *__restrict, - const char *__restrict, - struct tm *__restrict)); -_VOID _EXFUN(tzset, (_VOID)); -_VOID _EXFUN(_tzset_r, (struct _reent *)); - -typedef struct __tzrule_struct -{ - char ch; - int m; - int n; - int d; - int s; - time_t change; - long offset; /* Match type of _timezone. */ -} __tzrule_type; - -typedef struct __tzinfo_struct -{ - int __tznorth; - int __tzyear; - __tzrule_type __tzrule[2]; -} __tzinfo_type; - -__tzinfo_type *_EXFUN (__gettzinfo, (_VOID)); - -/* getdate functions */ - -#ifdef HAVE_GETDATE -#ifndef _REENT_ONLY -#define getdate_err (*__getdate_err()) -int *_EXFUN(__getdate_err,(_VOID)); - -struct tm * _EXFUN(getdate, (const char *)); -/* getdate_err is set to one of the following values to indicate the error. - 1 the DATEMSK environment variable is null or undefined, - 2 the template file cannot be opened for reading, - 3 failed to get file status information, - 4 the template file is not a regular file, - 5 an error is encountered while reading the template file, - 6 memory allication failed (not enough memory available), - 7 there is no line in the template that matches the input, - 8 invalid input specification */ -#endif /* !_REENT_ONLY */ - -/* getdate_r returns the error code as above */ -int _EXFUN(getdate_r, (const char *, struct tm *)); -#endif /* HAVE_GETDATE */ - -/* defines for the opengroup specifications Derived from Issue 1 of the SVID. */ -extern __IMPORT long _timezone; -extern __IMPORT int _daylight; -extern __IMPORT char *_tzname[2]; - -/* POSIX defines the external tzname being defined in time.h */ -#ifndef tzname -#define tzname _tzname -#endif -#endif /* !__STRICT_ANSI__ */ - -#ifdef __cplusplus -} -#endif - -#include - -#ifdef __CYGWIN__ -#include -#endif /*__CYGWIN__*/ - -#if defined(_POSIX_TIMERS) - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* Clocks, P1003.1b-1993, p. 263 */ +#define _POSIX_TIMERS 1 +#define CLOCK_MONOTONIC (clockid_t)4 +#define CLOCK_BOOTTIME (clockid_t)4 int _EXFUN(clock_settime, (clockid_t clock_id, const struct timespec *tp)); int _EXFUN(clock_gettime, (clockid_t clock_id, struct timespec *tp)); int _EXFUN(clock_getres, (clockid_t clock_id, struct timespec *res)); -/* Create a Per-Process Timer, P1003.1b-1993, p. 264 */ - -int _EXFUN(timer_create, - (clockid_t clock_id, - struct sigevent *__restrict evp, - timer_t *__restrict timerid)); - -/* Delete a Per_process Timer, P1003.1b-1993, p. 266 */ - -int _EXFUN(timer_delete, (timer_t timerid)); - -/* Per-Process Timers, P1003.1b-1993, p. 267 */ - -int _EXFUN(timer_settime, - (timer_t timerid, int flags, - const struct itimerspec *__restrict value, - struct itimerspec *__restrict ovalue)); -int _EXFUN(timer_gettime, (timer_t timerid, struct itimerspec *value)); -int _EXFUN(timer_getoverrun, (timer_t timerid)); - -/* High Resolution Sleep, P1003.1b-1993, p. 269 */ - -int _EXFUN(nanosleep, (const struct timespec *rqtp, struct timespec *rmtp)); - #ifdef __cplusplus } #endif -#endif /* _POSIX_TIMERS */ - -#if defined(_POSIX_CLOCK_SELECTION) - -#ifdef __cplusplus -extern "C" { -#endif - -int _EXFUN(clock_nanosleep, - (clockid_t clock_id, int flags, const struct timespec *rqtp, - struct timespec *rmtp)); - -#ifdef __cplusplus -} -#endif - -#endif /* _POSIX_CLOCK_SELECTION */ - -#ifdef __cplusplus -extern "C" { -#endif - -/* CPU-time Clock Attributes, P1003.4b/D8, p. 54 */ - -/* values for the clock enable attribute */ - -#define CLOCK_ENABLED 1 /* clock is enabled, i.e. counting execution time */ -#define CLOCK_DISABLED 0 /* clock is disabled */ - -/* values for the pthread cputime_clock_allowed attribute */ - -#define CLOCK_ALLOWED 1 /* If a thread is created with this value a */ - /* CPU-time clock attached to that thread */ - /* shall be accessible. */ -#define CLOCK_DISALLOWED 0 /* If a thread is created with this value, the */ - /* thread shall not have a CPU-time clock */ - /* accessible. */ - -/* Manifest Constants, P1003.1b-1993, p. 262 */ - -#define CLOCK_REALTIME (clockid_t)1 - -/* Flag indicating time is "absolute" with respect to the clock - associated with a time. */ - -#define TIMER_ABSTIME 4 - -/* Manifest Constants, P1003.4b/D8, p. 55 */ - -#if defined(_POSIX_CPUTIME) - -/* When used in a clock or timer function call, this is interpreted as - the identifier of the CPU_time clock associated with the PROCESS - making the function call. */ - -#define CLOCK_PROCESS_CPUTIME_ID (clockid_t)2 - -#endif - -#if defined(_POSIX_THREAD_CPUTIME) - -/* When used in a clock or timer function call, this is interpreted as - the identifier of the CPU_time clock associated with the THREAD - making the function call. */ - -#define CLOCK_THREAD_CPUTIME_ID (clockid_t)3 - -#endif - -#if defined(_POSIX_MONOTONIC_CLOCK) - -/* The identifier for the system-wide monotonic clock, which is defined - * as a clock whose value cannot be set via clock_settime() and which - * cannot have backward clock jumps. */ - -#define CLOCK_MONOTONIC (clockid_t)4 - -#endif - -#if defined(_POSIX_CPUTIME) - -/* Accessing a Process CPU-time CLock, P1003.4b/D8, p. 55 */ - -int _EXFUN(clock_getcpuclockid, (pid_t pid, clockid_t *clock_id)); - -#endif /* _POSIX_CPUTIME */ - -#if defined(_POSIX_CPUTIME) || defined(_POSIX_THREAD_CPUTIME) - -/* CPU-time Clock Attribute Access, P1003.4b/D8, p. 56 */ - -int _EXFUN(clock_setenable_attr, (clockid_t clock_id, int attr)); -int _EXFUN(clock_getenable_attr, (clockid_t clock_id, int *attr)); - -#endif /* _POSIX_CPUTIME or _POSIX_THREAD_CPUTIME */ - -#ifdef __cplusplus -} -#endif - -#endif /* _TIME_H_ */ - +#endif /* _ESP_TIME_H */ diff --git a/tools/sdk/include/nvs_flash/nvs.h b/tools/sdk/include/nvs_flash/nvs.h index b3ba37fb..bcc46563 100644 --- a/tools/sdk/include/nvs_flash/nvs.h +++ b/tools/sdk/include/nvs_flash/nvs.h @@ -44,6 +44,7 @@ typedef uint32_t nvs_handle; #define ESP_ERR_NVS_NO_FREE_PAGES (ESP_ERR_NVS_BASE + 0x0d) /*!< NVS partition doesn't contain any empty pages. This may happen if NVS partition was truncated. Erase the whole partition and call nvs_flash_init again. */ #define ESP_ERR_NVS_VALUE_TOO_LONG (ESP_ERR_NVS_BASE + 0x0e) /*!< String or blob length is longer than supported by the implementation */ #define ESP_ERR_NVS_PART_NOT_FOUND (ESP_ERR_NVS_BASE + 0x0f) /*!< Partition with specified name is not found in the partition table */ +#define ESP_ERR_NVS_NEW_VERSION_FOUND (ESP_ERR_NVS_BASE + 0x10) /*!< NVS partition contains data in new format and cannot be recognized by this version of code */ #define NVS_DEFAULT_PART_NAME "nvs" /*!< Default partition name of the NVS partition in the partition table */ /** @@ -126,7 +127,7 @@ esp_err_t nvs_open_from_partition(const char *part_name, const char* name, nvs_o * 15 characters. Shouldn't be empty. * @param[in] value The value to set. * For strings, the maximum length (including null character) is - * 1984 bytes. + * 4000 bytes. * * @return * - ESP_OK if value was set successfully @@ -163,7 +164,8 @@ esp_err_t nvs_set_str (nvs_handle handle, const char* key, const char* value); * @param[in] key Key name. Maximal length is 15 characters. Shouldn't be empty. * @param[in] value The value to set. * @param[in] length length of binary value to set, in bytes; Maximum length is - * 1984 bytes. + * 508000 bytes or (97.6% of the partition size - 4000) bytes + * whichever is lower. * * @return * - ESP_OK if value was set successfully diff --git a/tools/sdk/include/openssl/internal/x509_vfy.h b/tools/sdk/include/openssl/internal/x509_vfy.h index d5b0d1a2..fec367d5 100644 --- a/tools/sdk/include/openssl/internal/x509_vfy.h +++ b/tools/sdk/include/openssl/internal/x509_vfy.h @@ -1,111 +1,111 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _X509_VFY_H_ -#define _X509_VFY_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -#define X509_V_OK 0 -#define X509_V_ERR_UNSPECIFIED 1 -#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT 2 -#define X509_V_ERR_UNABLE_TO_GET_CRL 3 -#define X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE 4 -#define X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE 5 -#define X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY 6 -#define X509_V_ERR_CERT_SIGNATURE_FAILURE 7 -#define X509_V_ERR_CRL_SIGNATURE_FAILURE 8 -#define X509_V_ERR_CERT_NOT_YET_VALID 9 -#define X509_V_ERR_CERT_HAS_EXPIRED 10 -#define X509_V_ERR_CRL_NOT_YET_VALID 11 -#define X509_V_ERR_CRL_HAS_EXPIRED 12 -#define X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD 13 -#define X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD 14 -#define X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD 15 -#define X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD 16 -#define X509_V_ERR_OUT_OF_MEM 17 -#define X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT 18 -#define X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN 19 -#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY 20 -#define X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE 21 -#define X509_V_ERR_CERT_CHAIN_TOO_LONG 22 -#define X509_V_ERR_CERT_REVOKED 23 -#define X509_V_ERR_INVALID_CA 24 -#define X509_V_ERR_PATH_LENGTH_EXCEEDED 25 -#define X509_V_ERR_INVALID_PURPOSE 26 -#define X509_V_ERR_CERT_UNTRUSTED 27 -#define X509_V_ERR_CERT_REJECTED 28 -/* These are 'informational' when looking for issuer cert */ -#define X509_V_ERR_SUBJECT_ISSUER_MISMATCH 29 -#define X509_V_ERR_AKID_SKID_MISMATCH 30 -#define X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH 31 -#define X509_V_ERR_KEYUSAGE_NO_CERTSIGN 32 -#define X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER 33 -#define X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION 34 -#define X509_V_ERR_KEYUSAGE_NO_CRL_SIGN 35 -#define X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION 36 -#define X509_V_ERR_INVALID_NON_CA 37 -#define X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED 38 -#define X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE 39 -#define X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED 40 -#define X509_V_ERR_INVALID_EXTENSION 41 -#define X509_V_ERR_INVALID_POLICY_EXTENSION 42 -#define X509_V_ERR_NO_EXPLICIT_POLICY 43 -#define X509_V_ERR_DIFFERENT_CRL_SCOPE 44 -#define X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE 45 -#define X509_V_ERR_UNNESTED_RESOURCE 46 -#define X509_V_ERR_PERMITTED_VIOLATION 47 -#define X509_V_ERR_EXCLUDED_VIOLATION 48 -#define X509_V_ERR_SUBTREE_MINMAX 49 -/* The application is not happy */ -#define X509_V_ERR_APPLICATION_VERIFICATION 50 -#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE 51 -#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX 52 -#define X509_V_ERR_UNSUPPORTED_NAME_SYNTAX 53 -#define X509_V_ERR_CRL_PATH_VALIDATION_ERROR 54 -/* Another issuer check debug option */ -#define X509_V_ERR_PATH_LOOP 55 -/* Suite B mode algorithm violation */ -#define X509_V_ERR_SUITE_B_INVALID_VERSION 56 -#define X509_V_ERR_SUITE_B_INVALID_ALGORITHM 57 -#define X509_V_ERR_SUITE_B_INVALID_CURVE 58 -#define X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM 59 -#define X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED 60 -#define X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 61 -/* Host, email and IP check errors */ -#define X509_V_ERR_HOSTNAME_MISMATCH 62 -#define X509_V_ERR_EMAIL_MISMATCH 63 -#define X509_V_ERR_IP_ADDRESS_MISMATCH 64 -/* DANE TLSA errors */ -#define X509_V_ERR_DANE_NO_MATCH 65 -/* security level errors */ -#define X509_V_ERR_EE_KEY_TOO_SMALL 66 -#define X509_V_ERR_CA_KEY_TOO_SMALL 67 -#define X509_V_ERR_CA_MD_TOO_WEAK 68 -/* Caller error */ -#define X509_V_ERR_INVALID_CALL 69 -/* Issuer lookup error */ -#define X509_V_ERR_STORE_LOOKUP 70 -/* Certificate transparency */ -#define X509_V_ERR_NO_VALID_SCTS 71 - -#define X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION 72 - -#ifdef __cplusplus -} -#endif - -#endif +// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _X509_VFY_H_ +#define _X509_VFY_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#define X509_V_OK 0 +#define X509_V_ERR_UNSPECIFIED 1 +#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT 2 +#define X509_V_ERR_UNABLE_TO_GET_CRL 3 +#define X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE 4 +#define X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE 5 +#define X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY 6 +#define X509_V_ERR_CERT_SIGNATURE_FAILURE 7 +#define X509_V_ERR_CRL_SIGNATURE_FAILURE 8 +#define X509_V_ERR_CERT_NOT_YET_VALID 9 +#define X509_V_ERR_CERT_HAS_EXPIRED 10 +#define X509_V_ERR_CRL_NOT_YET_VALID 11 +#define X509_V_ERR_CRL_HAS_EXPIRED 12 +#define X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD 13 +#define X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD 14 +#define X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD 15 +#define X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD 16 +#define X509_V_ERR_OUT_OF_MEM 17 +#define X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT 18 +#define X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN 19 +#define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY 20 +#define X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE 21 +#define X509_V_ERR_CERT_CHAIN_TOO_LONG 22 +#define X509_V_ERR_CERT_REVOKED 23 +#define X509_V_ERR_INVALID_CA 24 +#define X509_V_ERR_PATH_LENGTH_EXCEEDED 25 +#define X509_V_ERR_INVALID_PURPOSE 26 +#define X509_V_ERR_CERT_UNTRUSTED 27 +#define X509_V_ERR_CERT_REJECTED 28 +/* These are 'informational' when looking for issuer cert */ +#define X509_V_ERR_SUBJECT_ISSUER_MISMATCH 29 +#define X509_V_ERR_AKID_SKID_MISMATCH 30 +#define X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH 31 +#define X509_V_ERR_KEYUSAGE_NO_CERTSIGN 32 +#define X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER 33 +#define X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION 34 +#define X509_V_ERR_KEYUSAGE_NO_CRL_SIGN 35 +#define X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION 36 +#define X509_V_ERR_INVALID_NON_CA 37 +#define X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED 38 +#define X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE 39 +#define X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED 40 +#define X509_V_ERR_INVALID_EXTENSION 41 +#define X509_V_ERR_INVALID_POLICY_EXTENSION 42 +#define X509_V_ERR_NO_EXPLICIT_POLICY 43 +#define X509_V_ERR_DIFFERENT_CRL_SCOPE 44 +#define X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE 45 +#define X509_V_ERR_UNNESTED_RESOURCE 46 +#define X509_V_ERR_PERMITTED_VIOLATION 47 +#define X509_V_ERR_EXCLUDED_VIOLATION 48 +#define X509_V_ERR_SUBTREE_MINMAX 49 +/* The application is not happy */ +#define X509_V_ERR_APPLICATION_VERIFICATION 50 +#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE 51 +#define X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX 52 +#define X509_V_ERR_UNSUPPORTED_NAME_SYNTAX 53 +#define X509_V_ERR_CRL_PATH_VALIDATION_ERROR 54 +/* Another issuer check debug option */ +#define X509_V_ERR_PATH_LOOP 55 +/* Suite B mode algorithm violation */ +#define X509_V_ERR_SUITE_B_INVALID_VERSION 56 +#define X509_V_ERR_SUITE_B_INVALID_ALGORITHM 57 +#define X509_V_ERR_SUITE_B_INVALID_CURVE 58 +#define X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM 59 +#define X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED 60 +#define X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 61 +/* Host, email and IP check errors */ +#define X509_V_ERR_HOSTNAME_MISMATCH 62 +#define X509_V_ERR_EMAIL_MISMATCH 63 +#define X509_V_ERR_IP_ADDRESS_MISMATCH 64 +/* DANE TLSA errors */ +#define X509_V_ERR_DANE_NO_MATCH 65 +/* security level errors */ +#define X509_V_ERR_EE_KEY_TOO_SMALL 66 +#define X509_V_ERR_CA_KEY_TOO_SMALL 67 +#define X509_V_ERR_CA_MD_TOO_WEAK 68 +/* Caller error */ +#define X509_V_ERR_INVALID_CALL 69 +/* Issuer lookup error */ +#define X509_V_ERR_STORE_LOOKUP 70 +/* Certificate transparency */ +#define X509_V_ERR_NO_VALID_SCTS 71 + +#define X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION 72 + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/openssl/openssl/ssl.h b/tools/sdk/include/openssl/openssl/ssl.h index 95fd6e9e..88d7bca6 100644 --- a/tools/sdk/include/openssl/openssl/ssl.h +++ b/tools/sdk/include/openssl/openssl/ssl.h @@ -1,1822 +1,1822 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _SSL_H_ -#define _SSL_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -#include "internal/ssl_x509.h" -#include "internal/ssl_pkey.h" - -/* -{ -*/ - -#define SSL_CB_ALERT 0x4000 - -#define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT (1 << 0) -#define X509_CHECK_FLAG_NO_WILDCARDS (1 << 1) -#define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS (1 << 2) -#define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS (1 << 3) -#define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS (1 << 4) - -/** - * @brief create a SSL context - * - * @param method - the SSL context method point - * - * @return the context point - */ -SSL_CTX* SSL_CTX_new(const SSL_METHOD *method); - -/** - * @brief free a SSL context - * - * @param method - the SSL context point - * - * @return none - */ -void SSL_CTX_free(SSL_CTX *ctx); - -/** - * @brief create a SSL - * - * @param ctx - the SSL context point - * - * @return the SSL point - */ -SSL* SSL_new(SSL_CTX *ctx); - -/** - * @brief free the SSL - * - * @param ssl - the SSL point - * - * @return none - */ -void SSL_free(SSL *ssl); - -/** - * @brief connect to the remote SSL server - * - * @param ssl - the SSL point - * - * @return result - * 1 : OK - * -1 : failed - */ -int SSL_connect(SSL *ssl); - -/** - * @brief accept the remote connection - * - * @param ssl - the SSL point - * - * @return result - * 1 : OK - * -1 : failed - */ -int SSL_accept(SSL *ssl); - -/** - * @brief read data from to remote - * - * @param ssl - the SSL point which has been connected - * @param buffer - the received data buffer point - * @param len - the received data length - * - * @return result - * > 0 : OK, and return received data bytes - * = 0 : connection is closed - * < 0 : an error catch - */ -int SSL_read(SSL *ssl, void *buffer, int len); - -/** - * @brief send the data to remote - * - * @param ssl - the SSL point which has been connected - * @param buffer - the send data buffer point - * @param len - the send data length - * - * @return result - * > 0 : OK, and return sent data bytes - * = 0 : connection is closed - * < 0 : an error catch - */ -int SSL_write(SSL *ssl, const void *buffer, int len); - -/** - * @brief get the verifying result of the SSL certification - * - * @param ssl - the SSL point - * - * @return the result of verifying - */ -long SSL_get_verify_result(const SSL *ssl); - -/** - * @brief shutdown the connection - * - * @param ssl - the SSL point - * - * @return result - * 1 : OK - * 0 : shutdown is not finished - * -1 : an error catch - */ -int SSL_shutdown(SSL *ssl); - -/** - * @brief bind the socket file description into the SSL - * - * @param ssl - the SSL point - * @param fd - socket handle - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_set_fd(SSL *ssl, int fd); - -/** - * @brief Set the hostname for SNI - * - * @param ssl - the SSL context point - * @param hostname - pointer to the hostname - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_set_tlsext_host_name(SSL* ssl, const char *hostname); - -/** - * @brief These functions load the private key into the SSL_CTX or SSL object - * - * @param ctx - the SSL context point - * @param pkey - private key object point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey); - -/** - * @brief These functions load the certification into the SSL_CTX or SSL object - * - * @param ctx - the SSL context point - * @param pkey - certification object point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x); - -/** - * @brief create the target SSL context client method - * - * @param none - * - * @return the SSLV2.3 version SSL context client method - */ -const SSL_METHOD* SSLv23_client_method(void); - -/** - * @brief create the target SSL context client method - * - * @param none - * - * @return the TLSV1.0 version SSL context client method - */ -const SSL_METHOD* TLSv1_client_method(void); - -/** - * @brief create the target SSL context client method - * - * @param none - * - * @return the SSLV1.0 version SSL context client method - */ -const SSL_METHOD* SSLv3_client_method(void); - -/** - * @brief create the target SSL context client method - * - * @param none - * - * @return the TLSV1.1 version SSL context client method - */ -const SSL_METHOD* TLSv1_1_client_method(void); - -/** - * @brief create the target SSL context client method - * - * @param none - * - * @return the TLSV1.2 version SSL context client method - */ -const SSL_METHOD* TLSv1_2_client_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the TLS any version SSL context client method - */ -const SSL_METHOD* TLS_client_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the SSLV2.3 version SSL context server method - */ -const SSL_METHOD* SSLv23_server_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the TLSV1.1 version SSL context server method - */ -const SSL_METHOD* TLSv1_1_server_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the TLSV1.2 version SSL context server method - */ -const SSL_METHOD* TLSv1_2_server_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the TLSV1.0 version SSL context server method - */ -const SSL_METHOD* TLSv1_server_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the SSLV3.0 version SSL context server method - */ -const SSL_METHOD* SSLv3_server_method(void); - -/** - * @brief create the target SSL context server method - * - * @param none - * - * @return the TLS any version SSL context server method - */ -const SSL_METHOD* TLS_server_method(void); - - -/** - * @brief set the SSL context ALPN select callback function - * - * @param ctx - SSL context point - * @param cb - ALPN select callback function - * @param arg - ALPN select callback function entry private data point - * - * @return none - */ -void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, - int (*cb) (SSL *ssl, - const unsigned char **out, - unsigned char *outlen, - const unsigned char *in, - unsigned int inlen, - void *arg), - void *arg); - - -/** - * @brief set the SSL context ALPN select protocol - * - * @param ctx - SSL context point - * @param protos - ALPN protocol name - * @param protos_len - ALPN protocol name bytes - * - * @return result - * 0 : OK - * 1 : failed - */ -int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos, unsigned int protos_len); - -/** - * @brief set the SSL context next ALPN select callback function - * - * @param ctx - SSL context point - * @param cb - ALPN select callback function - * @param arg - ALPN select callback function entry private data point - * - * @return none - */ -void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx, - int (*cb) (SSL *ssl, - unsigned char **out, - unsigned char *outlen, - const unsigned char *in, - unsigned int inlen, - void *arg), - void *arg); - -/** - * @brief get SSL error code - * - * @param ssl - SSL point - * @param ret_code - SSL return code - * - * @return SSL error number - */ -int SSL_get_error(const SSL *ssl, int ret_code); - -/** - * @brief clear the SSL error code - * - * @param none - * - * @return none - */ -void ERR_clear_error(void); - -/** - * @brief get the current SSL error code - * - * @param none - * - * @return current SSL error number - */ -int ERR_get_error(void); - -/** - * @brief register the SSL error strings - * - * @param none - * - * @return none - */ -void ERR_load_SSL_strings(void); - -/** - * @brief initialize the SSL library - * - * @param none - * - * @return none - */ -void SSL_library_init(void); - -/** - * @brief generates a human-readable string representing the error code e - * and store it into the "ret" point memory - * - * @param e - error code - * @param ret - memory point to store the string - * - * @return the result string point - */ -char *ERR_error_string(unsigned long e, char *ret); - -/** - * @brief add the SSL context option - * - * @param ctx - SSL context point - * @param opt - new SSL context option - * - * @return the SSL context option - */ -unsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long opt); - -/** - * @brief add the SSL context mode - * - * @param ctx - SSL context point - * @param mod - new SSL context mod - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_mode(SSL_CTX *ctx, int mod); - -/* -} -*/ - -/** - * @brief perform the SSL handshake - * - * @param ssl - SSL point - * - * @return result - * 1 : OK - * 0 : failed - * -1 : a error catch - */ -int SSL_do_handshake(SSL *ssl); - -/** - * @brief get the SSL current version - * - * @param ssl - SSL point - * - * @return the version string - */ -const char *SSL_get_version(const SSL *ssl); - -/** - * @brief set the SSL context version - * - * @param ctx - SSL context point - * @param meth - SSL method point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth); - -/** - * @brief get the bytes numbers which are to be read - * - * @param ssl - SSL point - * - * @return bytes number - */ -int SSL_pending(const SSL *ssl); - -/** - * @brief check if SSL want nothing - * - * @param ssl - SSL point - * - * @return result - * 0 : false - * 1 : true - */ -int SSL_want_nothing(const SSL *ssl); - -/** - * @brief check if SSL want to read - * - * @param ssl - SSL point - * - * @return result - * 0 : false - * 1 : true - */ -int SSL_want_read(const SSL *ssl); - -/** - * @brief check if SSL want to write - * - * @param ssl - SSL point - * - * @return result - * 0 : false - * 1 : true - */ -int SSL_want_write(const SSL *ssl); - -/** - * @brief get the SSL context current method - * - * @param ctx - SSL context point - * - * @return the SSL context current method - */ -const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx); - -/** - * @brief get the SSL current method - * - * @param ssl - SSL point - * - * @return the SSL current method - */ -const SSL_METHOD *SSL_get_ssl_method(SSL *ssl); - -/** - * @brief set the SSL method - * - * @param ssl - SSL point - * @param meth - SSL method point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_set_ssl_method(SSL *ssl, const SSL_METHOD *method); - -/** - * @brief add CA client certification into the SSL - * - * @param ssl - SSL point - * @param x - CA certification point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_add_client_CA(SSL *ssl, X509 *x); - -/** - * @brief add CA client certification into the SSL context - * - * @param ctx - SSL context point - * @param x - CA certification point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x); - -/** - * @brief set the SSL CA certification list - * - * @param ssl - SSL point - * @param name_list - CA certification list - * - * @return none - */ -void SSL_set_client_CA_list(SSL *ssl, STACK_OF(X509_NAME) *name_list); - -/** - * @brief set the SSL context CA certification list - * - * @param ctx - SSL context point - * @param name_list - CA certification list - * - * @return none - */ -void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list); - -/** - * @briefget the SSL CA certification list - * - * @param ssl - SSL point - * - * @return CA certification list - */ -STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *ssl); - -/** - * @brief get the SSL context CA certification list - * - * @param ctx - SSL context point - * - * @return CA certification list - */ -STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx); - -/** - * @brief get the SSL certification point - * - * @param ssl - SSL point - * - * @return SSL certification point - */ -X509 *SSL_get_certificate(const SSL *ssl); - -/** - * @brief get the SSL private key point - * - * @param ssl - SSL point - * - * @return SSL private key point - */ -EVP_PKEY *SSL_get_privatekey(const SSL *ssl); - -/** - * @brief set the SSL information callback function - * - * @param ssl - SSL point - * @param cb - information callback function - * - * @return none - */ -void SSL_set_info_callback(SSL *ssl, void (*cb) (const SSL *ssl, int type, int val)); - -/** - * @brief get the SSL state - * - * @param ssl - SSL point - * - * @return SSL state - */ -OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl); - -/** - * @brief set the SSL context read buffer length - * - * @param ctx - SSL context point - * @param len - read buffer length - * - * @return none - */ -void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len); - -/** - * @brief set the SSL read buffer length - * - * @param ssl - SSL point - * @param len - read buffer length - * - * @return none - */ -void SSL_set_default_read_buffer_len(SSL *ssl, size_t len); - -/** - * @brief set the SSL security level - * - * @param ssl - SSL point - * @param level - security level - * - * @return none - */ -void SSL_set_security_level(SSL *ssl, int level); - -/** - * @brief get the SSL security level - * - * @param ssl - SSL point - * - * @return security level - */ -int SSL_get_security_level(const SSL *ssl); - -/** - * @brief get the SSL verifying mode of the SSL context - * - * @param ctx - SSL context point - * - * @return verifying mode - */ -int SSL_CTX_get_verify_mode(const SSL_CTX *ctx); - -/** - * @brief get the SSL verifying depth of the SSL context - * - * @param ctx - SSL context point - * - * @return verifying depth - */ -int SSL_CTX_get_verify_depth(const SSL_CTX *ctx); - -/** - * @brief set the SSL context verifying of the SSL context - * - * @param ctx - SSL context point - * @param mode - verifying mode - * @param verify_callback - verifying callback function - * - * @return none - */ -void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*verify_callback)(int, X509_STORE_CTX *)); - -/** - * @brief set the SSL verifying of the SSL context - * - * @param ctx - SSL point - * @param mode - verifying mode - * @param verify_callback - verifying callback function - * - * @return none - */ -void SSL_set_verify(SSL *s, int mode, int (*verify_callback)(int, X509_STORE_CTX *)); - -/** - * @brief set the SSL verify depth of the SSL context - * - * @param ctx - SSL context point - * @param depth - verifying depth - * - * @return none - */ -void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth); - -/** - * @brief certification verifying callback function - * - * @param preverify_ok - verifying result - * @param x509_ctx - X509 certification point - * - * @return verifying result - */ -int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx); - -/** - * @brief set the session timeout time - * - * @param ctx - SSL context point - * @param t - new session timeout time - * - * @return old session timeout time - */ -long SSL_CTX_set_timeout(SSL_CTX *ctx, long t); - -/** - * @brief get the session timeout time - * - * @param ctx - SSL context point - * - * @return current session timeout time - */ -long SSL_CTX_get_timeout(const SSL_CTX *ctx); - -/** - * @brief set the SSL context cipher through the list string - * - * @param ctx - SSL context point - * @param str - cipher controller list string - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str); - -/** - * @brief set the SSL cipher through the list string - * - * @param ssl - SSL point - * @param str - cipher controller list string - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_set_cipher_list(SSL *ssl, const char *str); - -/** - * @brief get the SSL cipher list string - * - * @param ssl - SSL point - * - * @return cipher controller list string - */ -const char *SSL_get_cipher_list(const SSL *ssl, int n); - -/** - * @brief get the SSL cipher - * - * @param ssl - SSL point - * - * @return current cipher - */ -const SSL_CIPHER *SSL_get_current_cipher(const SSL *ssl); - -/** - * @brief get the SSL cipher string - * - * @param ssl - SSL point - * - * @return cipher string - */ -const char *SSL_get_cipher(const SSL *ssl); - -/** - * @brief get the SSL context object X509 certification storage - * - * @param ctx - SSL context point - * - * @return x509 certification storage - */ -X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx); - -/** - * @brief set the SSL context object X509 certification store - * - * @param ctx - SSL context point - * @param store - X509 certification store - * - * @return none - */ -void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store); - -/** - * @brief get the SSL specifical statement - * - * @param ssl - SSL point - * - * @return specifical statement - */ -int SSL_want(const SSL *ssl); - -/** - * @brief check if the SSL is SSL_X509_LOOKUP state - * - * @param ssl - SSL point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_want_x509_lookup(const SSL *ssl); - -/** - * @brief reset the SSL - * - * @param ssl - SSL point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_clear(SSL *ssl); - -/** - * @brief get the socket handle of the SSL - * - * @param ssl - SSL point - * - * @return result - * >= 0 : yes, and return socket handle - * < 0 : a error catch - */ -int SSL_get_fd(const SSL *ssl); - -/** - * @brief get the read only socket handle of the SSL - * - * @param ssl - SSL point - * - * @return result - * >= 0 : yes, and return socket handle - * < 0 : a error catch - */ -int SSL_get_rfd(const SSL *ssl); - -/** - * @brief get the write only socket handle of the SSL - * - * @param ssl - SSL point - * - * @return result - * >= 0 : yes, and return socket handle - * < 0 : a error catch - */ -int SSL_get_wfd(const SSL *ssl); - -/** - * @brief set the SSL if we can read as many as data - * - * @param ssl - SSL point - * @param yes - enable the function - * - * @return none - */ -void SSL_set_read_ahead(SSL *s, int yes); - -/** - * @brief set the SSL context if we can read as many as data - * - * @param ctx - SSL context point - * @param yes - enbale the function - * - * @return none - */ -void SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes); - -/** - * @brief get the SSL ahead signal if we can read as many as data - * - * @param ssl - SSL point - * - * @return SSL context ahead signal - */ -int SSL_get_read_ahead(const SSL *ssl); - -/** - * @brief get the SSL context ahead signal if we can read as many as data - * - * @param ctx - SSL context point - * - * @return SSL context ahead signal - */ -long SSL_CTX_get_read_ahead(SSL_CTX *ctx); - -/** - * @brief check if some data can be read - * - * @param ssl - SSL point - * - * @return - * 1 : there are bytes to be read - * 0 : no data - */ -int SSL_has_pending(const SSL *ssl); - -/** - * @brief load the X509 certification into SSL context - * - * @param ctx - SSL context point - * @param x - X509 certification point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);//loads the certificate x into ctx - -/** - * @brief load the ASN1 certification into SSL context - * - * @param ctx - SSL context point - * @param len - certification length - * @param d - data point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, const unsigned char *d); - -/** - * @brief load the certification file into SSL context - * - * @param ctx - SSL context point - * @param file - certification file name - * @param type - certification encoding type - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type); - -/** - * @brief load the certification chain file into SSL context - * - * @param ctx - SSL context point - * @param file - certification chain file name - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file); - - -/** - * @brief load the ASN1 private key into SSL context - * - * @param ctx - SSL context point - * @param d - data point - * @param len - private key length - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx, const unsigned char *d, long len);//adds the private key of type pk stored at memory location d (length len) to ctx - -/** - * @brief load the private key file into SSL context - * - * @param ctx - SSL context point - * @param file - private key file name - * @param type - private key encoding type - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type); - -/** - * @brief load the RSA private key into SSL context - * - * @param ctx - SSL context point - * @param x - RSA private key point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa); - -/** - * @brief load the RSA ASN1 private key into SSL context - * - * @param ctx - SSL context point - * @param d - data point - * @param len - RSA private key length - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, long len); - -/** - * @brief load the RSA private key file into SSL context - * - * @param ctx - SSL context point - * @param file - RSA private key file name - * @param type - private key encoding type - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type); - - -/** - * @brief check if the private key and certification is matched - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_check_private_key(const SSL_CTX *ctx); - -/** - * @brief set the SSL context server information - * - * @param ctx - SSL context point - * @param serverinfo - server information string - * @param serverinfo_length - server information length - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo, size_t serverinfo_length); - -/** - * @brief load the SSL context server infomation file into SSL context - * - * @param ctx - SSL context point - * @param file - server information file - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file); - -/** - * @brief SSL select next function - * - * @param out - point of output data point - * @param outlen - output data length - * @param in - input data - * @param inlen - input data length - * @param client - client data point - * @param client_len -client data length - * - * @return NPN state - * OPENSSL_NPN_UNSUPPORTED : not support - * OPENSSL_NPN_NEGOTIATED : negotiated - * OPENSSL_NPN_NO_OVERLAP : no overlap - */ -int SSL_select_next_proto(unsigned char **out, unsigned char *outlen, - const unsigned char *in, unsigned int inlen, - const unsigned char *client, unsigned int client_len); - -/** - * @brief load the extra certification chain into the SSL context - * - * @param ctx - SSL context point - * @param x509 - X509 certification - * - * @return result - * 1 : OK - * 0 : failed - */ -long SSL_CTX_add_extra_chain_cert(SSL_CTX *ctx, X509 *); - -/** - * @brief control the SSL context - * - * @param ctx - SSL context point - * @param cmd - command - * @param larg - parameter length - * @param parg - parameter point - * - * @return result - * 1 : OK - * 0 : failed - */ -long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, char *parg); - -/** - * @brief get the SSL context cipher - * - * @param ctx - SSL context point - * - * @return SSL context cipher - */ -STACK *SSL_CTX_get_ciphers(const SSL_CTX *ctx); - -/** - * @brief check if the SSL context can read as many as data - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -long SSL_CTX_get_default_read_ahead(SSL_CTX *ctx); - -/** - * @brief get the SSL context extra data - * - * @param ctx - SSL context point - * @param idx - index - * - * @return data point - */ -char *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx); - -/** - * @brief get the SSL context quiet shutdown option - * - * @param ctx - SSL context point - * - * @return quiet shutdown option - */ -int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx); - -/** - * @brief load the SSL context CA file - * - * @param ctx - SSL context point - * @param CAfile - CA certification file - * @param CApath - CA certification file path - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, const char *CApath); - -/** - * @brief add SSL context reference count by '1' - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_up_ref(SSL_CTX *ctx); - -/** - * @brief set SSL context application private data - * - * @param ctx - SSL context point - * @param arg - private data - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_app_data(SSL_CTX *ctx, void *arg); - -/** - * @brief set SSL context client certification callback function - * - * @param ctx - SSL context point - * @param cb - callback function - * - * @return none - */ -void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey)); - -/** - * @brief set the SSL context if we can read as many as data - * - * @param ctx - SSL context point - * @param m - enable the fuction - * - * @return none - */ -void SSL_CTX_set_default_read_ahead(SSL_CTX *ctx, int m); - -/** - * @brief set SSL context default verifying path - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx); - -/** - * @brief set SSL context default verifying directory - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx); - -/** - * @brief set SSL context default verifying file - * - * @param ctx - SSL context point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_default_verify_file(SSL_CTX *ctx); - -/** - * @brief set SSL context extra data - * - * @param ctx - SSL context point - * @param idx - data index - * @param arg - data point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, char *arg); - -/** - * @brief clear the SSL context option bit of "op" - * - * @param ctx - SSL context point - * @param op - option - * - * @return SSL context option - */ -unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op); - -/** - * @brief get the SSL context option - * - * @param ctx - SSL context point - * @param op - option - * - * @return SSL context option - */ -unsigned long SSL_CTX_get_options(SSL_CTX *ctx); - -/** - * @brief set the SSL context quiet shutdown mode - * - * @param ctx - SSL context point - * @param mode - mode - * - * @return none - */ -void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode); - -/** - * @brief get the SSL context X509 certification - * - * @param ctx - SSL context point - * - * @return X509 certification - */ -X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx); - -/** - * @brief get the SSL context private key - * - * @param ctx - SSL context point - * - * @return private key - */ -EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx); - -/** - * @brief set SSL context PSK identity hint - * - * @param ctx - SSL context point - * @param hint - PSK identity hint - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *hint); - -/** - * @brief set SSL context PSK server callback function - * - * @param ctx - SSL context point - * @param callback - callback function - * - * @return none - */ -void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, - unsigned int (*callback)(SSL *ssl, - const char *identity, - unsigned char *psk, - int max_psk_len)); -/** - * @brief get alert description string - * - * @param value - alert value - * - * @return alert description string - */ -const char *SSL_alert_desc_string(int value); - -/** - * @brief get alert description long string - * - * @param value - alert value - * - * @return alert description long string - */ -const char *SSL_alert_desc_string_long(int value); - -/** - * @brief get alert type string - * - * @param value - alert value - * - * @return alert type string - */ -const char *SSL_alert_type_string(int value); - -/** - * @brief get alert type long string - * - * @param value - alert value - * - * @return alert type long string - */ -const char *SSL_alert_type_string_long(int value); - -/** - * @brief get SSL context of the SSL - * - * @param ssl - SSL point - * - * @return SSL context - */ -SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl); - -/** - * @brief get SSL application data - * - * @param ssl - SSL point - * - * @return application data - */ -char *SSL_get_app_data(SSL *ssl); - -/** - * @brief get SSL cipher bits - * - * @param ssl - SSL point - * @param alg_bits - algorithm bits - * - * @return strength bits - */ -int SSL_get_cipher_bits(const SSL *ssl, int *alg_bits); - -/** - * @brief get SSL cipher name - * - * @param ssl - SSL point - * - * @return SSL cipher name - */ -char *SSL_get_cipher_name(const SSL *ssl); - -/** - * @brief get SSL cipher version - * - * @param ssl - SSL point - * - * @return SSL cipher version - */ -char *SSL_get_cipher_version(const SSL *ssl); - -/** - * @brief get SSL extra data - * - * @param ssl - SSL point - * @param idx - data index - * - * @return extra data - */ -char *SSL_get_ex_data(const SSL *ssl, int idx); - -/** - * @brief get index of the SSL extra data X509 storage context - * - * @param none - * - * @return data index - */ -int SSL_get_ex_data_X509_STORE_CTX_idx(void); - -/** - * @brief get peer certification chain - * - * @param ssl - SSL point - * - * @return certification chain - */ -STACK *SSL_get_peer_cert_chain(const SSL *ssl); - -/** - * @brief get peer certification - * - * @param ssl - SSL point - * - * @return certification - */ -X509 *SSL_get_peer_certificate(const SSL *ssl); - -/** - * @brief get SSL quiet shutdown mode - * - * @param ssl - SSL point - * - * @return quiet shutdown mode - */ -int SSL_get_quiet_shutdown(const SSL *ssl); - -/** - * @brief get SSL read only IO handle - * - * @param ssl - SSL point - * - * @return IO handle - */ -BIO *SSL_get_rbio(const SSL *ssl); - -/** - * @brief get SSL shared ciphers - * - * @param ssl - SSL point - * @param buf - buffer to store the ciphers - * @param len - buffer len - * - * @return shared ciphers - */ -char *SSL_get_shared_ciphers(const SSL *ssl, char *buf, int len); - -/** - * @brief get SSL shutdown mode - * - * @param ssl - SSL point - * - * @return shutdown mode - */ -int SSL_get_shutdown(const SSL *ssl); - -/** - * @brief get SSL session time - * - * @param ssl - SSL point - * - * @return session time - */ -long SSL_get_time(const SSL *ssl); - -/** - * @brief get SSL session timeout time - * - * @param ssl - SSL point - * - * @return session timeout time - */ -long SSL_get_timeout(const SSL *ssl); - -/** - * @brief get SSL verifying mode - * - * @param ssl - SSL point - * - * @return verifying mode - */ -int SSL_get_verify_mode(const SSL *ssl); - -/** - * @brief get SSL verify parameters - * - * @param ssl - SSL point - * - * @return verify parameters - */ -X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl); - -/** - * @brief set expected hostname the peer cert CN should have - * - * @param param - verify parameters from SSL_get0_param() - * - * @param name - the expected hostname - * - * @param namelen - the length of the hostname, or 0 if NUL terminated - * - * @return verify parameters - */ -int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param, - const char *name, size_t namelen); - -/** - * @brief set parameters for X509 host verify action - * - * @param param -verify parameters from SSL_get0_param() - * - * @param flags - bitfield of X509_CHECK_FLAG_... parameters to set - * - * @return 1 for success, 0 for failure - */ -int X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param, - unsigned long flags); - -/** - * @brief clear parameters for X509 host verify action - * - * @param param -verify parameters from SSL_get0_param() - * - * @param flags - bitfield of X509_CHECK_FLAG_... parameters to clear - * - * @return 1 for success, 0 for failure - */ -int X509_VERIFY_PARAM_clear_hostflags(X509_VERIFY_PARAM *param, - unsigned long flags); - -/** - * @brief get SSL write only IO handle - * - * @param ssl - SSL point - * - * @return IO handle - */ -BIO *SSL_get_wbio(const SSL *ssl); - -/** - * @brief load SSL client CA certification file - * - * @param file - file name - * - * @return certification loading object - */ -STACK *SSL_load_client_CA_file(const char *file); - -/** - * @brief add SSL reference by '1' - * - * @param ssl - SSL point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_up_ref(SSL *ssl); - -/** - * @brief read and put data into buf, but not clear the SSL low-level storage - * - * @param ssl - SSL point - * @param buf - storage buffer point - * @param num - data bytes - * - * @return result - * > 0 : OK, and return read bytes - * = 0 : connect is closed - * < 0 : a error catch - */ -int SSL_peek(SSL *ssl, void *buf, int num); - -/** - * @brief make SSL renegotiate - * - * @param ssl - SSL point - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_renegotiate(SSL *ssl); - -/** - * @brief get the state string where SSL is reading - * - * @param ssl - SSL point - * - * @return state string - */ -const char *SSL_rstate_string(SSL *ssl); - -/** - * @brief get the statement long string where SSL is reading - * - * @param ssl - SSL point - * - * @return statement long string - */ -const char *SSL_rstate_string_long(SSL *ssl); - -/** - * @brief set SSL accept statement - * - * @param ssl - SSL point - * - * @return none - */ -void SSL_set_accept_state(SSL *ssl); - -/** - * @brief set SSL application data - * - * @param ssl - SSL point - * @param arg - SSL application data point - * - * @return none - */ -void SSL_set_app_data(SSL *ssl, char *arg); - -/** - * @brief set SSL BIO - * - * @param ssl - SSL point - * @param rbio - read only IO - * @param wbio - write only IO - * - * @return none - */ -void SSL_set_bio(SSL *ssl, BIO *rbio, BIO *wbio); - -/** - * @brief clear SSL option - * - * @param ssl - SSL point - * @param op - clear option - * - * @return SSL option - */ -unsigned long SSL_clear_options(SSL *ssl, unsigned long op); - -/** - * @brief get SSL option - * - * @param ssl - SSL point - * - * @return SSL option - */ -unsigned long SSL_get_options(SSL *ssl); - -/** - * @brief clear SSL option - * - * @param ssl - SSL point - * @param op - setting option - * - * @return SSL option - */ -unsigned long SSL_set_options(SSL *ssl, unsigned long op); - -/** - * @brief set SSL quiet shutdown mode - * - * @param ssl - SSL point - * @param mode - quiet shutdown mode - * - * @return none - */ -void SSL_set_quiet_shutdown(SSL *ssl, int mode); - -/** - * @brief set SSL shutdown mode - * - * @param ssl - SSL point - * @param mode - shutdown mode - * - * @return none - */ -void SSL_set_shutdown(SSL *ssl, int mode); - -/** - * @brief set SSL session time - * - * @param ssl - SSL point - * @param t - session time - * - * @return session time - */ -void SSL_set_time(SSL *ssl, long t); - -/** - * @brief set SSL session timeout time - * - * @param ssl - SSL point - * @param t - session timeout time - * - * @return session timeout time - */ -void SSL_set_timeout(SSL *ssl, long t); - -/** - * @brief get SSL statement string - * - * @param ssl - SSL point - * - * @return SSL statement string - */ -char *SSL_state_string(const SSL *ssl); - -/** - * @brief get SSL statement long string - * - * @param ssl - SSL point - * - * @return SSL statement long string - */ -char *SSL_state_string_long(const SSL *ssl); - -/** - * @brief get SSL renegotiation count - * - * @param ssl - SSL point - * - * @return renegotiation count - */ -long SSL_total_renegotiations(SSL *ssl); - -/** - * @brief get SSL version - * - * @param ssl - SSL point - * - * @return SSL version - */ -int SSL_version(const SSL *ssl); - -/** - * @brief set SSL PSK identity hint - * - * @param ssl - SSL point - * @param hint - identity hint - * - * @return result - * 1 : OK - * 0 : failed - */ -int SSL_use_psk_identity_hint(SSL *ssl, const char *hint); - -/** - * @brief get SSL PSK identity hint - * - * @param ssl - SSL point - * - * @return identity hint - */ -const char *SSL_get_psk_identity_hint(SSL *ssl); - -/** - * @brief get SSL PSK identity - * - * @param ssl - SSL point - * - * @return identity - */ -const char *SSL_get_psk_identity(SSL *ssl); - -#ifdef __cplusplus -} -#endif - -#endif +// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _SSL_H_ +#define _SSL_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#include "internal/ssl_x509.h" +#include "internal/ssl_pkey.h" + +/* +{ +*/ + +#define SSL_CB_ALERT 0x4000 + +#define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT (1 << 0) +#define X509_CHECK_FLAG_NO_WILDCARDS (1 << 1) +#define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS (1 << 2) +#define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS (1 << 3) +#define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS (1 << 4) + +/** + * @brief create a SSL context + * + * @param method - the SSL context method point + * + * @return the context point + */ +SSL_CTX* SSL_CTX_new(const SSL_METHOD *method); + +/** + * @brief free a SSL context + * + * @param method - the SSL context point + * + * @return none + */ +void SSL_CTX_free(SSL_CTX *ctx); + +/** + * @brief create a SSL + * + * @param ctx - the SSL context point + * + * @return the SSL point + */ +SSL* SSL_new(SSL_CTX *ctx); + +/** + * @brief free the SSL + * + * @param ssl - the SSL point + * + * @return none + */ +void SSL_free(SSL *ssl); + +/** + * @brief connect to the remote SSL server + * + * @param ssl - the SSL point + * + * @return result + * 1 : OK + * -1 : failed + */ +int SSL_connect(SSL *ssl); + +/** + * @brief accept the remote connection + * + * @param ssl - the SSL point + * + * @return result + * 1 : OK + * -1 : failed + */ +int SSL_accept(SSL *ssl); + +/** + * @brief read data from to remote + * + * @param ssl - the SSL point which has been connected + * @param buffer - the received data buffer point + * @param len - the received data length + * + * @return result + * > 0 : OK, and return received data bytes + * = 0 : connection is closed + * < 0 : an error catch + */ +int SSL_read(SSL *ssl, void *buffer, int len); + +/** + * @brief send the data to remote + * + * @param ssl - the SSL point which has been connected + * @param buffer - the send data buffer point + * @param len - the send data length + * + * @return result + * > 0 : OK, and return sent data bytes + * = 0 : connection is closed + * < 0 : an error catch + */ +int SSL_write(SSL *ssl, const void *buffer, int len); + +/** + * @brief get the verifying result of the SSL certification + * + * @param ssl - the SSL point + * + * @return the result of verifying + */ +long SSL_get_verify_result(const SSL *ssl); + +/** + * @brief shutdown the connection + * + * @param ssl - the SSL point + * + * @return result + * 1 : OK + * 0 : shutdown is not finished + * -1 : an error catch + */ +int SSL_shutdown(SSL *ssl); + +/** + * @brief bind the socket file description into the SSL + * + * @param ssl - the SSL point + * @param fd - socket handle + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_set_fd(SSL *ssl, int fd); + +/** + * @brief Set the hostname for SNI + * + * @param ssl - the SSL context point + * @param hostname - pointer to the hostname + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_set_tlsext_host_name(SSL* ssl, const char *hostname); + +/** + * @brief These functions load the private key into the SSL_CTX or SSL object + * + * @param ctx - the SSL context point + * @param pkey - private key object point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey); + +/** + * @brief These functions load the certification into the SSL_CTX or SSL object + * + * @param ctx - the SSL context point + * @param pkey - certification object point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x); + +/** + * @brief create the target SSL context client method + * + * @param none + * + * @return the SSLV2.3 version SSL context client method + */ +const SSL_METHOD* SSLv23_client_method(void); + +/** + * @brief create the target SSL context client method + * + * @param none + * + * @return the TLSV1.0 version SSL context client method + */ +const SSL_METHOD* TLSv1_client_method(void); + +/** + * @brief create the target SSL context client method + * + * @param none + * + * @return the SSLV1.0 version SSL context client method + */ +const SSL_METHOD* SSLv3_client_method(void); + +/** + * @brief create the target SSL context client method + * + * @param none + * + * @return the TLSV1.1 version SSL context client method + */ +const SSL_METHOD* TLSv1_1_client_method(void); + +/** + * @brief create the target SSL context client method + * + * @param none + * + * @return the TLSV1.2 version SSL context client method + */ +const SSL_METHOD* TLSv1_2_client_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the TLS any version SSL context client method + */ +const SSL_METHOD* TLS_client_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the SSLV2.3 version SSL context server method + */ +const SSL_METHOD* SSLv23_server_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the TLSV1.1 version SSL context server method + */ +const SSL_METHOD* TLSv1_1_server_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the TLSV1.2 version SSL context server method + */ +const SSL_METHOD* TLSv1_2_server_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the TLSV1.0 version SSL context server method + */ +const SSL_METHOD* TLSv1_server_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the SSLV3.0 version SSL context server method + */ +const SSL_METHOD* SSLv3_server_method(void); + +/** + * @brief create the target SSL context server method + * + * @param none + * + * @return the TLS any version SSL context server method + */ +const SSL_METHOD* TLS_server_method(void); + + +/** + * @brief set the SSL context ALPN select callback function + * + * @param ctx - SSL context point + * @param cb - ALPN select callback function + * @param arg - ALPN select callback function entry private data point + * + * @return none + */ +void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx, + int (*cb) (SSL *ssl, + const unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, + void *arg), + void *arg); + + +/** + * @brief set the SSL context ALPN select protocol + * + * @param ctx - SSL context point + * @param protos - ALPN protocol name + * @param protos_len - ALPN protocol name bytes + * + * @return result + * 0 : OK + * 1 : failed + */ +int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos, unsigned int protos_len); + +/** + * @brief set the SSL context next ALPN select callback function + * + * @param ctx - SSL context point + * @param cb - ALPN select callback function + * @param arg - ALPN select callback function entry private data point + * + * @return none + */ +void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx, + int (*cb) (SSL *ssl, + unsigned char **out, + unsigned char *outlen, + const unsigned char *in, + unsigned int inlen, + void *arg), + void *arg); + +/** + * @brief get SSL error code + * + * @param ssl - SSL point + * @param ret_code - SSL return code + * + * @return SSL error number + */ +int SSL_get_error(const SSL *ssl, int ret_code); + +/** + * @brief clear the SSL error code + * + * @param none + * + * @return none + */ +void ERR_clear_error(void); + +/** + * @brief get the current SSL error code + * + * @param none + * + * @return current SSL error number + */ +int ERR_get_error(void); + +/** + * @brief register the SSL error strings + * + * @param none + * + * @return none + */ +void ERR_load_SSL_strings(void); + +/** + * @brief initialize the SSL library + * + * @param none + * + * @return none + */ +void SSL_library_init(void); + +/** + * @brief generates a human-readable string representing the error code e + * and store it into the "ret" point memory + * + * @param e - error code + * @param ret - memory point to store the string + * + * @return the result string point + */ +char *ERR_error_string(unsigned long e, char *ret); + +/** + * @brief add the SSL context option + * + * @param ctx - SSL context point + * @param opt - new SSL context option + * + * @return the SSL context option + */ +unsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long opt); + +/** + * @brief add the SSL context mode + * + * @param ctx - SSL context point + * @param mod - new SSL context mod + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_mode(SSL_CTX *ctx, int mod); + +/* +} +*/ + +/** + * @brief perform the SSL handshake + * + * @param ssl - SSL point + * + * @return result + * 1 : OK + * 0 : failed + * -1 : a error catch + */ +int SSL_do_handshake(SSL *ssl); + +/** + * @brief get the SSL current version + * + * @param ssl - SSL point + * + * @return the version string + */ +const char *SSL_get_version(const SSL *ssl); + +/** + * @brief set the SSL context version + * + * @param ctx - SSL context point + * @param meth - SSL method point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth); + +/** + * @brief get the bytes numbers which are to be read + * + * @param ssl - SSL point + * + * @return bytes number + */ +int SSL_pending(const SSL *ssl); + +/** + * @brief check if SSL want nothing + * + * @param ssl - SSL point + * + * @return result + * 0 : false + * 1 : true + */ +int SSL_want_nothing(const SSL *ssl); + +/** + * @brief check if SSL want to read + * + * @param ssl - SSL point + * + * @return result + * 0 : false + * 1 : true + */ +int SSL_want_read(const SSL *ssl); + +/** + * @brief check if SSL want to write + * + * @param ssl - SSL point + * + * @return result + * 0 : false + * 1 : true + */ +int SSL_want_write(const SSL *ssl); + +/** + * @brief get the SSL context current method + * + * @param ctx - SSL context point + * + * @return the SSL context current method + */ +const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx); + +/** + * @brief get the SSL current method + * + * @param ssl - SSL point + * + * @return the SSL current method + */ +const SSL_METHOD *SSL_get_ssl_method(SSL *ssl); + +/** + * @brief set the SSL method + * + * @param ssl - SSL point + * @param meth - SSL method point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_set_ssl_method(SSL *ssl, const SSL_METHOD *method); + +/** + * @brief add CA client certification into the SSL + * + * @param ssl - SSL point + * @param x - CA certification point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_add_client_CA(SSL *ssl, X509 *x); + +/** + * @brief add CA client certification into the SSL context + * + * @param ctx - SSL context point + * @param x - CA certification point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x); + +/** + * @brief set the SSL CA certification list + * + * @param ssl - SSL point + * @param name_list - CA certification list + * + * @return none + */ +void SSL_set_client_CA_list(SSL *ssl, STACK_OF(X509_NAME) *name_list); + +/** + * @brief set the SSL context CA certification list + * + * @param ctx - SSL context point + * @param name_list - CA certification list + * + * @return none + */ +void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list); + +/** + * @briefget the SSL CA certification list + * + * @param ssl - SSL point + * + * @return CA certification list + */ +STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *ssl); + +/** + * @brief get the SSL context CA certification list + * + * @param ctx - SSL context point + * + * @return CA certification list + */ +STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx); + +/** + * @brief get the SSL certification point + * + * @param ssl - SSL point + * + * @return SSL certification point + */ +X509 *SSL_get_certificate(const SSL *ssl); + +/** + * @brief get the SSL private key point + * + * @param ssl - SSL point + * + * @return SSL private key point + */ +EVP_PKEY *SSL_get_privatekey(const SSL *ssl); + +/** + * @brief set the SSL information callback function + * + * @param ssl - SSL point + * @param cb - information callback function + * + * @return none + */ +void SSL_set_info_callback(SSL *ssl, void (*cb) (const SSL *ssl, int type, int val)); + +/** + * @brief get the SSL state + * + * @param ssl - SSL point + * + * @return SSL state + */ +OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl); + +/** + * @brief set the SSL context read buffer length + * + * @param ctx - SSL context point + * @param len - read buffer length + * + * @return none + */ +void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len); + +/** + * @brief set the SSL read buffer length + * + * @param ssl - SSL point + * @param len - read buffer length + * + * @return none + */ +void SSL_set_default_read_buffer_len(SSL *ssl, size_t len); + +/** + * @brief set the SSL security level + * + * @param ssl - SSL point + * @param level - security level + * + * @return none + */ +void SSL_set_security_level(SSL *ssl, int level); + +/** + * @brief get the SSL security level + * + * @param ssl - SSL point + * + * @return security level + */ +int SSL_get_security_level(const SSL *ssl); + +/** + * @brief get the SSL verifying mode of the SSL context + * + * @param ctx - SSL context point + * + * @return verifying mode + */ +int SSL_CTX_get_verify_mode(const SSL_CTX *ctx); + +/** + * @brief get the SSL verifying depth of the SSL context + * + * @param ctx - SSL context point + * + * @return verifying depth + */ +int SSL_CTX_get_verify_depth(const SSL_CTX *ctx); + +/** + * @brief set the SSL context verifying of the SSL context + * + * @param ctx - SSL context point + * @param mode - verifying mode + * @param verify_callback - verifying callback function + * + * @return none + */ +void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, int (*verify_callback)(int, X509_STORE_CTX *)); + +/** + * @brief set the SSL verifying of the SSL context + * + * @param ctx - SSL point + * @param mode - verifying mode + * @param verify_callback - verifying callback function + * + * @return none + */ +void SSL_set_verify(SSL *s, int mode, int (*verify_callback)(int, X509_STORE_CTX *)); + +/** + * @brief set the SSL verify depth of the SSL context + * + * @param ctx - SSL context point + * @param depth - verifying depth + * + * @return none + */ +void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth); + +/** + * @brief certification verifying callback function + * + * @param preverify_ok - verifying result + * @param x509_ctx - X509 certification point + * + * @return verifying result + */ +int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx); + +/** + * @brief set the session timeout time + * + * @param ctx - SSL context point + * @param t - new session timeout time + * + * @return old session timeout time + */ +long SSL_CTX_set_timeout(SSL_CTX *ctx, long t); + +/** + * @brief get the session timeout time + * + * @param ctx - SSL context point + * + * @return current session timeout time + */ +long SSL_CTX_get_timeout(const SSL_CTX *ctx); + +/** + * @brief set the SSL context cipher through the list string + * + * @param ctx - SSL context point + * @param str - cipher controller list string + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str); + +/** + * @brief set the SSL cipher through the list string + * + * @param ssl - SSL point + * @param str - cipher controller list string + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_set_cipher_list(SSL *ssl, const char *str); + +/** + * @brief get the SSL cipher list string + * + * @param ssl - SSL point + * + * @return cipher controller list string + */ +const char *SSL_get_cipher_list(const SSL *ssl, int n); + +/** + * @brief get the SSL cipher + * + * @param ssl - SSL point + * + * @return current cipher + */ +const SSL_CIPHER *SSL_get_current_cipher(const SSL *ssl); + +/** + * @brief get the SSL cipher string + * + * @param ssl - SSL point + * + * @return cipher string + */ +const char *SSL_get_cipher(const SSL *ssl); + +/** + * @brief get the SSL context object X509 certification storage + * + * @param ctx - SSL context point + * + * @return x509 certification storage + */ +X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx); + +/** + * @brief set the SSL context object X509 certification store + * + * @param ctx - SSL context point + * @param store - X509 certification store + * + * @return none + */ +void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store); + +/** + * @brief get the SSL specifical statement + * + * @param ssl - SSL point + * + * @return specifical statement + */ +int SSL_want(const SSL *ssl); + +/** + * @brief check if the SSL is SSL_X509_LOOKUP state + * + * @param ssl - SSL point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_want_x509_lookup(const SSL *ssl); + +/** + * @brief reset the SSL + * + * @param ssl - SSL point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_clear(SSL *ssl); + +/** + * @brief get the socket handle of the SSL + * + * @param ssl - SSL point + * + * @return result + * >= 0 : yes, and return socket handle + * < 0 : a error catch + */ +int SSL_get_fd(const SSL *ssl); + +/** + * @brief get the read only socket handle of the SSL + * + * @param ssl - SSL point + * + * @return result + * >= 0 : yes, and return socket handle + * < 0 : a error catch + */ +int SSL_get_rfd(const SSL *ssl); + +/** + * @brief get the write only socket handle of the SSL + * + * @param ssl - SSL point + * + * @return result + * >= 0 : yes, and return socket handle + * < 0 : a error catch + */ +int SSL_get_wfd(const SSL *ssl); + +/** + * @brief set the SSL if we can read as many as data + * + * @param ssl - SSL point + * @param yes - enable the function + * + * @return none + */ +void SSL_set_read_ahead(SSL *s, int yes); + +/** + * @brief set the SSL context if we can read as many as data + * + * @param ctx - SSL context point + * @param yes - enbale the function + * + * @return none + */ +void SSL_CTX_set_read_ahead(SSL_CTX *ctx, int yes); + +/** + * @brief get the SSL ahead signal if we can read as many as data + * + * @param ssl - SSL point + * + * @return SSL context ahead signal + */ +int SSL_get_read_ahead(const SSL *ssl); + +/** + * @brief get the SSL context ahead signal if we can read as many as data + * + * @param ctx - SSL context point + * + * @return SSL context ahead signal + */ +long SSL_CTX_get_read_ahead(SSL_CTX *ctx); + +/** + * @brief check if some data can be read + * + * @param ssl - SSL point + * + * @return + * 1 : there are bytes to be read + * 0 : no data + */ +int SSL_has_pending(const SSL *ssl); + +/** + * @brief load the X509 certification into SSL context + * + * @param ctx - SSL context point + * @param x - X509 certification point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);//loads the certificate x into ctx + +/** + * @brief load the ASN1 certification into SSL context + * + * @param ctx - SSL context point + * @param len - certification length + * @param d - data point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len, const unsigned char *d); + +/** + * @brief load the certification file into SSL context + * + * @param ctx - SSL context point + * @param file - certification file name + * @param type - certification encoding type + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file, int type); + +/** + * @brief load the certification chain file into SSL context + * + * @param ctx - SSL context point + * @param file - certification chain file name + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file); + + +/** + * @brief load the ASN1 private key into SSL context + * + * @param ctx - SSL context point + * @param d - data point + * @param len - private key length + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx, const unsigned char *d, long len);//adds the private key of type pk stored at memory location d (length len) to ctx + +/** + * @brief load the private key file into SSL context + * + * @param ctx - SSL context point + * @param file - private key file name + * @param type - private key encoding type + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file, int type); + +/** + * @brief load the RSA private key into SSL context + * + * @param ctx - SSL context point + * @param x - RSA private key point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa); + +/** + * @brief load the RSA ASN1 private key into SSL context + * + * @param ctx - SSL context point + * @param d - data point + * @param len - RSA private key length + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d, long len); + +/** + * @brief load the RSA private key file into SSL context + * + * @param ctx - SSL context point + * @param file - RSA private key file name + * @param type - private key encoding type + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file, int type); + + +/** + * @brief check if the private key and certification is matched + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_check_private_key(const SSL_CTX *ctx); + +/** + * @brief set the SSL context server information + * + * @param ctx - SSL context point + * @param serverinfo - server information string + * @param serverinfo_length - server information length + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo, size_t serverinfo_length); + +/** + * @brief load the SSL context server infomation file into SSL context + * + * @param ctx - SSL context point + * @param file - server information file + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file); + +/** + * @brief SSL select next function + * + * @param out - point of output data point + * @param outlen - output data length + * @param in - input data + * @param inlen - input data length + * @param client - client data point + * @param client_len -client data length + * + * @return NPN state + * OPENSSL_NPN_UNSUPPORTED : not support + * OPENSSL_NPN_NEGOTIATED : negotiated + * OPENSSL_NPN_NO_OVERLAP : no overlap + */ +int SSL_select_next_proto(unsigned char **out, unsigned char *outlen, + const unsigned char *in, unsigned int inlen, + const unsigned char *client, unsigned int client_len); + +/** + * @brief load the extra certification chain into the SSL context + * + * @param ctx - SSL context point + * @param x509 - X509 certification + * + * @return result + * 1 : OK + * 0 : failed + */ +long SSL_CTX_add_extra_chain_cert(SSL_CTX *ctx, X509 *); + +/** + * @brief control the SSL context + * + * @param ctx - SSL context point + * @param cmd - command + * @param larg - parameter length + * @param parg - parameter point + * + * @return result + * 1 : OK + * 0 : failed + */ +long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, char *parg); + +/** + * @brief get the SSL context cipher + * + * @param ctx - SSL context point + * + * @return SSL context cipher + */ +STACK *SSL_CTX_get_ciphers(const SSL_CTX *ctx); + +/** + * @brief check if the SSL context can read as many as data + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +long SSL_CTX_get_default_read_ahead(SSL_CTX *ctx); + +/** + * @brief get the SSL context extra data + * + * @param ctx - SSL context point + * @param idx - index + * + * @return data point + */ +char *SSL_CTX_get_ex_data(const SSL_CTX *ctx, int idx); + +/** + * @brief get the SSL context quiet shutdown option + * + * @param ctx - SSL context point + * + * @return quiet shutdown option + */ +int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx); + +/** + * @brief load the SSL context CA file + * + * @param ctx - SSL context point + * @param CAfile - CA certification file + * @param CApath - CA certification file path + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile, const char *CApath); + +/** + * @brief add SSL context reference count by '1' + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_up_ref(SSL_CTX *ctx); + +/** + * @brief set SSL context application private data + * + * @param ctx - SSL context point + * @param arg - private data + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_app_data(SSL_CTX *ctx, void *arg); + +/** + * @brief set SSL context client certification callback function + * + * @param ctx - SSL context point + * @param cb - callback function + * + * @return none + */ +void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx, int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey)); + +/** + * @brief set the SSL context if we can read as many as data + * + * @param ctx - SSL context point + * @param m - enable the fuction + * + * @return none + */ +void SSL_CTX_set_default_read_ahead(SSL_CTX *ctx, int m); + +/** + * @brief set SSL context default verifying path + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx); + +/** + * @brief set SSL context default verifying directory + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx); + +/** + * @brief set SSL context default verifying file + * + * @param ctx - SSL context point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_default_verify_file(SSL_CTX *ctx); + +/** + * @brief set SSL context extra data + * + * @param ctx - SSL context point + * @param idx - data index + * @param arg - data point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, char *arg); + +/** + * @brief clear the SSL context option bit of "op" + * + * @param ctx - SSL context point + * @param op - option + * + * @return SSL context option + */ +unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op); + +/** + * @brief get the SSL context option + * + * @param ctx - SSL context point + * @param op - option + * + * @return SSL context option + */ +unsigned long SSL_CTX_get_options(SSL_CTX *ctx); + +/** + * @brief set the SSL context quiet shutdown mode + * + * @param ctx - SSL context point + * @param mode - mode + * + * @return none + */ +void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode); + +/** + * @brief get the SSL context X509 certification + * + * @param ctx - SSL context point + * + * @return X509 certification + */ +X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx); + +/** + * @brief get the SSL context private key + * + * @param ctx - SSL context point + * + * @return private key + */ +EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx); + +/** + * @brief set SSL context PSK identity hint + * + * @param ctx - SSL context point + * @param hint - PSK identity hint + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *hint); + +/** + * @brief set SSL context PSK server callback function + * + * @param ctx - SSL context point + * @param callback - callback function + * + * @return none + */ +void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, + unsigned int (*callback)(SSL *ssl, + const char *identity, + unsigned char *psk, + int max_psk_len)); +/** + * @brief get alert description string + * + * @param value - alert value + * + * @return alert description string + */ +const char *SSL_alert_desc_string(int value); + +/** + * @brief get alert description long string + * + * @param value - alert value + * + * @return alert description long string + */ +const char *SSL_alert_desc_string_long(int value); + +/** + * @brief get alert type string + * + * @param value - alert value + * + * @return alert type string + */ +const char *SSL_alert_type_string(int value); + +/** + * @brief get alert type long string + * + * @param value - alert value + * + * @return alert type long string + */ +const char *SSL_alert_type_string_long(int value); + +/** + * @brief get SSL context of the SSL + * + * @param ssl - SSL point + * + * @return SSL context + */ +SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl); + +/** + * @brief get SSL application data + * + * @param ssl - SSL point + * + * @return application data + */ +char *SSL_get_app_data(SSL *ssl); + +/** + * @brief get SSL cipher bits + * + * @param ssl - SSL point + * @param alg_bits - algorithm bits + * + * @return strength bits + */ +int SSL_get_cipher_bits(const SSL *ssl, int *alg_bits); + +/** + * @brief get SSL cipher name + * + * @param ssl - SSL point + * + * @return SSL cipher name + */ +char *SSL_get_cipher_name(const SSL *ssl); + +/** + * @brief get SSL cipher version + * + * @param ssl - SSL point + * + * @return SSL cipher version + */ +char *SSL_get_cipher_version(const SSL *ssl); + +/** + * @brief get SSL extra data + * + * @param ssl - SSL point + * @param idx - data index + * + * @return extra data + */ +char *SSL_get_ex_data(const SSL *ssl, int idx); + +/** + * @brief get index of the SSL extra data X509 storage context + * + * @param none + * + * @return data index + */ +int SSL_get_ex_data_X509_STORE_CTX_idx(void); + +/** + * @brief get peer certification chain + * + * @param ssl - SSL point + * + * @return certification chain + */ +STACK *SSL_get_peer_cert_chain(const SSL *ssl); + +/** + * @brief get peer certification + * + * @param ssl - SSL point + * + * @return certification + */ +X509 *SSL_get_peer_certificate(const SSL *ssl); + +/** + * @brief get SSL quiet shutdown mode + * + * @param ssl - SSL point + * + * @return quiet shutdown mode + */ +int SSL_get_quiet_shutdown(const SSL *ssl); + +/** + * @brief get SSL read only IO handle + * + * @param ssl - SSL point + * + * @return IO handle + */ +BIO *SSL_get_rbio(const SSL *ssl); + +/** + * @brief get SSL shared ciphers + * + * @param ssl - SSL point + * @param buf - buffer to store the ciphers + * @param len - buffer len + * + * @return shared ciphers + */ +char *SSL_get_shared_ciphers(const SSL *ssl, char *buf, int len); + +/** + * @brief get SSL shutdown mode + * + * @param ssl - SSL point + * + * @return shutdown mode + */ +int SSL_get_shutdown(const SSL *ssl); + +/** + * @brief get SSL session time + * + * @param ssl - SSL point + * + * @return session time + */ +long SSL_get_time(const SSL *ssl); + +/** + * @brief get SSL session timeout time + * + * @param ssl - SSL point + * + * @return session timeout time + */ +long SSL_get_timeout(const SSL *ssl); + +/** + * @brief get SSL verifying mode + * + * @param ssl - SSL point + * + * @return verifying mode + */ +int SSL_get_verify_mode(const SSL *ssl); + +/** + * @brief get SSL verify parameters + * + * @param ssl - SSL point + * + * @return verify parameters + */ +X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl); + +/** + * @brief set expected hostname the peer cert CN should have + * + * @param param - verify parameters from SSL_get0_param() + * + * @param name - the expected hostname + * + * @param namelen - the length of the hostname, or 0 if NUL terminated + * + * @return verify parameters + */ +int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param, + const char *name, size_t namelen); + +/** + * @brief set parameters for X509 host verify action + * + * @param param -verify parameters from SSL_get0_param() + * + * @param flags - bitfield of X509_CHECK_FLAG_... parameters to set + * + * @return 1 for success, 0 for failure + */ +int X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param, + unsigned long flags); + +/** + * @brief clear parameters for X509 host verify action + * + * @param param -verify parameters from SSL_get0_param() + * + * @param flags - bitfield of X509_CHECK_FLAG_... parameters to clear + * + * @return 1 for success, 0 for failure + */ +int X509_VERIFY_PARAM_clear_hostflags(X509_VERIFY_PARAM *param, + unsigned long flags); + +/** + * @brief get SSL write only IO handle + * + * @param ssl - SSL point + * + * @return IO handle + */ +BIO *SSL_get_wbio(const SSL *ssl); + +/** + * @brief load SSL client CA certification file + * + * @param file - file name + * + * @return certification loading object + */ +STACK *SSL_load_client_CA_file(const char *file); + +/** + * @brief add SSL reference by '1' + * + * @param ssl - SSL point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_up_ref(SSL *ssl); + +/** + * @brief read and put data into buf, but not clear the SSL low-level storage + * + * @param ssl - SSL point + * @param buf - storage buffer point + * @param num - data bytes + * + * @return result + * > 0 : OK, and return read bytes + * = 0 : connect is closed + * < 0 : a error catch + */ +int SSL_peek(SSL *ssl, void *buf, int num); + +/** + * @brief make SSL renegotiate + * + * @param ssl - SSL point + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_renegotiate(SSL *ssl); + +/** + * @brief get the state string where SSL is reading + * + * @param ssl - SSL point + * + * @return state string + */ +const char *SSL_rstate_string(SSL *ssl); + +/** + * @brief get the statement long string where SSL is reading + * + * @param ssl - SSL point + * + * @return statement long string + */ +const char *SSL_rstate_string_long(SSL *ssl); + +/** + * @brief set SSL accept statement + * + * @param ssl - SSL point + * + * @return none + */ +void SSL_set_accept_state(SSL *ssl); + +/** + * @brief set SSL application data + * + * @param ssl - SSL point + * @param arg - SSL application data point + * + * @return none + */ +void SSL_set_app_data(SSL *ssl, char *arg); + +/** + * @brief set SSL BIO + * + * @param ssl - SSL point + * @param rbio - read only IO + * @param wbio - write only IO + * + * @return none + */ +void SSL_set_bio(SSL *ssl, BIO *rbio, BIO *wbio); + +/** + * @brief clear SSL option + * + * @param ssl - SSL point + * @param op - clear option + * + * @return SSL option + */ +unsigned long SSL_clear_options(SSL *ssl, unsigned long op); + +/** + * @brief get SSL option + * + * @param ssl - SSL point + * + * @return SSL option + */ +unsigned long SSL_get_options(SSL *ssl); + +/** + * @brief clear SSL option + * + * @param ssl - SSL point + * @param op - setting option + * + * @return SSL option + */ +unsigned long SSL_set_options(SSL *ssl, unsigned long op); + +/** + * @brief set SSL quiet shutdown mode + * + * @param ssl - SSL point + * @param mode - quiet shutdown mode + * + * @return none + */ +void SSL_set_quiet_shutdown(SSL *ssl, int mode); + +/** + * @brief set SSL shutdown mode + * + * @param ssl - SSL point + * @param mode - shutdown mode + * + * @return none + */ +void SSL_set_shutdown(SSL *ssl, int mode); + +/** + * @brief set SSL session time + * + * @param ssl - SSL point + * @param t - session time + * + * @return session time + */ +void SSL_set_time(SSL *ssl, long t); + +/** + * @brief set SSL session timeout time + * + * @param ssl - SSL point + * @param t - session timeout time + * + * @return session timeout time + */ +void SSL_set_timeout(SSL *ssl, long t); + +/** + * @brief get SSL statement string + * + * @param ssl - SSL point + * + * @return SSL statement string + */ +char *SSL_state_string(const SSL *ssl); + +/** + * @brief get SSL statement long string + * + * @param ssl - SSL point + * + * @return SSL statement long string + */ +char *SSL_state_string_long(const SSL *ssl); + +/** + * @brief get SSL renegotiation count + * + * @param ssl - SSL point + * + * @return renegotiation count + */ +long SSL_total_renegotiations(SSL *ssl); + +/** + * @brief get SSL version + * + * @param ssl - SSL point + * + * @return SSL version + */ +int SSL_version(const SSL *ssl); + +/** + * @brief set SSL PSK identity hint + * + * @param ssl - SSL point + * @param hint - identity hint + * + * @return result + * 1 : OK + * 0 : failed + */ +int SSL_use_psk_identity_hint(SSL *ssl, const char *hint); + +/** + * @brief get SSL PSK identity hint + * + * @param ssl - SSL point + * + * @return identity hint + */ +const char *SSL_get_psk_identity_hint(SSL *ssl); + +/** + * @brief get SSL PSK identity + * + * @param ssl - SSL point + * + * @return identity + */ +const char *SSL_get_psk_identity(SSL *ssl); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/sdmmc/sdmmc_cmd.h b/tools/sdk/include/sdmmc/sdmmc_cmd.h index 7b68ed7c..aa12a447 100644 --- a/tools/sdk/include/sdmmc/sdmmc_cmd.h +++ b/tools/sdk/include/sdmmc/sdmmc_cmd.h @@ -1,4 +1,4 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. diff --git a/tools/sdk/include/soc/soc/can_struct.h b/tools/sdk/include/soc/soc/can_struct.h new file mode 100644 index 00000000..3f566b13 --- /dev/null +++ b/tools/sdk/include/soc/soc/can_struct.h @@ -0,0 +1,211 @@ +// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#ifndef _SOC_CAN_STRUCT_H_ +#define _SOC_CAN_STRUCT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/* -------------------------- Register Definitions -------------------------- */ + +/* The CAN peripheral's registers are 8bits, however the ESP32 can only access + * peripheral registers every 32bits. Therefore each CAN register is mapped to + * the least significant byte of every 32bits. + */ +typedef union { + struct { + uint32_t byte: 8; /* LSB */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_reg_t; + +typedef union { + struct { + uint32_t reset: 1; /* MOD.0 Reset Mode */ + uint32_t listen_only: 1; /* MOD.1 Listen Only Mode */ + uint32_t self_test: 1; /* MOD.2 Self Test Mode */ + uint32_t acceptance_filter: 1; /* MOD.3 Acceptance Filter Mode */ + uint32_t reserved28: 28; /* Internal Reserved. MOD.4 Sleep Mode not supported */ + }; + uint32_t val; +} can_mode_reg_t; + +typedef union { + struct { + uint32_t tx_req: 1; /* CMR.0 Transmission Request */ + uint32_t abort_tx: 1; /* CMR.1 Abort Transmission */ + uint32_t release_rx_buff: 1; /* CMR.2 Release Receive Buffer */ + uint32_t clear_data_overrun: 1; /* CMR.3 Clear Data Overrun */ + uint32_t self_rx_req: 1; /* CMR.4 Self Reception Request */ + uint32_t reserved27: 27; /* Internal Reserved */ + }; + uint32_t val; +} can_cmd_reg_t; + +typedef union { + struct { + uint32_t rx_buff: 1; /* SR.0 Receive Buffer Status */ + uint32_t data_overrun: 1; /* SR.1 Data Overrun Status */ + uint32_t tx_buff: 1; /* SR.2 Transmit Buffer Status */ + uint32_t tx_complete: 1; /* SR.3 Transmission Complete Status */ + uint32_t rx: 1; /* SR.4 Receive Status */ + uint32_t tx: 1; /* SR.5 Transmit Status */ + uint32_t error: 1; /* SR.6 Error Status */ + uint32_t bus: 1; /* SR.7 Bus Status */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_status_reg_t; + +typedef union { + struct { + uint32_t rx: 1; /* IR.0 Receive Interrupt */ + uint32_t tx: 1; /* IR.1 Transmit Interrupt */ + uint32_t err_warn: 1; /* IR.2 Error Interrupt */ + uint32_t data_overrun: 1; /* IR.3 Data Overrun Interrupt */ + uint32_t reserved1: 1; /* Internal Reserved (Wake-up not supported) */ + uint32_t err_passive: 1; /* IR.5 Error Passive Interrupt */ + uint32_t arb_lost: 1; /* IR.6 Arbitration Lost Interrupt */ + uint32_t bus_err: 1; /* IR.7 Bus Error Interrupt */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_intr_reg_t; + +typedef union { + struct { + uint32_t rx: 1; /* IER.0 Receive Interrupt Enable */ + uint32_t tx: 1; /* IER.1 Transmit Interrupt Enable */ + uint32_t err_warn: 1; /* IER.2 Error Interrupt Enable */ + uint32_t data_overrun: 1; /* IER.3 Data Overrun Interrupt Enable */ + uint32_t reserved1: 1; /* Internal Reserved (Wake-up not supported) */ + uint32_t err_passive: 1; /* IER.5 Error Passive Interrupt Enable */ + uint32_t arb_lost: 1; /* IER.6 Arbitration Lost Interrupt Enable */ + uint32_t bus_err: 1; /* IER.7 Bus Error Interrupt Enable */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_intr_en_reg_t; + +typedef union { + struct { + uint32_t baud_rate_prescaler: 6; /* BTR0[5:0] Baud Rate Prescaler */ + uint32_t sync_jump_width: 2; /* BTR0[7:6] Synchronization Jump Width*/ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_bus_tim_0_reg_t; + +typedef union { + struct { + uint32_t time_seg_1: 4; /* BTR1[3:0] Timing Segment 1 */ + uint32_t time_seg_2: 3; /* BTR1[6:4] Timing Segment 2 */ + uint32_t sampling: 1; /* BTR1.7 Sampling*/ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_bus_tim_1_reg_t; + +typedef union { + struct { + uint32_t arbitration_lost_capture: 5; /* ALC[4:0] Arbitration lost capture */ + uint32_t reserved27: 27; /* Internal Reserved */ + }; + uint32_t val; +} can_arb_lost_cap_reg_t; + +typedef union { + struct { + uint32_t segment: 5; /* ECC[4:0] Error Code Segment 0 to 5 */ + uint32_t direction: 1; /* ECC.5 Error Direction (TX/RX) */ + uint32_t error_code: 2; /* ECC[7:6] Error Code */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_err_code_cap_reg_t; + +typedef struct { + can_reg_t code_reg[4]; + can_reg_t mask_reg[4]; + uint32_t reserved32[5]; +} can_acc_filter_t; + +typedef union { + struct { + uint32_t rx_message_counter: 5; /* RMC[4:0] RX Message Counter */ + uint32_t reserved27: 27; /* Internal Reserved */ + }; + uint32_t val; +} can_rx_msg_cnt_reg_t; + +typedef union { + struct { + uint32_t clock_divider: 3; /* CDR[2:0] CLKOUT frequency selector based of fOSC */ + uint32_t clock_off: 1; /* CDR.3 CLKOUT enable/disable */ + uint32_t reserved3: 3; /* Internal Reserved. RXINTEN and CBP not supported */ + uint32_t can_mode: 1; /* CDR.7 BasicCAN:0 PeliCAN:1 */ + uint32_t reserved24: 24; /* Internal Reserved */ + }; + uint32_t val; +} can_clk_div_reg_t; + +/* ---------------------------- Register Layout ------------------------------ */ + +typedef volatile struct { + //Configuration and Control Registers + can_mode_reg_t mode_reg; /* Address 0 */ + can_cmd_reg_t command_reg; /* Address 1 */ + can_status_reg_t status_reg; /* Address 2 */ + can_intr_reg_t interrupt_reg; /* Address 3 */ + can_intr_en_reg_t interrupt_enable_reg; /* Address 4 */ + uint32_t reserved_05; /* Address 5 */ + can_bus_tim_0_reg_t bus_timing_0_reg; /* Address 6 */ + can_bus_tim_1_reg_t bus_timing_1_reg; /* Address 7 */ + uint32_t reserved_08; /* Address 8 (Output control not supported) */ + uint32_t reserved_09; /* Address 9 (Test Register not supported) */ + uint32_t reserved_10; /* Address 10 */ + + //Capture and Counter Registers + can_arb_lost_cap_reg_t arbitration_lost_captue_reg; /* Address 11 */ + can_err_code_cap_reg_t error_code_capture_reg; /* Address 12 */ + can_reg_t error_warning_limit_reg; /* EWLR[7:0] Error Warning Limit: Address 13 */ + can_reg_t rx_error_counter_reg; /* RXERR[7:0] Receive Error Counter: Address 14 */ + can_reg_t tx_error_counter_reg; /* TXERR[7:0] Transmit Error Counter: Address 15 */ + + //Shared Registers (TX Buff/RX Buff/Acc Filter) + union { + can_acc_filter_t acceptance_filter; + can_reg_t tx_rx_buffer[13]; + }; /* Address 16-28 TX/RX Buffer and Acc Filter*/; + + //Misc Registers + can_rx_msg_cnt_reg_t rx_message_counter_reg; /* Address 29 */ + can_reg_t reserved_30; /* Address 30 (RX Buffer Start Address not supported) */ + can_clk_div_reg_t clock_divider_reg; /* Address 31 */ + + //Start of RX FIFO +} can_dev_t; + +_Static_assert(sizeof(can_dev_t) == 128, "CAN registers should be 32 * 4 bytes"); + +extern can_dev_t CAN; + +#ifdef __cplusplus +} +#endif + +#endif /* _SOC_CAN_STRUCT_H_ */ + diff --git a/tools/sdk/include/soc/soc/rmt_struct.h b/tools/sdk/include/soc/soc/rmt_struct.h index 68e244ad..3fb254ad 100644 --- a/tools/sdk/include/soc/soc/rmt_struct.h +++ b/tools/sdk/include/soc/soc/rmt_struct.h @@ -19,7 +19,9 @@ extern "C" { #endif typedef volatile struct { - uint32_t data_ch[8]; /*The R/W ram address for channel0-7 by apb fifo access.*/ + uint32_t data_ch[8]; /*The R/W ram address for channel0-7 by apb fifo access. + Note that in some circumstances, data read from the FIFO may get lost. As RMT memory area accesses using the RMTMEM method do not have this issue + and provide all the functionality that the FIFO register has, it is encouraged to use that instead.*/ struct{ union { struct { @@ -39,7 +41,7 @@ typedef volatile struct { uint32_t rx_en: 1; /*Set this bit to enable receiving data for channel0-7.*/ uint32_t mem_wr_rst: 1; /*Set this bit to reset write ram address for channel0-7 by receiver access.*/ uint32_t mem_rd_rst: 1; /*Set this bit to reset read ram address for channel0-7 by transmitter access.*/ - uint32_t apb_mem_rst: 1; /*Set this bit to reset W/R ram address for channel0-7 by apb fifo access*/ + uint32_t apb_mem_rst: 1; /*Set this bit to reset W/R ram address for channel0-7 by apb fifo access (using fifo is discouraged, please see the note above at data_ch[] item)*/ uint32_t mem_owner: 1; /*This is the mark of channel0-7's ram usage right.1'b1:receiver uses the ram 0:transmitter uses the ram*/ uint32_t tx_conti_mode: 1; /*Set this bit to continue sending from the first data to the last data in channel0-7 again and again.*/ uint32_t rx_filter_en: 1; /*This is the receive filter enable bit for channel0-7.*/ @@ -54,7 +56,7 @@ typedef volatile struct { } conf1; } conf_ch[8]; uint32_t status_ch[8]; /*The status for channel0-7*/ - uint32_t apb_mem_addr_ch[8]; /*The ram relative address in channel0-7 by apb fifo access*/ + uint32_t apb_mem_addr_ch[8]; /*The ram relative address in channel0-7 by apb fifo access (using fifo is discouraged, please see the note above at data_ch[] item)*/ union { struct { uint32_t ch0_tx_end: 1; /*The interrupt raw bit for channel 0 turns to high level when the transmit process is done.*/ @@ -219,7 +221,7 @@ typedef volatile struct { } tx_lim_ch[8]; union { struct { - uint32_t fifo_mask: 1; /*Set this bit to disable apb fifo access*/ + uint32_t fifo_mask: 1; /*Set this bit to enable RMTMEM and disable apb fifo access (using fifo is discouraged, please see the note above at data_ch[] item)*/ uint32_t mem_tx_wrap_en: 1; /*when data need to be send is more than channel's mem can store then set this bit to enable reuse of mem this bit is used together with reg_rmt_tx_lim_chn.*/ uint32_t reserved2: 30; }; @@ -243,22 +245,11 @@ typedef struct { }; } rmt_item32_t; -typedef struct { - union { - struct { - uint16_t duration :15; - uint16_t level :1; - }; - uint16_t val; - }; -} rmt_item16_t; - //Allow access to RMT memory using RMTMEM.chan[0].data32[8] typedef volatile struct { struct { union { rmt_item32_t data32[64]; - rmt_item16_t data16[128]; }; } chan[8]; } rmt_mem_t; diff --git a/tools/sdk/include/soc/soc/rtc.h b/tools/sdk/include/soc/soc/rtc.h index 1ece26c9..a528bdd1 100644 --- a/tools/sdk/include/soc/soc/rtc.h +++ b/tools/sdk/include/soc/soc/rtc.h @@ -75,6 +75,26 @@ typedef enum { RTC_CPU_FREQ_2M = 4, //!< 2 MHz } rtc_cpu_freq_t; +/** + * @brief CPU clock source + */ +typedef enum { + RTC_CPU_FREQ_SRC_XTAL, //!< XTAL + RTC_CPU_FREQ_SRC_PLL, //!< PLL (480M or 320M) + RTC_CPU_FREQ_SRC_8M, //!< Internal 8M RTC oscillator + RTC_CPU_FREQ_SRC_APLL //!< APLL +} rtc_cpu_freq_src_t; + +/** + * @brief CPU clock configuration structure + */ +typedef struct { + rtc_cpu_freq_src_t source; //!< The clock from which CPU clock is derived + uint32_t source_freq_mhz; //!< Source clock frequency + uint32_t div; //!< Divider, freq_mhz = source_freq_mhz / div + uint32_t freq_mhz; //!< CPU clock frequency +} rtc_cpu_freq_config_t; + /** * @brief RTC SLOW_CLK frequency values */ @@ -108,13 +128,13 @@ typedef enum { * Initialization parameters for rtc_clk_init */ typedef struct { - rtc_xtal_freq_t xtal_freq : 8; //!< Main XTAL frequency - rtc_cpu_freq_t cpu_freq : 3; //!< CPU frequency to set - rtc_fast_freq_t fast_freq : 1; //!< RTC_FAST_CLK frequency to set - rtc_slow_freq_t slow_freq : 2; //!< RTC_SLOW_CLK frequency to set - uint32_t clk_8m_div : 3; //!< RTC 8M clock divider (division is by clk_8m_div+1, i.e. 0 means 8MHz frequency) - uint32_t slow_clk_dcap : 8; //!< RTC 150k clock adjustment parameter (higher value leads to lower frequency) - uint32_t clk_8m_dfreq : 8; //!< RTC 8m clock adjustment parameter (higher value leads to higher frequency) + rtc_xtal_freq_t xtal_freq : 8; //!< Main XTAL frequency + rtc_cpu_freq_t cpu_freq_mhz : 10; //!< CPU frequency to set, in MHz + rtc_fast_freq_t fast_freq : 1; //!< RTC_FAST_CLK frequency to set + rtc_slow_freq_t slow_freq : 2; //!< RTC_SLOW_CLK frequency to set + uint32_t clk_8m_div : 3; //!< RTC 8M clock divider (division is by clk_8m_div+1, i.e. 0 means 8MHz frequency) + uint32_t slow_clk_dcap : 8; //!< RTC 150k clock adjustment parameter (higher value leads to lower frequency) + uint32_t clk_8m_dfreq : 8; //!< RTC 8m clock adjustment parameter (higher value leads to higher frequency) } rtc_clk_config_t; /** @@ -122,7 +142,7 @@ typedef struct { */ #define RTC_CLK_CONFIG_DEFAULT() { \ .xtal_freq = RTC_XTAL_FREQ_AUTO, \ - .cpu_freq = RTC_CPU_FREQ_80M, \ + .cpu_freq_mhz = 80, \ .fast_freq = RTC_FAST_FREQ_8M, \ .slow_freq = RTC_SLOW_FREQ_RTC, \ .clk_8m_div = 0, \ @@ -173,6 +193,11 @@ void rtc_clk_xtal_freq_update(rtc_xtal_freq_t xtal_freq); */ void rtc_clk_32k_enable(bool en); +/** + * @brief Configure 32 kHz XTAL oscillator to accept external clock signal + */ +void rtc_clk_32k_enable_external(); + /** * @brief Get the state of 32k XTAL oscillator * @return true if 32k XTAL oscillator has been enabled @@ -281,6 +306,9 @@ rtc_fast_freq_t rtc_clk_fast_freq_get(); /** * @brief Switch CPU frequency * + * @note This function is deprecated and will be removed. + * See rtc_clk_cpu_freq_config_set instead. + * * If a PLL-derived frequency is requested (80, 160, 240 MHz), this function * will enable the PLL. Otherwise, PLL will be disabled. * Note: this function is not optimized for switching speed. It may take several @@ -288,11 +316,14 @@ rtc_fast_freq_t rtc_clk_fast_freq_get(); * * @param cpu_freq new CPU frequency */ -void rtc_clk_cpu_freq_set(rtc_cpu_freq_t cpu_freq); +void rtc_clk_cpu_freq_set(rtc_cpu_freq_t cpu_freq) __attribute__((deprecated)); /** * @brief Switch CPU frequency * + * @note This function is deprecated and will be removed. + * See rtc_clk_cpu_freq_set_config_fast instead. + * * This is a faster version of rtc_clk_cpu_freq_set, which can handle some of * the frequency switch paths (XTAL -> PLL, PLL -> XTAL). * When switching from PLL to XTAL, PLL is not disabled (unlike rtc_clk_cpu_freq_set). @@ -307,11 +338,14 @@ void rtc_clk_cpu_freq_set(rtc_cpu_freq_t cpu_freq); * * @param cpu_freq new CPU frequency */ -void rtc_clk_cpu_freq_set_fast(rtc_cpu_freq_t cpu_freq); +void rtc_clk_cpu_freq_set_fast(rtc_cpu_freq_t cpu_freq) __attribute__((deprecated)); /** * @brief Get the currently selected CPU frequency * + * @note This function is deprecated and will be removed. + * See rtc_clk_cpu_freq_get_config instead. + * * Although CPU can be clocked by APLL and RTC 8M sources, such support is not * exposed through this library. As such, this function will not return * meaningful values when these clock sources are configured (e.g. using direct @@ -320,22 +354,97 @@ void rtc_clk_cpu_freq_set_fast(rtc_cpu_freq_t cpu_freq); * * @return CPU frequency (one of rtc_cpu_freq_t values) */ -rtc_cpu_freq_t rtc_clk_cpu_freq_get(); +rtc_cpu_freq_t rtc_clk_cpu_freq_get() __attribute__((deprecated)); /** * @brief Get corresponding frequency value for rtc_cpu_freq_t enum value + * + * @note This function is deprecated and will be removed. + * See rtc_clk_cpu_freq_get/set_config instead. + * * @param cpu_freq CPU frequency, on of rtc_cpu_freq_t values * @return CPU frequency, in HZ */ -uint32_t rtc_clk_cpu_freq_value(rtc_cpu_freq_t cpu_freq); +uint32_t rtc_clk_cpu_freq_value(rtc_cpu_freq_t cpu_freq) __attribute__((deprecated)); /** * @brief Get rtc_cpu_freq_t enum value for given CPU frequency + * + * @note This function is deprecated and will be removed. + * See rtc_clk_cpu_freq_mhz_to_config instead. + * * @param cpu_freq_mhz CPU frequency, one of 80, 160, 240, 2, and XTAL frequency * @param[out] out_val output, rtc_cpu_freq_t value corresponding to the frequency * @return true if the given frequency value matches one of enum values */ - bool rtc_clk_cpu_freq_from_mhz(int cpu_freq_mhz, rtc_cpu_freq_t* out_val); + bool rtc_clk_cpu_freq_from_mhz(int cpu_freq_mhz, rtc_cpu_freq_t* out_val) __attribute__((deprecated)); + +/** + * @brief Get CPU frequency config corresponding to a rtc_cpu_freq_t value + * @param cpu_freq CPU frequency enumeration value + * @param[out] out_config Output, CPU frequency configuration structure + */ + void rtc_clk_cpu_freq_to_config(rtc_cpu_freq_t cpu_freq, rtc_cpu_freq_config_t* out_config); + + /** + * @brief Get CPU frequency config for a given frequency + * @param freq_mhz Frequency in MHz + * @param[out] out_config Output, CPU frequency configuration structure + * @return true if frequency can be obtained, false otherwise + */ + bool rtc_clk_cpu_freq_mhz_to_config(uint32_t freq_mhz, rtc_cpu_freq_config_t* out_config); + + /** + * @brief Switch CPU frequency + * + * This function sets CPU frequency according to the given configuration + * structure. It enables PLLs, if necessary. + * + * @note This function in not intended to be called by applications in FreeRTOS + * environment. This is because it does not adjust various timers based on the + * new CPU frequency. + * + * @param config CPU frequency configuration structure + */ + void rtc_clk_cpu_freq_set_config(const rtc_cpu_freq_config_t* config); + + /** + * @brief Switch CPU frequency (optimized for speed) + * + * This function is a faster equivalent of rtc_clk_cpu_freq_set_config. + * It works faster because it does not disable PLLs when switching from PLL to + * XTAL and does not enabled them when switching back. If PLL is not already + * enabled when this function is called to switch from XTAL to PLL frequency, + * or the PLL which is enabled is the wrong one, this function will fall back + * to calling rtc_clk_cpu_freq_set_config. + * + * Unlike rtc_clk_cpu_freq_set_config, this function relies on static data, + * so it is less safe to use it e.g. from a panic handler (when memory might + * be corrupted). + * + * @note This function in not intended to be called by applications in FreeRTOS + * environment. This is because it does not adjust various timers based on the + * new CPU frequency. + * + * @param config CPU frequency configuration structure + */ + void rtc_clk_cpu_freq_set_config_fast(const rtc_cpu_freq_config_t* config); + + /** + * @brief Get the currently used CPU frequency configuration + * @param[out] out_config Output, CPU frequency configuration structure + */ + void rtc_clk_cpu_freq_get_config(rtc_cpu_freq_config_t* out_config); + + /** + * @brief Switch CPU clock source to XTAL + * + * Short form for filling in rtc_cpu_freq_config_t structure and calling + * rtc_clk_cpu_freq_set_config when a switch to XTAL is needed. + * Assumes that XTAL frequency has been determined — don't call in startup code. + */ + void rtc_clk_cpu_freq_set_xtal(); + /** * @brief Store new APB frequency value into RTC_APB_FREQ_REG diff --git a/tools/sdk/include/soc/soc/rtc_wdt.h b/tools/sdk/include/soc/soc/rtc_wdt.h new file mode 100644 index 00000000..ec7175a0 --- /dev/null +++ b/tools/sdk/include/soc/soc/rtc_wdt.h @@ -0,0 +1,193 @@ +// Copyright 2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* Recommendation of using API RTC_WDT. +1) Setting and enabling rtc_wdt: +@code + rtc_wdt_protect_off(); + rtc_wdt_disable(); + rtc_wdt_set_length_of_reset_signal(RTC_WDT_SYS_RESET_SIG, RTC_WDT_LENGTH_3_2us); + rtc_wdt_set_stage(RTC_WDT_STAGE0, RTC_WDT_STAGE_ACTION_RESET_SYSTEM); //RTC_WDT_STAGE_ACTION_RESET_SYSTEM or RTC_WDT_STAGE_ACTION_RESET_RTC + rtc_wdt_set_time(RTC_WDT_STAGE0, 7000); // timeout rtd_wdt 7000ms. + rtc_wdt_enable(); + rtc_wdt_protect_on(); + @endcode + +* If you use this option RTC_WDT_STAGE_ACTION_RESET_SYSTEM then after reset you can see these messages. +They can help to understand where the CPUs were when the WDT was triggered. + W (30) boot: PRO CPU has been reset by WDT. + W (30) boot: WDT reset info: PRO CPU PC=0x400xxxxx + ... function where it happened + + W (31) boot: WDT reset info: APP CPU PC=0x400xxxxx + ... function where it happened + +* If you use this option RTC_WDT_STAGE_ACTION_RESET_RTC then you will see message (rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)) +without description where were CPUs when it happened. + +2) Reset counter of rtc_wdt: +@code + rtc_wdt_feed(); +@endcode + +3) Disable rtc_wdt: +@code + rtc_wdt_disable(); +@endcode + */ + +#ifndef _SOC_RTC_WDT_H +#define _SOC_RTC_WDT_H + +#include +#include +#include "soc/rtc_cntl_reg.h" +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/// List of stage of rtc watchdog. WDT has 4 stage. +typedef enum { + RTC_WDT_STAGE0 = 0, /*!< Stage 0 */ + RTC_WDT_STAGE1 = 1, /*!< Stage 1 */ + RTC_WDT_STAGE2 = 2, /*!< Stage 2 */ + RTC_WDT_STAGE3 = 3 /*!< Stage 3 */ +} rtc_wdt_stage_t; + +/// List of action. When the time of stage expires this action will be triggered. +typedef enum { + RTC_WDT_STAGE_ACTION_OFF = RTC_WDT_STG_SEL_OFF, /*!< Disabled. This stage will have no effects on the system. */ + RTC_WDT_STAGE_ACTION_INTERRUPT = RTC_WDT_STG_SEL_INT, /*!< Trigger an interrupt. When the stage expires an interrupt is triggered. */ + RTC_WDT_STAGE_ACTION_RESET_CPU = RTC_WDT_STG_SEL_RESET_CPU, /*!< Reset a CPU core. */ + RTC_WDT_STAGE_ACTION_RESET_SYSTEM = RTC_WDT_STG_SEL_RESET_SYSTEM, /*!< Reset the main system includes the CPU and all peripherals. The RTC is an exception to this, and it will not be reset. */ + RTC_WDT_STAGE_ACTION_RESET_RTC = RTC_WDT_STG_SEL_RESET_RTC /*!< Reset the main system and the RTC. */ +} rtc_wdt_stage_action_t; + +/// Type of reset signal +typedef enum { + RTC_WDT_SYS_RESET_SIG = 0, /*!< System reset signal length selection */ + RTC_WDT_CPU_RESET_SIG = 1 /*!< CPU reset signal length selection */ +} rtc_wdt_reset_sig_t; + +/// Length of reset signal +typedef enum { + RTC_WDT_LENGTH_100ns = 0, /*!< 100 ns */ + RTC_WDT_LENGTH_200ns = 1, /*!< 200 ns */ + RTC_WDT_LENGTH_300ns = 2, /*!< 300 ns */ + RTC_WDT_LENGTH_400ns = 3, /*!< 400 ns */ + RTC_WDT_LENGTH_500ns = 4, /*!< 500 ns */ + RTC_WDT_LENGTH_800ns = 5, /*!< 800 ns */ + RTC_WDT_LENGTH_1_6us = 6, /*!< 1.6 us */ + RTC_WDT_LENGTH_3_2us = 7 /*!< 3.2 us */ +} rtc_wdt_length_sig_t; + +/** + * @brief Get status of protect of rtc_wdt. + * + * @return + * - True if the protect of RTC_WDT is set + */ +bool rtc_wdt_get_protect_status(); + +/** + * @brief Set protect of rtc_wdt. + */ +void rtc_wdt_protect_on(); + +/** + * @brief Reset protect of rtc_wdt. + */ +void rtc_wdt_protect_off(); + +/** + * @brief Enable rtc_wdt. + */ +void rtc_wdt_enable(); + +/** + * @brief Disable rtc_wdt. + */ +void rtc_wdt_disable(); + +/** + * @brief Reset counter rtc_wdt. + * + * It returns to stage 0 and its expiry counter restarts from 0. + */ +void rtc_wdt_feed(); + +/** + * @brief Set time for required stage. + * + * @param[in] stage Stage of rtc_wdt. + * @param[in] timeout_ms Timeout for this stage. + * + * @return + * - ESP_OK In case of success + * - ESP_ERR_INVALID_ARG If stage has invalid value + */ +esp_err_t rtc_wdt_set_time(rtc_wdt_stage_t stage, unsigned int timeout_ms); + +/** + * @brief Get the timeout set for the required stage. + * + * @param[in] stage Stage of rtc_wdt. + * @param[out] timeout_ms Timeout set for this stage. (not elapsed time). + * + * @return + * - ESP_OK In case of success + * - ESP_ERR_INVALID_ARG If stage has invalid value + */ +esp_err_t rtc_wdt_get_timeout(rtc_wdt_stage_t stage, unsigned int* timeout_ms); + +/** + * @brief Set an action for required stage. + * + * @param[in] stage Stage of rtc_wdt. + * @param[in] stage_sel Action for this stage. When the time of stage expires this action will be triggered. + * + * @return + * - ESP_OK In case of success + * - ESP_ERR_INVALID_ARG If stage or stage_sel have invalid value + */ +esp_err_t rtc_wdt_set_stage(rtc_wdt_stage_t stage, rtc_wdt_stage_action_t stage_sel); + +/** + * @brief Set a length of reset signal. + * + * @param[in] reset_src Type of reset signal. + * @param[in] reset_signal_length A length of reset signal. + * + * @return + * - ESP_OK In case of success + * - ESP_ERR_INVALID_ARG If reset_src or reset_signal_length have invalid value + */ +esp_err_t rtc_wdt_set_length_of_reset_signal(rtc_wdt_reset_sig_t reset_src, rtc_wdt_length_sig_t reset_signal_length); + +/** + * @brief Return true if rtc_wdt is enabled. + * + * @return + * - True rtc_wdt is enabled + */ +bool rtc_wdt_is_on(); + +#ifdef __cplusplus +} +#endif + +#endif // _SOC_RTC_WDT_H diff --git a/tools/sdk/include/soc/soc/sdio_slave_periph.h b/tools/sdk/include/soc/soc/sdio_slave_periph.h index cc1c8cbc..467104dc 100644 --- a/tools/sdk/include/soc/soc/sdio_slave_periph.h +++ b/tools/sdk/include/soc/soc/sdio_slave_periph.h @@ -1,49 +1,49 @@ -// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _SOC_SDIO_SLAVE_PERIPH_H_ -#define _SOC_SDIO_SLAVE_PERIPH_H_ - -#include -//include soc related (generated) definitions -#include "soc/sdio_slave_pins.h" -#include "soc/slc_reg.h" -#include "soc/slc_struct.h" -#include "soc/host_reg.h" -#include "soc/host_struct.h" -#include "soc/hinf_reg.h" -#include "soc/hinf_struct.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** pin and signal information of each slot */ -typedef struct { - uint32_t clk_gpio; - uint32_t cmd_gpio; - uint32_t d0_gpio; - uint32_t d1_gpio; - uint32_t d2_gpio; - uint32_t d3_gpio; - int func; -} sdio_slave_slot_info_t; - -extern const sdio_slave_slot_info_t sdio_slave_slot_info[]; - -#ifdef __cplusplus -} -#endif - +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _SOC_SDIO_SLAVE_PERIPH_H_ +#define _SOC_SDIO_SLAVE_PERIPH_H_ + +#include +//include soc related (generated) definitions +#include "soc/sdio_slave_pins.h" +#include "soc/slc_reg.h" +#include "soc/slc_struct.h" +#include "soc/host_reg.h" +#include "soc/host_struct.h" +#include "soc/hinf_reg.h" +#include "soc/hinf_struct.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** pin and signal information of each slot */ +typedef struct { + uint32_t clk_gpio; + uint32_t cmd_gpio; + uint32_t d0_gpio; + uint32_t d1_gpio; + uint32_t d2_gpio; + uint32_t d3_gpio; + int func; +} sdio_slave_slot_info_t; + +extern const sdio_slave_slot_info_t sdio_slave_slot_info[]; + +#ifdef __cplusplus +} +#endif + #endif /* _SOC_SDIO_SLAVE_PERIPH_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/soc/soc/sdio_slave_pins.h b/tools/sdk/include/soc/soc/sdio_slave_pins.h index 968f194a..97c8bec0 100644 --- a/tools/sdk/include/soc/soc/sdio_slave_pins.h +++ b/tools/sdk/include/soc/soc/sdio_slave_pins.h @@ -1,34 +1,34 @@ -// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _SOC_SDIO_SLAVE_PINS_H_ -#define _SOC_SDIO_SLAVE_PINS_H_ - -#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_CLK 6 -#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_CMD 11 -#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D0 7 -#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D1 8 -#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D2 9 -#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D3 10 -#define SDIO_SLAVE_SLOT0_FUNC 0 - -#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_CLK 14 -#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_CMD 15 -#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D0 2 -#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D1 4 -#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D2 12 -#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D3 13 -#define SDIO_SLAVE_SLOT1_FUNC 4 - +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _SOC_SDIO_SLAVE_PINS_H_ +#define _SOC_SDIO_SLAVE_PINS_H_ + +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_CLK 6 +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_CMD 11 +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D0 7 +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D1 8 +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D2 9 +#define SDIO_SLAVE_SLOT0_IOMUX_PIN_NUM_D3 10 +#define SDIO_SLAVE_SLOT0_FUNC 0 + +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_CLK 14 +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_CMD 15 +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D0 2 +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D1 4 +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D2 12 +#define SDIO_SLAVE_SLOT1_IOMUX_PIN_NUM_D3 13 +#define SDIO_SLAVE_SLOT1_FUNC 4 + #endif /* _SOC_SDIO_SLAVE_PINS_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/soc/soc/sdmmc_periph.h b/tools/sdk/include/soc/soc/sdmmc_periph.h index 183a6581..79dfaf34 100644 --- a/tools/sdk/include/soc/soc/sdmmc_periph.h +++ b/tools/sdk/include/soc/soc/sdmmc_periph.h @@ -1,53 +1,53 @@ -// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _SOC_SDMMC_PERIPH_H_ -#define _SOC_SDMMC_PERIPH_H_ - -#include -//include soc related (generated) definitions -#include "soc/sdmmc_pins.h" -#include "soc/sdmmc_reg.h" -#include "soc/sdmmc_struct.h" -#include "soc/gpio_sig_map.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - uint8_t clk_gpio; - uint8_t cmd_gpio; - uint8_t d0_gpio; - uint8_t d1_gpio; - uint8_t d2_gpio; - uint8_t d3_gpio; - uint8_t d4_gpio; - uint8_t d5_gpio; - uint8_t d6_gpio; - uint8_t d7_gpio; - uint8_t card_detect; - uint8_t write_protect; - uint8_t card_int; - uint8_t width; -} sdmmc_slot_info_t; - -/** pin and signal information of each slot */ -extern const sdmmc_slot_info_t sdmmc_slot_info[]; - -#ifdef __cplusplus -} -#endif - +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _SOC_SDMMC_PERIPH_H_ +#define _SOC_SDMMC_PERIPH_H_ + +#include +//include soc related (generated) definitions +#include "soc/sdmmc_pins.h" +#include "soc/sdmmc_reg.h" +#include "soc/sdmmc_struct.h" +#include "soc/gpio_sig_map.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + uint8_t clk_gpio; + uint8_t cmd_gpio; + uint8_t d0_gpio; + uint8_t d1_gpio; + uint8_t d2_gpio; + uint8_t d3_gpio; + uint8_t d4_gpio; + uint8_t d5_gpio; + uint8_t d6_gpio; + uint8_t d7_gpio; + uint8_t card_detect; + uint8_t write_protect; + uint8_t card_int; + uint8_t width; +} sdmmc_slot_info_t; + +/** pin and signal information of each slot */ +extern const sdmmc_slot_info_t sdmmc_slot_info[]; + +#ifdef __cplusplus +} +#endif + #endif /* _SOC_SDMMC_PERIPH_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/soc/soc/sdmmc_pins.h b/tools/sdk/include/soc/soc/sdmmc_pins.h index 9a37ad0c..c0b32823 100644 --- a/tools/sdk/include/soc/soc/sdmmc_pins.h +++ b/tools/sdk/include/soc/soc/sdmmc_pins.h @@ -1,38 +1,38 @@ -// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _SOC_SDMMC_PINS_H_ -#define _SOC_SDMMC_PINS_H_ - -#define SDMMC_SLOT0_IOMUX_PIN_NUM_CLK 6 -#define SDMMC_SLOT0_IOMUX_PIN_NUM_CMD 11 -#define SDMMC_SLOT0_IOMUX_PIN_NUM_D0 7 -#define SDMMC_SLOT0_IOMUX_PIN_NUM_D1 8 -#define SDMMC_SLOT0_IOMUX_PIN_NUM_D2 9 -#define SDMMC_SLOT0_IOMUX_PIN_NUM_D3 10 -#define SDMMC_SLOT0_IOMUX_PIN_NUM_D4 16 -#define SDMMC_SLOT0_IOMUX_PIN_NUM_D5 17 -#define SDMMC_SLOT0_IOMUX_PIN_NUM_D6 5 -#define SDMMC_SLOT0_IOMUX_PIN_NUM_D7 18 -#define SDMMC_SLOT0_FUNC 0 - -#define SDMMC_SLOT1_IOMUX_PIN_NUM_CLK 14 -#define SDMMC_SLOT1_IOMUX_PIN_NUM_CMD 15 -#define SDMMC_SLOT1_IOMUX_PIN_NUM_D0 2 -#define SDMMC_SLOT1_IOMUX_PIN_NUM_D1 4 -#define SDMMC_SLOT1_IOMUX_PIN_NUM_D2 12 -#define SDMMC_SLOT1_IOMUX_PIN_NUM_D3 13 -#define SDMMC_SLOT1_FUNC 4 - +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _SOC_SDMMC_PINS_H_ +#define _SOC_SDMMC_PINS_H_ + +#define SDMMC_SLOT0_IOMUX_PIN_NUM_CLK 6 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_CMD 11 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D0 7 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D1 8 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D2 9 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D3 10 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D4 16 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D5 17 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D6 5 +#define SDMMC_SLOT0_IOMUX_PIN_NUM_D7 18 +#define SDMMC_SLOT0_FUNC 0 + +#define SDMMC_SLOT1_IOMUX_PIN_NUM_CLK 14 +#define SDMMC_SLOT1_IOMUX_PIN_NUM_CMD 15 +#define SDMMC_SLOT1_IOMUX_PIN_NUM_D0 2 +#define SDMMC_SLOT1_IOMUX_PIN_NUM_D1 4 +#define SDMMC_SLOT1_IOMUX_PIN_NUM_D2 12 +#define SDMMC_SLOT1_IOMUX_PIN_NUM_D3 13 +#define SDMMC_SLOT1_FUNC 4 + #endif /* _SOC_SDMMC_PINS_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/soc/soc/sdmmc_reg.h b/tools/sdk/include/soc/soc/sdmmc_reg.h index 2f9c68f8..0e92f682 100644 --- a/tools/sdk/include/soc/soc/sdmmc_reg.h +++ b/tools/sdk/include/soc/soc/sdmmc_reg.h @@ -71,6 +71,7 @@ #define SDMMC_INTMASK_EBE BIT(15) #define SDMMC_INTMASK_ACD BIT(14) #define SDMMC_INTMASK_SBE BIT(13) +#define SDMMC_INTMASK_BCI BIT(13) #define SDMMC_INTMASK_HLE BIT(12) #define SDMMC_INTMASK_FRUN BIT(11) #define SDMMC_INTMASK_HTO BIT(10) diff --git a/tools/sdk/include/soc/soc/sdmmc_struct.h b/tools/sdk/include/soc/soc/sdmmc_struct.h index 7e3c6912..6aa64b43 100644 --- a/tools/sdk/include/soc/soc/sdmmc_struct.h +++ b/tools/sdk/include/soc/soc/sdmmc_struct.h @@ -283,7 +283,12 @@ typedef volatile struct { uint32_t usrid; ///< user ID uint32_t verid; ///< IP block version uint32_t hcon; ///< compile-time IP configuration - uint32_t uhs; ///< TBD + union { + struct { + uint32_t voltage: 16; ///< voltage control for slots; no-op on ESP32. + uint32_t ddr: 16; ///< bit N enables DDR mode for card N + }; + } uhs; ///< UHS related settings union { struct { @@ -348,7 +353,16 @@ typedef volatile struct { uint32_t bufaddrl; ///< unused uint32_t bufaddru; ///< unused uint32_t reserved_a8[22]; - uint32_t cardthrctl; + union { + struct { + uint32_t read_thr_en : 1; ///< initiate transfer only if FIFO has more space than the read threshold + uint32_t busy_clr_int_en : 1; ///< enable generation of busy clear interrupts + uint32_t write_thr_en : 1; ///< equivalent of read_thr_en for writes + uint32_t reserved1 : 13; + uint32_t card_threshold : 12; ///< threshold value for reads/writes, in bytes + }; + uint32_t val; + } cardthrctl; uint32_t back_end_power; uint32_t uhs_reg_ext; uint32_t emmc_ddr_reg; diff --git a/tools/sdk/include/soc/soc/soc.h b/tools/sdk/include/soc/soc/soc.h index 660abbdb..59d171f3 100644 --- a/tools/sdk/include/soc/soc/soc.h +++ b/tools/sdk/include/soc/soc/soc.h @@ -120,6 +120,7 @@ #define DR_REG_I2C1_EXT_BASE 0x3ff67000 #define DR_REG_SDMMC_BASE 0x3ff68000 #define DR_REG_EMAC_BASE 0x3ff69000 +#define DR_REG_CAN_BASE 0x3ff6B000 #define DR_REG_PWM1_BASE 0x3ff6C000 #define DR_REG_I2S1_BASE 0x3ff6D000 #define DR_REG_UART2_BASE 0x3ff6E000 @@ -133,6 +134,7 @@ #ifndef __ASSEMBLER__ #define BIT(nr) (1UL << (nr)) +#define BIT64(nr) (1ULL << (nr)) #else #define BIT(nr) (1 << (nr)) #endif diff --git a/tools/sdk/include/soc/soc/soc_memory_layout.h b/tools/sdk/include/soc/soc/soc_memory_layout.h index 6273b1db..b1e8d6eb 100644 --- a/tools/sdk/include/soc/soc/soc_memory_layout.h +++ b/tools/sdk/include/soc/soc/soc_memory_layout.h @@ -20,6 +20,38 @@ #include "sdkconfig.h" #include "esp_attr.h" +#ifdef CONFIG_BT_ENABLED + +#define SOC_MEM_BT_DATA_START 0x3ffae6e0 +#define SOC_MEM_BT_DATA_END 0x3ffaff10 +#define SOC_MEM_BT_EM_START 0x3ffb0000 +#define SOC_MEM_BT_EM_END 0x3ffb7cd8 +#define SOC_MEM_BT_EM_BTDM0_START 0x3ffb0000 +#define SOC_MEM_BT_EM_BTDM0_END 0x3ffb09a8 +#define SOC_MEM_BT_EM_BLE_START 0x3ffb09a8 +#define SOC_MEM_BT_EM_BLE_END 0x3ffb1ddc +#define SOC_MEM_BT_EM_BTDM1_START 0x3ffb1ddc +#define SOC_MEM_BT_EM_BTDM1_END 0x3ffb2730 +#define SOC_MEM_BT_EM_BREDR_START 0x3ffb2730 +#define SOC_MEM_BT_EM_BREDR_NO_SYNC_END 0x3ffb6388 //Not calculate with synchronize connection support +#define SOC_MEM_BT_EM_BREDR_END 0x3ffb7cd8 //Calculate with synchronize connection support +#define SOC_MEM_BT_EM_SYNC0_START 0x3ffb6388 +#define SOC_MEM_BT_EM_SYNC0_END 0x3ffb6bf8 +#define SOC_MEM_BT_EM_SYNC1_START 0x3ffb6bf8 +#define SOC_MEM_BT_EM_SYNC1_END 0x3ffb7468 +#define SOC_MEM_BT_EM_SYNC2_START 0x3ffb7468 +#define SOC_MEM_BT_EM_SYNC2_END 0x3ffb7cd8 +#define SOC_MEM_BT_BSS_START 0x3ffb8000 +#define SOC_MEM_BT_BSS_END 0x3ffb9a20 +#define SOC_MEM_BT_MISC_START 0x3ffbdb28 +#define SOC_MEM_BT_MISC_END 0x3ffbdb5c + +#define SOC_MEM_BT_EM_PER_SYNC_SIZE 0x870 + +#define SOC_MEM_BT_EM_BREDR_REAL_END (SOC_MEM_BT_EM_BREDR_NO_SYNC_END + CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_EFF * SOC_MEM_BT_EM_PER_SYNC_SIZE) + +#endif //CONFIG_BT_ENABLED + #define SOC_MEMORY_TYPE_NO_PRIOS 3 /* Type descriptor holds a description for a particular type of memory on a particular SoC. @@ -57,8 +89,55 @@ typedef struct intptr_t end; } soc_reserved_region_t; -extern const soc_reserved_region_t soc_reserved_regions[]; -extern const size_t soc_reserved_region_count; +/* Use this macro to reserved a fixed region of RAM (hardcoded addresses) + * for a particular purpose. + * + * Usually used to mark out memory addresses needed for hardware or ROM code + * purposes. + * + * Don't call this macro from user code which can use normal C static allocation + * instead. + * + * @param START Start address to be reserved. + * @param END One after the address of the last byte to be reserved. (ie length of + * the reserved region is (END - START) in bytes. + * @param NAME Name for the reserved region. Must be a valid variable name, + * unique to this source file. + */ +#define SOC_RESERVE_MEMORY_REGION(START, END, NAME) \ + __attribute__((section(".reserved_memory_address"))) __attribute__((used)) \ + static soc_reserved_region_t reserved_region_##NAME = { START, END }; + +/* Return available memory regions for this SoC. Each available memory + * region is a contiguous piece of memory which is not being used by + * static data, used by ROM code, or reserved by a component using + * the SOC_RESERVE_MEMORY_REGION() macro. + * + * This result is soc_memory_regions[] minus all regions reserved + * via the SOC_RESERVE_MEMORY_REGION() macro (which may also split + * some regions up.) + * + * At startup, all available memory returned by this function is + * registered as heap space. + * + * @note OS-level startup function only, not recommended to call from + * app code. + * + * @param regions Pointer to an array for reading available regions into. + * Size of the array should be at least the result of + * soc_get_available_memory_region_max_count(). Entries in the array + * will be ordered by memory address. + * + * @return Number of entries copied to 'regions'. Will be no greater than + * the result of soc_get_available_memory_region_max_count(). + */ +size_t soc_get_available_memory_regions(soc_memory_region_t *regions); + +/* Return the maximum number of available memory regions which could be + * returned by soc_get_available_memory_regions(). Used to size the + * array passed to that function. + */ +size_t soc_get_available_memory_region_max_count(); inline static bool IRAM_ATTR esp_ptr_dma_capable(const void *p) { diff --git a/tools/sdk/include/soc/soc/spi_periph.h b/tools/sdk/include/soc/soc/spi_periph.h index 00c5f3e1..19b3f745 100644 --- a/tools/sdk/include/soc/soc/spi_periph.h +++ b/tools/sdk/include/soc/soc/spi_periph.h @@ -1,66 +1,66 @@ -// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _SOC_SPI_PERIPH_H_ -#define _SOC_SPI_PERIPH_H_ - -#include -#include "soc/soc.h" -#include "soc/periph_defs.h" -//include soc related (generated) definitions -#include "soc/spi_pins.h" -#include "soc/spi_reg.h" -#include "soc/spi_struct.h" -#include "soc/gpio_sig_map.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -/* - Stores a bunch of per-spi-peripheral data. -*/ -typedef struct { - const uint8_t spiclk_out; //GPIO mux output signals - const uint8_t spiclk_in; - const uint8_t spid_out; - const uint8_t spiq_out; - const uint8_t spiwp_out; - const uint8_t spihd_out; - const uint8_t spid_in; //GPIO mux input signals - const uint8_t spiq_in; - const uint8_t spiwp_in; - const uint8_t spihd_in; - const uint8_t spics_out[3]; // /CS GPIO output mux signals - const uint8_t spics_in; - const uint8_t spiclk_iomux_pin; //IO pins of IO_MUX muxed signals - const uint8_t spid_iomux_pin; - const uint8_t spiq_iomux_pin; - const uint8_t spiwp_iomux_pin; - const uint8_t spihd_iomux_pin; - const uint8_t spics0_iomux_pin; - const uint8_t irq; //irq source for interrupt mux - const uint8_t irq_dma; //dma irq source for interrupt mux - const periph_module_t module; //peripheral module, for enabling clock etc - spi_dev_t *hw; //Pointer to the hardware registers -} spi_signal_conn_t; - -extern const spi_signal_conn_t spi_periph_signal[3]; - -#ifdef __cplusplus -} -#endif - +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _SOC_SPI_PERIPH_H_ +#define _SOC_SPI_PERIPH_H_ + +#include +#include "soc/soc.h" +#include "soc/periph_defs.h" +//include soc related (generated) definitions +#include "soc/spi_pins.h" +#include "soc/spi_reg.h" +#include "soc/spi_struct.h" +#include "soc/gpio_sig_map.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* + Stores a bunch of per-spi-peripheral data. +*/ +typedef struct { + const uint8_t spiclk_out; //GPIO mux output signals + const uint8_t spiclk_in; + const uint8_t spid_out; + const uint8_t spiq_out; + const uint8_t spiwp_out; + const uint8_t spihd_out; + const uint8_t spid_in; //GPIO mux input signals + const uint8_t spiq_in; + const uint8_t spiwp_in; + const uint8_t spihd_in; + const uint8_t spics_out[3]; // /CS GPIO output mux signals + const uint8_t spics_in; + const uint8_t spiclk_iomux_pin; //IO pins of IO_MUX muxed signals + const uint8_t spid_iomux_pin; + const uint8_t spiq_iomux_pin; + const uint8_t spiwp_iomux_pin; + const uint8_t spihd_iomux_pin; + const uint8_t spics0_iomux_pin; + const uint8_t irq; //irq source for interrupt mux + const uint8_t irq_dma; //dma irq source for interrupt mux + const periph_module_t module; //peripheral module, for enabling clock etc + spi_dev_t *hw; //Pointer to the hardware registers +} spi_signal_conn_t; + +extern const spi_signal_conn_t spi_periph_signal[3]; + +#ifdef __cplusplus +} +#endif + #endif /* _SOC_SPI_PERIPH_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/soc/soc/spi_pins.h b/tools/sdk/include/soc/soc/spi_pins.h index 49be9b7c..eb7af858 100644 --- a/tools/sdk/include/soc/soc/spi_pins.h +++ b/tools/sdk/include/soc/soc/spi_pins.h @@ -1,39 +1,39 @@ -// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _SOC_SPI_PINS_H_ -#define _SOC_SPI_PINS_H_ - -#define SPI_IOMUX_PIN_NUM_MISO 7 -#define SPI_IOMUX_PIN_NUM_MOSI 8 -#define SPI_IOMUX_PIN_NUM_CLK 6 -#define SPI_IOMUX_PIN_NUM_CS 11 -#define SPI_IOMUX_PIN_NUM_WP 10 -#define SPI_IOMUX_PIN_NUM_HD 9 - -#define HSPI_IOMUX_PIN_NUM_MISO 12 -#define HSPI_IOMUX_PIN_NUM_MOSI 13 -#define HSPI_IOMUX_PIN_NUM_CLK 14 -#define HSPI_IOMUX_PIN_NUM_CS 15 -#define HSPI_IOMUX_PIN_NUM_WP 2 -#define HSPI_IOMUX_PIN_NUM_HD 4 - -#define VSPI_IOMUX_PIN_NUM_MISO 19 -#define VSPI_IOMUX_PIN_NUM_MOSI 23 -#define VSPI_IOMUX_PIN_NUM_CLK 18 -#define VSPI_IOMUX_PIN_NUM_CS 5 -#define VSPI_IOMUX_PIN_NUM_WP 22 -#define VSPI_IOMUX_PIN_NUM_HD 21 - +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _SOC_SPI_PINS_H_ +#define _SOC_SPI_PINS_H_ + +#define SPI_IOMUX_PIN_NUM_MISO 7 +#define SPI_IOMUX_PIN_NUM_MOSI 8 +#define SPI_IOMUX_PIN_NUM_CLK 6 +#define SPI_IOMUX_PIN_NUM_CS 11 +#define SPI_IOMUX_PIN_NUM_WP 10 +#define SPI_IOMUX_PIN_NUM_HD 9 + +#define HSPI_IOMUX_PIN_NUM_MISO 12 +#define HSPI_IOMUX_PIN_NUM_MOSI 13 +#define HSPI_IOMUX_PIN_NUM_CLK 14 +#define HSPI_IOMUX_PIN_NUM_CS 15 +#define HSPI_IOMUX_PIN_NUM_WP 2 +#define HSPI_IOMUX_PIN_NUM_HD 4 + +#define VSPI_IOMUX_PIN_NUM_MISO 19 +#define VSPI_IOMUX_PIN_NUM_MOSI 23 +#define VSPI_IOMUX_PIN_NUM_CLK 18 +#define VSPI_IOMUX_PIN_NUM_CS 5 +#define VSPI_IOMUX_PIN_NUM_WP 22 +#define VSPI_IOMUX_PIN_NUM_HD 21 + #endif /* _SOC_SPI_PINS_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/spi_flash/esp_partition.h b/tools/sdk/include/spi_flash/esp_partition.h index f3d5a424..5345fa97 100644 --- a/tools/sdk/include/spi_flash/esp_partition.h +++ b/tools/sdk/include/spi_flash/esp_partition.h @@ -286,6 +286,37 @@ esp_err_t esp_partition_mmap(const esp_partition_t* partition, uint32_t offset, spi_flash_mmap_memory_t memory, const void** out_ptr, spi_flash_mmap_handle_t* out_handle); +/** + * @brief Get SHA-256 digest for required partition. + * + * For apps with SHA-256 appended to the app image, the result is the appended SHA-256 value for the app image content. + * The hash is verified before returning, if app content is invalid then the function returns ESP_ERR_IMAGE_INVALID. + * For apps without SHA-256 appended to the image, the result is the SHA-256 of all bytes in the app image. + * For other partition types, the result is the SHA-256 of the entire partition. + * + * @param[in] partition Pointer to info for partition containing app or data. (fields: address, size and type, are required to be filled). + * @param[out] sha_256 Returned SHA-256 digest for a given partition. + * + * @return + * - ESP_OK: In case of successful operation. + * - ESP_ERR_INVALID_ARG: The size was 0 or the sha_256 was NULL. + * - ESP_ERR_NO_MEM: Cannot allocate memory for sha256 operation. + * - ESP_ERR_IMAGE_INVALID: App partition doesn't contain a valid app image. + * - ESP_FAIL: An allocation error occurred. + */ +esp_err_t esp_partition_get_sha256(const esp_partition_t *partition, uint8_t *sha_256); + +/** + * @brief Check for the identity of two partitions by SHA-256 digest. + * + * @param[in] partition_1 Pointer to info for partition 1 containing app or data. (fields: address, size and type, are required to be filled). + * @param[in] partition_2 Pointer to info for partition 2 containing app or data. (fields: address, size and type, are required to be filled). + * + * @return + * - True: In case of the two firmware is equal. + * - False: Otherwise + */ +bool esp_partition_check_identity(const esp_partition_t *partition_1, const esp_partition_t *partition_2); #ifdef __cplusplus } diff --git a/tools/sdk/include/spi_flash/esp_spi_flash.h b/tools/sdk/include/spi_flash/esp_spi_flash.h index 9caa47e4..7977e116 100644 --- a/tools/sdk/include/spi_flash/esp_spi_flash.h +++ b/tools/sdk/include/spi_flash/esp_spi_flash.h @@ -185,8 +185,8 @@ typedef uint32_t spi_flash_mmap_handle_t; * @param size Size of region to be mapped. This size will be rounded * up to a 64kB boundary * @param memory Address space where the region should be mapped (data or instruction) - * @param out_ptr Output, pointer to the mapped memory region - * @param out_handle Output, handle which should be used for spi_flash_munmap call + * @param[out] out_ptr Output, pointer to the mapped memory region + * @param[out] out_handle Output, handle which should be used for spi_flash_munmap call * * @return ESP_OK on success, ESP_ERR_NO_MEM if pages can not be allocated */ @@ -204,14 +204,19 @@ esp_err_t spi_flash_mmap(size_t src_addr, size_t size, spi_flash_mmap_memory_t m * @param pages An array of numbers indicating the 64kB pages in flash to be mapped * contiguously into memory. These indicate the indexes of the 64kB pages, * not the byte-size addresses as used in other functions. - * @param pagecount Number of entries in the pages array + * Array must be located in internal memory. + * @param page_count Number of entries in the pages array * @param memory Address space where the region should be mapped (instruction or data) - * @param out_ptr Output, pointer to the mapped memory region - * @param out_handle Output, handle which should be used for spi_flash_munmap call + * @param[out] out_ptr Output, pointer to the mapped memory region + * @param[out] out_handle Output, handle which should be used for spi_flash_munmap call * - * @return ESP_OK on success, ESP_ERR_NO_MEM if pages can not be allocated + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM if pages can not be allocated + * - ESP_ERR_INVALID_ARG if pagecount is zero or pages array is not in + * internal memory */ -esp_err_t spi_flash_mmap_pages(int *pages, size_t pagecount, spi_flash_mmap_memory_t memory, +esp_err_t spi_flash_mmap_pages(const int *pages, size_t page_count, spi_flash_mmap_memory_t memory, const void** out_ptr, spi_flash_mmap_handle_t* out_handle); diff --git a/tools/sdk/include/tcp_transport/transport.h b/tools/sdk/include/tcp_transport/transport.h new file mode 100644 index 00000000..a54cb83c --- /dev/null +++ b/tools/sdk/include/tcp_transport/transport.h @@ -0,0 +1,265 @@ +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _TRANSPORT_H_ +#define _TRANSPORT_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef struct transport_list_t* transport_list_handle_t; +typedef struct transport_item_t* transport_handle_t; + +typedef int (*connect_func)(transport_handle_t t, const char *host, int port, int timeout_ms); +typedef int (*io_func)(transport_handle_t t, const char *buffer, int len, int timeout_ms); +typedef int (*io_read_func)(transport_handle_t t, char *buffer, int len, int timeout_ms); +typedef int (*trans_func)(transport_handle_t t); +typedef int (*poll_func)(transport_handle_t t, int timeout_ms); +typedef transport_handle_t (*payload_transfer_func)(transport_handle_t); + +/** + * @brief Create transport list + * + * @return A handle can hold all transports + */ +transport_list_handle_t transport_list_init(); + +/** + * @brief Cleanup and free all transports, include itself, + * this function will invoke transport_destroy of every transport have added this the list + * + * @param[in] list The list + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t transport_list_destroy(transport_list_handle_t list); + +/** + * @brief Add a transport to the list, and define a scheme to indentify this transport in the list + * + * @param[in] list The list + * @param[in] t The Transport + * @param[in] scheme The scheme + * + * @return + * - ESP_OK + */ +esp_err_t transport_list_add(transport_list_handle_t list, transport_handle_t t, const char *scheme); + +/** + * @brief This function will remove all transport from the list, + * invoke transport_destroy of every transport have added this the list + * + * @param[in] list The list + * + * @return + * - ESP_OK + * - ESP_ERR_INVALID_ARG + */ +esp_err_t transport_list_clean(transport_list_handle_t list); + +/** + * @brief Get the transport by scheme, which has been defined when calling function `transport_list_add` + * + * @param[in] list The list + * @param[in] tag The tag + * + * @return The transport handle + */ +transport_handle_t transport_list_get_transport(transport_list_handle_t list, const char *scheme); + +/** + * @brief Initialize a transport handle object + * + * @return The transport handle + */ +transport_handle_t transport_init(); + +/** + * @brief Cleanup and free memory the transport + * + * @param[in] t The transport handle + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t transport_destroy(transport_handle_t t); + +/** + * @brief Get default port number used by this transport + * + * @param[in] t The transport handle + * + * @return the port number + */ +int transport_get_default_port(transport_handle_t t); + +/** + * @brief Set default port number that can be used by this transport + * + * @param[in] t The transport handle + * @param[in] port The port number + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t transport_set_default_port(transport_handle_t t, int port); + +/** + * @brief Transport connection function, to make a connection to server + * + * @param t The transport handle + * @param[in] host Hostname + * @param[in] port Port + * @param[in] timeout_ms The timeout milliseconds + * + * @return + * - socket for will use by this transport + * - (-1) if there are any errors, should check errno + */ +int transport_connect(transport_handle_t t, const char *host, int port, int timeout_ms); + +/** + * @brief Transport read function + * + * @param t The transport handle + * @param buffer The buffer + * @param[in] len The length + * @param[in] timeout_ms The timeout milliseconds + * + * @return + * - Number of bytes was read + * - (-1) if there are any errors, should check errno + */ +int transport_read(transport_handle_t t, char *buffer, int len, int timeout_ms); + +/** + * @brief Poll the transport until readable or timeout + * + * @param[in] t The transport handle + * @param[in] timeout_ms The timeout milliseconds + * + * @return + * - 0 Timeout + * - (-1) If there are any errors, should check errno + * - other The transport can read + */ +int transport_poll_read(transport_handle_t t, int timeout_ms); + +/** + * @brief Transport write function + * + * @param t The transport handle + * @param buffer The buffer + * @param[in] len The length + * @param[in] timeout_ms The timeout milliseconds + * + * @return + * - Number of bytes was written + * - (-1) if there are any errors, should check errno + */ +int transport_write(transport_handle_t t, const char *buffer, int len, int timeout_ms); + +/** + * @brief Poll the transport until writeable or timeout + * + * @param[in] t The transport handle + * @param[in] timeout_ms The timeout milliseconds + * + * @return + * - 0 Timeout + * - (-1) If there are any errors, should check errno + * - other The transport can write + */ +int transport_poll_write(transport_handle_t t, int timeout_ms); + +/** + * @brief Transport close + * + * @param t The transport handle + * + * @return + * - 0 if ok + * - (-1) if there are any errors, should check errno + */ +int transport_close(transport_handle_t t); + +/** + * @brief Get user data context of this transport + * + * @param[in] t The transport handle + * + * @return The user data context + */ +void *transport_get_context_data(transport_handle_t t); + +/** + * @brief Get transport handle of underlying protocol + * which can access this protocol payload directly + * (used for receiving longer msg multiple times) + * + * @param[in] t The transport handle + * + * @return Payload transport handle + */ +transport_handle_t transport_get_payload_transport_handle(transport_handle_t t); + +/** + * @brief Set the user context data for this transport + * + * @param[in] t The transport handle + * @param data The user data context + * + * @return + * - ESP_OK + */ +esp_err_t transport_set_context_data(transport_handle_t t, void *data); + +/** + * @brief Set transport functions for the transport handle + * + * @param[in] t The transport handle + * @param[in] _connect The connect function pointer + * @param[in] _read The read function pointer + * @param[in] _write The write function pointer + * @param[in] _close The close function pointer + * @param[in] _poll_read The poll read function pointer + * @param[in] _poll_write The poll write function pointer + * @param[in] _destroy The destroy function pointer + * @param[in] _parrent_transport The parrent transfer getter pointer + * + * @return + * - ESP_OK + */ +esp_err_t transport_set_func(transport_handle_t t, + connect_func _connect, + io_read_func _read, + io_func _write, + trans_func _close, + poll_func _poll_read, + poll_func _poll_write, + trans_func _destroy, + payload_transfer_func _parrent_transport); +#ifdef __cplusplus +} +#endif +#endif diff --git a/tools/sdk/include/tcp_transport/transport_ssl.h b/tools/sdk/include/tcp_transport/transport_ssl.h new file mode 100644 index 00000000..a00b36ba --- /dev/null +++ b/tools/sdk/include/tcp_transport/transport_ssl.h @@ -0,0 +1,48 @@ +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _TRANSPORT_SSL_H_ +#define _TRANSPORT_SSL_H_ + +#include "transport.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * @brief Create new SSL transport, the transport handle must be release transport_destroy callback + * + * @return the allocated transport_handle_t, or NULL if the handle can not be allocated + */ +transport_handle_t transport_ssl_init(); + +/** + * @brief Set SSL certificate data (as PEM format). + * Note that, this function stores the pointer to data, rather than making a copy. + * So we need to make sure to keep the data lifetime before cleanup the connection + * + * @param t ssl transport + * @param[in] data The pem data + * @param[in] len The length + */ +void transport_ssl_set_cert_data(transport_handle_t t, const char *data, int len); + + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/tools/sdk/include/tcp_transport/transport_tcp.h b/tools/sdk/include/tcp_transport/transport_tcp.h new file mode 100644 index 00000000..e1cc1d34 --- /dev/null +++ b/tools/sdk/include/tcp_transport/transport_tcp.h @@ -0,0 +1,36 @@ +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _TRANSPORT_TCP_H_ +#define _TRANSPORT_TCP_H_ + +#include "transport.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Create TCP transport, the transport handle must be release transport_destroy callback + * + * @return the allocated transport_handle_t, or NULL if the handle can not be allocated + */ +transport_handle_t transport_tcp_init(); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/include/tcp_transport/transport_utils.h b/tools/sdk/include/tcp_transport/transport_utils.h new file mode 100644 index 00000000..0e72812e --- /dev/null +++ b/tools/sdk/include/tcp_transport/transport_utils.h @@ -0,0 +1,40 @@ +// Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _TRANSPORT_UTILS_H_ +#define _TRANSPORT_UTILS_H_ +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Convert milliseconds to timeval struct + * + * @param[in] timeout_ms The timeout milliseconds + * @param[out] tv Timeval struct + */ +void transport_utils_ms_to_timeval(int timeout_ms, struct timeval *tv); + + +#define TRANSPORT_MEM_CHECK(TAG, a, action) if (!(a)) { \ + ESP_LOGE(TAG,"%s:%d (%s): %s", __FILE__, __LINE__, __FUNCTION__, "Memory exhausted"); \ + action; \ + } + +#ifdef __cplusplus +} +#endif +#endif /* _TRANSPORT_UTILS_H_ */ \ No newline at end of file diff --git a/tools/sdk/include/tcpip_adapter/tcpip_adapter.h b/tools/sdk/include/tcpip_adapter/tcpip_adapter.h index 7ab31d1c..205c05fa 100644 --- a/tools/sdk/include/tcpip_adapter/tcpip_adapter.h +++ b/tools/sdk/include/tcpip_adapter/tcpip_adapter.h @@ -33,19 +33,17 @@ * get free station list APIs in application side. Other APIs are used in esp-idf internal, * otherwise the state maybe wrong. * - * TODO: ipv6 support will be added, use menuconfig to disable CONFIG_TCPIP_LWIP + * TODO: ipv6 support will be added */ #include #include "rom/queue.h" #include "esp_wifi_types.h" - -#define CONFIG_TCPIP_LWIP 1 -#define CONFIG_DHCP_STA_LIST 1 +#include "sdkconfig.h" #if CONFIG_TCPIP_LWIP #include "lwip/ip_addr.h" -#include "apps/dhcpserver.h" +#include "dhcpserver/dhcpserver.h" #ifdef __cplusplus extern "C" { @@ -81,7 +79,6 @@ typedef struct { typedef dhcps_lease_t tcpip_adapter_dhcps_lease_t; -#if CONFIG_DHCP_STA_LIST typedef struct { uint8_t mac[6]; ip4_addr_t ip; @@ -91,12 +88,10 @@ typedef struct { tcpip_adapter_sta_info_t sta[ESP_WIFI_MAX_CONN_NUM]; int num; } tcpip_adapter_sta_list_t; -#endif #endif -#define ESP_ERR_TCPIP_ADAPTER_BASE 0x5000 // TODO: move base address to esp_err.h - +#define ESP_ERR_TCPIP_ADAPTER_BASE 0x5000 #define ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS ESP_ERR_TCPIP_ADAPTER_BASE + 0x01 #define ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY ESP_ERR_TCPIP_ADAPTER_BASE + 0x02 #define ESP_ERR_TCPIP_ADAPTER_DHCPC_START_FAILED ESP_ERR_TCPIP_ADAPTER_BASE + 0x03 @@ -105,7 +100,6 @@ typedef struct { #define ESP_ERR_TCPIP_ADAPTER_NO_MEM ESP_ERR_TCPIP_ADAPTER_BASE + 0x06 #define ESP_ERR_TCPIP_ADAPTER_DHCP_NOT_STOPPED ESP_ERR_TCPIP_ADAPTER_BASE + 0x07 -/* TODO: add Ethernet interface */ typedef enum { TCPIP_ADAPTER_IF_STA = 0, /**< ESP32 station interface */ TCPIP_ADAPTER_IF_AP, /**< ESP32 soft-AP interface */ @@ -522,8 +516,17 @@ esp_err_t tcpip_adapter_dhcpc_start(tcpip_adapter_if_t tcpip_if); */ esp_err_t tcpip_adapter_dhcpc_stop(tcpip_adapter_if_t tcpip_if); - - +/** + * @brief Get data from ethernet interface + * + * This function should be installed by esp_eth_init, so Ethernet packets will be forward to TCPIP stack. + * + * @param[in] void *buffer: the received data point + * @param[in] uint16_t len: the received data length + * @param[in] void *eb: parameter + * + * @return ESP_OK + */ esp_err_t tcpip_adapter_eth_input(void *buffer, uint16_t len, void *eb); /** @@ -561,7 +564,7 @@ esp_err_t tcpip_adapter_ap_input(void *buffer, uint16_t len, void *eb); * * @return ESP_IF_WIFI_STA * ESP_IF_WIFI_AP - ESP_IF_ETH + * ESP_IF_ETH * ESP_IF_MAX */ esp_interface_t tcpip_adapter_get_esp_if(void *dev); diff --git a/tools/sdk/include/ulp/esp32/ulp.h b/tools/sdk/include/ulp/esp32/ulp.h index 64bfff8c..6960ac97 100644 --- a/tools/sdk/include/ulp/esp32/ulp.h +++ b/tools/sdk/include/ulp/esp32/ulp.h @@ -17,11 +17,14 @@ #include #include #include "esp_err.h" +#include "soc/soc.h" #ifdef __cplusplus extern "C" { #endif +#define ULP_FSM_PREPARE_SLEEP_CYCLES 2 /*!< Cycles spent by FSM preparing ULP for sleep */ +#define ULP_FSM_WAKEUP_SLEEP_CYCLES 2 /*!< Cycles spent by FSM waking up ULP from sleep */ /** * @defgroup ulp_registers ULP coprocessor registers @@ -860,7 +863,7 @@ esp_err_t ulp_process_macros_and_load(uint32_t load_addr, const ulp_insn_t* prog * 3. TEXT_SIZE, size of .text section (2 bytes) * 4. DATA_SIZE, size of .data section (2 bytes) * 5. BSS_SIZE, size of .bss section (2 bytes) - * 6. (TEXT_OFFSET - 16) bytes of arbitrary data (will not be loaded into RTC memory) + * 6. (TEXT_OFFSET - 12) bytes of arbitrary data (will not be loaded into RTC memory) * 7. .text section * 8. .data section * @@ -897,6 +900,12 @@ esp_err_t ulp_run(uint32_t entry_point); * * @param period_index wakeup period setting number (0 - 4) * @param period_us wakeup period, us + * @note The ULP FSM requires two clock cycles to wakeup before being able to run the program. + * Then additional 16 cycles are reserved after wakeup waiting until the 8M clock is stable. + * The FSM also requires two more clock cycles to go to sleep after the program execution is halted. + * The minimum wakeup period that may be set up for the ULP + * is equal to the total number of cycles spent on the above internal tasks. + * For a default configuration of the ULP running at 150kHz it makes about 133us. * @return * - ESP_OK on success * - ESP_ERR_INVALID_ARG if period_index is out of range diff --git a/tools/sdk/include/vfs/esp_vfs.h b/tools/sdk/include/vfs/esp_vfs.h index 4d847274..d7467d22 100644 --- a/tools/sdk/include/vfs/esp_vfs.h +++ b/tools/sdk/include/vfs/esp_vfs.h @@ -26,8 +26,10 @@ #include #include #include +#include #include #include +#include "sdkconfig.h" #ifdef __cplusplus extern "C" { @@ -178,6 +180,37 @@ typedef struct int (*truncate_p)(void* ctx, const char *path, off_t length); int (*truncate)(const char *path, off_t length); }; +#ifdef CONFIG_SUPPORT_TERMIOS + union { + int (*tcsetattr_p)(void *ctx, int fd, int optional_actions, const struct termios *p); + int (*tcsetattr)(int fd, int optional_actions, const struct termios *p); + }; + union { + int (*tcgetattr_p)(void *ctx, int fd, struct termios *p); + int (*tcgetattr)(int fd, struct termios *p); + }; + union { + int (*tcdrain_p)(void *ctx, int fd); + int (*tcdrain)(int fd); + }; + union { + int (*tcflush_p)(void *ctx, int fd, int select); + int (*tcflush)(int fd, int select); + }; + union { + int (*tcflow_p)(void *ctx, int fd, int action); + int (*tcflow)(int fd, int action); + }; + union { + pid_t (*tcgetsid_p)(void *ctx, int fd); + pid_t (*tcgetsid)(int fd); + }; + union { + int (*tcsendbreak_p)(void *ctx, int fd, int duration); + int (*tcsendbreak)(int fd, int duration); + }; +#endif // CONFIG_SUPPORT_TERMIOS + /** start_select is called for setting up synchronous I/O multiplexing of the desired file descriptors in the given VFS */ esp_err_t (*start_select)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, SemaphoreHandle_t *signal_sem); /** socket select function for socket FDs with the functionality of POSIX select(); this should be set only for the socket VFS */ diff --git a/tools/sdk/include/vfs/sys/ioctl.h b/tools/sdk/include/vfs/sys/ioctl.h index 95bad981..90cbb47d 100644 --- a/tools/sdk/include/vfs/sys/ioctl.h +++ b/tools/sdk/include/vfs/sys/ioctl.h @@ -14,5 +14,12 @@ #pragma once +#ifdef __cplusplus +extern "C" { +#endif + int ioctl(int fd, int request, ...); +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/include/wear_levelling/wear_levelling.h b/tools/sdk/include/wear_levelling/wear_levelling.h index 60f252e9..137b13f1 100644 --- a/tools/sdk/include/wear_levelling/wear_levelling.h +++ b/tools/sdk/include/wear_levelling/wear_levelling.h @@ -1,136 +1,136 @@ -// Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _wear_levelling_H_ -#define _wear_levelling_H_ - -#include "esp_log.h" -#include "esp_partition.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** -* @brief wear levelling handle -*/ -typedef int32_t wl_handle_t; - -#define WL_INVALID_HANDLE -1 - -/** -* @brief Mount WL for defined partition -* -* @param partition that will be used for access -* @param out_handle handle of the WL instance -* -* @return -* - ESP_OK, if the allocation was successfully; -* - ESP_ERR_INVALID_ARG, if WL allocation was unsuccessful; -* - ESP_ERR_NO_MEM, if there was no memory to allocate WL components; -*/ -esp_err_t wl_mount(const esp_partition_t *partition, wl_handle_t *out_handle); - -/** -* @brief Unmount WL for defined partition -* -* @param handle WL partition handle -* -* @return -* - ESP_OK, if the operation completed successfully; -* - or one of error codes from lower-level flash driver. -*/ -esp_err_t wl_unmount(wl_handle_t handle); - -/** -* @brief Erase part of the WL storage -* -* @param handle WL handle that are related to the partition -* @param start_addr Address where erase operation should start. Must be aligned -* to the result of function wl_sector_size(...). -* @param size Size of the range which should be erased, in bytes. -* Must be divisible by result of function wl_sector_size(...).. -* -* @return -* - ESP_OK, if the range was erased successfully; -* - ESP_ERR_INVALID_ARG, if iterator or dst are NULL; -* - ESP_ERR_INVALID_SIZE, if erase would go out of bounds of the partition; -* - or one of error codes from lower-level flash driver. -*/ -esp_err_t wl_erase_range(wl_handle_t handle, size_t start_addr, size_t size); - -/** -* @brief Write data to the WL storage -* -* Before writing data to flash, corresponding region of flash needs to be erased. -* This can be done using wl_erase_range function. -* -* @param handle WL handle that are related to the partition -* @param dest_addr Address where the data should be written, relative to the -* beginning of the partition. -* @param src Pointer to the source buffer. Pointer must be non-NULL and -* buffer must be at least 'size' bytes long. -* @param size Size of data to be written, in bytes. -* -* @note Prior to writing to WL storage, make sure it has been erased with -* wl_erase_range call. -* -* @return -* - ESP_OK, if data was written successfully; -* - ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; -* - ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; -* - or one of error codes from lower-level flash driver. -*/ -esp_err_t wl_write(wl_handle_t handle, size_t dest_addr, const void *src, size_t size); - -/** -* @brief Read data from the WL storage -* -* @param handle WL module instance that was initialized before -* @param dest Pointer to the buffer where data should be stored. -* Pointer must be non-NULL and buffer must be at least 'size' bytes long. -* @param src_addr Address of the data to be read, relative to the -* beginning of the partition. -* @param size Size of data to be read, in bytes. -* -* @return -* - ESP_OK, if data was read successfully; -* - ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; -* - ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; -* - or one of error codes from lower-level flash driver. -*/ -esp_err_t wl_read(wl_handle_t handle, size_t src_addr, void *dest, size_t size); - -/** -* @brief Get size of the WL storage -* -* @param handle WL module handle that was initialized before -* @return usable size, in bytes -*/ -size_t wl_size(wl_handle_t handle); - -/** -* @brief Get sector size of the WL instance -* -* @param handle WL module handle that was initialized before -* @return sector size, in bytes -*/ -size_t wl_sector_size(wl_handle_t handle); - - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // _wear_levelling_H_ +// Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef _wear_levelling_H_ +#define _wear_levelling_H_ + +#include "esp_log.h" +#include "esp_partition.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @brief wear levelling handle +*/ +typedef int32_t wl_handle_t; + +#define WL_INVALID_HANDLE -1 + +/** +* @brief Mount WL for defined partition +* +* @param partition that will be used for access +* @param out_handle handle of the WL instance +* +* @return +* - ESP_OK, if the allocation was successfully; +* - ESP_ERR_INVALID_ARG, if WL allocation was unsuccessful; +* - ESP_ERR_NO_MEM, if there was no memory to allocate WL components; +*/ +esp_err_t wl_mount(const esp_partition_t *partition, wl_handle_t *out_handle); + +/** +* @brief Unmount WL for defined partition +* +* @param handle WL partition handle +* +* @return +* - ESP_OK, if the operation completed successfully; +* - or one of error codes from lower-level flash driver. +*/ +esp_err_t wl_unmount(wl_handle_t handle); + +/** +* @brief Erase part of the WL storage +* +* @param handle WL handle that are related to the partition +* @param start_addr Address where erase operation should start. Must be aligned +* to the result of function wl_sector_size(...). +* @param size Size of the range which should be erased, in bytes. +* Must be divisible by result of function wl_sector_size(...).. +* +* @return +* - ESP_OK, if the range was erased successfully; +* - ESP_ERR_INVALID_ARG, if iterator or dst are NULL; +* - ESP_ERR_INVALID_SIZE, if erase would go out of bounds of the partition; +* - or one of error codes from lower-level flash driver. +*/ +esp_err_t wl_erase_range(wl_handle_t handle, size_t start_addr, size_t size); + +/** +* @brief Write data to the WL storage +* +* Before writing data to flash, corresponding region of flash needs to be erased. +* This can be done using wl_erase_range function. +* +* @param handle WL handle that are related to the partition +* @param dest_addr Address where the data should be written, relative to the +* beginning of the partition. +* @param src Pointer to the source buffer. Pointer must be non-NULL and +* buffer must be at least 'size' bytes long. +* @param size Size of data to be written, in bytes. +* +* @note Prior to writing to WL storage, make sure it has been erased with +* wl_erase_range call. +* +* @return +* - ESP_OK, if data was written successfully; +* - ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; +* - ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; +* - or one of error codes from lower-level flash driver. +*/ +esp_err_t wl_write(wl_handle_t handle, size_t dest_addr, const void *src, size_t size); + +/** +* @brief Read data from the WL storage +* +* @param handle WL module instance that was initialized before +* @param dest Pointer to the buffer where data should be stored. +* Pointer must be non-NULL and buffer must be at least 'size' bytes long. +* @param src_addr Address of the data to be read, relative to the +* beginning of the partition. +* @param size Size of data to be read, in bytes. +* +* @return +* - ESP_OK, if data was read successfully; +* - ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; +* - ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; +* - or one of error codes from lower-level flash driver. +*/ +esp_err_t wl_read(wl_handle_t handle, size_t src_addr, void *dest, size_t size); + +/** +* @brief Get size of the WL storage +* +* @param handle WL module handle that was initialized before +* @return usable size, in bytes +*/ +size_t wl_size(wl_handle_t handle); + +/** +* @brief Get sector size of the WL instance +* +* @param handle WL module handle that was initialized before +* @return sector size, in bytes +*/ +size_t wl_sector_size(wl_handle_t handle); + + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // _wear_levelling_H_ diff --git a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_peap_common.h b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_peap_common.h index c0dc6ed8..7aad0dff 100644 --- a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_peap_common.h +++ b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_peap_common.h @@ -1,16 +1,16 @@ -/* - * EAP-PEAP common routines - * Copyright (c) 2008-2011, Jouni Malinen - * - * This software may be distributed under the terms of the BSD license. - * See README for more details. - */ - -#ifndef EAP_PEAP_COMMON_H -#define EAP_PEAP_COMMON_H - -int peap_prfplus(int version, const u8 *key, size_t key_len, - const char *label, const u8 *seed, size_t seed_len, - u8 *buf, size_t buf_len); - -#endif /* EAP_PEAP_COMMON_H */ +/* + * EAP-PEAP common routines + * Copyright (c) 2008-2011, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef EAP_PEAP_COMMON_H +#define EAP_PEAP_COMMON_H + +int peap_prfplus(int version, const u8 *key, size_t key_len, + const char *label, const u8 *seed, size_t seed_len, + u8 *buf, size_t buf_len); + +#endif /* EAP_PEAP_COMMON_H */ diff --git a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_tlv_common.h b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_tlv_common.h index 8f0f83f7..3286055a 100644 --- a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_tlv_common.h +++ b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_tlv_common.h @@ -1,112 +1,112 @@ -/* - * EAP-TLV definitions (draft-josefsson-pppext-eap-tls-eap-10.txt) - * Copyright (c) 2004-2008, Jouni Malinen - * - * This software may be distributed under the terms of the BSD license. - * See README for more details. - */ - -#ifndef EAP_TLV_COMMON_H -#define EAP_TLV_COMMON_H - -/* EAP-TLV TLVs (draft-josefsson-ppext-eap-tls-eap-10.txt) */ -#define EAP_TLV_RESULT_TLV 3 /* Acknowledged Result */ -#define EAP_TLV_NAK_TLV 4 -#define EAP_TLV_ERROR_CODE_TLV 5 -#define EAP_TLV_CONNECTION_BINDING_TLV 6 -#define EAP_TLV_VENDOR_SPECIFIC_TLV 7 -#define EAP_TLV_URI_TLV 8 -#define EAP_TLV_EAP_PAYLOAD_TLV 9 -#define EAP_TLV_INTERMEDIATE_RESULT_TLV 10 -#define EAP_TLV_PAC_TLV 11 /* RFC 5422, Section 4.2 */ -#define EAP_TLV_CRYPTO_BINDING_TLV 12 -#define EAP_TLV_CALLING_STATION_ID_TLV 13 -#define EAP_TLV_CALLED_STATION_ID_TLV 14 -#define EAP_TLV_NAS_PORT_TYPE_TLV 15 -#define EAP_TLV_SERVER_IDENTIFIER_TLV 16 -#define EAP_TLV_IDENTITY_TYPE_TLV 17 -#define EAP_TLV_SERVER_TRUSTED_ROOT_TLV 18 -#define EAP_TLV_REQUEST_ACTION_TLV 19 -#define EAP_TLV_PKCS7_TLV 20 - -#define EAP_TLV_RESULT_SUCCESS 1 -#define EAP_TLV_RESULT_FAILURE 2 - -#define EAP_TLV_TYPE_MANDATORY 0x8000 -#define EAP_TLV_TYPE_MASK 0x3fff - -#ifdef _MSC_VER -#pragma pack(push, 1) -#endif /* _MSC_VER */ - -struct eap_tlv_hdr { - be16 tlv_type; - be16 length; -} STRUCT_PACKED; - -struct eap_tlv_nak_tlv { - be16 tlv_type; - be16 length; - be32 vendor_id; - be16 nak_type; -} STRUCT_PACKED; - -struct eap_tlv_result_tlv { - be16 tlv_type; - be16 length; - be16 status; -} STRUCT_PACKED; - -/* RFC 4851, Section 4.2.7 - Intermediate-Result TLV */ -struct eap_tlv_intermediate_result_tlv { - be16 tlv_type; - be16 length; - be16 status; - /* Followed by optional TLVs */ -} STRUCT_PACKED; - -/* RFC 4851, Section 4.2.8 - Crypto-Binding TLV */ -struct eap_tlv_crypto_binding_tlv { - be16 tlv_type; - be16 length; - u8 reserved; - u8 version; - u8 received_version; - u8 subtype; - u8 nonce[32]; - u8 compound_mac[20]; -} STRUCT_PACKED; - -struct eap_tlv_pac_ack_tlv { - be16 tlv_type; - be16 length; - be16 pac_type; - be16 pac_len; - be16 result; -} STRUCT_PACKED; - -/* RFC 4851, Section 4.2.9 - Request-Action TLV */ -struct eap_tlv_request_action_tlv { - be16 tlv_type; - be16 length; - be16 action; -} STRUCT_PACKED; - -/* RFC 5422, Section 4.2.6 - PAC-Type TLV */ -struct eap_tlv_pac_type_tlv { - be16 tlv_type; /* PAC_TYPE_PAC_TYPE */ - be16 length; - be16 pac_type; -} STRUCT_PACKED; - -#ifdef _MSC_VER -#pragma pack(pop) -#endif /* _MSC_VER */ - -#define EAP_TLV_CRYPTO_BINDING_SUBTYPE_REQUEST 0 -#define EAP_TLV_CRYPTO_BINDING_SUBTYPE_RESPONSE 1 - -#define EAP_TLV_ACTION_PROCESS_TLV 1 -#define EAP_TLV_ACTION_NEGOTIATE_EAP 2 - -#endif /* EAP_TLV_COMMON_H */ +/* + * EAP-TLV definitions (draft-josefsson-pppext-eap-tls-eap-10.txt) + * Copyright (c) 2004-2008, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef EAP_TLV_COMMON_H +#define EAP_TLV_COMMON_H + +/* EAP-TLV TLVs (draft-josefsson-ppext-eap-tls-eap-10.txt) */ +#define EAP_TLV_RESULT_TLV 3 /* Acknowledged Result */ +#define EAP_TLV_NAK_TLV 4 +#define EAP_TLV_ERROR_CODE_TLV 5 +#define EAP_TLV_CONNECTION_BINDING_TLV 6 +#define EAP_TLV_VENDOR_SPECIFIC_TLV 7 +#define EAP_TLV_URI_TLV 8 +#define EAP_TLV_EAP_PAYLOAD_TLV 9 +#define EAP_TLV_INTERMEDIATE_RESULT_TLV 10 +#define EAP_TLV_PAC_TLV 11 /* RFC 5422, Section 4.2 */ +#define EAP_TLV_CRYPTO_BINDING_TLV 12 +#define EAP_TLV_CALLING_STATION_ID_TLV 13 +#define EAP_TLV_CALLED_STATION_ID_TLV 14 +#define EAP_TLV_NAS_PORT_TYPE_TLV 15 +#define EAP_TLV_SERVER_IDENTIFIER_TLV 16 +#define EAP_TLV_IDENTITY_TYPE_TLV 17 +#define EAP_TLV_SERVER_TRUSTED_ROOT_TLV 18 +#define EAP_TLV_REQUEST_ACTION_TLV 19 +#define EAP_TLV_PKCS7_TLV 20 + +#define EAP_TLV_RESULT_SUCCESS 1 +#define EAP_TLV_RESULT_FAILURE 2 + +#define EAP_TLV_TYPE_MANDATORY 0x8000 +#define EAP_TLV_TYPE_MASK 0x3fff + +#ifdef _MSC_VER +#pragma pack(push, 1) +#endif /* _MSC_VER */ + +struct eap_tlv_hdr { + be16 tlv_type; + be16 length; +} STRUCT_PACKED; + +struct eap_tlv_nak_tlv { + be16 tlv_type; + be16 length; + be32 vendor_id; + be16 nak_type; +} STRUCT_PACKED; + +struct eap_tlv_result_tlv { + be16 tlv_type; + be16 length; + be16 status; +} STRUCT_PACKED; + +/* RFC 4851, Section 4.2.7 - Intermediate-Result TLV */ +struct eap_tlv_intermediate_result_tlv { + be16 tlv_type; + be16 length; + be16 status; + /* Followed by optional TLVs */ +} STRUCT_PACKED; + +/* RFC 4851, Section 4.2.8 - Crypto-Binding TLV */ +struct eap_tlv_crypto_binding_tlv { + be16 tlv_type; + be16 length; + u8 reserved; + u8 version; + u8 received_version; + u8 subtype; + u8 nonce[32]; + u8 compound_mac[20]; +} STRUCT_PACKED; + +struct eap_tlv_pac_ack_tlv { + be16 tlv_type; + be16 length; + be16 pac_type; + be16 pac_len; + be16 result; +} STRUCT_PACKED; + +/* RFC 4851, Section 4.2.9 - Request-Action TLV */ +struct eap_tlv_request_action_tlv { + be16 tlv_type; + be16 length; + be16 action; +} STRUCT_PACKED; + +/* RFC 5422, Section 4.2.6 - PAC-Type TLV */ +struct eap_tlv_pac_type_tlv { + be16 tlv_type; /* PAC_TYPE_PAC_TYPE */ + be16 length; + be16 pac_type; +} STRUCT_PACKED; + +#ifdef _MSC_VER +#pragma pack(pop) +#endif /* _MSC_VER */ + +#define EAP_TLV_CRYPTO_BINDING_SUBTYPE_REQUEST 0 +#define EAP_TLV_CRYPTO_BINDING_SUBTYPE_RESPONSE 1 + +#define EAP_TLV_ACTION_PROCESS_TLV 1 +#define EAP_TLV_ACTION_NEGOTIATE_EAP 2 + +#endif /* EAP_TLV_COMMON_H */ diff --git a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_ttls.h b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_ttls.h index 568038d0..17901d42 100644 --- a/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_ttls.h +++ b/tools/sdk/include/wpa_supplicant/wpa2/eap_peer/eap_ttls.h @@ -1,65 +1,65 @@ -/* - * EAP server/peer: EAP-TTLS (RFC 5281) - * Copyright (c) 2004-2007, Jouni Malinen - * - * This software may be distributed under the terms of the BSD license. - * See README for more details. - */ - -#ifndef EAP_TTLS_H -#define EAP_TTLS_H - -struct ttls_avp { - be32 avp_code; - be32 avp_length; /* 8-bit flags, 24-bit length; - * length includes AVP header */ - /* optional 32-bit Vendor-ID */ - /* Data */ -}; - -struct ttls_avp_vendor { - be32 avp_code; - be32 avp_length; /* 8-bit flags, 24-bit length; - * length includes AVP header */ - be32 vendor_id; - /* Data */ -}; - -#define AVP_FLAGS_VENDOR 0x80 -#define AVP_FLAGS_MANDATORY 0x40 - -#define AVP_PAD(start, pos) \ -do { \ - int __pad; \ - __pad = (4 - (((pos) - (start)) & 3)) & 3; \ - os_memset((pos), 0, __pad); \ - pos += __pad; \ -} while (0) - - -/* RFC 2865 */ -#define RADIUS_ATTR_USER_NAME 1 -#define RADIUS_ATTR_USER_PASSWORD 2 -#define RADIUS_ATTR_CHAP_PASSWORD 3 -#define RADIUS_ATTR_REPLY_MESSAGE 18 -#define RADIUS_ATTR_CHAP_CHALLENGE 60 -#define RADIUS_ATTR_EAP_MESSAGE 79 - -/* RFC 2548 */ -#define RADIUS_VENDOR_ID_MICROSOFT 311 -#define RADIUS_ATTR_MS_CHAP_RESPONSE 1 -#define RADIUS_ATTR_MS_CHAP_ERROR 2 -#define RADIUS_ATTR_MS_CHAP_NT_ENC_PW 6 -#define RADIUS_ATTR_MS_CHAP_CHALLENGE 11 -#define RADIUS_ATTR_MS_CHAP2_RESPONSE 25 -#define RADIUS_ATTR_MS_CHAP2_SUCCESS 26 -#define RADIUS_ATTR_MS_CHAP2_CPW 27 - -#define EAP_TTLS_MSCHAPV2_CHALLENGE_LEN 16 -#define EAP_TTLS_MSCHAPV2_RESPONSE_LEN 50 -#define EAP_TTLS_MSCHAP_CHALLENGE_LEN 8 -#define EAP_TTLS_MSCHAP_RESPONSE_LEN 50 -#define EAP_TTLS_CHAP_CHALLENGE_LEN 16 -#define EAP_TTLS_CHAP_PASSWORD_LEN 16 - -#endif /* EAP_TTLS_H */ +/* + * EAP server/peer: EAP-TTLS (RFC 5281) + * Copyright (c) 2004-2007, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#ifndef EAP_TTLS_H +#define EAP_TTLS_H + +struct ttls_avp { + be32 avp_code; + be32 avp_length; /* 8-bit flags, 24-bit length; + * length includes AVP header */ + /* optional 32-bit Vendor-ID */ + /* Data */ +}; + +struct ttls_avp_vendor { + be32 avp_code; + be32 avp_length; /* 8-bit flags, 24-bit length; + * length includes AVP header */ + be32 vendor_id; + /* Data */ +}; + +#define AVP_FLAGS_VENDOR 0x80 +#define AVP_FLAGS_MANDATORY 0x40 + +#define AVP_PAD(start, pos) \ +do { \ + int __pad; \ + __pad = (4 - (((pos) - (start)) & 3)) & 3; \ + os_memset((pos), 0, __pad); \ + pos += __pad; \ +} while (0) + + +/* RFC 2865 */ +#define RADIUS_ATTR_USER_NAME 1 +#define RADIUS_ATTR_USER_PASSWORD 2 +#define RADIUS_ATTR_CHAP_PASSWORD 3 +#define RADIUS_ATTR_REPLY_MESSAGE 18 +#define RADIUS_ATTR_CHAP_CHALLENGE 60 +#define RADIUS_ATTR_EAP_MESSAGE 79 + +/* RFC 2548 */ +#define RADIUS_VENDOR_ID_MICROSOFT 311 +#define RADIUS_ATTR_MS_CHAP_RESPONSE 1 +#define RADIUS_ATTR_MS_CHAP_ERROR 2 +#define RADIUS_ATTR_MS_CHAP_NT_ENC_PW 6 +#define RADIUS_ATTR_MS_CHAP_CHALLENGE 11 +#define RADIUS_ATTR_MS_CHAP2_RESPONSE 25 +#define RADIUS_ATTR_MS_CHAP2_SUCCESS 26 +#define RADIUS_ATTR_MS_CHAP2_CPW 27 + +#define EAP_TTLS_MSCHAPV2_CHALLENGE_LEN 16 +#define EAP_TTLS_MSCHAPV2_RESPONSE_LEN 50 +#define EAP_TTLS_MSCHAP_CHALLENGE_LEN 8 +#define EAP_TTLS_MSCHAP_RESPONSE_LEN 50 +#define EAP_TTLS_CHAP_CHALLENGE_LEN 16 +#define EAP_TTLS_CHAP_PASSWORD_LEN 16 + +#endif /* EAP_TTLS_H */ diff --git a/tools/sdk/ld/esp32.common.ld b/tools/sdk/ld/esp32.common.ld index 26acd7b2..cf1a3a7a 100644 --- a/tools/sdk/ld/esp32.common.ld +++ b/tools/sdk/ld/esp32.common.ld @@ -10,7 +10,7 @@ SECTIONS { . = ALIGN(4); *(.rtc.literal .rtc.text) - *rtc_wake_stub*.o(.literal .text .literal.* .text.*) + *rtc_wake_stub*.*(.literal .text .literal.* .text.*) } > rtc_iram_seg /* RTC slow memory holds RTC wake stub @@ -22,7 +22,7 @@ SECTIONS _rtc_data_start = ABSOLUTE(.); *(.rtc.data) *(.rtc.rodata) - *rtc_wake_stub*.o(.data .rodata .data.* .rodata.* .bss .bss.*) + *rtc_wake_stub*.*(.data .rodata .data.* .rodata.* .bss .bss.*) _rtc_data_end = ABSOLUTE(.); } > rtc_slow_seg @@ -30,8 +30,9 @@ SECTIONS .rtc.bss (NOLOAD) : { _rtc_bss_start = ABSOLUTE(.); - *rtc_wake_stub*.o(.bss .bss.*) - *rtc_wake_stub*.o(COMMON) + *rtc_wake_stub*.*(.bss .bss.*) + *rtc_wake_stub*.*(COMMON) + *(.rtc.bss) _rtc_bss_end = ABSOLUTE(.); } > rtc_slow_seg @@ -52,6 +53,7 @@ SECTIONS /* Send .iram0 code to iram */ .iram0.vectors : { + _iram_start = ABSOLUTE(.); /* Vectors go to IRAM */ _init_start = ABSOLUTE(.); /* Vectors according to builds/RF-2015.2-win32/esp108_v1_2_s5_512int_2/config.html */ @@ -85,11 +87,7 @@ SECTIONS *(.init.literal) *(.init) _init_end = ABSOLUTE(.); - - /* This goes here, not at top of linker script, so addr2line finds it last, - and uses it in preference to the first symbol in IRAM */ - _iram_start = ABSOLUTE(0); - } > iram0_0_seg +} > iram0_0_seg .iram0.text : { @@ -97,25 +95,35 @@ SECTIONS _iram_text_start = ABSOLUTE(.); *(.iram1 .iram1.*) *libfreertos.a:(.literal .text .literal.* .text.*) - *libheap.a:multi_heap.o(.literal .text .literal.* .text.*) - *libheap.a:multi_heap_poisoning.o(.literal .text .literal.* .text.*) - *libesp32.a:panic.o(.literal .text .literal.* .text.*) - *libesp32.a:core_dump.o(.literal .text .literal.* .text.*) + *libheap.a:multi_heap.*(.literal .text .literal.* .text.*) + *libheap.a:multi_heap_poisoning.*(.literal .text .literal.* .text.*) + *libesp32.a:panic.*(.literal .text .literal.* .text.*) + *libesp32.a:core_dump.*(.literal .text .literal.* .text.*) *libapp_trace.a:(.literal .text .literal.* .text.*) - *libxtensa-debug-module.a:eri.o(.literal .text .literal.* .text.*) + *libxtensa-debug-module.a:eri.*(.literal .text .literal.* .text.*) *librtc.a:(.literal .text .literal.* .text.*) - *libsoc.a:(.literal .text .literal.* .text.*) + *libsoc.a:rtc_*.*(.literal .text .literal.* .text.*) + *libsoc.a:cpu_util.*(.literal .text .literal.* .text.*) *libhal.a:(.literal .text .literal.* .text.*) - *libgcc.a:lib2funcs.o(.literal .text .literal.* .text.*) - *libspi_flash.a:spi_flash_rom_patch.o(.literal .text .literal.* .text.*) + *libgcc.a:lib2funcs.*(.literal .text .literal.* .text.*) + *libspi_flash.a:spi_flash_rom_patch.*(.literal .text .literal.* .text.*) *libgcov.a:(.literal .text .literal.* .text.*) INCLUDE esp32.spiram.rom-functions-iram.ld _iram_text_end = ABSOLUTE(.); + _iram_end = ABSOLUTE(.); } > iram0_0_seg - + .dram0.data : { _data_start = ABSOLUTE(.); + _bt_data_start = ABSOLUTE(.); + *libbt.a:(.data .data.*) + . = ALIGN (4); + _bt_data_end = ABSOLUTE(.); + _btdm_data_start = ABSOLUTE(.); + *libbtdm_app.a:(.data .data.*) + . = ALIGN (4); + _btdm_data_end = ABSOLUTE(.); *(.data) *(.data.*) *(.gnu.linkonce.d.*) @@ -128,13 +136,13 @@ SECTIONS *(.gnu.linkonce.s2.*) *(.jcr) *(.dram1 .dram1.*) - *libesp32.a:panic.o(.rodata .rodata.*) + *libesp32.a:panic.*(.rodata .rodata.*) *libphy.a:(.rodata .rodata.*) - *libsoc.a:rtc_clk.o(.rodata .rodata.*) + *libsoc.a:rtc_clk.*(.rodata .rodata.*) *libapp_trace.a:(.rodata .rodata.*) *libgcov.a:(.rodata .rodata.*) - *libheap.a:multi_heap.o(.rodata .rodata.*) - *libheap.a:multi_heap_poisoning.o(.rodata .rodata.*) + *libheap.a:multi_heap.*(.rodata .rodata.*) + *libheap.a:multi_heap_poisoning.*(.rodata .rodata.*) INCLUDE esp32.spiram.rom-functions-dram.ld _data_end = ABSOLUTE(.); . = ALIGN(4); @@ -159,6 +167,14 @@ SECTIONS { . = ALIGN (8); _bss_start = ABSOLUTE(.); + _bt_bss_start = ABSOLUTE(.); + *libbt.a:(.bss .bss.* COMMON) + . = ALIGN (4); + _bt_bss_end = ABSOLUTE(.); + _btdm_bss_start = ABSOLUTE(.); + *libbtdm_app.a:(.bss .bss.* COMMON) + . = ALIGN (4); + _btdm_bss_end = ABSOLUTE(.); *(.dynsbss) *(.sbss) *(.sbss.*) @@ -198,13 +214,13 @@ SECTIONS . = (. + 7) & ~ 3; /* C++ constructor and destructor tables, properly ordered: */ __init_array_start = ABSOLUTE(.); - KEEP (*crtbegin.o(.ctors)) - KEEP (*(EXCLUDE_FILE (*crtend.o) .ctors)) + KEEP (*crtbegin.*(.ctors)) + KEEP (*(EXCLUDE_FILE (*crtend.*) .ctors)) KEEP (*(SORT(.ctors.*))) KEEP (*(.ctors)) __init_array_end = ABSOLUTE(.); - KEEP (*crtbegin.o(.dtors)) - KEEP (*(EXCLUDE_FILE (*crtend.o) .dtors)) + KEEP (*crtbegin.*(.dtors)) + KEEP (*(EXCLUDE_FILE (*crtend.*) .dtors)) KEEP (*(SORT(.dtors.*))) KEEP (*(.dtors)) /* C++ exception handlers table: */ @@ -215,6 +231,11 @@ SECTIONS *(.xt_except_desc_end) *(.dynamic) *(.gnu.version_d) + /* Addresses of memory regions reserved via + SOC_RESERVE_MEMORY_REGION() */ + soc_reserved_memory_region_start = ABSOLUTE(.); + KEEP (*(.reserved_memory_address)) + soc_reserved_memory_region_end = ABSOLUTE(.); _rodata_end = ABSOLUTE(.); /* Literals are also RO data. */ _lit4_start = ABSOLUTE(.); diff --git a/tools/sdk/ld/esp32.peripherals.ld b/tools/sdk/ld/esp32.peripherals.ld index 3403ee8a..2dce0e0f 100644 --- a/tools/sdk/ld/esp32.peripherals.ld +++ b/tools/sdk/ld/esp32.peripherals.ld @@ -26,6 +26,7 @@ PROVIDE ( SPI3 = 0x3ff65000 ); PROVIDE ( SYSCON = 0x3ff66000 ); PROVIDE ( I2C1 = 0x3ff67000 ); PROVIDE ( SDMMC = 0x3ff68000 ); +PROVIDE ( CAN = 0x3ff6B000 ); PROVIDE ( MCPWM1 = 0x3ff6C000 ); PROVIDE ( I2S1 = 0x3ff6D000 ); PROVIDE ( UART2 = 0x3ff6E000 ); diff --git a/tools/sdk/ld/esp32.rom.ld b/tools/sdk/ld/esp32.rom.ld index ab36d7bb..fe5a4e7c 100644 --- a/tools/sdk/ld/esp32.rom.ld +++ b/tools/sdk/ld/esp32.rom.ld @@ -4,32 +4,22 @@ Generated for ROM with MD5sum: ab8282ae908fe9e7a63fb2a4ac2df013 ../../rom_image/prorom.elf */ PROVIDE ( abort = 0x4000bba4 ); -PROVIDE ( __absvdi2 = 0x4006387c ); -PROVIDE ( __absvsi2 = 0x40063868 ); PROVIDE ( Add2SelfBigHex256 = 0x40015b7c ); PROVIDE ( AddBigHex256 = 0x40015b28 ); PROVIDE ( AddBigHexModP256 = 0x40015c98 ); -PROVIDE ( __adddf3 = 0x40002590 ); PROVIDE ( AddP256 = 0x40015c74 ); PROVIDE ( AddPdiv2_256 = 0x40015ce0 ); -PROVIDE ( __addsf3 = 0x400020e8 ); -PROVIDE ( __addvdi3 = 0x40002cbc ); -PROVIDE ( __addvsi3 = 0x40002c98 ); PROVIDE ( aes_128_cbc_decrypt = 0x4005cc7c ); PROVIDE ( aes_128_cbc_encrypt = 0x4005cc18 ); PROVIDE ( aes_unwrap = 0x4005ccf0 ); PROVIDE ( app_gpio_arg = 0x3ffe003c ); PROVIDE ( app_gpio_handler = 0x3ffe0040 ); -PROVIDE ( __ashldi3 = 0x4000c818 ); -PROVIDE ( __ashrdi3 = 0x4000c830 ); PROVIDE ( base64_decode = 0x4005ced8 ); PROVIDE ( base64_encode = 0x4005cdbc ); PROVIDE ( BasePoint_x_256 = 0x3ff97488 ); PROVIDE ( BasePoint_y_256 = 0x3ff97468 ); PROVIDE ( bigHexInversion256 = 0x400168f0 ); PROVIDE ( bigHexP256 = 0x3ff973bc ); -PROVIDE ( __bswapdi2 = 0x400649c4 ); -PROVIDE ( __bswapsi2 = 0x4006499c ); PROVIDE ( btdm_r_ble_bt_handler_tab_p_get = 0x40019b0c ); PROVIDE ( btdm_r_btdm_option_data_p_get = 0x40010004 ); PROVIDE ( btdm_r_btdm_rom_version_get = 0x40010078 ); @@ -52,11 +42,6 @@ PROVIDE ( calc_rtc_memory_crc = 0x40008170 ); PROVIDE ( calloc = 0x4000bee4 ); PROVIDE ( __clear_cache = 0x40063860 ); PROVIDE ( _close_r = 0x4000bd3c ); -PROVIDE ( __clrsbdi2 = 0x40064a38 ); -PROVIDE ( __clrsbsi2 = 0x40064a20 ); -PROVIDE ( __clzdi2 = 0x4000ca50 ); -PROVIDE ( __clzsi2 = 0x4000c7e8 ); -PROVIDE ( __cmpdi2 = 0x40063820 ); PROVIDE ( co_default_bdaddr = 0x3ffae704 ); PROVIDE ( co_null_bdaddr = 0x3ffb80e0 ); PROVIDE ( co_sca2ppm = 0x3ff971e8 ); @@ -68,8 +53,6 @@ PROVIDE ( crc8_be = 0x4005d114 ); PROVIDE ( crc8_le = 0x4005d0e0 ); PROVIDE ( _ctype_ = 0x3ff96354 ); PROVIDE ( __ctype_ptr__ = 0x3ff96350 ); -PROVIDE ( __ctzdi2 = 0x4000ca64 ); -PROVIDE ( __ctzsi2 = 0x4000c7f0 ); PROVIDE ( _data_end_rom = 0x4000d5c8 ); PROVIDE ( _data_end_btdm_rom = 0x4000d4f8 ); PROVIDE ( _data_start_rom = 0x4000d4f8 ); @@ -102,49 +85,21 @@ PROVIDE ( dh_group2_generator = 0x3ff9ada2 ); PROVIDE ( dh_group2_prime = 0x3ff9ad22 ); PROVIDE ( dh_group5_generator = 0x3ff9ad21 ); PROVIDE ( dh_group5_prime = 0x3ff9ac61 ); -PROVIDE ( __divdc3 = 0x40064460 ); -PROVIDE ( __divdf3 = 0x40002954 ); -PROVIDE ( __divdi3 = 0x4000ca84 ); -PROVIDE ( __divsc3 = 0x40064200 ); -PROVIDE ( __divsf3 = 0x4000234c ); -PROVIDE ( __divsi3 = 0x4000c7b8 ); PROVIDE ( g_rom_spiflash_dummy_len_plus = 0x3ffae290 ); PROVIDE ( ecc_env = 0x3ffb8d60 ); PROVIDE ( ecc_Jacobian_InfinityPoint256 = 0x3ff972e8 ); PROVIDE ( em_buf_env = 0x3ffb8d74 ); PROVIDE ( environ = 0x3ffae0b4 ); -PROVIDE ( __eqdf2 = 0x400636a8 ); -PROVIDE ( __eqsf2 = 0x40063374 ); PROVIDE ( esp_crc8 = 0x4005d144 ); PROVIDE ( _etext = 0x4000d66c ); PROVIDE ( ets_readySet_ = 0x3ffe01f0 ); PROVIDE ( ets_startup_callback = 0x3ffe0404 ); PROVIDE ( exc_cause_table = 0x3ff991d0 ); PROVIDE ( _exit_r = 0x4000bd28 ); -PROVIDE ( __extendsfdf2 = 0x40002c34 ); -PROVIDE ( __ffsdi2 = 0x4000ca2c ); -PROVIDE ( __ffssi2 = 0x4000c804 ); -PROVIDE ( __fixdfdi = 0x40002ac4 ); -PROVIDE ( __fixdfsi = 0x40002a78 ); -PROVIDE ( __fixsfdi = 0x4000244c ); -PROVIDE ( __fixsfsi = 0x4000240c ); -PROVIDE ( __fixunsdfsi = 0x40002b30 ); -PROVIDE ( __fixunssfdi = 0x40002504 ); -PROVIDE ( __fixunssfsi = 0x400024ac ); -PROVIDE ( __floatdidf = 0x4000c988 ); -PROVIDE ( __floatdisf = 0x4000c8c0 ); -PROVIDE ( __floatsidf = 0x4000c944 ); -PROVIDE ( __floatsisf = 0x4000c870 ); -PROVIDE ( __floatundidf = 0x4000c978 ); -PROVIDE ( __floatundisf = 0x4000c8b0 ); -PROVIDE ( __floatunsidf = 0x4000c938 ); -PROVIDE ( __floatunsisf = 0x4000c864 ); PROVIDE ( free = 0x4000beb8 ); PROVIDE ( _free_r = 0x4000bbcc ); PROVIDE ( _fstat_r = 0x4000bccc ); PROVIDE ( __gcc_bcmp = 0x40064a70 ); -PROVIDE ( __gedf2 = 0x40063768 ); -PROVIDE ( __gesf2 = 0x4006340c ); PROVIDE ( _getpid_r = 0x4000bcfc ); PROVIDE ( __getreent = 0x4000be8c ); PROVIDE ( _gettimeofday_r = 0x4000bc58 ); @@ -154,8 +109,6 @@ PROVIDE ( GF_Point_Jacobian_To_Affine256 = 0x40016b0c ); PROVIDE ( _global_impure_ptr = 0x3ffae0b0 ); PROVIDE ( g_phyFuns_instance = 0x3ffae0c4 ); PROVIDE ( g_rom_flashchip = 0x3ffae270 ); -PROVIDE ( __gtdf2 = 0x400636dc ); -PROVIDE ( __gtsf2 = 0x400633a0 ); PROVIDE ( gTxMsg = 0x3ffe0050 ); PROVIDE ( hci_cmd_desc_root_tab = 0x3ff976d4 ); PROVIDE ( hci_cmd_desc_tab_ctrl_bb = 0x3ff97b70 ); @@ -201,8 +154,6 @@ PROVIDE ( ld_env = 0x3ffb9510 ); PROVIDE ( ld_pcm_settings_dft = 0x3ff98a0c ); PROVIDE ( ld_sched_params = 0x3ffb96c0 ); PROVIDE ( ld_sync_train_channels = 0x3ff98a3c ); -PROVIDE ( __ledf2 = 0x40063704 ); -PROVIDE ( __lesf2 = 0x400633c0 ); PROVIDE ( _link_r = 0x4000bc9c ); PROVIDE ( llc_default_handler = 0x3ff98b3c ); PROVIDE ( llc_default_state_tab_p_get = 0x40046058 ); @@ -225,6 +176,7 @@ PROVIDE ( lld_evt_elt_wait_get = 0x400468e4 ); PROVIDE ( lld_evt_get_next_free_slot = 0x4004692c ); PROVIDE ( lld_pdu_adv_pk_desc_tab = 0x3ff98c70 ); PROVIDE ( lld_pdu_llcp_pk_desc_tab = 0x3ff98b68 ); +PROVIDE ( lld_pdu_tx_flush_list = 0x4004a760 ); PROVIDE ( lld_pdu_pack = 0x4004ab14 ); PROVIDE ( LLM_AA_CT1 = 0x3ff98d8a ); PROVIDE ( LLM_AA_CT2 = 0x3ff98d88 ); @@ -255,9 +207,6 @@ PROVIDE ( _lock_release_recursive = 0x4000be78 ); PROVIDE ( _lock_try_acquire = 0x4000be3c ); PROVIDE ( _lock_try_acquire_recursive = 0x4000be50 ); PROVIDE ( _lseek_r = 0x4000bd8c ); -PROVIDE ( __lshrdi3 = 0x4000c84c ); -PROVIDE ( __ltdf2 = 0x40063790 ); -PROVIDE ( __ltsf2 = 0x4006342c ); PROVIDE ( malloc = 0x4000bea0 ); PROVIDE ( _malloc_r = 0x4000bbb4 ); PROVIDE ( maxSecretKey_256 = 0x3ff97448 ); @@ -267,43 +216,19 @@ PROVIDE ( MD5Init = 0x4005da7c ); PROVIDE ( MD5Update = 0x4005da9c ); PROVIDE ( md5_vector = 0x4005db80 ); PROVIDE ( mmu_init = 0x400095a4 ); -PROVIDE ( __moddi3 = 0x4000cd4c ); -PROVIDE ( __modsi3 = 0x4000c7c0 ); PROVIDE ( __month_lengths = 0x3ff9609c ); -PROVIDE ( __muldc3 = 0x40063bf4 ); -PROVIDE ( __muldf3 = 0x4006358c ); -PROVIDE ( __muldi3 = 0x4000c9fc ); -PROVIDE ( __mulsc3 = 0x40063934 ); -PROVIDE ( __mulsf3 = 0x400632c8 ); -PROVIDE ( __mulsi3 = 0x4000c7b0 ); PROVIDE ( MultiplyBigHexByUint32_256 = 0x40016214 ); PROVIDE ( MultiplyBigHexModP256 = 0x400160b8 ); PROVIDE ( MultiplyByU32ModP256 = 0x40015fdc ); PROVIDE ( multofup = 0x4000ab8c ); -PROVIDE ( __mulvdi3 = 0x40002d78 ); -PROVIDE ( __mulvsi3 = 0x40002d60 ); PROVIDE ( mz_adler32 = 0x4005edbc ); PROVIDE ( mz_crc32 = 0x4005ee88 ); PROVIDE ( mz_free = 0x4005eed4 ); -PROVIDE ( __nedf2 = 0x400636a8 ); -PROVIDE ( __negdf2 = 0x400634a0 ); -PROVIDE ( __negdi2 = 0x4000ca14 ); -PROVIDE ( __negsf2 = 0x400020c0 ); -PROVIDE ( __negvdi2 = 0x40002e98 ); -PROVIDE ( __negvsi2 = 0x40002e78 ); -PROVIDE ( __nesf2 = 0x40063374 ); PROVIDE ( notEqual256 = 0x40015b04 ); -PROVIDE ( __nsau_data = 0x3ff96544 ); PROVIDE ( one_bits = 0x3ff971f8 ); PROVIDE ( _open_r = 0x4000bd54 ); -PROVIDE ( __paritysi2 = 0x40002f3c ); PROVIDE ( pbkdf2_sha1 = 0x40060ba4 ); PROVIDE ( phy_get_romfuncs = 0x40004100 ); -PROVIDE ( __popcountdi2 = 0x40002ef8 ); -PROVIDE ( __popcountsi2 = 0x40002ed0 ); -PROVIDE ( __popcount_tab = 0x3ff96544 ); -PROVIDE ( __powidf2 = 0x400638d4 ); -PROVIDE ( __powisf2 = 0x4006389c ); PROVIDE ( _Pri_4_HandlerAddress = 0x3ffe0648 ); PROVIDE ( _Pri_5_HandlerAddress = 0x3ffe064c ); PROVIDE ( r_btdm_option_data = 0x3ffae6e0 ); @@ -347,6 +272,9 @@ PROVIDE ( r_E1 = 0x400108e8 ); PROVIDE ( r_E21 = 0x40010968 ); PROVIDE ( r_E22 = 0x400109b4 ); PROVIDE ( r_E3 = 0x40010a58 ); +PROVIDE ( lm_n192_mod_mul = 0x40011dc0 ); +PROVIDE ( lm_n192_mod_add = 0x40011e9c ); +PROVIDE ( lm_n192_mod_sub = 0x40011eec ); PROVIDE ( r_ea_alarm_clear = 0x40015ab4 ); PROVIDE ( r_ea_alarm_set = 0x40015a10 ); PROVIDE ( _read_r = 0x4000bda8 ); @@ -376,6 +304,7 @@ PROVIDE ( r_ecc_gen_new_public_key = 0x400170c0 ); PROVIDE ( r_ecc_gen_new_secret_key = 0x400170e4 ); PROVIDE ( r_ecc_get_debug_Keys = 0x40017224 ); PROVIDE ( r_ecc_init = 0x40016dbc ); +PROVIDE ( ecc_point_multiplication_uint8_256 = 0x40016804); PROVIDE ( RecvBuff = 0x3ffe009c ); PROVIDE ( r_em_buf_init = 0x4001729c ); PROVIDE ( r_em_buf_rx_buff_addr_get = 0x400173e8 ); @@ -674,6 +603,14 @@ PROVIDE ( r_lc_util_get_offset_clke = 0x4002f538 ); PROVIDE ( r_lc_util_get_offset_clkn = 0x4002f51c ); PROVIDE ( r_lc_util_set_loc_trans_coll = 0x4002f500 ); PROVIDE ( r_lc_version = 0x40020a30 ); +PROVIDE ( lc_set_encap_pdu_data_p192 = 0x4002e4c8 ); +PROVIDE ( lc_set_encap_pdu_data_p256 = 0x4002e454 ); +PROVIDE ( lm_get_auth_method = 0x40023420); +PROVIDE ( lmp_accepted_ext_handler = 0x40027290 ); +PROVIDE ( lmp_not_accepted_ext_handler = 0x40029c54 ); +PROVIDE ( lmp_clk_adj_handler = 0x40027468 ); +PROVIDE ( lmp_clk_adj_ack_handler = 0x400274f4 ); +PROVIDE ( lm_get_auth_method = 0x40023420); PROVIDE ( lmp_accepted_ext_handler = 0x40027290 ); PROVIDE ( lmp_not_accepted_ext_handler = 0x40029c54 ); PROVIDE ( lmp_clk_adj_handler = 0x40027468 ); @@ -761,7 +698,14 @@ PROVIDE ( lmp_io_cap_req_handler = 0x4002c7a4 ); PROVIDE ( ld_acl_tx_packet_type_select = 0x4002fb40 ); PROVIDE ( ld_acl_sched = 0x40033268 ); PROVIDE ( ld_acl_sniff_sched = 0x4003340c ); +PROVIDE ( ld_acl_rx = 0x4003274c ); +PROVIDE ( ld_acl_tx = 0x4002ffdc ); +PROVIDE ( ld_acl_rx_sync = 0x4002fbec ); +PROVIDE ( ld_acl_rx_sync2 = 0x4002fd8c ); +PROVIDE ( ld_acl_rx_no_sync = 0x4002fe78 ); +PROVIDE ( ld_sco_modify = 0x40031778 ); PROVIDE ( lm_cmd_cmp_send = 0x40051838 ); +PROVIDE ( ld_sco_frm_cbk = 0x400349dc ); PROVIDE ( r_ld_acl_active_hop_types_get = 0x40036e10 ); PROVIDE ( r_ld_acl_afh_confirm = 0x40036d40 ); PROVIDE ( r_ld_acl_afh_prepare = 0x40036c84 ); @@ -1417,15 +1361,11 @@ PROVIDE ( _start = 0x40000704 ); PROVIDE ( start_tb_console = 0x4005a980 ); PROVIDE ( _stat_r = 0x4000bcb4 ); PROVIDE ( _stext = 0x40000560 ); -PROVIDE ( __subdf3 = 0x400026e4 ); -PROVIDE ( __subsf3 = 0x400021d0 ); PROVIDE ( SubtractBigHex256 = 0x40015bcc ); PROVIDE ( SubtractBigHexMod256 = 0x40015e8c ); PROVIDE ( SubtractBigHexUint32_256 = 0x40015f8c ); PROVIDE ( SubtractFromSelfBigHex256 = 0x40015c20 ); PROVIDE ( SubtractFromSelfBigHexSign256 = 0x40015dc8 ); -PROVIDE ( __subvdi3 = 0x40002d20 ); -PROVIDE ( __subvsi3 = 0x40002cf8 ); PROVIDE ( sw_to_hw = 0x3ffb8d40 ); PROVIDE ( syscall_table_ptr_app = 0x3ffae020 ); PROVIDE ( syscall_table_ptr_pro = 0x3ffae024 ); @@ -1443,20 +1383,9 @@ PROVIDE ( _timezone = 0x3ffae0a0 ); PROVIDE ( tinfl_decompress = 0x4005ef30 ); PROVIDE ( tinfl_decompress_mem_to_callback = 0x40060090 ); PROVIDE ( tinfl_decompress_mem_to_mem = 0x40060050 ); -PROVIDE ( __truncdfsf2 = 0x40002b90 ); PROVIDE ( _tzname = 0x3ffae030 ); PROVIDE ( UartDev = 0x3ffe019c ); -PROVIDE ( __ucmpdi2 = 0x40063840 ); -PROVIDE ( __udivdi3 = 0x4000cff8 ); -PROVIDE ( __udivmoddi4 = 0x40064ab0 ); -PROVIDE ( __udivsi3 = 0x4000c7c8 ); -PROVIDE ( __udiv_w_sdiv = 0x40064aa8 ); -PROVIDE ( __umoddi3 = 0x4000d280 ); -PROVIDE ( __umodsi3 = 0x4000c7d0 ); -PROVIDE ( __umulsidi3 = 0x4000c7d8 ); PROVIDE ( _unlink_r = 0x4000bc84 ); -PROVIDE ( __unorddf2 = 0x400637f4 ); -PROVIDE ( __unordsf2 = 0x40063478 ); PROVIDE ( user_code_start = 0x3ffe0400 ); PROVIDE ( veryBigHexP256 = 0x3ff9736c ); PROVIDE ( __wctomb = 0x3ff96540 ); @@ -1704,6 +1633,7 @@ PROVIDE ( hci_tl_env = 0x3ffb8154 ); PROVIDE ( ld_acl_env = 0x3ffb8258 ); PROVIDE ( ea_env = 0x3ffb80ec ); PROVIDE ( lc_sco_data_path_config = 0x3ffb81f8 ); +PROVIDE ( lc_sco_env = 0x3ffb81fc ); PROVIDE ( ld_active_ch_map = 0x3ffb8334 ); PROVIDE ( ld_bcst_acl_env = 0x3ffb8274 ); PROVIDE ( ld_csb_rx_env = 0x3ffb8278 ); diff --git a/tools/sdk/ld/esp32.rom.libgcc.ld b/tools/sdk/ld/esp32.rom.libgcc.ld new file mode 100644 index 00000000..51448b33 --- /dev/null +++ b/tools/sdk/ld/esp32.rom.libgcc.ld @@ -0,0 +1,91 @@ +__absvdi2 = 0x4006387c; +__absvsi2 = 0x40063868; +__adddf3 = 0x40002590; +__addsf3 = 0x400020e8; +__addvdi3 = 0x40002cbc; +__addvsi3 = 0x40002c98; +__ashldi3 = 0x4000c818; +__ashrdi3 = 0x4000c830; +__bswapdi2 = 0x40064b08; +__bswapsi2 = 0x40064ae0; +__clrsbdi2 = 0x40064b7c; +__clrsbsi2 = 0x40064b64; +__clzdi2 = 0x4000ca50; +__clzsi2 = 0x4000c7e8; +__cmpdi2 = 0x40063820; +__ctzdi2 = 0x4000ca64; +__ctzsi2 = 0x4000c7f0; +__divdc3 = 0x400645a4; +__divdf3 = 0x40002954; +__divdi3 = 0x4000ca84; +__divsc3 = 0x4006429c; +__divsf3 = 0x4000234c; +__divsi3 = 0x4000c7b8; +__eqdf2 = 0x400636a8; +__eqsf2 = 0x40063374; +__extendsfdf2 = 0x40002c34; +__ffsdi2 = 0x4000ca2c; +__ffssi2 = 0x4000c804; +__fixdfdi = 0x40002ac4; +__fixdfsi = 0x40002a78; +__fixsfdi = 0x4000244c; +__fixsfsi = 0x4000240c; +__fixunsdfsi = 0x40002b30; +__fixunssfdi = 0x40002504; +__fixunssfsi = 0x400024ac; +__floatdidf = 0x4000c988; +__floatdisf = 0x4000c8c0; +__floatsidf = 0x4000c944; +__floatsisf = 0x4000c870; +__floatundidf = 0x4000c978; +__floatundisf = 0x4000c8b0; +__floatunsidf = 0x4000c938; +__floatunsisf = 0x4000c864; +__gedf2 = 0x40063768; +__gesf2 = 0x4006340c; +__gtdf2 = 0x400636dc; +__gtsf2 = 0x400633a0; +__ledf2 = 0x40063704; +__lesf2 = 0x400633c0; +__lshrdi3 = 0x4000c84c; +__ltdf2 = 0x40063790; +__ltsf2 = 0x4006342c; +__moddi3 = 0x4000cd4c; +__modsi3 = 0x4000c7c0; +__muldc3 = 0x40063c90; +__muldf3 = 0x4006358c; +__muldi3 = 0x4000c9fc; +__mulsc3 = 0x40063944; +__mulsf3 = 0x400632c8; +__mulsi3 = 0x4000c7b0; +__mulvdi3 = 0x40002d78; +__mulvsi3 = 0x40002d60; +__nedf2 = 0x400636a8; +__negdf2 = 0x400634a0; +__negdi2 = 0x4000ca14; +__negsf2 = 0x400020c0; +__negvdi2 = 0x40002e98; +__negvsi2 = 0x40002e78; +__nesf2 = 0x40063374; +__nsau_data = 0x3ff96544; +__paritysi2 = 0x40002f3c; +__popcount_tab = 0x3ff96544; +__popcountdi2 = 0x40002ef8; +__popcountsi2 = 0x40002ed0; +__powidf2 = 0x400638e4; +__powisf2 = 0x4006389c; +__subdf3 = 0x400026e4; +__subsf3 = 0x400021d0; +__subvdi3 = 0x40002d20; +__subvsi3 = 0x40002cf8; +__truncdfsf2 = 0x40002b90; +__ucmpdi2 = 0x40063840; +__udiv_w_sdiv = 0x40064bec; +__udivdi3 = 0x4000cff8; +__udivmoddi4 = 0x40064bf4; +__udivsi3 = 0x4000c7c8; +__umoddi3 = 0x4000d280; +__umodsi3 = 0x4000c7d0; +__umulsidi3 = 0x4000c7d8; +__unorddf2 = 0x400637f4; +__unordsf2 = 0x40063478; diff --git a/tools/sdk/ld/esp32_out.ld b/tools/sdk/ld/esp32_out.ld index f82b39fc..fef78d56 100644 --- a/tools/sdk/ld/esp32_out.ld +++ b/tools/sdk/ld/esp32_out.ld @@ -45,8 +45,8 @@ MEMORY in heap at runtime. However due to static ROM memory usage at this 176KB mark, the additional static memory temporarily cannot be used. */ - dram0_0_seg (RW) : org = 0x3FFB0000 + 0x10000, - len = 0x2c200 - 0x10000 + dram0_0_seg (RW) : org = 0x3FFB0000 + 0xdb5c, + len = 0x2c200 - 0xdb5c /* Flash mapped constant data */ drom0_0_seg (R) : org = 0x3F400018, len = 0x400000-0x18 /* (See iram0_2_seg for meaning of 0x18 offset in the above.) */ diff --git a/tools/sdk/lib/libapp_trace.a b/tools/sdk/lib/libapp_trace.a index 074cebc3..53aa0850 100644 Binary files a/tools/sdk/lib/libapp_trace.a and b/tools/sdk/lib/libapp_trace.a differ diff --git a/tools/sdk/lib/libapp_update.a b/tools/sdk/lib/libapp_update.a index 3ba13ff6..9b9a638d 100644 Binary files a/tools/sdk/lib/libapp_update.a and b/tools/sdk/lib/libapp_update.a differ diff --git a/tools/sdk/lib/libasio.a b/tools/sdk/lib/libasio.a new file mode 100644 index 00000000..e8503e86 Binary files /dev/null and b/tools/sdk/lib/libasio.a differ diff --git a/tools/sdk/lib/libbootloader_support.a b/tools/sdk/lib/libbootloader_support.a index 02e9db89..a6a1c24c 100644 Binary files a/tools/sdk/lib/libbootloader_support.a and b/tools/sdk/lib/libbootloader_support.a differ diff --git a/tools/sdk/lib/libbt.a b/tools/sdk/lib/libbt.a index fb0bd9bb..9155a3dd 100644 Binary files a/tools/sdk/lib/libbt.a and b/tools/sdk/lib/libbt.a differ diff --git a/tools/sdk/lib/libbtdm_app.a b/tools/sdk/lib/libbtdm_app.a index d592c28f..1d740072 100755 Binary files a/tools/sdk/lib/libbtdm_app.a and b/tools/sdk/lib/libbtdm_app.a differ diff --git a/tools/sdk/lib/libcoap.a b/tools/sdk/lib/libcoap.a index 9aaa9797..73394186 100644 Binary files a/tools/sdk/lib/libcoap.a and b/tools/sdk/lib/libcoap.a differ diff --git a/tools/sdk/lib/libcoexist.a b/tools/sdk/lib/libcoexist.a index 9aef5d3a..f9b3070b 100644 Binary files a/tools/sdk/lib/libcoexist.a and b/tools/sdk/lib/libcoexist.a differ diff --git a/tools/sdk/lib/libconsole.a b/tools/sdk/lib/libconsole.a index 8ca4b9af..fa550763 100644 Binary files a/tools/sdk/lib/libconsole.a and b/tools/sdk/lib/libconsole.a differ diff --git a/tools/sdk/lib/libcore.a b/tools/sdk/lib/libcore.a index dae77dc6..77f94aa2 100644 Binary files a/tools/sdk/lib/libcore.a and b/tools/sdk/lib/libcore.a differ diff --git a/tools/sdk/lib/libcxx.a b/tools/sdk/lib/libcxx.a index 6629744a..37275dcc 100644 Binary files a/tools/sdk/lib/libcxx.a and b/tools/sdk/lib/libcxx.a differ diff --git a/tools/sdk/lib/libdriver.a b/tools/sdk/lib/libdriver.a index 86f6a01d..a3769e44 100644 Binary files a/tools/sdk/lib/libdriver.a and b/tools/sdk/lib/libdriver.a differ diff --git a/tools/sdk/lib/libesp-tls.a b/tools/sdk/lib/libesp-tls.a index 13c797ee..614c313c 100644 Binary files a/tools/sdk/lib/libesp-tls.a and b/tools/sdk/lib/libesp-tls.a differ diff --git a/tools/sdk/lib/libesp32.a b/tools/sdk/lib/libesp32.a index 2d5c6f8e..44ca0237 100644 Binary files a/tools/sdk/lib/libesp32.a and b/tools/sdk/lib/libesp32.a differ diff --git a/tools/sdk/lib/libesp_adc_cal.a b/tools/sdk/lib/libesp_adc_cal.a index ac98c9b7..2166bd8a 100644 Binary files a/tools/sdk/lib/libesp_adc_cal.a and b/tools/sdk/lib/libesp_adc_cal.a differ diff --git a/tools/sdk/lib/libesp_http_client.a b/tools/sdk/lib/libesp_http_client.a index aea9595a..898fe3da 100644 Binary files a/tools/sdk/lib/libesp_http_client.a and b/tools/sdk/lib/libesp_http_client.a differ diff --git a/tools/sdk/lib/libesp_https_ota.a b/tools/sdk/lib/libesp_https_ota.a new file mode 100644 index 00000000..ab4afea0 Binary files /dev/null and b/tools/sdk/lib/libesp_https_ota.a differ diff --git a/tools/sdk/lib/libesp_ringbuf.a b/tools/sdk/lib/libesp_ringbuf.a new file mode 100644 index 00000000..8cc6d55a Binary files /dev/null and b/tools/sdk/lib/libesp_ringbuf.a differ diff --git a/tools/sdk/lib/libespnow.a b/tools/sdk/lib/libespnow.a index dd878a9a..a112eba7 100644 Binary files a/tools/sdk/lib/libespnow.a and b/tools/sdk/lib/libespnow.a differ diff --git a/tools/sdk/lib/libethernet.a b/tools/sdk/lib/libethernet.a index 66154564..0a7f785f 100644 Binary files a/tools/sdk/lib/libethernet.a and b/tools/sdk/lib/libethernet.a differ diff --git a/tools/sdk/lib/libexpat.a b/tools/sdk/lib/libexpat.a index f8499e6f..d29fdb47 100644 Binary files a/tools/sdk/lib/libexpat.a and b/tools/sdk/lib/libexpat.a differ diff --git a/tools/sdk/lib/libfatfs.a b/tools/sdk/lib/libfatfs.a index 4afc355a..3b888b9e 100644 Binary files a/tools/sdk/lib/libfatfs.a and b/tools/sdk/lib/libfatfs.a differ diff --git a/tools/sdk/lib/libfreertos.a b/tools/sdk/lib/libfreertos.a index 240dc35d..730e5105 100644 Binary files a/tools/sdk/lib/libfreertos.a and b/tools/sdk/lib/libfreertos.a differ diff --git a/tools/sdk/lib/libheap.a b/tools/sdk/lib/libheap.a index 4f578b30..d9c42bef 100644 Binary files a/tools/sdk/lib/libheap.a and b/tools/sdk/lib/libheap.a differ diff --git a/tools/sdk/lib/libhttp_server.a b/tools/sdk/lib/libhttp_server.a new file mode 100644 index 00000000..a4ace21e Binary files /dev/null and b/tools/sdk/lib/libhttp_server.a differ diff --git a/tools/sdk/lib/libjsmn.a b/tools/sdk/lib/libjsmn.a index d06035a3..745761d1 100644 Binary files a/tools/sdk/lib/libjsmn.a and b/tools/sdk/lib/libjsmn.a differ diff --git a/tools/sdk/lib/libjson.a b/tools/sdk/lib/libjson.a index 4c14dabf..f0665f40 100644 Binary files a/tools/sdk/lib/libjson.a and b/tools/sdk/lib/libjson.a differ diff --git a/tools/sdk/lib/liblog.a b/tools/sdk/lib/liblog.a index d5c08eac..26501c40 100644 Binary files a/tools/sdk/lib/liblog.a and b/tools/sdk/lib/liblog.a differ diff --git a/tools/sdk/lib/liblwip.a b/tools/sdk/lib/liblwip.a index 7dafe5bc..84b01280 100644 Binary files a/tools/sdk/lib/liblwip.a and b/tools/sdk/lib/liblwip.a differ diff --git a/tools/sdk/lib/libmbedtls.a b/tools/sdk/lib/libmbedtls.a index c267bd86..652fd64b 100644 Binary files a/tools/sdk/lib/libmbedtls.a and b/tools/sdk/lib/libmbedtls.a differ diff --git a/tools/sdk/lib/libmdns.a b/tools/sdk/lib/libmdns.a index 9e3ee4e0..6c5e8f24 100644 Binary files a/tools/sdk/lib/libmdns.a and b/tools/sdk/lib/libmdns.a differ diff --git a/tools/sdk/lib/libmesh.a b/tools/sdk/lib/libmesh.a index fa95e25e..8515da90 100644 Binary files a/tools/sdk/lib/libmesh.a and b/tools/sdk/lib/libmesh.a differ diff --git a/tools/sdk/lib/libmicro-ecc.a b/tools/sdk/lib/libmicro-ecc.a index b9347c37..73658578 100644 Binary files a/tools/sdk/lib/libmicro-ecc.a and b/tools/sdk/lib/libmicro-ecc.a differ diff --git a/tools/sdk/lib/libmqtt.a b/tools/sdk/lib/libmqtt.a new file mode 100644 index 00000000..2218e74a Binary files /dev/null and b/tools/sdk/lib/libmqtt.a differ diff --git a/tools/sdk/lib/libnet80211.a b/tools/sdk/lib/libnet80211.a index eb23156b..286011fb 100644 Binary files a/tools/sdk/lib/libnet80211.a and b/tools/sdk/lib/libnet80211.a differ diff --git a/tools/sdk/lib/libnewlib.a b/tools/sdk/lib/libnewlib.a index 4107a24d..93bd3f0e 100644 Binary files a/tools/sdk/lib/libnewlib.a and b/tools/sdk/lib/libnewlib.a differ diff --git a/tools/sdk/lib/libnghttp.a b/tools/sdk/lib/libnghttp.a index bea3c1c8..21aac7e9 100644 Binary files a/tools/sdk/lib/libnghttp.a and b/tools/sdk/lib/libnghttp.a differ diff --git a/tools/sdk/lib/libnvs_flash.a b/tools/sdk/lib/libnvs_flash.a index b0310160..7e688fcc 100644 Binary files a/tools/sdk/lib/libnvs_flash.a and b/tools/sdk/lib/libnvs_flash.a differ diff --git a/tools/sdk/lib/libopenssl.a b/tools/sdk/lib/libopenssl.a index 4e3c710e..60566b57 100644 Binary files a/tools/sdk/lib/libopenssl.a and b/tools/sdk/lib/libopenssl.a differ diff --git a/tools/sdk/lib/libphy.a b/tools/sdk/lib/libphy.a old mode 100755 new mode 100644 index b6b9c938..86014fe3 Binary files a/tools/sdk/lib/libphy.a and b/tools/sdk/lib/libphy.a differ diff --git a/tools/sdk/lib/libpp.a b/tools/sdk/lib/libpp.a index 8f778cf0..87db8a1b 100644 Binary files a/tools/sdk/lib/libpp.a and b/tools/sdk/lib/libpp.a differ diff --git a/tools/sdk/lib/libpthread.a b/tools/sdk/lib/libpthread.a index 6d2a789c..74f35cca 100644 Binary files a/tools/sdk/lib/libpthread.a and b/tools/sdk/lib/libpthread.a differ diff --git a/tools/sdk/lib/librtc.a b/tools/sdk/lib/librtc.a index 71c6c90f..dac81d53 100644 Binary files a/tools/sdk/lib/librtc.a and b/tools/sdk/lib/librtc.a differ diff --git a/tools/sdk/lib/libsdmmc.a b/tools/sdk/lib/libsdmmc.a index a92344fd..0604f90f 100644 Binary files a/tools/sdk/lib/libsdmmc.a and b/tools/sdk/lib/libsdmmc.a differ diff --git a/tools/sdk/lib/libsmartconfig.a b/tools/sdk/lib/libsmartconfig.a index 24a5efe0..50429d9f 100644 Binary files a/tools/sdk/lib/libsmartconfig.a and b/tools/sdk/lib/libsmartconfig.a differ diff --git a/tools/sdk/lib/libsmartconfig_ack.a b/tools/sdk/lib/libsmartconfig_ack.a index 270b2294..4298b0f2 100644 Binary files a/tools/sdk/lib/libsmartconfig_ack.a and b/tools/sdk/lib/libsmartconfig_ack.a differ diff --git a/tools/sdk/lib/libsoc.a b/tools/sdk/lib/libsoc.a index 8a76a7f5..7df3ab87 100644 Binary files a/tools/sdk/lib/libsoc.a and b/tools/sdk/lib/libsoc.a differ diff --git a/tools/sdk/lib/libspi_flash.a b/tools/sdk/lib/libspi_flash.a index 9421c65a..aaa69374 100644 Binary files a/tools/sdk/lib/libspi_flash.a and b/tools/sdk/lib/libspi_flash.a differ diff --git a/tools/sdk/lib/libspiffs.a b/tools/sdk/lib/libspiffs.a index 459c36cc..1fd8d283 100644 Binary files a/tools/sdk/lib/libspiffs.a and b/tools/sdk/lib/libspiffs.a differ diff --git a/tools/sdk/lib/libtcp_transport.a b/tools/sdk/lib/libtcp_transport.a new file mode 100644 index 00000000..f96c6fdb Binary files /dev/null and b/tools/sdk/lib/libtcp_transport.a differ diff --git a/tools/sdk/lib/libtcpip_adapter.a b/tools/sdk/lib/libtcpip_adapter.a index 6d48dfbf..87577629 100644 Binary files a/tools/sdk/lib/libtcpip_adapter.a and b/tools/sdk/lib/libtcpip_adapter.a differ diff --git a/tools/sdk/lib/libulp.a b/tools/sdk/lib/libulp.a index bfd4a790..80cceb4c 100644 Binary files a/tools/sdk/lib/libulp.a and b/tools/sdk/lib/libulp.a differ diff --git a/tools/sdk/lib/libvfs.a b/tools/sdk/lib/libvfs.a index b3b1fd09..64a64181 100644 Binary files a/tools/sdk/lib/libvfs.a and b/tools/sdk/lib/libvfs.a differ diff --git a/tools/sdk/lib/libwear_levelling.a b/tools/sdk/lib/libwear_levelling.a index 550a55b5..e6f93531 100644 Binary files a/tools/sdk/lib/libwear_levelling.a and b/tools/sdk/lib/libwear_levelling.a differ diff --git a/tools/sdk/lib/libwpa.a b/tools/sdk/lib/libwpa.a index 026e2b80..37b743c8 100644 Binary files a/tools/sdk/lib/libwpa.a and b/tools/sdk/lib/libwpa.a differ diff --git a/tools/sdk/lib/libwpa2.a b/tools/sdk/lib/libwpa2.a index f3690707..40714a17 100644 Binary files a/tools/sdk/lib/libwpa2.a and b/tools/sdk/lib/libwpa2.a differ diff --git a/tools/sdk/lib/libwpa_supplicant.a b/tools/sdk/lib/libwpa_supplicant.a index 607ffe29..a90b8429 100644 Binary files a/tools/sdk/lib/libwpa_supplicant.a and b/tools/sdk/lib/libwpa_supplicant.a differ diff --git a/tools/sdk/lib/libwps.a b/tools/sdk/lib/libwps.a index f22c0e3c..2801af92 100644 Binary files a/tools/sdk/lib/libwps.a and b/tools/sdk/lib/libwps.a differ diff --git a/tools/sdk/lib/libxtensa-debug-module.a b/tools/sdk/lib/libxtensa-debug-module.a index 669238f6..1c20cf52 100644 Binary files a/tools/sdk/lib/libxtensa-debug-module.a and b/tools/sdk/lib/libxtensa-debug-module.a differ diff --git a/tools/sdk/sdkconfig b/tools/sdk/sdkconfig index ff5b2f02..24d75d54 100644 --- a/tools/sdk/sdkconfig +++ b/tools/sdk/sdkconfig @@ -35,6 +35,7 @@ CONFIG_ARDUHAL_PARTITION_SCHEME_NO_OTA= CONFIG_ARDUHAL_PARTITION_SCHEME_MIN_SPIFFS= CONFIG_ARDUHAL_PARTITION_SCHEME="default" CONFIG_AUTOCONNECT_WIFI= +CONFIG_ARDUINO_SELECTIVE_COMPILATION= # # Bootloader config @@ -50,10 +51,14 @@ CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_8V= CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V=y CONFIG_BOOTLOADER_FACTORY_RESET= CONFIG_BOOTLOADER_APP_TEST= +CONFIG_BOOTLOADER_WDT_ENABLE=y +CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE= +CONFIG_BOOTLOADER_WDT_TIME_MS=9000 # # Security features # +CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT= CONFIG_SECURE_BOOT_ENABLED= CONFIG_FLASH_ENCRYPTION_ENABLED= @@ -147,6 +152,19 @@ CONFIG_AWS_IOT_SDK= # Bluetooth # CONFIG_BT_ENABLED=y + +# +# Bluetooth controller +# +CONFIG_BTDM_CONTROLLER_MODE_BLE_ONLY= +CONFIG_BTDM_CONTROLLER_MODE_BR_EDR_ONLY= +CONFIG_BTDM_CONTROLLER_MODE_BTDM=y +CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN=3 +CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN=2 +CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN=0 +CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN_EFF=3 +CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_ACL_CONN_EFF=2 +CONFIG_BTDM_CONTROLLER_BR_EDR_MAX_SYNC_CONN_EFF=0 CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE_0=y CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE_1= CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE=0 @@ -160,6 +178,13 @@ CONFIG_BTDM_CONTROLLER_MODEM_SLEEP=y CONFIG_BTDM_MODEM_SLEEP_MODE_ORIG=y CONFIG_BTDM_MODEM_SLEEP_MODE_EVED= CONFIG_BTDM_LPCLK_SEL_MAIN_XTAL=y +CONFIG_BLE_SCAN_DUPLICATE=y +CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR=y +CONFIG_SCAN_DUPLICATE_BY_ADV_DATA= +CONFIG_SCAN_DUPLICATE_BY_ADV_DATA_AND_DEVICE_ADDR= +CONFIG_SCAN_DUPLICATE_TYPE=0 +CONFIG_DUPLICATE_SCAN_CACHE_SIZE=20 +CONFIG_BLE_MESH_SCAN_DUPLICATE_EN= CONFIG_BLUEDROID_ENABLED=y CONFIG_BLUEDROID_PINNED_TO_CORE_0=y CONFIG_BLUEDROID_PINNED_TO_CORE_1= @@ -183,11 +208,9 @@ CONFIG_BT_STACK_NO_LOG=y CONFIG_BT_ACL_CONNECTIONS=4 CONFIG_BT_ALLOCATION_FROM_SPIRAM_FIRST=y CONFIG_BT_BLE_DYNAMIC_ENV_MEMORY=y -CONFIG_BLE_SCAN_DUPLICATE=y -CONFIG_DUPLICATE_SCAN_CACHE_SIZE=20 -CONFIG_BLE_MESH_SCAN_DUPLICATE_EN= +CONFIG_BLE_HOST_QUEUE_CONGESTION_CHECK= CONFIG_SMP_ENABLE=y -CONFIG_BT_RESERVE_DRAM=0x10000 +CONFIG_BT_RESERVE_DRAM=0xdb5c # # Driver configurations @@ -200,10 +223,12 @@ CONFIG_ADC_FORCE_XPD_FSM= CONFIG_ADC2_DISABLE_DAC=y # -# SPI master configuration +# SPI configuration # CONFIG_SPI_MASTER_IN_IRAM= CONFIG_SPI_MASTER_ISR_IN_IRAM=y +CONFIG_SPI_SLAVE_IN_IRAM= +CONFIG_SPI_SLAVE_ISR_IN_IRAM=y # # ESP32-specific @@ -280,12 +305,15 @@ CONFIG_BROWNOUT_DET_LVL_SEL_5= CONFIG_BROWNOUT_DET_LVL_SEL_6= CONFIG_BROWNOUT_DET_LVL_SEL_7= CONFIG_BROWNOUT_DET_LVL=0 +CONFIG_REDUCE_PHY_TX_POWER=y CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1=y CONFIG_ESP32_TIME_SYSCALL_USE_RTC= CONFIG_ESP32_TIME_SYSCALL_USE_FRC1= CONFIG_ESP32_TIME_SYSCALL_USE_NONE= CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_RC=y CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_CRYSTAL= +CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_OSC= +CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_8MD256= CONFIG_ESP32_RTC_CLK_CAL_CYCLES=1024 CONFIG_ESP32_DEEP_SLEEP_WAKEUP_DELAY=2000 CONFIG_ESP32_XTAL_FREQ_40= @@ -351,7 +379,9 @@ CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y CONFIG_DMA_RX_BUF_NUM=10 CONFIG_DMA_TX_BUF_NUM=10 CONFIG_EMAC_L2_TO_L3_RX_BUF_MODE=y +CONFIG_EMAC_CHECK_LINK_PERIOD_MS=2000 CONFIG_EMAC_TASK_PRIORITY=20 +CONFIG_EMAC_TASK_STACK_SIZE=3072 # # FAT Filesystem support @@ -419,6 +449,7 @@ CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0 CONFIG_FREERTOS_USE_TRACE_FACILITY= CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS= CONFIG_FREERTOS_DEBUG_INTERNALS= +CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER=y # # Heap memory debugging @@ -429,6 +460,12 @@ CONFIG_HEAP_POISONING_COMPREHENSIVE= CONFIG_HEAP_TRACING= CONFIG_HEAP_TASK_TRACKING= +# +# HTTP Server +# +CONFIG_HTTPD_MAX_REQ_HDR_LEN=512 +CONFIG_HTTPD_MAX_URI_LEN=512 + # # libsodium # @@ -461,8 +498,11 @@ CONFIG_LWIP_IP_FRAG= CONFIG_LWIP_IP_REASSEMBLY= CONFIG_LWIP_STATS= CONFIG_LWIP_ETHARP_TRUST_IP_MAC=y +CONFIG_ESP_GRATUITOUS_ARP=y +CONFIG_GARP_TMR_INTERVAL=60 CONFIG_TCPIP_RECVMBOX_SIZE=32 CONFIG_LWIP_DHCP_DOES_ARP_CHECK= +CONFIG_LWIP_DHCP_RESTORE_LAST_IP=y # # DHCP server @@ -518,6 +558,7 @@ CONFIG_LWIP_MAX_RAW_PCBS=16 # # mbedTLS # +CONFIG_MBEDTLS_PLATFORM_MEMORY= CONFIG_MBEDTLS_SSL_MAX_CONTENT_LEN=16384 CONFIG_MBEDTLS_DEBUG= CONFIG_MBEDTLS_HARDWARE_AES=y @@ -597,6 +638,17 @@ CONFIG_MBEDTLS_ECP_NIST_OPTIM=y # CONFIG_MDNS_MAX_SERVICES=10 +# +# ESP-MQTT Configurations +# +CONFIG_MQTT_PROTOCOL_311=y +CONFIG_MQTT_TRANSPORT_SSL=y +CONFIG_MQTT_TRANSPORT_WEBSOCKET=y +CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y +CONFIG_MQTT_USE_CUSTOM_CONFIG= +CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED= +CONFIG_MQTT_CUSTOM_OUTBOX= + # # OpenSSL # @@ -652,14 +704,16 @@ CONFIG_SPIFFS_CHECK_DBG= CONFIG_SPIFFS_TEST_VISUALISATION= # -# tcpip adapter +# TCP/IP Adapter # CONFIG_IP_LOST_TIMER_INTERVAL=120 +CONFIG_TCPIP_LWIP=y # # Virtual file system # CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT=y +CONFIG_SUPPORT_TERMIOS=y # # Wear Levelling