feature/esp_http_client: Added the esp_http_client component from idf.

Added the component and the example from IDF.
This commit is contained in:
Supreet Deshpande
2019-02-13 14:55:43 +05:30
parent cd9a7899bf
commit ee32bd51a1
22 changed files with 3015 additions and 0 deletions

@ -0,0 +1,11 @@
set(COMPONENT_SRCS "esp_http_client.c"
"lib/http_auth.c"
"lib/http_header.c"
"lib/http_utils.c")
set(COMPONENT_ADD_INCLUDEDIRS "include")
set(COMPONENT_PRIV_INCLUDEDIRS "lib/include")
set(COMPONENT_REQUIRES "nghttp")
set(COMPONENT_PRIV_REQUIRES "mbedtls" "lwip" "esp-tls" "tcp_transport")
register_component()

@ -0,0 +1,10 @@
menu "ESP HTTP client"
config ESP_HTTP_CLIENT_ENABLE_HTTPS
bool "Enable https"
default y
help
This option will enable https protocol by linking mbedtls library and initializing SSL transport
endmenu

@ -0,0 +1,6 @@
#
# Component Makefile
#
COMPONENT_SRCDIRS := . lib
COMPONENT_PRIV_INCLUDEDIRS := lib/include

File diff suppressed because it is too large Load Diff

