http_server.c 12 KB

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