server-http.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. #include "common.h"
  2. #include "server-http.h"
  3. #include "server-common.h"
  4. #include <cpp-httplib/httplib.h>
  5. #include <functional>
  6. #include <string>
  7. #include <thread>
  8. // auto generated files (see README.md for details)
  9. #include "index.html.gz.hpp"
  10. #include "loading.html.hpp"
  11. //
  12. // HTTP implementation using cpp-httplib
  13. //
  14. class server_http_context::Impl {
  15. public:
  16. std::unique_ptr<httplib::Server> srv;
  17. };
  18. server_http_context::server_http_context()
  19. : pimpl(std::make_unique<server_http_context::Impl>())
  20. {}
  21. server_http_context::~server_http_context() = default;
  22. static void log_server_request(const httplib::Request & req, const httplib::Response & res) {
  23. // skip GH copilot requests when using default port
  24. if (req.path == "/v1/health") {
  25. return;
  26. }
  27. // reminder: this function is not covered by httplib's exception handler; if someone does more complicated stuff, think about wrapping it in try-catch
  28. SRV_INF("request: %s %s %s %d\n", req.method.c_str(), req.path.c_str(), req.remote_addr.c_str(), res.status);
  29. SRV_DBG("request: %s\n", req.body.c_str());
  30. SRV_DBG("response: %s\n", res.body.c_str());
  31. }
  32. bool server_http_context::init(const common_params & params) {
  33. path_prefix = params.api_prefix;
  34. port = params.port;
  35. hostname = params.hostname;
  36. auto & srv = pimpl->srv;
  37. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  38. if (params.ssl_file_key != "" && params.ssl_file_cert != "") {
  39. LOG_INF("Running with SSL: key = %s, cert = %s\n", params.ssl_file_key.c_str(), params.ssl_file_cert.c_str());
  40. srv.reset(
  41. new httplib::SSLServer(params.ssl_file_cert.c_str(), params.ssl_file_key.c_str())
  42. );
  43. } else {
  44. LOG_INF("Running without SSL\n");
  45. srv.reset(new httplib::Server());
  46. }
  47. #else
  48. if (params.ssl_file_key != "" && params.ssl_file_cert != "") {
  49. LOG_ERR("Server is built without SSL support\n");
  50. return false;
  51. }
  52. srv.reset(new httplib::Server());
  53. #endif
  54. srv->set_default_headers({{"Server", "llama.cpp"}});
  55. srv->set_logger(log_server_request);
  56. srv->set_exception_handler([](const httplib::Request &, httplib::Response & res, const std::exception_ptr & ep) {
  57. // this is fail-safe; exceptions should already handled by `ex_wrapper`
  58. std::string message;
  59. try {
  60. std::rethrow_exception(ep);
  61. } catch (const std::exception & e) {
  62. message = e.what();
  63. } catch (...) {
  64. message = "Unknown Exception";
  65. }
  66. res.status = 500;
  67. res.set_content(message, "text/plain");
  68. LOG_ERR("got exception: %s\n", message.c_str());
  69. });
  70. srv->set_error_handler([](const httplib::Request &, httplib::Response & res) {
  71. if (res.status == 404) {
  72. res.set_content(
  73. safe_json_to_str(json {
  74. {"error", {
  75. {"message", "File Not Found"},
  76. {"type", "not_found_error"},
  77. {"code", 404}
  78. }}
  79. }),
  80. "application/json; charset=utf-8"
  81. );
  82. }
  83. // for other error codes, we skip processing here because it's already done by res->error()
  84. });
  85. // set timeouts and change hostname and port
  86. srv->set_read_timeout (params.timeout_read);
  87. srv->set_write_timeout(params.timeout_write);
  88. if (params.api_keys.size() == 1) {
  89. auto key = params.api_keys[0];
  90. std::string substr = key.substr(std::max((int)(key.length() - 4), 0));
  91. LOG_INF("%s: api_keys: ****%s\n", __func__, substr.c_str());
  92. } else if (params.api_keys.size() > 1) {
  93. LOG_INF("%s: api_keys: %zu keys loaded\n", __func__, params.api_keys.size());
  94. }
  95. //
  96. // Middlewares
  97. //
  98. auto middleware_validate_api_key = [api_keys = params.api_keys](const httplib::Request & req, httplib::Response & res) {
  99. static const std::unordered_set<std::string> public_endpoints = {
  100. "/health",
  101. "/v1/health",
  102. "/models",
  103. "/v1/models",
  104. "/api/tags"
  105. };
  106. // If API key is not set, skip validation
  107. if (api_keys.empty()) {
  108. return true;
  109. }
  110. // If path is public or is static file, skip validation
  111. if (public_endpoints.find(req.path) != public_endpoints.end() || req.path == "/") {
  112. return true;
  113. }
  114. // Check for API key in the header
  115. auto auth_header = req.get_header_value("Authorization");
  116. std::string prefix = "Bearer ";
  117. if (auth_header.substr(0, prefix.size()) == prefix) {
  118. std::string received_api_key = auth_header.substr(prefix.size());
  119. if (std::find(api_keys.begin(), api_keys.end(), received_api_key) != api_keys.end()) {
  120. return true; // API key is valid
  121. }
  122. }
  123. // API key is invalid or not provided
  124. res.status = 401;
  125. res.set_content(
  126. safe_json_to_str(json {
  127. {"error", {
  128. {"message", "Invalid API Key"},
  129. {"type", "authentication_error"},
  130. {"code", 401}
  131. }}
  132. }),
  133. "application/json; charset=utf-8"
  134. );
  135. LOG_WRN("Unauthorized: Invalid API Key\n");
  136. return false;
  137. };
  138. auto middleware_server_state = [this](const httplib::Request & req, httplib::Response & res) {
  139. bool ready = is_ready.load();
  140. if (!ready) {
  141. auto tmp = string_split<std::string>(req.path, '.');
  142. if (req.path == "/" || tmp.back() == "html") {
  143. res.set_content(reinterpret_cast<const char*>(loading_html), loading_html_len, "text/html; charset=utf-8");
  144. res.status = 503;
  145. } else if (req.path == "/models" || req.path == "/v1/models" || req.path == "/api/tags") {
  146. // allow the models endpoint to be accessed during loading
  147. return true;
  148. } else {
  149. res.status = 503;
  150. res.set_content(
  151. safe_json_to_str(json {
  152. {"error", {
  153. {"message", "Loading model"},
  154. {"type", "unavailable_error"},
  155. {"code", 503}
  156. }}
  157. }),
  158. "application/json; charset=utf-8"
  159. );
  160. }
  161. return false;
  162. }
  163. return true;
  164. };
  165. // register server middlewares
  166. srv->set_pre_routing_handler([middleware_validate_api_key, middleware_server_state](const httplib::Request & req, httplib::Response & res) {
  167. res.set_header("Access-Control-Allow-Origin", req.get_header_value("Origin"));
  168. // If this is OPTIONS request, skip validation because browsers don't include Authorization header
  169. if (req.method == "OPTIONS") {
  170. res.set_header("Access-Control-Allow-Credentials", "true");
  171. res.set_header("Access-Control-Allow-Methods", "GET, POST");
  172. res.set_header("Access-Control-Allow-Headers", "*");
  173. res.set_content("", "text/html"); // blank response, no data
  174. return httplib::Server::HandlerResponse::Handled; // skip further processing
  175. }
  176. if (!middleware_server_state(req, res)) {
  177. return httplib::Server::HandlerResponse::Handled;
  178. }
  179. if (!middleware_validate_api_key(req, res)) {
  180. return httplib::Server::HandlerResponse::Handled;
  181. }
  182. return httplib::Server::HandlerResponse::Unhandled;
  183. });
  184. int n_threads_http = params.n_threads_http;
  185. if (n_threads_http < 1) {
  186. // +2 threads for monitoring endpoints
  187. n_threads_http = std::max(params.n_parallel + 2, (int32_t) std::thread::hardware_concurrency() - 1);
  188. }
  189. LOG_INF("%s: using %d threads for HTTP server\n", __func__, n_threads_http);
  190. srv->new_task_queue = [n_threads_http] { return new httplib::ThreadPool(n_threads_http); };
  191. //
  192. // Web UI setup
  193. //
  194. if (!params.webui) {
  195. LOG_INF("Web UI is disabled\n");
  196. } else {
  197. // register static assets routes
  198. if (!params.public_path.empty()) {
  199. // Set the base directory for serving static files
  200. bool is_found = srv->set_mount_point(params.api_prefix + "/", params.public_path);
  201. if (!is_found) {
  202. LOG_ERR("%s: static assets path not found: %s\n", __func__, params.public_path.c_str());
  203. return 1;
  204. }
  205. } else {
  206. // using embedded static index.html
  207. srv->Get(params.api_prefix + "/", [](const httplib::Request & req, httplib::Response & res) {
  208. if (req.get_header_value("Accept-Encoding").find("gzip") == std::string::npos) {
  209. res.set_content("Error: gzip is not supported by this browser", "text/plain");
  210. } else {
  211. res.set_header("Content-Encoding", "gzip");
  212. // COEP and COOP headers, required by pyodide (python interpreter)
  213. res.set_header("Cross-Origin-Embedder-Policy", "require-corp");
  214. res.set_header("Cross-Origin-Opener-Policy", "same-origin");
  215. res.set_content(reinterpret_cast<const char*>(index_html_gz), index_html_gz_len, "text/html; charset=utf-8");
  216. }
  217. return false;
  218. });
  219. }
  220. }
  221. return true;
  222. }
  223. bool server_http_context::start() {
  224. // Bind and listen
  225. auto & srv = pimpl->srv;
  226. bool was_bound = false;
  227. bool is_sock = false;
  228. if (string_ends_with(std::string(hostname), ".sock")) {
  229. is_sock = true;
  230. LOG_INF("%s: setting address family to AF_UNIX\n", __func__);
  231. srv->set_address_family(AF_UNIX);
  232. // bind_to_port requires a second arg, any value other than 0 should
  233. // simply get ignored
  234. was_bound = srv->bind_to_port(hostname, 8080);
  235. } else {
  236. LOG_INF("%s: binding port with default address family\n", __func__);
  237. // bind HTTP listen port
  238. if (port == 0) {
  239. int bound_port = srv->bind_to_any_port(hostname);
  240. was_bound = (bound_port >= 0);
  241. if (was_bound) {
  242. port = bound_port;
  243. }
  244. } else {
  245. was_bound = srv->bind_to_port(hostname, port);
  246. }
  247. }
  248. if (!was_bound) {
  249. LOG_ERR("%s: couldn't bind HTTP server socket, hostname: %s, port: %d\n", __func__, hostname.c_str(), port);
  250. return false;
  251. }
  252. // run the HTTP server in a thread
  253. thread = std::thread([this]() { pimpl->srv->listen_after_bind(); });
  254. srv->wait_until_ready();
  255. listening_address = is_sock ? string_format("unix://%s", hostname.c_str())
  256. : string_format("http://%s:%d", hostname.c_str(), port);
  257. return true;
  258. }
  259. void server_http_context::stop() const {
  260. if (pimpl->srv) {
  261. pimpl->srv->stop();
  262. }
  263. }
  264. static void set_headers(httplib::Response & res, const std::map<std::string, std::string> & headers) {
  265. for (const auto & [key, value] : headers) {
  266. res.set_header(key, value);
  267. }
  268. }
  269. static std::map<std::string, std::string> get_params(const httplib::Request & req) {
  270. std::map<std::string, std::string> params;
  271. for (const auto & [key, value] : req.params) {
  272. params[key] = value;
  273. }
  274. for (const auto & [key, value] : req.path_params) {
  275. params[key] = value;
  276. }
  277. return params;
  278. }
  279. static std::map<std::string, std::string> get_headers(const httplib::Request & req) {
  280. std::map<std::string, std::string> headers;
  281. for (const auto & [key, value] : req.headers) {
  282. headers[key] = value;
  283. }
  284. return headers;
  285. }
  286. static void process_handler_response(server_http_res_ptr & response, httplib::Response & res) {
  287. if (response->is_stream()) {
  288. res.status = response->status;
  289. set_headers(res, response->headers);
  290. std::string content_type = response->content_type;
  291. // convert to shared_ptr as both chunked_content_provider() and on_complete() need to use it
  292. std::shared_ptr<server_http_res> r_ptr = std::move(response);
  293. const auto chunked_content_provider = [response = r_ptr](size_t, httplib::DataSink & sink) -> bool {
  294. std::string chunk;
  295. bool has_next = response->next(chunk);
  296. if (!chunk.empty()) {
  297. // TODO: maybe handle sink.write unsuccessful? for now, we rely on is_connection_closed()
  298. sink.write(chunk.data(), chunk.size());
  299. SRV_DBG("http: streamed chunk: %s\n", chunk.c_str());
  300. }
  301. if (!has_next) {
  302. sink.done();
  303. SRV_DBG("%s", "http: stream ended\n");
  304. }
  305. return has_next;
  306. };
  307. const auto on_complete = [response = r_ptr](bool) mutable {
  308. response.reset(); // trigger the destruction of the response object
  309. };
  310. res.set_chunked_content_provider(content_type, chunked_content_provider, on_complete);
  311. } else {
  312. res.status = response->status;
  313. set_headers(res, response->headers);
  314. res.set_content(response->data, response->content_type);
  315. }
  316. }
  317. void server_http_context::get(const std::string & path, const server_http_context::handler_t & handler) const {
  318. pimpl->srv->Get(path_prefix + path, [handler](const httplib::Request & req, httplib::Response & res) {
  319. server_http_res_ptr response = handler(server_http_req{
  320. get_params(req),
  321. get_headers(req),
  322. req.path,
  323. req.body,
  324. req.is_connection_closed
  325. });
  326. process_handler_response(response, res);
  327. });
  328. }
  329. void server_http_context::post(const std::string & path, const server_http_context::handler_t & handler) const {
  330. pimpl->srv->Post(path_prefix + path, [handler](const httplib::Request & req, httplib::Response & res) {
  331. server_http_res_ptr response = handler(server_http_req{
  332. get_params(req),
  333. get_headers(req),
  334. req.path,
  335. req.body,
  336. req.is_connection_closed
  337. });
  338. process_handler_response(response, res);
  339. });
  340. }