@ -0,0 +1,382 @@
// 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 _ESP_HTTP_CLIENT_H
#define _ESP_HTTP_CLIENT_H
#include "freertos/FreeRTOS.h"
#include "http_parser.h"
#include "sdkconfig.h"
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
#define DEFAULT_HTTP_BUF_SIZE (512)
typedef struct esp_http_client *esp_http_client_handle_t;
typedef struct esp_http_client_event *esp_http_client_event_handle_t;
/**
* @brief HTTP Client events id
*/
typedef enum {
HTTP_EVENT_ERROR = 0, /*!< This event occurs when there are any errors during execution */
HTTP_EVENT_ON_CONNECTED, /*!< Once the HTTP has been connected to the server, no data exchange has been performed */
HTTP_EVENT_HEADER_SENT, /*!< After sending all the headers to the server */
HTTP_EVENT_ON_HEADER, /*!< Occurs when receiving each header sent from the server */
HTTP_EVENT_ON_DATA, /*!< Occurs when receiving data from the server, possibly multiple portions of the packet */
HTTP_EVENT_ON_FINISH, /*!< Occurs when finish a HTTP session */
HTTP_EVENT_DISCONNECTED, /*!< The connection has been disconnected */
} esp_http_client_event_id_t;
/**
* @brief HTTP Client events data
*/
typedef struct esp_http_client_event {
esp_http_client_event_id_t event_id; /*!< event_id, to know the cause of the event */
esp_http_client_handle_t client; /*!< esp_http_client_handle_t context */
void *data; /*!< data of the event */
int data_len; /*!< data length of data */
void *user_data; /*!< user_data context, from esp_http_client_config_t user_data */
char *header_key; /*!< For HTTP_EVENT_ON_HEADER event_id, it's store current http header key */
char *header_value; /*!< For HTTP_EVENT_ON_HEADER event_id, it's store current http header value */
} esp_http_client_event_t;
/**
* @brief HTTP Client transport
*/
typedef enum {
HTTP_TRANSPORT_UNKNOWN = 0x0, /*!< Unknown */
HTTP_TRANSPORT_OVER_TCP, /*!< Transport over tcp */
HTTP_TRANSPORT_OVER_SSL, /*!< Transport over ssl */
} esp_http_client_transport_t;
typedef esp_err_t (*http_event_handle_cb)(esp_http_client_event_t *evt);
/**
* @brief HTTP method
*/
typedef enum {
HTTP_METHOD_GET = 0, /*!< HTTP GET Method */
HTTP_METHOD_POST, /*!< HTTP POST Method */
HTTP_METHOD_PUT, /*!< HTTP PUT Method */
HTTP_METHOD_PATCH, /*!< HTTP PATCH Method */
HTTP_METHOD_DELETE, /*!< HTTP DELETE Method */
HTTP_METHOD_HEAD, /*!< HTTP HEAD Method */
HTTP_METHOD_NOTIFY, /*!< HTTP NOTIFY Method */
HTTP_METHOD_SUBSCRIBE, /*!< HTTP SUBSCRIBE Method */
HTTP_METHOD_UNSUBSCRIBE,/*!< HTTP UNSUBSCRIBE Method */
HTTP_METHOD_OPTIONS, /*!< HTTP OPTIONS Method */
HTTP_METHOD_MAX,
} esp_http_client_method_t;
/**
* @brief HTTP Authentication type
*/
typedef enum {
HTTP_AUTH_TYPE_NONE = 0, /*!< No authention */
HTTP_AUTH_TYPE_BASIC, /*!< HTTP Basic authentication */
HTTP_AUTH_TYPE_DIGEST, /*!< HTTP Disgest authentication */
} esp_http_client_auth_type_t;
/**
* @brief HTTP configuration
*/
typedef struct {
const char *url; /*!< HTTP URL, the information on the URL is most important, it overrides the other fields below, if any */
const char *host; /*!< Domain or IP as string */
int port; /*!< Port to connect, default depend on esp_http_client_transport_t (80 or 443) */
const char *username; /*!< Using for Http authentication */
const char *password; /*!< Using for Http authentication */
esp_http_client_auth_type_t auth_type; /*!< Http authentication type, see `esp_http_client_auth_type_t` */
const char *path; /*!< HTTP Path, if not set, default is `/` */
const char *query; /*!< HTTP query */
const char *cert_pem; /*!< SSL Certification, PEM format as string, if the client requires to verify server */
esp_http_client_method_t method; /*!< HTTP Method */
int timeout_ms; /*!< Network timeout in milliseconds */
bool disable_auto_redirect; /*!< Disable HTTP automatic redirects */
int max_redirection_count; /*!< Max redirection number, using default value if zero*/
http_event_handle_cb event_handler; /*!< HTTP Event Handle */
esp_http_client_transport_t transport_type; /*!< HTTP transport type, see `esp_http_client_transport_t` */
int buffer_size; /*!< HTTP buffer size (both send and receive) */
void *user_data; /*!< HTTP user_data context */
bool is_async; /*!< Set asynchronous mode, only supported with HTTPS for now */
} esp_http_client_config_t;
#define ESP_ERR_HTTP_BASE (0x7000) /*!< Starting number of HTTP error codes */
#define ESP_ERR_HTTP_MAX_REDIRECT (ESP_ERR_HTTP_BASE + 1) /*!< The error exceeds the number of HTTP redirects */
#define ESP_ERR_HTTP_CONNECT (ESP_ERR_HTTP_BASE + 2) /*!< Error open the HTTP connection */
#define ESP_ERR_HTTP_WRITE_DATA (ESP_ERR_HTTP_BASE + 3) /*!< Error write HTTP data */
#define ESP_ERR_HTTP_FETCH_HEADER (ESP_ERR_HTTP_BASE + 4) /*!< Error read HTTP header from server */
#define ESP_ERR_HTTP_INVALID_TRANSPORT (ESP_ERR_HTTP_BASE + 5) /*!< There are no transport support for the input scheme */
#define ESP_ERR_HTTP_CONNECTING (ESP_ERR_HTTP_BASE + 6) /*!< HTTP connection hasn't been established yet */
#define ESP_ERR_HTTP_EAGAIN (ESP_ERR_HTTP_BASE + 7) /*!< Mapping of errno EAGAIN to esp_err_t */
/**
* @brief Start a HTTP session
* This function must be the first function to call,
* and it returns a esp_http_client_handle_t that you must use as input to other functions in the interface.
* This call MUST have a corresponding call to esp_http_client_cleanup when the operation is complete.
*
* @param[in] config The configurations, see `http_client_config_t`
*
* @return
* - `esp_http_client_handle_t`
* - NULL if any errors
*/
esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config);
/**
* @brief Invoke this function after `esp_http_client_init` and all the options calls are made, and will perform the
* transfer as described in the options. It must be called with the same esp_http_client_handle_t as input as the esp_http_client_init call returned.
* esp_http_client_perform performs the entire request in either blocking or non-blocking manner. By default, the API performs request in a blocking manner and returns when done,
* or if it failed, and in non-blocking manner, it returns if EAGAIN/EWOULDBLOCK or EINPROGRESS is encountered, or if it failed. And in case of non-blocking request,
* the user may call this API multiple times unless request & response is complete or there is a failure. To enable non-blocking esp_http_client_perform(), `is_async` member of esp_http_client_config_t
* must be set while making a call to esp_http_client_init() API.
* You can do any amount of calls to esp_http_client_perform while using the same esp_http_client_handle_t. The underlying connection may be kept open if the server allows it.
* If you intend to transfer more than one file, you are even encouraged to do so.
* esp_http_client will then attempt to re-use the same connection for the following transfers, thus making the operations faster, less CPU intense and using less network resources.
* Just note that you will have to use `esp_http_client_set_**` between the invokes to set options for the following esp_http_client_perform.
*
* @note You must never call this function simultaneously from two places using the same client handle.
* Let the function return first before invoking it another time.
* If you want parallel transfers, you must use several esp_http_client_handle_t.
* This function include `esp_http_client_open` -> `esp_http_client_write` -> `esp_http_client_fetch_headers` -> `esp_http_client_read` (and option) `esp_http_client_close`.
*
* @param client The esp_http_client handle
*
* @return
* - ESP_OK on successful
* - ESP_FAIL on error
*/
esp_err_t esp_http_client_perform(esp_http_client_handle_t client);
/**
* @brief Set URL for client, when performing this behavior, the options in the URL will replace the old ones
*
* @param[in] client The esp_http_client handle
* @param[in] url The url
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url);
/**
* @brief Set post data, this function must be called before `esp_http_client_perform`.
* Note: The data parameter passed to this function is a pointer and this function will not copy the data
*
* @param[in] client The esp_http_client handle
* @param[in] data post data pointer
* @param[in] len post length
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int len);
/**
* @brief Get current post field information
*
* @param[in] client The client
* @param[out] data Point to post data pointer
*
* @return Size of post data
*/
int esp_http_client_get_post_field(esp_http_client_handle_t client, char **data);
/**
* @brief Set http request header, this function must be called after esp_http_client_init and before any
* perform function
*
* @param[in] client The esp_http_client handle
* @param[in] key The header key
* @param[in] value The header value
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char *value);
/**
* @brief Get http request header.
* The value parameter will be set to NULL if there is no header which is same as
* the key specified, otherwise the address of header value will be assigned to value parameter.
* This function must be called after `esp_http_client_init`.
*
* @param[in] client The esp_http_client handle
* @param[in] key The header key
* @param[out] value The header value
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_http_client_get_header(esp_http_client_handle_t client, const char *key, char **value);
/**
* @brief Set http request method
*
* @param[in] client The esp_http_client handle
* @param[in] method The method
*
* @return ESP_OK
*/
esp_err_t esp_http_client_set_method(esp_http_client_handle_t client, esp_http_client_method_t method);
/**
* @brief Delete http request header
*
* @param[in] client The esp_http_client handle
* @param[in] key The key
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_http_client_delete_header(esp_http_client_handle_t client, const char *key);
/**
* @brief This function will be open the connection, write all header strings and return
*
* @param[in] client The esp_http_client handle
* @param[in] write_len HTTP Content length need to write to the server
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_http_client_open(esp_http_client_handle_t client, int write_len);
/**
* @brief This function will write data to the HTTP connection previously opened by esp_http_client_open()
*
* @param[in] client The esp_http_client handle
* @param buffer The buffer
* @param[in] len This value must not be larger than the write_len parameter provided to esp_http_client_open()
*
* @return
* - (-1) if any errors
* - Length of data written
*/
int esp_http_client_write(esp_http_client_handle_t client, const char *buffer, int len);
/**
* @brief This function need to call after esp_http_client_open, it will read from http stream, process all receive headers
*
* @param[in] client The esp_http_client handle
*
* @return
* - (0) if stream doesn't contain content-length header, or chunked encoding (checked by `esp_http_client_is_chunked` response)
* - (-1: ESP_FAIL) if any errors
* - Download data length defined by content-length header
*/
int esp_http_client_fetch_headers(esp_http_client_handle_t client);
/**
* @brief Check response data is chunked
*
* @param[in] client The esp_http_client handle
*
* @return true or false
*/
bool esp_http_client_is_chunked_response(esp_http_client_handle_t client);
/**
* @brief Read data from http stream
*
* @param[in] client The esp_http_client handle
* @param buffer The buffer
* @param[in] len The length
*
* @return
* - (-1) if any errors
* - Length of data was read
*/
int esp_http_client_read(esp_http_client_handle_t client, char *buffer, int len);
/**
* @brief Get http response status code, the valid value if this function invoke after `esp_http_client_perform`
*
* @param[in] client The esp_http_client handle
*
* @return Status code
*/
int esp_http_client_get_status_code(esp_http_client_handle_t client);
/**
* @brief Get http response content length (from header Content-Length)
* the valid value if this function invoke after `esp_http_client_perform`
*
* @param[in] client The esp_http_client handle
*
* @return
* - (-1) Chunked transfer
* - Content-Length value as bytes
*/
int esp_http_client_get_content_length(esp_http_client_handle_t client);
/**
* @brief Close http connection, still kept all http request resources
*
* @param[in] client The esp_http_client handle
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_http_client_close(esp_http_client_handle_t client);
/**
* @brief This function must be the last function to call for an session.
* It is the opposite of the esp_http_client_init function and must be called with the same handle as input that a esp_http_client_init call returned.
* This might close all connections this handle has used and possibly has kept open until now.
* Don't call this function if you intend to transfer more files, re-using handles is a key to good performance with esp_http_client.
*
* @param[in] client The esp_http_client handle
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client);
/**
* @brief Get transport type
*
* @param[in] client The esp_http_client handle
*
* @return
* - HTTP_TRANSPORT_UNKNOWN
* - HTTP_TRANSPORT_OVER_TCP
* - HTTP_TRANSPORT_OVER_SSL
*/
esp_http_client_transport_t esp_http_client_get_transport_type(esp_http_client_handle_t client);
#ifdef __cplusplus
}
#endif
#endif

