123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214 |
- #include "kbf/http/client.h"
- #include <freertos/task.h>
- #include <esp_log.h>
- #include <esp_tls.h>
- #include <memory>
- #include "kbf/exception.h"
- #include "kbf/http/exception.h"
- #include "kbf/macros.h"
- using namespace kbf;
- using std::make_shared;
- using std::string;
- using std::shared_ptr;
- using std::optional;
- using std::nullopt;
- using std::map;
- http::Client::Client(int timeoutMs, bool async) : timeoutMs(timeoutMs), async(async), buffer() {
- ESP_LOGD(TAG, "%s()", __func__);
- init();
- }
- void http::Client::init() {
- ESP_LOGD(TAG, "%s()", __func__);
- esp_http_client_config_t config{};
- config.event_handler = handleHttpEvent;
- config.user_data = this;
- config.host = "localhost";
- config.path = "/";
- config.disable_auto_redirect = false; // do not set to true, IDF bug :(
- config.max_redirection_count = 0;
- config.timeout_ms = timeoutMs;
- config.is_async = async;
- config.use_global_ca_store = true;
- handle = esp_http_client_init(&config);
- }
- http::Client::~Client() {
- ESP_LOGD(TAG, "%s()", __func__);
- CHECK_ABORT(esp_http_client_cleanup(handle));
- }
- std::shared_ptr<kbf::http::Response>
- http::Client::performRequest(const kbf::http::Method method, const std::string &url, const nlohmann::json *postData,
- const optional<const map<string, string>> &headers) {
- ESP_LOGD(TAG, "%s(); method: %d, url: %s", __func__, method, url.c_str());
- if (running) {
- ESP_LOGE(TAG, "request already in progress");
- return nullptr;
- }
- running = true;
- response = std::make_shared<Response>();
- buffer.clear();
- string body;
- if (method == GET) {
- esp_http_client_set_method(handle, HTTP_METHOD_GET);
- } else if (method == POST) {
- body = postData ? postData->dump() : "";
- ESP_LOGV(TAG, "request body:");
- ESP_LOG_BUFFER_HEXDUMP(TAG, body.c_str(), body.size(), ESP_LOG_VERBOSE);
- esp_http_client_set_method(handle, HTTP_METHOD_POST);
- esp_http_client_set_header(handle, "Content-Type", "application/json");
- esp_http_client_set_post_field(handle, body.c_str(), body.length());
- } else {
- ESP_LOGE(TAG, "unhandled method: %d", method);
- throw kbf::exception::KBFError("unknown HTTP method " + std::to_string(method));
- }
- if (headers) {
- ESP_LOGD(TAG, "adding headers");
- for (auto const &[key, value] : *headers) {
- ESP_LOGD(TAG, " %s: %s", key.c_str(), value.c_str());
- esp_http_client_set_header(handle, key.c_str(), value.c_str());
- }
- }
- esp_http_client_set_url(handle, url.c_str());
- auto err = esp_http_client_perform(handle);
- if (err == ESP_ERR_HTTP_MAX_REDIRECT) {
- // TODO this seems get triggered on HTTP 4XX
- ESP_LOGW(TAG, "reached redirect limit");
- updateResponse(*this);
- err = ESP_OK;
- }
- if (err == ESP_ERR_HTTP_EAGAIN) {
- ESP_LOGD(TAG, "async request in progress, returning nullptr");
- return nullptr;
- } else if (err == ESP_OK) {
- ESP_LOGD(TAG, "success");
- return response;
- } else if ((err == ESP_ERR_HTTP_FETCH_HEADER || err == ESP_FAIL)) {
- // TODO happens on timeout and conn reset as well; can we distinguish between errors here properly?
- if (retry) {
- ESP_LOGE(TAG, "retry failed (%s)", esp_err_to_name(err));
- throw exception::RequestError();
- }
- if (timeoutMs) {
- ESP_LOGE(TAG, "request failed (%s), assuming timeout", esp_err_to_name(err));
- throw exception::Timeout();
- }
- ESP_LOGW(TAG, "request failed (%s), maybe the connection was dropped? retrying...", esp_err_to_name(err));
- retry = true;
- esp_http_client_cleanup(handle);
- init();
- if (method == http::GET) {
- return get(url, headers);
- } else if (method == http::POST) {
- return post(url, *postData, headers);
- } else {
- throw kbf::exception::KBFError("unknown HTTP method " + std::to_string(method));
- }
- } else if (err == ESP_ERR_HTTP_CONNECT) {
- ESP_LOGW(TAG, "HTTP request failed: %s", esp_err_to_name(err));
- running = false;
- throw exception::ConnectionError();
- } else {
- ESP_LOGE(TAG, "unhandled HTTP error: %s", esp_err_to_name(err));
- running = false;
- throw kbf::exception::KBFError("unhandled HTTP error: %s" + string(esp_err_to_name(err)));
- }
- }
- esp_err_t http::Client::handleHttpEvent(esp_http_client_event_t *event) {
- auto client = (Client *) event->user_data;
- switch (event->event_id) {
- case HTTP_EVENT_ERROR:
- ESP_LOGE(TAG, "fixme: unhandled error event: HTTP_EVENT_ERROR");
- client->running = false;
- client->retry = false;
- throw kbf::exception::KBFError("HTTP_EVENT_ERROR");
- case HTTP_EVENT_ON_CONNECTED:
- ESP_LOGD(TAG, "connected");
- break;
- case HTTP_EVENT_HEADERS_SENT:
- ESP_LOGD(TAG, "request sent");
- break;
- case HTTP_EVENT_ON_HEADER:
- ESP_LOGD(TAG, "header received: %s: %s", event->header_key, event->header_value);
- client->response->headers[event->header_key] = event->header_value;
- break;
- case HTTP_EVENT_ON_DATA:
- ESP_LOGD(TAG, "data received");
- if (esp_http_client_is_chunked_response(client->handle)) {
- ESP_LOGE(TAG, "receiving chunked data not implemented");
- throw kbf::exception::KBFError("HTTP client chunked data not implemented");
- }
- client->buffer.append((char *) event->data, event->data_len);
- break;
- case HTTP_EVENT_ON_FINISH:
- ESP_LOGD(TAG, "finished");
- updateResponse(*client);
- break;
- case HTTP_EVENT_DISCONNECTED:
- ESP_LOGI(TAG, "disconnected");
- client->running = false;
- break;
- }
- return ESP_OK;
- }
- void http::Client::updateResponse(http::Client &client) {
- client.response->status = esp_http_client_get_status_code(client.handle);
- client.response->body = client.buffer;
- ESP_LOGD(TAG, "HTTP status: %d, Content-Length: %s", client.response->status,
- client.response->headers["Content-Length"].c_str());
- ESP_LOG_BUFFER_HEXDUMP(TAG, client.response->body.data(), client.response->body.length(), ESP_LOG_VERBOSE);
- if (client.onSuccess) { client.onSuccess(client, *client.response); }
- client.running = false;
- client.retry = false;
- }
- shared_ptr<http::Response>
- http::Client::get(const string &url, const optional<const map<string, string>> &headers) {
- ESP_LOGD(TAG, "%s(%s)", __func__, url.c_str());
- return performRequest(GET, url, nullptr, headers);
- }
- shared_ptr<http::Response>
- http::Client::post(const string &url, const nlohmann::json &data, const optional<const map<string, string>> &headers) {
- ESP_LOGD(TAG, "%s(%s)", __func__, url.c_str());
- return performRequest(POST, url, &data, headers);
- }
- void http::Client::addCert(const unsigned char *const start, const unsigned char *const end) {
- ESP_LOGI(TAG, "%s()", __func__);
- ESP_LOGD(TAG, "certificate:\n%s", start);
- CHECK(esp_tls_set_global_ca_store(start, end - start));
- }
- void http::Client::clearCerts() {
- ESP_LOGI(TAG, "%s()", __func__);
- esp_tls_free_global_ca_store();
- }
- void http::Client::disconnect() {
- ESP_LOGD(TAG, "%s()", __func__);
- CHECK(esp_http_client_close(handle));
- }
|