http_server.c 14 KB

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