@ -0,0 +1,151 @@
// 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.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include "tcpip_adapter.h"
#include "lwip/sockets.h"
#include "rom/md5_hash.h"
#include "mbedtls/base64.h"
#include "esp_system.h"
#include "esp_log.h"
#include "http_utils.h"
#include "http_auth.h"
#define MD5_MAX_LEN (33)
#define HTTP_AUTH_BUF_LEN (1024)
static const char *TAG = "HTTP_AUTH";
/**
* @brief This function hash a formatted string with MD5 and format the result as ascii characters
*
* @param md The buffer will hold the ascii result
* @param[in] fmt The format
*
* @return Length of the result
*/
static int md5_printf(char *md, const char *fmt, ...)
{
unsigned char *buf;
unsigned char digest[MD5_MAX_LEN];
int len, i;
struct MD5Context md5_ctx;
va_list ap;
va_start(ap, fmt);
len = vasprintf((char **)&buf, fmt, ap);
if (buf == NULL) {
return ESP_FAIL;
}
MD5Init(&md5_ctx);
MD5Update(&md5_ctx, buf, len);
MD5Final(digest, &md5_ctx);
for (i = 0; i < 16; ++i) {
sprintf(&md[i * 2], "%02x", (unsigned int)digest[i]);
}
va_end(ap);
free(buf);
return MD5_MAX_LEN;
}
char *http_auth_digest(const char *username, const char *password, esp_http_auth_data_t *auth_data)
{
char *ha1, *ha2 = NULL;
char *digest = NULL;
char *auth_str = NULL;
if (username == NULL ||
password == NULL ||
auth_data->nonce == NULL ||
auth_data->uri == NULL ||
auth_data->realm == NULL) {
return NULL;
}
ha1 = calloc(1, MD5_MAX_LEN);
HTTP_MEM_CHECK(TAG, ha1, goto _digest_exit);
ha2 = calloc(1, MD5_MAX_LEN);
HTTP_MEM_CHECK(TAG, ha2, goto _digest_exit);
digest = calloc(1, MD5_MAX_LEN);
HTTP_MEM_CHECK(TAG, digest, goto _digest_exit);
if (md5_printf(ha1, "%s:%s:%s", username, auth_data->realm, password) <= 0) {
goto _digest_exit;
}
ESP_LOGD(TAG, "%s %s %s %s\r\n", "Digest", username, auth_data->realm, password);
if (strcasecmp(auth_data->algorithm, "md5-sess") == 0) {
if (md5_printf(ha1, "%s:%s:%016llx", ha1, auth_data->nonce, auth_data->cnonce) <= 0) {
goto _digest_exit;
}
}
if (md5_printf(ha2, "%s:%s", auth_data->method, auth_data->uri) <= 0) {
goto _digest_exit;
}
//support qop = auth
if (auth_data->qop && strcasecmp(auth_data->qop, "auth-int") == 0) {
if (md5_printf(ha2, "%s:%s", ha2, "entity") <= 0) {
goto _digest_exit;
}
}
if (auth_data->qop) {
// response=MD5(HA1:nonce:nonceCount:cnonce:qop:HA2)
if (md5_printf(digest, "%s:%s:%08x:%016llx:%s:%s", ha1, auth_data->nonce, auth_data->nc, auth_data->cnonce, auth_data->qop, ha2) <= 0) {
goto _digest_exit;
}
} else {
// response=MD5(HA1:nonce:HA2)
if (md5_printf(digest, "%s:%s:%s", ha1, auth_data->nonce, ha2) <= 0) {
goto _digest_exit;
}
}
asprintf(&auth_str, "Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", algorithm=\"MD5\", "
"response=\"%s\", opaque=\"%s\", qop=%s, nc=%08x, cnonce=\"%016llx\"",
username, auth_data->realm, auth_data->nonce, auth_data->uri, digest, auth_data->opaque, auth_data->qop, auth_data->nc, auth_data->cnonce);
_digest_exit:
free(ha1);
free(ha2);
free(digest);
return auth_str;
}
char *http_auth_basic(const char *username, const char *password)
{
int out;
char *user_info = NULL;
char *digest = NULL;
size_t n = 0;
asprintf(&user_info, "%s:%s", username, password);
HTTP_MEM_CHECK(TAG, user_info, return NULL);
mbedtls_base64_encode(NULL, 0, &n, (const unsigned char *)user_info, strlen(user_info));
digest = calloc(1, 6 + n + 1);
HTTP_MEM_CHECK(TAG, digest, goto _basic_exit);
strcpy(digest, "Basic ");
mbedtls_base64_encode((unsigned char *)digest + 6, n, (size_t *)&out, (const unsigned char *)user_info, strlen(user_info));
_basic_exit:
free(user_info);
return digest;
}

