cpp-httplib/httplib.h

956 lines
22 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-10-11 20:52:34 -07:00
#ifndef _CPPHTTPLIB_HTTPSLIB_H_
#define _CPPHTTPLIB_HTTPSLIB_H_
2012-09-25 19:09:56 -07:00
2013-07-04 15:18:52 -07:00
#ifdef _MSC_VER
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
2016-03-04 14:49:15 -07:00
#define SO_SYNCHRONOUS_NONALERT 0x20
2012-09-25 19:09:56 -07:00
#endif
#ifndef SO_OPENTYPE
#define SO_OPENTYPE 0x7008
#endif
2015-08-04 15:13:39 -07:00
#if (_MSC_VER < 1900)
2012-10-12 13:09:39 -07:00
#define snprintf _snprintf_s
#endif
2013-07-04 15:18:52 -07:00
2015-07-15 13:41:11 -07:00
#define S_ISREG(m) (((m)&S_IFREG)==S_IFREG)
#define S_ISDIR(m) (((m)&S_IFDIR)==S_IFDIR)
2012-09-25 19:09:56 -07:00
#include <fcntl.h>
#include <io.h>
2012-09-22 21:40:46 -07:00
#include <winsock2.h>
2015-01-14 16:51:53 -07:00
#include <ws2tcpip.h>
2012-09-22 21:40:46 -07:00
#undef min
#undef max
2012-09-22 21:40:46 -07:00
typedef SOCKET socket_t;
#else
#include <pthread.h>
#include <unistd.h>
#include <netdb.h>
2013-04-24 03:09:19 -07:00
#include <cstring>
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
2013-07-04 15:18:52 -07:00
#include <fstream>
#include <functional>
#include <map>
2013-04-24 03:09:19 -07:00
#include <memory>
#include <regex>
#include <string>
2015-01-14 16:51:53 -07:00
#include <sys/stat.h>
#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);
void set_content(const char* s, size_t n, const char* content_type);
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
};
2012-09-22 21:40:46 -07:00
class Server {
public:
2012-10-12 13:09:39 -07:00
typedef std::function<void (const Request&, Response&)> Handler;
2012-10-12 14:41:58 -07:00
typedef std::function<void (const Request&, const Response&)> Logger;
2012-09-22 21:40:46 -07:00
2012-10-12 13:09:39 -07:00
Server();
2012-09-22 21:40:46 -07:00
void get(const char* pattern, Handler handler);
void post(const char* pattern, Handler handler);
2012-09-22 21:40:46 -07:00
2013-07-04 19:08:06 -07:00
bool set_base_dir(const char* path);
2013-07-04 15:18:52 -07:00
2012-10-03 17:11:22 -07:00
void set_error_handler(Handler handler);
2012-10-12 14:41:58 -07:00
void set_logger(Logger logger);
2012-09-27 17:54:54 -07:00
2012-10-12 13:09:39 -07:00
bool listen(const char* host, int port);
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(FILE* fp_read, FILE* fp_write);
2012-10-02 19:37:14 -07:00
bool read_request_line(FILE* fp, Request& req);
2012-10-12 13:09:39 -07:00
bool routing(Request& req, Response& res);
2015-07-15 13:41:11 -07:00
bool handle_file_request(Request& req, Response& res);
bool dispatch_request(Request& req, Response& res, Handlers& handlers);
2013-07-04 15:18:52 -07:00
socket_t svr_sock_;
std::string base_dir_;
Handlers get_handlers_;
Handlers post_handlers_;
Handler error_handler_;
Logger logger_;
2012-10-02 17:39:13 -07:00
};
class Client {
public:
Client(const char* host, int port);
std::shared_ptr<Response> get(const char* url);
2012-10-12 14:41:58 -07:00
std::shared_ptr<Response> head(const char* url);
2012-10-11 20:52:34 -07:00
std::shared_ptr<Response> post(const char* url, const std::string& body, const char* content_type);
std::shared_ptr<Response> post(const char* url, const Map& params);
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]);
}
}
template <typename T>
inline bool read_and_close_socket(socket_t sock, T callback)
2012-10-02 17:39:13 -07:00
{
FILE* fp_read;
FILE* fp_write;
2013-07-04 15:18:52 -07:00
#ifdef _MSC_VER
fp_read = _fdopen(_open_osfhandle(sock, _O_RDONLY), "rb");
fp_write = _fdopen(_open_osfhandle(sock, _O_WRONLY), "wb");
2012-10-02 17:39:13 -07:00
#else
fp_read = fdopen(sock, "rb");
fp_write = fdopen(sock, "wb");
#endif
auto ret = callback(fp_read, fp_write);
fclose(fp_read);
fclose(fp_write);
return ret;
2012-10-02 17:39:13 -07:00
}
2015-01-14 16:51:53 -07:00
inline int shutdown_socket(socket_t sock)
{
#ifdef _MSC_VER
return shutdown(sock, SD_BOTH);
#else
return shutdown(sock, SHUT_RDWR);
#endif
}
inline int close_socket(socket_t sock)
{
#ifdef _MSC_VER
return closesocket(sock);
#else
return close(sock);
#endif
}
2012-10-02 17:39:13 -07:00
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
{
2013-07-04 15:18:52 -07:00
#ifdef _MSC_VER
2012-09-25 19:09:56 -07:00
int opt = SO_SYNCHRONOUS_NONALERT;
setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
#endif
2015-01-14 16:51:53 -07:00
// Get address info
struct addrinfo hints;
struct addrinfo *result;
2012-09-22 21:40:46 -07:00
2015-01-14 16:51:53 -07:00
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;
2012-09-22 21:40:46 -07:00
2015-01-14 16:51:53 -07:00
auto service = std::to_string(port);
if (getaddrinfo(host, service.c_str(), &hints, &result)) {
return -1;
}
2015-01-14 16:51:53 -07:00
for (auto rp = result; rp; rp = rp->ai_next) {
// Create a socket
auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == -1) {
continue;
}
// Make 'reuse address' option available
int yes = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
// bind or connect
if (fn(sock, *rp)) {
freeaddrinfo(result);
return sock;
}
2012-09-22 21:40:46 -07:00
2015-01-14 16:51:53 -07:00
close_socket(sock);
}
freeaddrinfo(result);
return -1;
2012-10-02 17:39:13 -07:00
}
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)
{
2015-01-14 16:51:53 -07:00
return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
return false;
2012-10-02 17:39:13 -07:00
}
if (listen(sock, 5)) { // Listen through 5 channels
2015-01-14 16:51:53 -07:00
return false;
2012-10-02 17:39:13 -07:00
}
2015-01-14 16:51:53 -07:00
return true;
2012-10-02 17:39:13 -07:00
});
2012-09-22 21:40:46 -07:00
}
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
{
2015-01-14 16:51:53 -07:00
return create_socket(host, port, [](socket_t sock, struct addrinfo& ai) -> socket_t {
if (connect(sock, ai.ai_addr, ai.ai_addrlen)) {
return false;
2012-10-02 17:39:13 -07:00
}
2015-01-14 16:51:53 -07:00
return true;
2012-10-02 17:39:13 -07:00
});
}
2012-09-25 20:21:57 -07:00
2013-07-04 15:18:52 -07:00
inline bool is_file(const std::string& s)
{
2015-07-15 13:41:11 -07:00
struct stat st;
return stat(s.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
2013-07-04 19:08:06 -07:00
}
inline bool is_dir(const std::string& s)
{
2015-07-15 13:41:11 -07:00
struct stat st;
return stat(s.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
2013-07-04 15:18:52 -07:00
}
inline void read_file(const std::string& path, std::string& out)
{
2015-07-16 17:26:26 -07:00
std::ifstream fs(path, std::ios_base::binary);
2015-07-15 13:41:11 -07:00
fs.seekg(0, std::ios_base::end);
auto size = fs.tellg();
fs.seekg(0);
2015-07-16 17:26:26 -07:00
out.resize(size);
2015-07-15 13:41:11 -07:00
fs.read(&out[0], size);
2013-07-04 15:18:52 -07:00
}
inline std::string get_file_extention(const std::string& path)
{
2015-07-15 13:41:11 -07:00
std::smatch m;
auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
auto ret = std::regex_search(path, m, pat);
std::string content_type;
if (ret) {
return m[1].str();
}
return std::string();
2013-07-04 15:18:52 -07:00
}
inline const char* get_content_type_from_file_extention(const std::string& ext)
{
2015-07-15 13:41:11 -07:00
if (ext == "html") {
return "text/html";
}
return "text/plain";
2013-07-04 15:18:52 -07:00
}
2012-10-02 19:37:14 -07:00
inline const char* status_message(int status)
{
switch (status) {
2012-10-12 14:41:58 -07:00
case 200: return "OK";
case 400: return "Bad Request";
case 404: return "Not Found";
2012-10-02 19:37:14 -07:00
default:
2012-10-12 14:41:58 -07:00
case 500: return "Internal Server Error";
2012-10-02 19:37:14 -07:00
}
}
2013-05-11 13:11:30 -07:00
inline const char* get_header_value(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()) {
2013-04-24 03:09:19 -07:00
return std::stoi(it->second);
2012-10-02 17:39:13 -07:00
}
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");
2012-11-07 18:54:39 -07:00
const auto BUFSIZ_HEADER = 2048;
2012-10-02 17:39:13 -07:00
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 (!fread(&x.body[0], x.body.size(), 1, fp)) {
2012-10-03 18:55:01 -07:00
return false;
}
}
return true;
2012-10-02 17:39:13 -07:00
}
2012-10-03 20:47:59 -07:00
template <typename T>
2013-05-11 13:11:30 -07:00
inline void write_headers(FILE* fp, const T& res)
2012-10-03 20:47:59 -07:00
{
fprintf(fp, "Connection: close\r\n");
2013-05-11 13:11:30 -07:00
for (const auto& x: res.headers) {
if (x.first != "Content-Type" && x.first != "Content-Length") {
fprintf(fp, "%s: %s\r\n", x.first.c_str(), x.second.c_str());
2012-10-03 20:47:59 -07:00
}
}
2015-01-14 16:51:53 -07:00
auto t = get_header_value(res.headers, "Content-Type", "text/plain");
fprintf(fp, "Content-Type: %s\r\n", t);
2015-07-15 13:39:57 -07:00
fprintf(fp, "Content-Length: %ld\r\n", res.body.size());
2012-10-03 20:47:59 -07:00
fprintf(fp, "\r\n");
}
2012-10-12 14:41:58 -07:00
inline void write_response(FILE* fp, const Request& req, const Response& res)
2012-10-03 20:47:59 -07:00
{
fprintf(fp, "HTTP/1.0 %d %s\r\n", res.status, status_message(res.status));
write_headers(fp, res);
2012-10-12 14:41:58 -07:00
if (!res.body.empty() && req.method != "HEAD") {
2012-10-03 20:47:59 -07:00
fprintf(fp, "%s", res.body.c_str());
}
}
2012-10-11 20:52:34 -07:00
inline std::string encode_url(const std::string& s)
{
std::string result;
2012-11-07 18:54:39 -07:00
for (auto i = 0; s[i]; i++) {
2012-10-11 20:52:34 -07:00
switch (s[i]) {
2012-10-11 21:01:56 -07:00
case ' ': result += "+"; break;
2012-10-11 20:52:34 -07:00
case '\'': result += "%27"; break;
case ',': result += "%2C"; break;
case ':': result += "%3A"; break;
case ';': result += "%3B"; break;
default:
if (s[i] < 0) {
result += '%';
char hex[4];
2012-10-12 13:09:39 -07:00
size_t len = snprintf(hex, sizeof(hex), "%02X", (unsigned char)s[i]);
2012-10-11 20:52:34 -07:00
assert(len == 2);
result.append(hex, len);
} else {
result += s[i];
}
break;
}
2012-11-07 18:54:39 -07:00
}
2012-10-11 20:52:34 -07:00
return result;
}
inline bool is_hex(char c, int& v)
{
if (0x20 <= c && isdigit(c)) {
v = c - '0';
return true;
} else if ('A' <= c && c <= 'F') {
v = c - 'A' + 10;
return true;
} else if ('a' <= c && c <= 'f') {
v = c - 'a' + 10;
return true;
}
return false;
}
inline int from_hex_to_i(const std::string& s, int i, int cnt, int& val)
{
val = 0;
for (; s[i] && cnt; i++, cnt--) {
int v = 0;
if (is_hex(s[i], v)) {
val = val * 16 + v;
} else {
break;
}
}
return --i;
}
2015-01-14 16:51:53 -07:00
inline size_t to_utf8(int code, char* buff)
2012-10-11 20:52:34 -07:00
{
if (code < 0x0080) {
2012-10-12 13:09:39 -07:00
buff[0] = (code & 0x7F);
2012-10-11 20:52:34 -07:00
return 1;
} else if (code < 0x0800) {
2012-10-12 13:09:39 -07:00
buff[0] = (0xC0 | ((code >> 6) & 0x1F));
buff[1] = (0x80 | (code & 0x3F));
2012-10-11 20:52:34 -07:00
return 2;
} else if (code < 0xD800) {
2012-10-12 13:09:39 -07:00
buff[0] = (0xE0 | ((code >> 12) & 0xF));
buff[1] = (0x80 | ((code >> 6) & 0x3F));
buff[2] = (0x80 | (code & 0x3F));
2012-10-11 20:52:34 -07:00
return 3;
} else if (code < 0xE000) { // D800 - DFFF is invalid...
return 0;
} else if (code < 0x10000) {
2012-10-12 13:09:39 -07:00
buff[0] = (0xE0 | ((code >> 12) & 0xF));
buff[1] = (0x80 | ((code >> 6) & 0x3F));
buff[2] = (0x80 | (code & 0x3F));
2012-10-11 20:52:34 -07:00
return 3;
} else if (code < 0x110000) {
2012-10-12 13:09:39 -07:00
buff[0] = (0xF0 | ((code >> 18) & 0x7));
buff[1] = (0x80 | ((code >> 12) & 0x3F));
buff[2] = (0x80 | ((code >> 6) & 0x3F));
buff[3] = (0x80 | (code & 0x3F));
2012-10-11 20:52:34 -07:00
return 4;
}
// NOTREACHED
2012-10-12 13:09:39 -07:00
return 0;
2012-10-11 20:52:34 -07:00
}
inline std::string decode_url(const std::string& s)
{
std::string result;
for (int i = 0; s[i]; i++) {
if (s[i] == '%') {
i++;
assert(s[i]);
if (s[i] == '%') {
result += s[i];
} else if (s[i] == 'u') {
// Unicode
i++;
assert(s[i]);
int val = 0;
i = from_hex_to_i(s, i, 4, val);
char buff[4];
size_t len = to_utf8(val, buff);
if (len > 0) {
result.append(buff, len);
}
} else {
2012-10-12 13:09:39 -07:00
// HEX
2012-10-11 20:52:34 -07:00
int val = 0;
i = from_hex_to_i(s, i, 2, val);
2012-10-12 13:09:39 -07:00
result += val;
2012-10-11 20:52:34 -07:00
}
} else if (s[i] == '+') {
result += ' ';
} else {
result += s[i];
}
}
return result;
}
2012-10-03 20:47:59 -07:00
inline void write_request(FILE* fp, const Request& req)
{
2012-10-11 20:52:34 -07:00
auto url = encode_url(req.url);
fprintf(fp, "%s %s HTTP/1.0\r\n", req.method.c_str(), url.c_str());
2012-10-03 20:47:59 -07:00
write_headers(fp, req);
if (!req.body.empty()) {
2012-10-11 20:52:34 -07:00
if (req.has_header("application/x-www-form-urlencoded")) {
fprintf(fp, "%s", encode_url(req.body).c_str());
} else {
fprintf(fp, "%s", req.body.c_str());
}
2012-10-03 20:47:59 -07:00
}
}
2012-10-11 20:52:34 -07:00
inline void parse_query_text(const std::string& s, Map& params)
2012-10-03 20:47:59 -07:00
{
2012-10-11 20:52:34 -07:00
split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
2012-10-03 20:47:59 -07:00
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] = detail::decode_url(val);
2012-10-03 20:47:59 -07:00
});
}
2013-07-04 15:18:52 -07:00
#ifdef _MSC_VER
class WSInit {
public:
2016-03-04 14:49:15 -07:00
WSInit() {
WSADATA wsaData;
WSAStartup(0x0002, &wsaData);
}
2016-03-04 14:49:15 -07:00
~WSInit() {
WSACleanup();
}
};
static WSInit wsinit_;
#endif
} // 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
{
2013-05-11 13:11:30 -07:00
return detail::get_header_value(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
{
2013-05-11 13:11:30 -07:00
return detail::get_header_value(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;
}
inline void Response::set_content(const char* s, size_t n, const char* content_type)
{
body.assign(s, n);
set_header("Content-Type", content_type);
}
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-12 13:09:39 -07:00
inline Server::Server()
: svr_sock_(-1)
2012-09-22 21:40:46 -07:00
{
}
inline void Server::get(const char* pattern, Handler handler)
2012-09-22 21:40:46 -07:00
{
2012-10-11 20:52:34 -07:00
get_handlers_.push_back(std::make_pair(std::regex(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-10-11 20:52:34 -07:00
post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
2012-09-22 21:40:46 -07:00
}
2013-07-04 19:08:06 -07:00
inline bool Server::set_base_dir(const char* path)
2013-07-04 15:18:52 -07:00
{
2013-07-04 19:08:06 -07:00
if (detail::is_dir(path)) {
base_dir_ = path;
return true;
}
return false;
2013-07-04 15:18:52 -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-12 14:41:58 -07:00
inline void Server::set_logger(Logger logger)
2012-10-02 17:39:13 -07:00
{
logger_ = logger;
}
2012-10-12 13:09:39 -07:00
inline bool Server::listen(const char* host, int port)
2012-09-22 21:40:46 -07:00
{
2012-10-12 13:09:39 -07:00
svr_sock_ = detail::create_server_socket(host, port);
if (svr_sock_ == -1) {
2012-09-22 21:40:46 -07:00
return false;
}
2012-10-11 20:52:34 -07:00
auto ret = true;
2012-09-22 21:40:46 -07:00
for (;;) {
socket_t sock = accept(svr_sock_, NULL, NULL);
2012-10-11 20:52:34 -07:00
if (sock == -1) {
2012-10-11 20:52:34 -07:00
if (svr_sock_ != -1) {
detail::close_socket(svr_sock_);
ret = false;
} else {
2012-10-11 20:52:34 -07:00
; // The server socket was closed by user.
}
2012-10-11 20:52:34 -07:00
break;
2012-09-22 21:40:46 -07:00
}
// TODO: should be async
detail::read_and_close_socket(sock, [this](FILE* fp_read, FILE* fp_write) {
process_request(fp_read, fp_write);
return true;
});
2012-09-22 21:40:46 -07:00
}
2012-10-11 20:52:34 -07:00
return ret;
2012-09-22 21:40:46 -07:00
}
inline void Server::stop()
{
2012-10-11 20:52:34 -07:00
detail::shutdown_socket(svr_sock_);
detail::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-11-07 18:54:39 -07:00
const auto BUFSIZ_REQUESTLINE = 2048;
2012-09-24 04:57:09 -07:00
char buf[BUFSIZ_REQUESTLINE];
2012-10-02 17:39:13 -07:00
if (!fgets(buf, BUFSIZ_REQUESTLINE, fp)) {
return false;
}
2012-10-12 14:41:58 -07:00
static std::regex re("(GET|HEAD|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]);
2012-10-11 20:52:34 -07:00
req.url = detail::decode_url(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) {
detail::parse_query_text(m[3], 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;
}
2013-07-04 15:18:52 -07:00
inline bool Server::handle_file_request(Request& req, Response& res)
{
2013-07-04 19:08:06 -07:00
if (!base_dir_.empty()) {
std::string path = base_dir_ + req.url;
2013-07-04 15:18:52 -07:00
2013-07-04 19:08:06 -07:00
if (!path.empty() && path.back() == '/') {
path += "index.html";
}
2013-07-04 15:18:52 -07:00
2013-07-04 19:08:06 -07:00
if (detail::is_file(path)) {
detail::read_file(path, res.body);
res.set_header("Content-Type",
detail::get_content_type_from_file_extention(
detail::get_file_extention(path)));
res.status = 200;
return true;
}
}
2013-07-04 15:18:52 -07:00
2015-07-15 13:41:11 -07:00
return false;
2013-07-04 15:18:52 -07:00
}
2012-10-12 13:09:39 -07:00
inline bool Server::routing(Request& req, Response& res)
2012-10-03 21:38:32 -07:00
{
2015-07-15 13:41:11 -07:00
if (req.method == "GET" && handle_file_request(req, res)) {
return true;
2013-07-04 15:18:52 -07:00
}
2012-10-12 14:41:58 -07:00
if (req.method == "GET" || req.method == "HEAD") {
2012-10-12 13:09:39 -07:00
return dispatch_request(req, res, get_handlers_);
} else if (req.method == "POST") {
return dispatch_request(req, res, post_handlers_);
2012-10-03 21:38:32 -07:00
}
return false;
}
2012-10-12 13:09:39 -07:00
inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
2012-10-03 18:55:01 -07:00
{
2013-05-11 13:11:30 -07:00
for (const auto& x: handlers) {
const auto& pattern = x.first;
const auto& handler = x.second;
2012-10-03 18:55:01 -07:00
2012-10-12 13:09:39 -07:00
if (std::regex_match(req.url, req.matches, pattern)) {
handler(req, res);
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(FILE* fp_read, FILE* fp_write)
2012-09-22 21:40:46 -07:00
{
2012-10-12 13:09:39 -07:00
Request req;
Response res;
2012-09-24 20:13:01 -07:00
2012-10-12 13:09:39 -07:00
if (!read_request_line(fp_read, req) ||
!detail::read_headers(fp_read, req.headers)) {
2012-09-24 20:13:01 -07:00
return;
}
2012-10-12 13:09:39 -07:00
if (req.method == "POST") {
if (!detail::read_content(req, fp_read)) {
2012-10-03 18:55:01 -07:00
return;
}
static std::string type = "application/x-www-form-urlencoded";
if (!req.get_header_value("Content-Type").compare(0, type.size(), type)) {
detail::parse_query_text(req.body, req.params);
2012-10-03 20:47:59 -07:00
}
2012-09-24 20:13:01 -07:00
}
2012-10-12 13:09:39 -07:00
if (routing(req, res)) {
if (res.status == -1) {
res.status = 200;
2012-10-03 21:38:32 -07:00
}
} else {
2012-10-12 13:09:39 -07:00
res.status = 404;
2012-10-02 19:37:14 -07:00
}
2012-10-12 13:09:39 -07:00
assert(res.status != -1);
2012-10-02 19:37:14 -07:00
2012-10-12 13:09:39 -07:00
if (400 <= res.status && error_handler_) {
error_handler_(req, res);
2012-10-02 19:37:14 -07:00
}
2012-10-12 14:41:58 -07:00
detail::write_response(fp_write, req, res);
fflush(fp_write);
2012-10-03 18:55:01 -07:00
2012-10-02 17:39:13 -07:00
if (logger_) {
2012-10-12 13:09:39 -07:00
logger_(req, res);
2012-10-02 17:39:13 -07:00
}
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)
{
}
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
{
2012-11-07 18:54:39 -07:00
const auto BUFSIZ_RESPONSELINE = 2048;
2012-10-02 17:39:13 -07:00
char buf[BUFSIZ_RESPONSELINE];
if (!fgets(buf, BUFSIZ_RESPONSELINE, fp)) {
return false;
}
2013-04-24 03:09:19 -07:00
const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
2012-10-02 17:39:13 -07:00
std::cmatch m;
if (std::regex_match(buf, m, re)) {
2013-04-24 03:09:19 -07:00
res.status = std::stoi(std::string(m[1]));
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
{
2012-11-07 18:54:39 -07:00
auto 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
}
return detail::read_and_close_socket(sock, [&](FILE* fp_read, FILE* fp_write) {
2015-07-15 13:41:11 -07:00
// Send request
detail::write_request(fp_write, req);
fflush(fp_write);
// Receive response
if (!read_response_line(fp_read, res) ||
!detail::read_headers(fp_read, res.headers)) {
return false;
}
if (req.method != "HEAD") {
if (!detail::read_content(res, fp_read)) {
return false;
}
}
2012-10-02 17:39:13 -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;
}
2012-10-12 14:41:58 -07:00
inline std::shared_ptr<Response> Client::head(const char* url)
{
Request req;
req.method = "HEAD";
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-10-11 20:52:34 -07:00
inline std::shared_ptr<Response> Client::post(
const char* url, const Map& params)
{
std::string query;
for (auto it = params.begin(); it != params.end(); ++it) {
if (it != params.begin()) {
query += "&";
}
query += it->first;
query += "=";
query += it->second;
}
return post(url, query, "application/x-www-form-urlencoded");
}
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