cpp-httplib/httplib.h

681 lines
15 KiB
C
Raw Normal View History

2012-09-22 21:40:46 -07:00
//
2012-09-27 18:05:36 -07:00
// httplib.h
2012-09-22 21:40:46 -07:00
//
// Copyright (c) 2012 Yuji Hirose. All rights reserved.
// The Boost Software License 1.0
//
2012-09-25 19:09:56 -07:00
#ifndef HTTPSVRKIT_H
#define HTTPSVRKIT_H
2012-09-22 21:40:46 -07:00
#ifdef _WIN32
2012-09-26 08:49:04 -07:00
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_DEPRECATE
2012-09-25 19:09:56 -07:00
#ifndef SO_SYNCHRONOUS_NONALERT
#define SO_SYNCHRONOUS_NONALERT 0x20;
#endif
#ifndef SO_OPENTYPE
#define SO_OPENTYPE 0x7008
#endif
#include <fcntl.h>
#include <io.h>
2012-09-22 21:40:46 -07:00
#include <winsock2.h>
typedef SOCKET socket_t;
#else
#include <pthread.h>
#include <unistd.h>
#include <netdb.h>
2012-09-22 21:40:46 -07:00
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
2012-09-22 21:40:46 -07:00
typedef int socket_t;
#endif
#include <functional>
#include <map>
#include <regex>
#include <string>
#include <assert.h>
2012-09-27 18:05:36 -07:00
namespace httplib
2012-09-22 21:40:46 -07:00
{
2012-09-24 04:57:09 -07:00
typedef std::map<std::string, std::string> Map;
typedef std::multimap<std::string, std::string> MultiMap;
2012-10-03 17:11:22 -07:00
typedef std::smatch Match;
2012-09-22 21:40:46 -07:00
2012-09-24 04:57:09 -07:00
struct Request {
2012-09-24 20:13:01 -07:00
std::string method;
std::string url;
2012-10-02 17:39:13 -07:00
MultiMap headers;
2012-09-24 04:57:09 -07:00
std::string body;
2012-10-03 20:47:59 -07:00
Map params;
Match matches;
2012-10-03 17:11:22 -07:00
bool has_header(const char* key) const;
std::string get_header_value(const char* key) const;
2012-10-03 20:47:59 -07:00
void set_header(const char* key, const char* val);
bool has_param(const char* key) const;
2012-09-22 21:40:46 -07:00
};
2012-09-24 04:57:09 -07:00
struct Response {
2012-09-25 19:09:56 -07:00
int status;
2012-09-24 04:57:09 -07:00
MultiMap headers;
std::string body;
2012-09-25 19:09:56 -07:00
2012-10-03 17:11:22 -07:00
bool has_header(const char* key) const;
std::string get_header_value(const char* key) const;
void set_header(const char* key, const char* val);
2012-09-25 19:09:56 -07:00
void set_redirect(const char* url);
2012-10-03 17:11:22 -07:00
void set_content(const std::string& s, const char* content_type);
2012-10-03 21:38:32 -07:00
Response() : status(-1) {}
2012-09-24 04:57:09 -07:00
};
struct Connection {
2012-09-24 20:13:01 -07:00
Request request;
Response response;
2012-09-22 21:40:46 -07:00
};
class Server {
public:
typedef std::function<void (Connection& c)> Handler;
2012-09-22 21:40:46 -07:00
2012-10-02 17:39:13 -07:00
Server(const char* host, int port);
2012-09-22 21:40:46 -07:00
~Server();
void get(const char* pattern, Handler handler);
void post(const char* pattern, Handler handler);
2012-09-22 21:40:46 -07:00
2012-10-03 17:11:22 -07:00
void set_error_handler(Handler handler);
2012-10-03 18:55:01 -07:00
void set_logger(Handler logger);
2012-09-27 17:54:54 -07:00
2012-09-25 19:09:56 -07:00
bool run();
2012-09-22 21:40:46 -07:00
void stop();
private:
2012-10-03 18:55:01 -07:00
typedef std::vector<std::pair<std::regex, Handler>> Handlers;
2012-09-22 21:40:46 -07:00
void process_request(socket_t sock);
2012-10-02 19:37:14 -07:00
bool read_request_line(FILE* fp, Request& req);
2012-10-03 21:38:32 -07:00
bool routing(Connection& c);
bool dispatch_request(Connection& c, Handlers& handlers);
2012-10-02 17:39:13 -07:00
const std::string host_;
2012-09-25 19:09:56 -07:00
const int port_;
socket_t svr_sock_;
2012-09-27 17:54:54 -07:00
2012-10-03 18:55:01 -07:00
Handlers get_handlers_;
Handlers post_handlers_;
Handler error_handler_;
Handler logger_;
2012-10-02 17:39:13 -07:00
};
class Client {
public:
Client(const char* host, int port);
~Client();
std::shared_ptr<Response> get(const char* url);
std::shared_ptr<Response> post(
const char* url, const std::string& body, const char* content_type);
bool send(const Request& req, Response& res);
2012-10-02 17:39:13 -07:00
private:
2012-10-02 19:37:14 -07:00
bool read_response_line(FILE* fp, Response& res);
2012-10-02 17:39:13 -07:00
const std::string host_;
const int port_;
2012-09-22 21:40:46 -07:00
};
// Implementation
namespace detail {
2012-09-22 21:40:46 -07:00
2012-09-24 20:13:01 -07:00
template <class Fn>
void split(const char* b, const char* e, char d, Fn fn)
{
int i = 0;
int beg = 0;
while (e ? (b + i != e) : (b[i] != '\0')) {
if (b[i] == d) {
fn(&b[beg], &b[i]);
beg = i + 1;
}
i++;
}
2012-10-02 17:39:13 -07:00
if (i) {
2012-09-24 20:13:01 -07:00
fn(&b[beg], &b[i]);
}
}
2012-10-02 17:39:13 -07:00
inline void get_flie_pointers(int fd, FILE*& fp_read, FILE*& fp_write)
{
#ifdef _WIN32
int osfhandle = _open_osfhandle(fd, _O_RDONLY);
fp_read = fdopen(osfhandle, "rb");
fp_write = fdopen(osfhandle, "wb");
#else
fp_read = fdopen(fd, "rb");
fp_write = fdopen(fd, "wb");
#endif
}
template <typename Fn>
2012-10-03 17:11:22 -07:00
socket_t create_socket(const char* host, int port, Fn fn)
2012-09-22 21:40:46 -07:00
{
2012-09-25 19:09:56 -07:00
#ifdef _WIN32
int opt = SO_SYNCHRONOUS_NONALERT;
setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
#endif
// Create a socket
2012-09-22 21:40:46 -07:00
socket_t sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
return -1;
}
// Make 'reuse address' option available
2012-09-25 19:09:56 -07:00
int yes = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
2012-09-22 21:40:46 -07:00
// Get a host entry info
struct hostent* hp;
2012-10-02 17:39:13 -07:00
if (!(hp = gethostbyname(host))) {
return -1;
}
2012-09-22 21:40:46 -07:00
// Bind the socket to the given address
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
2012-09-22 21:40:46 -07:00
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
2012-09-22 21:40:46 -07:00
2012-10-02 17:39:13 -07:00
return fn(sock, addr);
}
2012-09-22 21:40:46 -07:00
2012-10-02 17:39:13 -07:00
inline socket_t create_server_socket(const char* host, int port)
{
return create_socket(host, port, [](socket_t sock, struct sockaddr_in& addr) -> socket_t {
if (::bind(sock, (struct sockaddr*)&addr, sizeof(addr))) {
return -1;
}
if (listen(sock, 5)) { // Listen through 5 channels
2012-10-02 17:39:13 -07:00
return -1;
}
return sock;
});
2012-09-22 21:40:46 -07:00
}
inline int shutdown_and_close_socket(socket_t sock)
2012-09-22 21:40:46 -07:00
{
#ifdef _WIN32
2012-09-26 18:35:49 -07:00
shutdown(sock, SD_BOTH);
return closesocket(sock);
2012-09-22 21:40:46 -07:00
#else
shutdown(sock, SHUT_RDWR);
2012-09-26 18:35:49 -07:00
return close(sock);
2012-09-22 21:40:46 -07:00
#endif
}
2012-10-02 17:39:13 -07:00
inline socket_t create_client_socket(const char* host, int port)
2012-09-25 20:21:57 -07:00
{
return create_socket(host, port, [](socket_t sock, struct sockaddr_in& addr) -> socket_t {
2012-10-02 17:39:13 -07:00
if (connect(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr_in))) {
return -1;
}
return sock;
});
}
2012-09-25 20:21:57 -07:00
2012-10-02 19:37:14 -07:00
inline const char* status_message(int status)
{
switch (status) {
case 400: return "Bad Request";
case 404: return "Not Found";
2012-10-02 19:37:14 -07:00
default:
status = 500;
return "Internal Server Error";
2012-10-02 19:37:14 -07:00
}
}
2012-10-03 17:11:22 -07:00
inline const char* get_header_value_text(const MultiMap& map, const char* key, const char* def)
2012-10-02 17:39:13 -07:00
{
auto it = map.find(key);
if (it != map.end()) {
return it->second.c_str();
}
return def;
}
inline int get_header_value_int(const MultiMap& map, const char* key, int def)
{
auto it = map.find(key);
if (it != map.end()) {
return std::atoi(it->second.c_str());
}
return def;
}
2012-10-03 18:55:01 -07:00
inline bool read_headers(FILE* fp, MultiMap& headers)
2012-10-02 17:39:13 -07:00
{
static std::regex re("(.+?): (.+?)\r\n");
const size_t BUFSIZ_HEADER = 2048;
char buf[BUFSIZ_HEADER];
2012-10-03 18:55:01 -07:00
for (;;) {
if (!fgets(buf, BUFSIZ_HEADER, fp)) {
return false;
}
if (!strcmp(buf, "\r\n")) {
break;
}
2012-10-02 17:39:13 -07:00
std::cmatch m;
if (std::regex_match(buf, m, re)) {
auto key = std::string(m[1]);
auto val = std::string(m[2]);
headers.insert(std::make_pair(key, val));
}
2012-09-25 20:21:57 -07:00
}
2012-10-03 18:55:01 -07:00
return true;
}
template <typename T>
bool read_content(T& x, FILE* fp)
{
auto len = get_header_value_int(x.headers, "Content-Length", 0);
if (len) {
x.body.assign(len, 0);
if (!fgets(&x.body[0], x.body.size() + 1, fp)) {
return false;
}
}
return true;
2012-10-02 17:39:13 -07:00
}
2012-10-03 20:47:59 -07:00
template <typename T>
inline void write_headers(FILE* fp, const T& x)
{
fprintf(fp, "Connection: close\r\n");
for (auto it = x.headers.begin(); it != x.headers.end(); ++it) {
if (it->first != "Content-Type" && it->first != "Content-Length") {
fprintf(fp, "%s: %s\r\n", it->first.c_str(), it->second.c_str());
}
}
if (!x.body.empty()) {
auto content_type = get_header_value_text(x.headers, "Content-Type", "text/plain");
fprintf(fp, "Content-Type: %s\r\n", content_type);
fprintf(fp, "Content-Length: %ld\r\n", x.body.size());
}
fprintf(fp, "\r\n");
}
inline void write_response(FILE* fp, const Response& res)
{
fprintf(fp, "HTTP/1.0 %d %s\r\n", res.status, status_message(res.status));
write_headers(fp, res);
if (!res.body.empty()) {
fprintf(fp, "%s", res.body.c_str());
}
}
inline void write_request(FILE* fp, const Request& req)
{
fprintf(fp, "%s %s HTTP/1.0\r\n", req.method.c_str(), req.url.c_str());
write_headers(fp, req);
if (!req.body.empty()) {
fprintf(fp, "%s", req.body.c_str());
}
}
inline void parse_query_text(const char* b, const char* e, Map& params)
{
split(b, e, '&', [&](const char* b, const char* e) {
std::string key;
std::string val;
split(b, e, '=', [&](const char* b, const char* e) {
if (key.empty()) {
key.assign(b, e);
} else {
val.assign(b, e);
}
});
params[key] = val;
});
}
inline void parse_query_text(const std::string& s, Map& params)
{
parse_query_text(&s[0], &s[s.size()], params);
}
} // namespace detail
// Request implementation
2012-10-03 17:11:22 -07:00
inline bool Request::has_header(const char* key) const
2012-10-02 17:39:13 -07:00
{
2012-10-03 17:11:22 -07:00
return headers.find(key) != headers.end();
}
2012-09-25 20:21:57 -07:00
2012-10-03 17:11:22 -07:00
inline std::string Request::get_header_value(const char* key) const
{
return detail::get_header_value_text(headers, key, "");
2012-10-03 17:11:22 -07:00
}
2012-09-25 20:21:57 -07:00
2012-10-03 20:47:59 -07:00
inline void Request::set_header(const char* key, const char* val)
{
headers.insert(std::make_pair(key, val));
}
inline bool Request::has_param(const char* key) const
{
return params.find(key) != params.end();
}
// Response implementation
2012-10-03 17:11:22 -07:00
inline bool Response::has_header(const char* key) const
{
return headers.find(key) != headers.end();
}
inline std::string Response::get_header_value(const char* key) const
{
return detail::get_header_value_text(headers, key, "");
2012-10-03 17:11:22 -07:00
}
inline void Response::set_header(const char* key, const char* val)
{
headers.insert(std::make_pair(key, val));
2012-09-25 20:21:57 -07:00
}
2012-10-02 17:39:13 -07:00
inline void Response::set_redirect(const char* url)
2012-09-25 19:09:56 -07:00
{
2012-10-03 17:11:22 -07:00
set_header("Location", url);
2012-09-25 19:09:56 -07:00
status = 302;
}
2012-10-02 17:39:13 -07:00
inline void Response::set_content(const std::string& s, const char* content_type)
2012-09-25 19:09:56 -07:00
{
body = s;
2012-10-03 17:11:22 -07:00
set_header("Content-Type", content_type);
2012-09-25 19:09:56 -07:00
}
// HTTP server implementation
2012-10-02 17:39:13 -07:00
inline Server::Server(const char* host, int port)
: host_(host)
2012-09-25 19:09:56 -07:00
, port_(port)
, svr_sock_(-1)
2012-09-22 21:40:46 -07:00
{
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(0x0002, &wsaData);
#endif
}
inline Server::~Server()
{
#ifdef _WIN32
WSACleanup();
#endif
}
inline void Server::get(const char* pattern, Handler handler)
2012-09-22 21:40:46 -07:00
{
2012-09-24 20:13:01 -07:00
get_handlers_.push_back(std::make_pair(pattern, handler));
2012-09-22 21:40:46 -07:00
}
inline void Server::post(const char* pattern, Handler handler)
2012-09-22 21:40:46 -07:00
{
2012-09-24 20:13:01 -07:00
post_handlers_.push_back(std::make_pair(pattern, handler));
2012-09-22 21:40:46 -07:00
}
2012-10-03 17:11:22 -07:00
inline void Server::set_error_handler(Handler handler)
2012-09-27 17:54:54 -07:00
{
2012-10-02 19:37:14 -07:00
error_handler_ = handler;
2012-09-27 17:54:54 -07:00
}
2012-10-03 18:55:01 -07:00
inline void Server::set_logger(Handler logger)
2012-10-02 17:39:13 -07:00
{
logger_ = logger;
}
2012-09-25 19:09:56 -07:00
inline bool Server::run()
2012-09-22 21:40:46 -07:00
{
svr_sock_ = detail::create_server_socket(host_.c_str(), port_);
if (svr_sock_ == -1) {
2012-09-22 21:40:46 -07:00
return false;
}
2012-09-27 17:54:54 -07:00
2012-09-22 21:40:46 -07:00
for (;;) {
socket_t sock = accept(svr_sock_, NULL, NULL);
if (sock == -1) {
if (svr_sock_ == -1) {
// The server socket was closed by user.
2012-09-22 21:40:46 -07:00
return true;
} else {
detail::shutdown_and_close_socket(svr_sock_);
return false;
}
2012-09-22 21:40:46 -07:00
}
// TODO: should be async
process_request(sock);
detail::shutdown_and_close_socket(sock);
2012-09-22 21:40:46 -07:00
}
// NOTREACHED
}
inline void Server::stop()
{
detail::shutdown_and_close_socket(svr_sock_);
svr_sock_ = -1;
2012-09-22 21:40:46 -07:00
}
2012-10-02 19:37:14 -07:00
inline bool Server::read_request_line(FILE* fp, Request& req)
2012-09-22 21:40:46 -07:00
{
2012-09-24 04:57:09 -07:00
const size_t BUFSIZ_REQUESTLINE = 2048;
char buf[BUFSIZ_REQUESTLINE];
2012-10-02 17:39:13 -07:00
if (!fgets(buf, BUFSIZ_REQUESTLINE, fp)) {
return false;
}
static std::regex re("(GET|POST) ([^?]+)(?:\\?(.+?))? HTTP/1\\.[01]\r\n");
2012-09-24 04:57:09 -07:00
2012-09-22 21:40:46 -07:00
std::cmatch m;
2012-09-24 04:57:09 -07:00
if (std::regex_match(buf, m, re)) {
2012-10-02 19:37:14 -07:00
req.method = std::string(m[1]);
req.url = std::string(m[2]);
2012-09-24 20:13:01 -07:00
// Parse query text
auto len = std::distance(m[3].first, m[3].second);
if (len > 0) {
const auto& pos = m[3];
detail::parse_query_text(pos.first, pos.second, req.params);
2012-09-24 20:13:01 -07:00
}
2012-09-22 21:40:46 -07:00
return true;
}
2012-09-24 04:57:09 -07:00
2012-09-22 21:40:46 -07:00
return false;
}
2012-10-03 21:38:32 -07:00
inline bool Server::routing(Connection& c)
{
if (c.request.method == "GET") {
return dispatch_request(c, get_handlers_);
} else if (c.request.method == "POST") {
return dispatch_request(c, post_handlers_);
}
return false;
}
inline bool Server::dispatch_request(Connection& c, Handlers& handlers)
2012-10-03 18:55:01 -07:00
{
for (auto it = handlers.begin(); it != handlers.end(); ++it) {
const auto& pattern = it->first;
const auto& handler = it->second;
2012-10-03 20:47:59 -07:00
if (std::regex_match(c.request.url, c.request.matches, pattern)) {
2012-10-03 18:55:01 -07:00
handler(c);
2012-10-03 21:38:32 -07:00
return true;
2012-10-03 18:55:01 -07:00
}
}
2012-10-03 21:38:32 -07:00
return false;
2012-10-03 18:55:01 -07:00
}
inline void Server::process_request(socket_t sock)
2012-09-22 21:40:46 -07:00
{
FILE* fp_read;
FILE* fp_write;
detail::get_flie_pointers(sock, fp_read, fp_write);
Connection c;
2012-09-24 20:13:01 -07:00
if (!read_request_line(fp_read, c.request) ||
!detail::read_headers(fp_read, c.request.headers)) {
2012-09-24 20:13:01 -07:00
return;
}
if (c.request.method == "POST") {
if (!detail::read_content(c.request, fp_read)) {
2012-10-03 18:55:01 -07:00
return;
}
if (c.request.get_header_value("Content-Type") == "application/x-www-form-urlencoded") {
detail::parse_query_text(c.request.body, c.request.params);
2012-10-03 20:47:59 -07:00
}
2012-09-24 20:13:01 -07:00
}
2012-10-03 21:38:32 -07:00
if (routing(c)) {
if (c.response.status == -1) {
c.response.status = 200;
}
} else {
c.response.status = 404;
2012-10-02 19:37:14 -07:00
}
2012-10-03 21:38:32 -07:00
assert(c.response.status != -1);
2012-10-02 19:37:14 -07:00
2012-10-03 21:38:32 -07:00
if (400 <= c.response.status && error_handler_) {
2012-10-03 18:55:01 -07:00
error_handler_(c);
2012-10-02 19:37:14 -07:00
}
detail::write_response(fp_write, c.response);
fflush(fp_write);
2012-10-03 18:55:01 -07:00
2012-10-02 17:39:13 -07:00
if (logger_) {
logger_(c);
}
2012-09-22 21:40:46 -07:00
}
2012-10-02 17:39:13 -07:00
// HTTP client implementation
inline Client::Client(const char* host, int port)
: host_(host)
, port_(port)
{
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(0x0002, &wsaData);
#endif
}
inline Client::~Client()
{
#ifdef _WIN32
WSACleanup();
#endif
}
2012-10-02 19:37:14 -07:00
inline bool Client::read_response_line(FILE* fp, Response& res)
2012-10-02 17:39:13 -07:00
{
const size_t BUFSIZ_RESPONSELINE = 2048;
char buf[BUFSIZ_RESPONSELINE];
if (!fgets(buf, BUFSIZ_RESPONSELINE, fp)) {
return false;
}
static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
std::cmatch m;
if (std::regex_match(buf, m, re)) {
2012-10-02 19:37:14 -07:00
res.status = std::atoi(std::string(m[1]).c_str());
2012-10-02 17:39:13 -07:00
}
return true;
}
2012-10-03 20:47:59 -07:00
inline bool Client::send(const Request& req, Response& res)
2012-10-02 17:39:13 -07:00
{
socket_t sock = detail::create_client_socket(host_.c_str(), port_);
2012-10-02 17:39:13 -07:00
if (sock == -1) {
2012-10-02 20:24:23 -07:00
return false;
2012-10-02 17:39:13 -07:00
}
FILE* fp_read;
FILE* fp_write;
detail::get_flie_pointers(sock, fp_read, fp_write);
2012-10-02 17:39:13 -07:00
// Send request
detail::write_request(fp_write, req);
2012-10-02 17:39:13 -07:00
fflush(fp_write);
2012-10-03 18:55:01 -07:00
if (!read_response_line(fp_read, res) ||
!detail::read_headers(fp_read, res.headers) ||
!detail::read_content(res, fp_read)) {
2012-10-02 20:24:23 -07:00
return false;
2012-10-02 17:39:13 -07:00
}
detail::shutdown_and_close_socket(sock);
2012-10-02 17:39:13 -07:00
2012-10-03 17:11:22 -07:00
return true;
2012-10-02 17:39:13 -07:00
}
inline std::shared_ptr<Response> Client::get(const char* url)
{
Request req;
req.method = "GET";
req.url = url;
auto res = std::make_shared<Response>();
return send(req, *res) ? res : nullptr;
}
inline std::shared_ptr<Response> Client::post(
const char* url, const std::string& body, const char* content_type)
{
Request req;
req.method = "POST";
req.url = url;
req.set_header("Content-Type", content_type);
req.body = body;
auto res = std::make_shared<Response>();
return send(req, *res) ? res : nullptr;
}
2012-09-27 18:05:36 -07:00
} // namespace httplib
2012-09-22 21:40:46 -07:00
2012-09-25 19:09:56 -07:00
#endif
2012-09-22 21:40:46 -07:00
// vim: et ts=4 sw=4 cin cino={1s ff=unix