@ -0,0 +1,239 @@
// 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.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "esp_log.h"
#include "http_header.h"
#include "http_utils.h"
static const char *TAG = "HTTP_HEADER";
#define HEADER_BUFFER (1024)
/**
* dictionary item struct, with key-value pair
*/
typedef struct http_header_item {
char *key; /*!< key */
char *value; /*!< value */
STAILQ_ENTRY(http_header_item) next; /*!< Point to next entry */
} http_header_item_t;
STAILQ_HEAD(http_header, http_header_item);
http_header_handle_t http_header_init()
{
http_header_handle_t header = calloc(1, sizeof(struct http_header));
HTTP_MEM_CHECK(TAG, header, return NULL);
STAILQ_INIT(header);
return header;
}
esp_err_t http_header_destroy(http_header_handle_t header)
{
esp_err_t err = http_header_clean(header);
free(header);
return err;
}
http_header_item_handle_t http_header_get_item(http_header_handle_t header, const char *key)
{
http_header_item_handle_t item;
if (header == NULL || key == NULL) {
return NULL;
}
STAILQ_FOREACH(item, header, next) {
if (strcasecmp(item->key, key) == 0) {
return item;
}
}
return NULL;
}
esp_err_t http_header_get(http_header_handle_t header, const char *key, char **value)
{
http_header_item_handle_t item;
item = http_header_get_item(header, key);
if (item) {
*value = item->value;
} else {
*value = NULL;
}
return ESP_OK;
}
static esp_err_t http_header_new_item(http_header_handle_t header, const char *key, const char *value)
{
http_header_item_handle_t item;
item = calloc(1, sizeof(http_header_item_t));
HTTP_MEM_CHECK(TAG, item, return ESP_ERR_NO_MEM);
http_utils_assign_string(&item->key, key, 0);
HTTP_MEM_CHECK(TAG, item->key, goto _header_new_item_exit);
http_utils_trim_whitespace(&item->key);
http_utils_assign_string(&item->value, value, 0);
HTTP_MEM_CHECK(TAG, item->value, goto _header_new_item_exit);
http_utils_trim_whitespace(&item->value);
STAILQ_INSERT_TAIL(header, item, next);
return ESP_OK;
_header_new_item_exit:
free(item->key);
free(item->value);
return ESP_ERR_NO_MEM;
}
esp_err_t http_header_set(http_header_handle_t header, const char *key, const char *value)
{
http_header_item_handle_t item;
if (value == NULL) {
return http_header_delete(header, key);
}
item = http_header_get_item(header, key);
if (item) {
free(item->value);
item->value = strdup(value);
http_utils_trim_whitespace(&item->value);
return ESP_OK;
}
return http_header_new_item(header, key, value);
}
esp_err_t http_header_set_from_string(http_header_handle_t header, const char *key_value_data)
{
char *eq_ch;
char *p_str;
p_str = strdup(key_value_data);
HTTP_MEM_CHECK(TAG, p_str, return ESP_ERR_NO_MEM);
eq_ch = strchr(p_str, ':');
if (eq_ch == NULL) {
free(p_str);
return ESP_ERR_INVALID_ARG;
}
*eq_ch = 0;
http_header_set(header, p_str, eq_ch + 1);
free(p_str);
return ESP_OK;
}
esp_err_t http_header_delete(http_header_handle_t header, const char *key)
{
http_header_item_handle_t item = http_header_get_item(header, key);
if (item) {
STAILQ_REMOVE(header, item, http_header_item, next);
free(item->key);
free(item->value);
free(item);
} else {
return ESP_ERR_NOT_FOUND;
}
return ESP_OK;
}
int http_header_set_format(http_header_handle_t header, const char *key, const char *format, ...)
{
va_list argptr;
int len = 0;
char *buf = NULL;
va_start(argptr, format);
len = vasprintf(&buf, format, argptr);
HTTP_MEM_CHECK(TAG, buf, return 0);
va_end(argptr);
if (buf == NULL) {
return 0;
}
http_header_set(header, key, buf);
free(buf);
return len;
}
int http_header_generate_string(http_header_handle_t header, int index, char *buffer, int *buffer_len)
{
http_header_item_handle_t item;
int siz = 0;
int idx = 0;
int ret_idx = -1;
bool is_end = false;
STAILQ_FOREACH(item, header, next) {
if (item->value && idx >= index) {
siz += strlen(item->key);
siz += strlen(item->value);
siz += 4; //': ' and '\r\n'
}
idx ++;
if (siz + 1 > *buffer_len - 2) {
ret_idx = idx - 1;
}
}
if (siz == 0) {
return 0;
}
if (ret_idx < 0) {
ret_idx = idx;
is_end = true;
}
int str_len = 0;
idx = 0;
STAILQ_FOREACH(item, header, next) {
if (item->value && idx >= index && idx < ret_idx) {
str_len += snprintf(buffer + str_len, *buffer_len - str_len, "%s: %s\r\n", item->key, item->value);
}
idx ++;
}
if (is_end) {
str_len += snprintf(buffer + str_len, *buffer_len - str_len, "\r\n");
}
*buffer_len = str_len;
return ret_idx;
}
esp_err_t http_header_clean(http_header_handle_t header)
{
http_header_item_handle_t item = STAILQ_FIRST(header), tmp;
while (item != NULL) {
tmp = STAILQ_NEXT(item, next);
free(item->key);
free(item->value);
free(item);
item = tmp;
}
STAILQ_INIT(header);
return ESP_OK;
}
int http_header_count(http_header_handle_t header)
{
http_header_item_handle_t item;
int count = 0;
STAILQ_FOREACH(item, header, next) {
count ++;
}
return count;
}

