137 lines
7.3 KiB
C++
137 lines
7.3 KiB
C++
//! \~\file microhttpd_server.h
|
||
//! \~\ingroup HTTPServer
|
||
//! \~\brief
|
||
//! \~english Base HTTP server API built on top of libmicrohttpd
|
||
//! \~russian Базовый API HTTP-сервера, построенный поверх libmicrohttpd
|
||
/*
|
||
PIP - Platform Independent Primitives
|
||
Base HTTP server API built on top of libmicrohttpd
|
||
Ivan Pelipenko peri4ko@yandex.ru
|
||
|
||
This program is free software: you can redistribute it and/or modify
|
||
it under the terms of the GNU Lesser General Public License as published by
|
||
the Free Software Foundation, either version 3 of the License, or
|
||
(at your option) any later version.
|
||
|
||
This program is distributed in the hope that it will be useful,
|
||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
GNU Lesser General Public License for more details.
|
||
|
||
You should have received a copy of the GNU Lesser General Public License
|
||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||
*/
|
||
|
||
#ifndef MICROHTTPD_SERVER_P_H
|
||
#define MICROHTTPD_SERVER_P_H
|
||
|
||
#include "pihttptypes.h"
|
||
#include "piobject.h"
|
||
#include "pip_http_server_export.h"
|
||
|
||
struct MicrohttpdServerConnection;
|
||
|
||
//! \~\ingroup HTTPServer
|
||
//! \~\brief
|
||
//! \~english Base HTTP server with request dispatch and optional basic authentication.
|
||
//! \~russian Базовый HTTP-сервер с диспетчеризацией запросов и необязательной basic-аутентификацией.
|
||
class PIP_HTTP_SERVER_EXPORT MicrohttpdServer: public PIObject {
|
||
PIOBJECT(MicrohttpdServer)
|
||
friend struct MicrohttpdServerConnection;
|
||
|
||
public:
|
||
//! \~english Creates a stopped server instance with default options.
|
||
//! \~russian Создает остановленный экземпляр сервера с настройками по умолчанию.
|
||
MicrohttpdServer();
|
||
//! \~english Stops the server and releases native resources.
|
||
//! \~russian Останавливает сервер и освобождает нативные ресурсы.
|
||
virtual ~MicrohttpdServer();
|
||
|
||
//! \~english Server configuration options accepted by \a setOption().
|
||
//! \~russian Параметры конфигурации сервера, принимаемые методом \a setOption().
|
||
enum class Option {
|
||
ConnectionLimit /** \~english Maximum number of simultaneously accepted connections. \~russian Максимальное число одновременно
|
||
принимаемых соединений. */
|
||
,
|
||
ConnectionTimeout /** \~english Per-connection timeout value. \~russian Значение таймаута для отдельного соединения. */,
|
||
HTTPSEnabled /** \~english Enables TLS mode for the daemon. \~russian Включает режим TLS для демона. */,
|
||
HTTPSMemKey /** \~english Private key stored in memory as \c PIByteArray. \~russian Приватный ключ, хранящийся в памяти в виде \c
|
||
PIByteArray. */
|
||
,
|
||
HTTPSMemCert /** \~english Certificate stored in memory as \c PIByteArray. \~russian Сертификат, хранящийся в памяти в виде \c
|
||
PIByteArray. */
|
||
,
|
||
HTTPSKeyPassword /** \~english Password for the in-memory private key as \c PIByteArray. \~russian Пароль для приватного ключа в
|
||
памяти в виде \c PIByteArray. */
|
||
};
|
||
|
||
//! \~english Sets a server option. The expected variant payload depends on the selected \a Option.
|
||
//! \~russian Устанавливает параметр сервера. Ожидаемый тип значения \c PIVariant зависит от выбранного \a Option.
|
||
void setOption(Option o, PIVariant v);
|
||
|
||
//! \~english Sets the bytes returned for requests to \c /favicon.ico.
|
||
//! \~russian Устанавливает байты, возвращаемые для запросов к \c /favicon.ico.
|
||
void setFavicon(const PIByteArray & im);
|
||
|
||
|
||
//! \~english Starts listening on the specified network address, restarting the daemon if needed.
|
||
//! \~russian Запускает прослушивание на указанном сетевом адресе, при необходимости перезапуская демон.
|
||
bool listen(PINetworkAddress addr);
|
||
|
||
//! \~english Starts listening on all interfaces for the specified port.
|
||
//! \~russian Запускает прослушивание на всех интерфейсах для указанного порта.
|
||
bool listenAll(ushort port) { return listen({0, port}); }
|
||
|
||
//! \~english Returns \c true while the native HTTP daemon is running.
|
||
//! \~russian Возвращает \c true, пока нативный HTTP-демон запущен.
|
||
bool isListen() const;
|
||
|
||
//! \~english Stops listening and shuts down the native HTTP daemon.
|
||
//! \~russian Останавливает прослушивание и завершает работу нативного HTTP-демона.
|
||
void stop();
|
||
|
||
|
||
//! \~english Enables HTTP Basic authentication checks for new requests.
|
||
//! \~russian Включает проверки HTTP Basic-аутентификации для новых запросов.
|
||
void enableBasicAuth() { setBasicAuthEnabled(true); }
|
||
|
||
//! \~english Disables HTTP Basic authentication checks.
|
||
//! \~russian Отключает проверки HTTP Basic-аутентификации.
|
||
void disableBasicAuth() { setBasicAuthEnabled(false); }
|
||
|
||
//! \~english Enables or disables HTTP Basic authentication checks.
|
||
//! \~russian Включает или отключает проверки HTTP Basic-аутентификации.
|
||
void setBasicAuthEnabled(bool yes) { use_basic_auth = yes; }
|
||
|
||
//! \~english Returns whether HTTP Basic authentication checks are enabled.
|
||
//! \~russian Возвращает, включены ли проверки HTTP Basic-аутентификации.
|
||
bool isBasicAuthEnabled() const { return use_basic_auth; }
|
||
|
||
//! \~english Sets the realm sent in HTTP Basic authentication challenges.
|
||
//! \~russian Устанавливает realm, отправляемый в challenge HTTP Basic-аутентификации.
|
||
void setBasicAuthRealm(const PIString & r) { realm = r; }
|
||
|
||
//! \~english Sets the callback that receives parsed requests and returns replies.
|
||
//! \~russian Устанавливает callback, который получает разобранные запросы и возвращает ответы.
|
||
void setRequestCallback(std::function<PIHTTP::MessageMutable(const PIHTTP::MessageConst &)> c) { callback = std::move(c); }
|
||
|
||
//! \~english Sets the credential validator used when HTTP Basic authentication is enabled.
|
||
//! \~russian Устанавливает валидатор учетных данных, используемый при включенной HTTP Basic-аутентификации.
|
||
void setBasicAuthCallback(std::function<bool(const PIString &, const PIString &)> c) { callback_auth = std::move(c); }
|
||
|
||
private:
|
||
static void addFixedHeaders(PIHTTP::MessageMutable & msg);
|
||
PRIVATE_DECLARATION(PIP_HTTP_SERVER_EXPORT)
|
||
|
||
PIByteArray favicon;
|
||
PIString realm;
|
||
PIMap<Option, PIVariant> opts;
|
||
std::function<PIHTTP::MessageMutable(const PIHTTP::MessageConst &)> callback;
|
||
std::function<bool(const PIString &, const PIString &)> callback_auth;
|
||
std::atomic_bool use_basic_auth = {false};
|
||
PIByteArray mem_key, mem_cert, key_pass;
|
||
};
|
||
|
||
|
||
#endif
|