http_server.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "daemon/common.h"
  3. #include "http_server.h"
  4. #include "h2o.h"
  5. #include "h2o_utils.h"
  6. static h2o_globalconf_t config;
  7. static h2o_context_t ctx;
  8. static h2o_accept_ctx_t accept_ctx;
  9. #define CONTENT_JSON_UTF8 H2O_STRLIT("application/json; charset=utf-8")
  10. #define CONTENT_TEXT_UTF8 H2O_STRLIT("text/plain; charset=utf-8")
  11. #define NBUF_INITIAL_SIZE_RESP (4096)
  12. #define API_V1_PREFIX "/api/v1/"
  13. #define HOST_SELECT_PREFIX "/host/"
  14. #define HTTPD_CONFIG_SECTION "httpd"
  15. #define HTTPD_ENABLED_DEFAULT false
  16. static void on_accept(h2o_socket_t *listener, const char *err)
  17. {
  18. h2o_socket_t *sock;
  19. if (err != NULL) {
  20. return;
  21. }
  22. if ((sock = h2o_evloop_socket_accept(listener)) == NULL)
  23. return;
  24. h2o_accept(&accept_ctx, sock);
  25. }
  26. static int create_listener(const char *ip, int port)
  27. {
  28. struct sockaddr_in addr;
  29. int fd, reuseaddr_flag = 1;
  30. h2o_socket_t *sock;
  31. memset(&addr, 0, sizeof(addr));
  32. addr.sin_family = AF_INET;
  33. addr.sin_addr.s_addr = inet_addr(ip);
  34. addr.sin_port = htons(port);
  35. if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ||
  36. setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_flag, sizeof(reuseaddr_flag)) != 0 ||
  37. bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 || listen(fd, SOMAXCONN) != 0) {
  38. return -1;
  39. }
  40. sock = h2o_evloop_socket_create(ctx.loop, fd, H2O_SOCKET_FLAG_DONT_READ);
  41. h2o_socket_read_start(sock, on_accept);
  42. return 0;
  43. }
  44. static int ssl_init()
  45. {
  46. if (!config_get_boolean(HTTPD_CONFIG_SECTION, "ssl", false))
  47. return 0;
  48. char default_fn[FILENAME_MAX + 1];
  49. snprintfz(default_fn, FILENAME_MAX, "%s/ssl/key.pem", netdata_configured_user_config_dir);
  50. const char *key_fn = config_get(HTTPD_CONFIG_SECTION, "ssl key", default_fn);
  51. snprintfz(default_fn, FILENAME_MAX, "%s/ssl/cert.pem", netdata_configured_user_config_dir);
  52. const char *cert_fn = config_get(HTTPD_CONFIG_SECTION, "ssl certificate", default_fn);
  53. #if OPENSSL_VERSION_NUMBER < OPENSSL_VERSION_110
  54. accept_ctx.ssl_ctx = SSL_CTX_new(SSLv23_server_method());
  55. #else
  56. accept_ctx.ssl_ctx = SSL_CTX_new(TLS_server_method());
  57. #endif
  58. SSL_CTX_set_options(accept_ctx.ssl_ctx, SSL_OP_NO_SSLv2);
  59. /* load certificate and private key */
  60. if (SSL_CTX_use_PrivateKey_file(accept_ctx.ssl_ctx, key_fn, SSL_FILETYPE_PEM) != 1) {
  61. error("Could not load server key from \"%s\"", key_fn);
  62. return -1;
  63. }
  64. if (SSL_CTX_use_certificate_file(accept_ctx.ssl_ctx, cert_fn, SSL_FILETYPE_PEM) != 1) {
  65. error("Could not load certificate from \"%s\"", cert_fn);
  66. return -1;
  67. }
  68. h2o_ssl_register_alpn_protocols(accept_ctx.ssl_ctx, h2o_http2_alpn_protocols);
  69. info("SSL support enabled");
  70. return 0;
  71. }
  72. // I did not find a way to do wildcard paths to make common handler for urls like:
  73. // /api/v1/info
  74. // /host/child/api/v1/info
  75. // /host/uuid/api/v1/info
  76. // ideally we could do something like "/*/api/v1/info" subscription
  77. // so we do it "manually" here with uberhandler
  78. static inline int _netdata_uberhandler(h2o_req_t *req, RRDHOST **host)
  79. {
  80. if (!h2o_memis(req->method.base, req->method.len, H2O_STRLIT("GET")))
  81. return -1;
  82. static h2o_generator_t generator = { NULL, NULL };
  83. h2o_iovec_t norm_path = req->path_normalized;
  84. if (norm_path.len > strlen(HOST_SELECT_PREFIX) && !memcmp(norm_path.base, HOST_SELECT_PREFIX, strlen(HOST_SELECT_PREFIX))) {
  85. h2o_iovec_t host_id; // host_id can be either and UUID or a hostname of the child
  86. norm_path.base += strlen(HOST_SELECT_PREFIX);
  87. norm_path.len -= strlen(HOST_SELECT_PREFIX);
  88. host_id = norm_path;
  89. size_t end_loc = h2o_strstr(host_id.base, host_id.len, "/", 1);
  90. if (end_loc != SIZE_MAX) {
  91. host_id.len = end_loc;
  92. norm_path.base += end_loc;
  93. norm_path.len -= end_loc;
  94. }
  95. char *c_host_id = iovec_to_cstr(&host_id);
  96. *host = rrdhost_find_by_hostname(c_host_id);
  97. if (!*host)
  98. *host = rrdhost_find_by_guid(c_host_id);
  99. if (!*host) {
  100. req->res.status = HTTP_RESP_BAD_REQUEST;
  101. req->res.reason = "Wrong host id";
  102. h2o_send_inline(req, H2O_STRLIT("Host id provided was not found!\n"));
  103. freez(c_host_id);
  104. return 0;
  105. }
  106. freez(c_host_id);
  107. // we have to rewrite URL here in case this is not an api call
  108. // so that the subsequent file upload handler can send the correct
  109. // files to the client
  110. // if this is not an API call we will abort this handler later
  111. // and let the internal serve file handler of h2o care for things
  112. if (end_loc == SIZE_MAX) {
  113. req->path.len = 1;
  114. req->path_normalized.len = 1;
  115. } else {
  116. size_t offset = norm_path.base - req->path_normalized.base;
  117. req->path.len -= offset;
  118. req->path.base += offset;
  119. req->query_at -= offset;
  120. req->path_normalized.len -= offset;
  121. req->path_normalized.base += offset;
  122. }
  123. }
  124. // workaround for a dashboard bug which causes sometimes urls like
  125. // "//api/v1/info" to be caled instead of "/api/v1/info"
  126. if (norm_path.len > 2 &&
  127. norm_path.base[0] == '/' &&
  128. norm_path.base[1] == '/' ) {
  129. norm_path.base++;
  130. norm_path.len--;
  131. }
  132. size_t api_loc = h2o_strstr(norm_path.base, norm_path.len, H2O_STRLIT(API_V1_PREFIX));
  133. if (api_loc == SIZE_MAX)
  134. return 1;
  135. h2o_iovec_t api_command = norm_path;
  136. api_command.base += api_loc + strlen(API_V1_PREFIX);
  137. api_command.len -= api_loc + strlen(API_V1_PREFIX);
  138. if (!api_command.len)
  139. return 1;
  140. // this (emulating struct web_client) is a hack and will be removed
  141. // in future PRs but needs bigger changes in old http_api_v1
  142. // we need to make the web_client_api_request_v1 to be web server
  143. // agnostic and remove the old webservers dependency creep into the
  144. // individual response generators and thus remove the need to "emulate"
  145. // the old webserver calling this function here and in ACLK
  146. struct web_client w;
  147. w.response.data = buffer_create(NBUF_INITIAL_SIZE_RESP, NULL);
  148. w.response.header = buffer_create(NBUF_INITIAL_SIZE_RESP, NULL);
  149. w.url_query_string_decoded = buffer_create(NBUF_INITIAL_SIZE_RESP, NULL);
  150. w.acl = WEB_CLIENT_ACL_DASHBOARD;
  151. char *path_c_str = iovec_to_cstr(&api_command);
  152. char *path_unescaped = url_unescape(path_c_str);
  153. freez(path_c_str);
  154. IF_HAS_URL_PARAMS(req) {
  155. h2o_iovec_t query_params = URL_PARAMS_IOVEC_INIT_WITH_QUESTIONMARK(req);
  156. char *query_c_str = iovec_to_cstr(&query_params);
  157. char *query_unescaped = url_unescape(query_c_str);
  158. freez(query_c_str);
  159. buffer_strcat(w.url_query_string_decoded, query_unescaped);
  160. freez(query_unescaped);
  161. }
  162. web_client_api_request_v1(*host, &w, path_unescaped);
  163. freez(path_unescaped);
  164. h2o_iovec_t body = buffer_to_h2o_iovec(w.response.data);
  165. // we move msg body to req->pool managed memory as it has to
  166. // live until whole response has been encrypted and sent
  167. // when req is finished memory will be freed with the pool
  168. void *managed = h2o_mem_alloc_shared(&req->pool, body.len, NULL);
  169. memcpy(managed, body.base, body.len);
  170. body.base = managed;
  171. req->res.status = HTTP_RESP_OK;
  172. req->res.reason = "OK";
  173. if (w.response.data->content_type == CT_APPLICATION_JSON)
  174. h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, NULL, CONTENT_JSON_UTF8);
  175. else
  176. h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, NULL, CONTENT_TEXT_UTF8);
  177. h2o_start_response(req, &generator);
  178. h2o_send(req, &body, 1, H2O_SEND_STATE_FINAL);
  179. buffer_free(w.response.data);
  180. buffer_free(w.response.header);
  181. buffer_free(w.url_query_string_decoded);
  182. return 0;
  183. }
  184. static int netdata_uberhandler(h2o_handler_t *self, h2o_req_t *req)
  185. {
  186. UNUSED(self);
  187. RRDHOST *host = localhost;
  188. int ret = _netdata_uberhandler(req, &host);
  189. char host_uuid_str[UUID_STR_LEN];
  190. uuid_unparse_lower(host->host_uuid, host_uuid_str);
  191. if (!ret) {
  192. log_access("HTTPD OK method: " PRINTF_H2O_IOVEC_FMT
  193. ", path: " PRINTF_H2O_IOVEC_FMT
  194. ", as host: %s"
  195. ", response: %d",
  196. PRINTF_H2O_IOVEC(&req->method),
  197. PRINTF_H2O_IOVEC(&req->input.path),
  198. host == localhost ? "localhost" : host_uuid_str,
  199. req->res.status);
  200. } else {
  201. log_access("HTTPD %d"
  202. " method: " PRINTF_H2O_IOVEC_FMT
  203. ", path: " PRINTF_H2O_IOVEC_FMT
  204. ", forwarding to file handler as path: " PRINTF_H2O_IOVEC_FMT,
  205. ret,
  206. PRINTF_H2O_IOVEC(&req->method),
  207. PRINTF_H2O_IOVEC(&req->input.path),
  208. PRINTF_H2O_IOVEC(&req->path));
  209. }
  210. return ret;
  211. }
  212. static int hdl_netdata_conf(h2o_handler_t *self, h2o_req_t *req)
  213. {
  214. UNUSED(self);
  215. if (!h2o_memis(req->method.base, req->method.len, H2O_STRLIT("GET")))
  216. return -1;
  217. BUFFER *buf = buffer_create(NBUF_INITIAL_SIZE_RESP, NULL);
  218. config_generate(buf, 0);
  219. void *managed = h2o_mem_alloc_shared(&req->pool, buf->len, NULL);
  220. memcpy(managed, buf->buffer, buf->len);
  221. req->res.status = HTTP_RESP_OK;
  222. req->res.reason = "OK";
  223. h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, NULL, CONTENT_TEXT_UTF8);
  224. h2o_send_inline(req, managed, buf->len);
  225. buffer_free(buf);
  226. return 0;
  227. }
  228. #define POLL_INTERVAL 100
  229. void *httpd_main(void *ptr) {
  230. struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr;
  231. h2o_pathconf_t *pathconf;
  232. h2o_hostconf_t *hostconf;
  233. netdata_thread_disable_cancelability();
  234. const char *bind_addr = config_get(HTTPD_CONFIG_SECTION, "bind to", "127.0.0.1");
  235. int bind_port = config_get_number(HTTPD_CONFIG_SECTION, "port", 19998);
  236. h2o_config_init(&config);
  237. hostconf = h2o_config_register_host(&config, h2o_iovec_init(H2O_STRLIT("default")), bind_port);
  238. pathconf = h2o_config_register_path(hostconf, "/netdata.conf", 0);
  239. h2o_handler_t *handler = h2o_create_handler(pathconf, sizeof(*handler));
  240. handler->on_req = hdl_netdata_conf;
  241. pathconf = h2o_config_register_path(hostconf, "/", 0);
  242. handler = h2o_create_handler(pathconf, sizeof(*handler));
  243. handler->on_req = netdata_uberhandler;
  244. h2o_file_register(pathconf, netdata_configured_web_dir, NULL, NULL, H2O_FILE_FLAG_SEND_COMPRESSED);
  245. h2o_context_init(&ctx, h2o_evloop_create(), &config);
  246. if(ssl_init()) {
  247. error_report("SSL was requested but could not be properly initialized. Aborting.");
  248. return NULL;
  249. }
  250. accept_ctx.ctx = &ctx;
  251. accept_ctx.hosts = config.hosts;
  252. if (create_listener(bind_addr, bind_port) != 0) {
  253. error("failed to create listener %s:%d", bind_addr, bind_port);
  254. return NULL;
  255. }
  256. while (service_running(SERVICE_HTTPD)) {
  257. int rc = h2o_evloop_run(ctx.loop, POLL_INTERVAL);
  258. if (rc < 0 && errno != EINTR) {
  259. error("h2o_evloop_run returned (%d) with errno other than EINTR. Aborting", rc);
  260. break;
  261. }
  262. }
  263. static_thread->enabled = NETDATA_MAIN_THREAD_EXITED;
  264. return NULL;
  265. }
  266. int httpd_is_enabled() {
  267. return config_get_boolean(HTTPD_CONFIG_SECTION, "enabled", HTTPD_ENABLED_DEFAULT);
  268. }