@ -0,0 +1,125 @@
// 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.
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "http_utils.h"
#ifndef mem_check
#define mem_check(x) assert(x)
#endif
char *http_utils_join_string(const char *first_str, int len_first, const char *second_str, int len_second)
{
int first_str_len = len_first > 0 ? len_first : strlen(first_str);
int second_str_len = len_second > 0 ? len_second : strlen(second_str);
char *ret = NULL;
if (first_str_len + second_str_len > 0) {
ret = calloc(1, first_str_len + second_str_len + 1);
mem_check(ret);
memcpy(ret, first_str, first_str_len);
memcpy(ret + first_str_len, second_str, second_str_len);
}
return ret;
}
char *http_utils_assign_string(char **str, const char *new_str, int len)
{
int l = len;
if (new_str == NULL) {
return NULL;
}
char *old_str = *str;
if (l <= 0) {
l = strlen(new_str);
}
if (old_str) {
old_str = realloc(old_str, l + 1);
mem_check(old_str);
old_str[l] = 0;
} else {
old_str = calloc(1, l + 1);
mem_check(old_str);
}
memcpy(old_str, new_str, l);
*str = old_str;
return old_str;
}
void http_utils_trim_whitespace(char **str)
{
char *end, *start;
if (str == NULL) {
return;
}
start = *str;
if (start == NULL) {
return;
}
// Trim leading space
while (isspace((unsigned char)*start)) start ++;
if (*start == 0) { // All spaces?
**str = 0;
return;
}
// Trim trailing space
end = (char *)(start + strlen(start) - 1);
while (end > start && isspace((unsigned char)*end)) {
end--;
}
// Write new null terminator
*(end + 1) = 0;
memmove(*str, start, strlen(start) + 1);
}
char *http_utils_get_string_between(const char *str, const char *begin, const char *end)
{
char *found = strstr(str, begin);
char *ret = NULL;
if (found) {
found += strlen(begin);
char *found_end = strstr(found, end);
if (found_end) {
ret = calloc(1, found_end - found + 1);
mem_check(ret);
memcpy(ret, found, found_end - found);
return ret;
}
}
return NULL;
}
int http_utils_str_starts_with(const char *str, const char *start)
{
int i;
int match_str_len = strlen(str);
int start_len = strlen(start);
if (start_len > match_str_len) {
return -1;
}
for (i = 0; i < start_len; i++) {
if (str[i] != start[i]) {
return 1;
}
}
return 0;
}

@ -0,0 +1,60 @@
// 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 _HTTP_BASIC_AUTH_H_
#define _HTTP_BASIC_AUTH_H_
/**
* HTTP Digest authentication data
*/
typedef struct {
char *method; /*!< Request method, example: GET */
char *algorithm; /*!< Authentication algorithm */
char *uri; /*!< URI of request example: /path/to/file.html */
char *realm; /*!< Authentication realm */
char *nonce; /*!< Authentication nonce */
char *qop; /*!< Authentication qop */
char *opaque; /*!< Authentication opaque */
uint64_t cnonce; /*!< Authentication cnonce */
int nc; /*!< Authentication nc */
} esp_http_auth_data_t;
/**
* @brief This use for Http digest authentication method, create http header for digest authentication.
* The returned string need to free after use
*
* @param[in] username The username
* @param[in] password The password
* @param auth_data The auth data
*
* @return
* - HTTP Header value of Authorization, valid for digest authentication, must be freed after usage
* - NULL
*/
char *http_auth_digest(const char *username, const char *password, esp_http_auth_data_t *auth_data);
/**
* @brief This use for Http basic authentication method, create header value for basic http authentication
* The returned string need to free after use
*
* @param[in] username The username
* @param[in] password The password
*
* @return
* - HTTP Header value of Authorization, valid for basic authentication, must be free after use
* - NULL
*/
char *http_auth_basic(const char *username, const char *password);
#endif

@ -0,0 +1,128 @@
// 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 _HTTP_HEADER_H_
#define _HTTP_HEADER_H_
#include "rom/queue.h"
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct http_header *http_header_handle_t;
typedef struct http_header_item *http_header_item_handle_t;
/**
* @brief initialize and allocate the memory for the header object
*
* @return
* - http_header_handle_t
* - NULL if any errors
*/
http_header_handle_t http_header_init();
/**
* @brief Cleanup and free all http header pairs
*
* @param[in] header The header
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t http_header_clean(http_header_handle_t header);
/**
* @brief Cleanup with http_header_clean and destroy http header handle object
*
* @param[in] header The header
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t http_header_destroy(http_header_handle_t header);
/**
* @brief Add a key-value pair of http header to the list,
* note that with value = NULL, this function will remove the header with `key` already exists in the list.
*
* @param[in] header The header
* @param[in] key The key
* @param[in] value The value
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t http_header_set(http_header_handle_t header, const char *key, const char *value);
/**
* @brief Sample as `http_header_set` but the value can be formated
*
* @param[in] header The header
* @param[in] key The key
* @param[in] format The format
* @param[in] ... format parameters
*
* @return Total length of value
*/
int http_header_set_format(http_header_handle_t header, const char *key, const char *format, ...);
/**
* @brief Get a value of header in header list
* The address of the value will be assign set to `value` parameter or NULL if no header with the key exists in the list
*
* @param[in] header The header
* @param[in] key The key
* @param[out] value The value
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t http_header_get(http_header_handle_t header, const char *key, char **value);
/**
* @brief Create HTTP header string from the header with index, output string to buffer with buffer_len
* Also return the last index of header was generated
*
* @param[in] header The header
* @param[in] index The index
* @param buffer The buffer
* @param buffer_len The buffer length
*
* @return The last index of header was generated
*/
int http_header_generate_string(http_header_handle_t header, int index, char *buffer, int *buffer_len);
/**
* @brief Remove the header with key from the headers list
*
* @param[in] header The header
* @param[in] key The key
*
* @return
* - ESP_OK
* - ESP_FAIL
*/
esp_err_t http_header_delete(http_header_handle_t header, const char *key);
#ifdef __cplusplus
}
#endif
#endif

@ -0,0 +1,86 @@
// 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 _HTTP_UTILS_H_
#define _HTTP_UTILS_H_
#include <sys/time.h>
#include "esp_transport_utils.h"
/**
* @brief Assign new_str to *str pointer, and realloc *str if it not NULL
*
* @param str pointer to string pointer
* @param new_str assign this tring to str
* @param len length of string, 0 if new_str is zero terminated
*
* @return
* - new_str pointer
* - NULL
*/
char *http_utils_assign_string(char **str, const char *new_str, int len);
/**
* @brief Remove white space at begin and end of string
*
* @param[in] str The string
*
* @return New strings have been trimmed
*/
void http_utils_trim_whitespace(char **str);
/**
* @brief Gets the string between 2 string.
* It will allocate a new memory space for this string, so you need to free it when no longer use
*
* @param[in] str The source string
* @param[in] begin The begin string
* @param[in] end The end string
*
* @return The string between begin and end
*/
char *http_utils_get_string_between(const char *str, const char *begin, const char *end);
/**
* @brief Join 2 strings to one
* It will allocate a new memory space for this string, so you need to free it when no longer use
*
* @param[in] first_str The first string
* @param[in] len_first The length first
* @param[in] second_str The second string
* @param[in] len_second The length second
*
* @return
* - New string pointer
* - NULL: Invalid input
*/
char *http_utils_join_string(const char *first_str, int len_first, const char *second_str, int len_second);
/**
* @brief Check if ``str`` is start with ``start``
*
* @param[in] str The string
* @param[in] start The start
*
* @return
* - (-1) if length of ``start`` larger than length of ``str``
* - (1) if ``start`` NOT starts with ``start``
* - (0) if ``str`` starts with ``start``
*/
int http_utils_str_starts_with(const char *str, const char *start);
#define HTTP_MEM_CHECK(TAG, a, action) ESP_TRANSPORT_MEM_CHECK(TAG, a, action)
#endif