web_api_v2.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "web_api_v2.h"
  3. #include "../rtc/webrtc.h"
  4. #define BEARER_TOKEN_EXPIRATION 86400
  5. struct bearer_token {
  6. time_t created_s;
  7. time_t expires_s;
  8. };
  9. static void bearer_token_cleanup(void) {
  10. static time_t attempts = 0;
  11. if(++attempts % 1000 != 0)
  12. return;
  13. time_t now_s = now_monotonic_sec();
  14. struct bearer_token *z;
  15. dfe_start_read(netdata_authorized_bearers, z) {
  16. if(z->expires_s < now_s)
  17. dictionary_del(netdata_authorized_bearers, z_dfe.name);
  18. }
  19. dfe_done(z);
  20. dictionary_garbage_collect(netdata_authorized_bearers);
  21. }
  22. void bearer_tokens_init(void) {
  23. netdata_authorized_bearers = dictionary_create_advanced(
  24. DICT_OPTION_DONT_OVERWRITE_VALUE | DICT_OPTION_FIXED_SIZE,
  25. NULL, sizeof(struct bearer_token));
  26. }
  27. static time_t bearer_get_token(uuid_t *uuid) {
  28. char uuid_str[UUID_STR_LEN];
  29. uuid_generate_random(*uuid);
  30. uuid_unparse_lower(*uuid, uuid_str);
  31. struct bearer_token t = { 0 }, *z;
  32. z = dictionary_set(netdata_authorized_bearers, uuid_str, &t, sizeof(t));
  33. if(!z->created_s) {
  34. z->created_s = now_monotonic_sec();
  35. z->expires_s = z->created_s + BEARER_TOKEN_EXPIRATION;
  36. }
  37. bearer_token_cleanup();
  38. return now_realtime_sec() + BEARER_TOKEN_EXPIRATION;
  39. }
  40. #define HTTP_REQUEST_AUTHORIZATION_BEARER "\r\nAuthorization: Bearer "
  41. #define HTTP_REQUEST_X_NETDATA_AUTH_BEARER "\r\nX-Netdata-Auth: Bearer "
  42. BEARER_STATUS extract_bearer_token_from_request(struct web_client *w, char *dst, size_t dst_len) {
  43. const char *req = buffer_tostring(w->response.data);
  44. size_t req_len = buffer_strlen(w->response.data);
  45. const char *bearer = NULL;
  46. const char *bearer_end = NULL;
  47. bearer = strcasestr(req, HTTP_REQUEST_X_NETDATA_AUTH_BEARER);
  48. if(bearer)
  49. bearer_end = bearer + sizeof(HTTP_REQUEST_X_NETDATA_AUTH_BEARER) - 1;
  50. else {
  51. bearer = strcasestr(req, HTTP_REQUEST_AUTHORIZATION_BEARER);
  52. if(bearer)
  53. bearer_end = bearer + sizeof(HTTP_REQUEST_AUTHORIZATION_BEARER) - 1;
  54. }
  55. if(!bearer || !bearer_end)
  56. return BEARER_STATUS_NO_BEARER_IN_HEADERS;
  57. const char *token_start = bearer_end;
  58. while(isspace(*token_start))
  59. token_start++;
  60. const char *token_end = token_start + UUID_STR_LEN - 1 + 2;
  61. if (token_end > req + req_len)
  62. return BEARER_STATUS_BEARER_DOES_NOT_FIT;
  63. strncpyz(dst, token_start, dst_len - 1);
  64. uuid_t uuid;
  65. if (uuid_parse(dst, uuid) != 0)
  66. return BEARER_STATUS_NOT_PARSABLE;
  67. return BEARER_STATUS_EXTRACTED_FROM_HEADER;
  68. }
  69. BEARER_STATUS api_check_bearer_token(struct web_client *w) {
  70. if(!netdata_authorized_bearers)
  71. return BEARER_STATUS_NO_BEARERS_DICTIONARY;
  72. char token[UUID_STR_LEN];
  73. BEARER_STATUS t = extract_bearer_token_from_request(w, token, sizeof(token));
  74. if(t != BEARER_STATUS_EXTRACTED_FROM_HEADER)
  75. return t;
  76. struct bearer_token *z = dictionary_get(netdata_authorized_bearers, token);
  77. if(!z)
  78. return BEARER_STATUS_NOT_FOUND_IN_DICTIONARY;
  79. if(z->expires_s < now_monotonic_sec())
  80. return BEARER_STATUS_EXPIRED;
  81. return BEARER_STATUS_AVAILABLE_AND_VALIDATED;
  82. }
  83. static bool verify_agent_uuids(const char *machine_guid, const char *node_id, const char *claim_id) {
  84. if(!machine_guid || !node_id || !claim_id)
  85. return false;
  86. if(strcmp(machine_guid, localhost->machine_guid) != 0)
  87. return false;
  88. char *agent_claim_id = get_agent_claimid();
  89. bool not_verified = (!agent_claim_id || strcmp(claim_id, agent_claim_id) != 0);
  90. freez(agent_claim_id);
  91. if(not_verified || !localhost->node_id)
  92. return false;
  93. char buf[UUID_STR_LEN];
  94. uuid_unparse_lower(*localhost->node_id, buf);
  95. if(strcmp(node_id, buf) != 0)
  96. return false;
  97. return true;
  98. }
  99. int api_v2_bearer_protection(RRDHOST *host __maybe_unused, struct web_client *w __maybe_unused, char *url) {
  100. char *machine_guid = NULL;
  101. char *claim_id = NULL;
  102. char *node_id = NULL;
  103. bool protection = netdata_is_protected_by_bearer;
  104. while (url) {
  105. char *value = strsep_skip_consecutive_separators(&url, "&");
  106. if (!value || !*value) continue;
  107. char *name = strsep_skip_consecutive_separators(&value, "=");
  108. if (!name || !*name) continue;
  109. if (!value || !*value) continue;
  110. if(!strcmp(name, "bearer_protection")) {
  111. if(!strcmp(value, "on") || !strcmp(value, "true") || !strcmp(value, "yes"))
  112. protection = true;
  113. else
  114. protection = false;
  115. }
  116. else if(!strcmp(name, "machine_guid"))
  117. machine_guid = value;
  118. else if(!strcmp(name, "claim_id"))
  119. claim_id = value;
  120. else if(!strcmp(name, "node_id"))
  121. node_id = value;
  122. }
  123. if(!verify_agent_uuids(machine_guid, node_id, claim_id)) {
  124. buffer_flush(w->response.data);
  125. buffer_strcat(w->response.data, "The request is missing or not matching local UUIDs");
  126. return HTTP_RESP_BAD_REQUEST;
  127. }
  128. netdata_is_protected_by_bearer = protection;
  129. BUFFER *wb = w->response.data;
  130. buffer_flush(wb);
  131. buffer_json_initialize(wb, "\"", "\"", 0, true, BUFFER_JSON_OPTIONS_DEFAULT);
  132. buffer_json_member_add_boolean(wb, "bearer_protection", netdata_is_protected_by_bearer);
  133. buffer_json_finalize(wb);
  134. return HTTP_RESP_OK;
  135. }
  136. int api_v2_bearer_token(RRDHOST *host __maybe_unused, struct web_client *w __maybe_unused, char *url __maybe_unused) {
  137. char *machine_guid = NULL;
  138. char *claim_id = NULL;
  139. char *node_id = NULL;
  140. while(url) {
  141. char *value = strsep_skip_consecutive_separators(&url, "&");
  142. if (!value || !*value) continue;
  143. char *name = strsep_skip_consecutive_separators(&value, "=");
  144. if (!name || !*name) continue;
  145. if (!value || !*value) continue;
  146. if(!strcmp(name, "machine_guid"))
  147. machine_guid = value;
  148. else if(!strcmp(name, "claim_id"))
  149. claim_id = value;
  150. else if(!strcmp(name, "node_id"))
  151. node_id = value;
  152. }
  153. if(!verify_agent_uuids(machine_guid, node_id, claim_id)) {
  154. buffer_flush(w->response.data);
  155. buffer_strcat(w->response.data, "The request is missing or not matching local UUIDs");
  156. return HTTP_RESP_BAD_REQUEST;
  157. }
  158. uuid_t uuid;
  159. time_t expires_s = bearer_get_token(&uuid);
  160. BUFFER *wb = w->response.data;
  161. buffer_flush(wb);
  162. buffer_json_initialize(wb, "\"", "\"", 0, true, BUFFER_JSON_OPTIONS_DEFAULT);
  163. buffer_json_member_add_string(wb, "mg", localhost->machine_guid);
  164. buffer_json_member_add_boolean(wb, "bearer_protection", netdata_is_protected_by_bearer);
  165. buffer_json_member_add_uuid(wb, "token", &uuid);
  166. buffer_json_member_add_time_t(wb, "expiration", expires_s);
  167. buffer_json_finalize(wb);
  168. return HTTP_RESP_OK;
  169. }
  170. static int web_client_api_request_v2_contexts_internal(RRDHOST *host __maybe_unused, struct web_client *w, char *url, CONTEXTS_V2_MODE mode) {
  171. struct api_v2_contexts_request req = { 0 };
  172. while(url) {
  173. char *value = strsep_skip_consecutive_separators(&url, "&");
  174. if(!value || !*value) continue;
  175. char *name = strsep_skip_consecutive_separators(&value, "=");
  176. if(!name || !*name) continue;
  177. if(!value || !*value) continue;
  178. // name and value are now the parameters
  179. // they are not null and not empty
  180. if(!strcmp(name, "scope_nodes"))
  181. req.scope_nodes = value;
  182. else if(!strcmp(name, "nodes"))
  183. req.nodes = value;
  184. else if((mode & (CONTEXTS_V2_CONTEXTS | CONTEXTS_V2_SEARCH | CONTEXTS_V2_ALERTS | CONTEXTS_V2_ALERT_TRANSITIONS)) && !strcmp(name, "scope_contexts"))
  185. req.scope_contexts = value;
  186. else if((mode & (CONTEXTS_V2_CONTEXTS | CONTEXTS_V2_SEARCH | CONTEXTS_V2_ALERTS | CONTEXTS_V2_ALERT_TRANSITIONS)) && !strcmp(name, "contexts"))
  187. req.contexts = value;
  188. else if((mode & CONTEXTS_V2_SEARCH) && !strcmp(name, "q"))
  189. req.q = value;
  190. else if(!strcmp(name, "options"))
  191. req.options = web_client_api_request_v2_context_options(value);
  192. else if(!strcmp(name, "after"))
  193. req.after = str2l(value);
  194. else if(!strcmp(name, "before"))
  195. req.before = str2l(value);
  196. else if(!strcmp(name, "timeout"))
  197. req.timeout_ms = str2l(value);
  198. else if(mode & (CONTEXTS_V2_ALERTS | CONTEXTS_V2_ALERT_TRANSITIONS)) {
  199. if (!strcmp(name, "alert"))
  200. req.alerts.alert = value;
  201. else if (!strcmp(name, "transition"))
  202. req.alerts.transition = value;
  203. else if(mode & CONTEXTS_V2_ALERTS) {
  204. if (!strcmp(name, "status"))
  205. req.alerts.status = web_client_api_request_v2_alert_status(value);
  206. }
  207. else if(mode & CONTEXTS_V2_ALERT_TRANSITIONS) {
  208. if (!strcmp(name, "last"))
  209. req.alerts.last = strtoul(value, NULL, 0);
  210. else if(!strcmp(name, "context"))
  211. req.contexts = value;
  212. else if (!strcmp(name, "anchor_gi")) {
  213. req.alerts.global_id_anchor = str2ull(value, NULL);
  214. }
  215. else {
  216. for(int i = 0; i < ATF_TOTAL_ENTRIES ;i++) {
  217. if(!strcmp(name, alert_transition_facets[i].query_param))
  218. req.alerts.facets[i] = value;
  219. }
  220. }
  221. }
  222. }
  223. }
  224. if ((mode & CONTEXTS_V2_ALERT_TRANSITIONS) && !req.alerts.last)
  225. req.alerts.last = 1;
  226. buffer_flush(w->response.data);
  227. buffer_no_cacheable(w->response.data);
  228. return rrdcontext_to_json_v2(w->response.data, &req, mode);
  229. }
  230. static int web_client_api_request_v2_alert_transitions(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  231. return web_client_api_request_v2_contexts_internal(host, w, url, CONTEXTS_V2_ALERT_TRANSITIONS | CONTEXTS_V2_NODES);
  232. }
  233. static int web_client_api_request_v2_alerts(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  234. return web_client_api_request_v2_contexts_internal(host, w, url, CONTEXTS_V2_ALERTS | CONTEXTS_V2_NODES);
  235. }
  236. static int web_client_api_request_v2_functions(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  237. return web_client_api_request_v2_contexts_internal(host, w, url, CONTEXTS_V2_FUNCTIONS | CONTEXTS_V2_NODES | CONTEXTS_V2_AGENTS | CONTEXTS_V2_VERSIONS);
  238. }
  239. static int web_client_api_request_v2_versions(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  240. return web_client_api_request_v2_contexts_internal(host, w, url, CONTEXTS_V2_VERSIONS);
  241. }
  242. static int web_client_api_request_v2_q(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  243. return web_client_api_request_v2_contexts_internal(host, w, url, CONTEXTS_V2_SEARCH | CONTEXTS_V2_CONTEXTS | CONTEXTS_V2_NODES | CONTEXTS_V2_AGENTS | CONTEXTS_V2_VERSIONS);
  244. }
  245. static int web_client_api_request_v2_contexts(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  246. return web_client_api_request_v2_contexts_internal(host, w, url, CONTEXTS_V2_CONTEXTS | CONTEXTS_V2_NODES | CONTEXTS_V2_AGENTS | CONTEXTS_V2_VERSIONS);
  247. }
  248. static int web_client_api_request_v2_nodes(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  249. return web_client_api_request_v2_contexts_internal(host, w, url, CONTEXTS_V2_NODES | CONTEXTS_V2_NODES_INFO);
  250. }
  251. static int web_client_api_request_v2_info(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  252. return web_client_api_request_v2_contexts_internal(host, w, url, CONTEXTS_V2_AGENTS | CONTEXTS_V2_AGENTS_INFO);
  253. }
  254. static int web_client_api_request_v2_node_instances(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  255. return web_client_api_request_v2_contexts_internal(host, w, url, CONTEXTS_V2_NODES | CONTEXTS_V2_NODE_INSTANCES | CONTEXTS_V2_AGENTS | CONTEXTS_V2_AGENTS_INFO | CONTEXTS_V2_VERSIONS);
  256. }
  257. static int web_client_api_request_v2_weights(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  258. return web_client_api_request_weights(host, w, url, WEIGHTS_METHOD_VALUE, WEIGHTS_FORMAT_MULTINODE, 2);
  259. }
  260. static int web_client_api_request_v2_claim(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  261. return api_v2_claim(w, url);
  262. }
  263. static int web_client_api_request_v2_alert_config(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  264. const char *config = NULL;
  265. while(url) {
  266. char *value = strsep_skip_consecutive_separators(&url, "&");
  267. if(!value || !*value) continue;
  268. char *name = strsep_skip_consecutive_separators(&value, "=");
  269. if(!name || !*name) continue;
  270. if(!value || !*value) continue;
  271. // name and value are now the parameters
  272. // they are not null and not empty
  273. if(!strcmp(name, "config"))
  274. config = value;
  275. }
  276. buffer_flush(w->response.data);
  277. if(!config) {
  278. w->response.data->content_type = CT_TEXT_PLAIN;
  279. buffer_strcat(w->response.data, "A config hash ID is required. Add ?config=UUID query param");
  280. return HTTP_RESP_BAD_REQUEST;
  281. }
  282. return contexts_v2_alert_config_to_json(w, config);
  283. }
  284. #define GROUP_BY_KEY_MAX_LENGTH 30
  285. static struct {
  286. char group_by[GROUP_BY_KEY_MAX_LENGTH + 1];
  287. char aggregation[GROUP_BY_KEY_MAX_LENGTH + 1];
  288. char group_by_label[GROUP_BY_KEY_MAX_LENGTH + 1];
  289. } group_by_keys[MAX_QUERY_GROUP_BY_PASSES];
  290. __attribute__((constructor)) void initialize_group_by_keys(void) {
  291. for(size_t g = 0; g < MAX_QUERY_GROUP_BY_PASSES ;g++) {
  292. snprintfz(group_by_keys[g].group_by, GROUP_BY_KEY_MAX_LENGTH, "group_by[%zu]", g);
  293. snprintfz(group_by_keys[g].aggregation, GROUP_BY_KEY_MAX_LENGTH, "aggregation[%zu]", g);
  294. snprintfz(group_by_keys[g].group_by_label, GROUP_BY_KEY_MAX_LENGTH, "group_by_label[%zu]", g);
  295. }
  296. }
  297. static int web_client_api_request_v2_data(RRDHOST *host __maybe_unused, struct web_client *w, char *url) {
  298. usec_t received_ut = now_monotonic_usec();
  299. int ret = HTTP_RESP_BAD_REQUEST;
  300. buffer_flush(w->response.data);
  301. char *google_version = "0.6",
  302. *google_reqId = "0",
  303. *google_sig = "0",
  304. *google_out = "json",
  305. *responseHandler = NULL,
  306. *outFileName = NULL;
  307. time_t last_timestamp_in_data = 0, google_timestamp = 0;
  308. char *scope_nodes = NULL;
  309. char *scope_contexts = NULL;
  310. char *nodes = NULL;
  311. char *contexts = NULL;
  312. char *instances = NULL;
  313. char *dimensions = NULL;
  314. char *before_str = NULL;
  315. char *after_str = NULL;
  316. char *resampling_time_str = NULL;
  317. char *points_str = NULL;
  318. char *timeout_str = NULL;
  319. char *labels = NULL;
  320. char *alerts = NULL;
  321. char *time_group_options = NULL;
  322. char *tier_str = NULL;
  323. size_t tier = 0;
  324. RRDR_TIME_GROUPING time_group = RRDR_GROUPING_AVERAGE;
  325. DATASOURCE_FORMAT format = DATASOURCE_JSON2;
  326. RRDR_OPTIONS options = RRDR_OPTION_VIRTUAL_POINTS | RRDR_OPTION_JSON_WRAP | RRDR_OPTION_RETURN_JWAR;
  327. struct group_by_pass group_by[MAX_QUERY_GROUP_BY_PASSES] = {
  328. {
  329. .group_by = RRDR_GROUP_BY_DIMENSION,
  330. .group_by_label = NULL,
  331. .aggregation = RRDR_GROUP_BY_FUNCTION_AVERAGE,
  332. },
  333. };
  334. size_t group_by_idx = 0, group_by_label_idx = 0, aggregation_idx = 0;
  335. while(url) {
  336. char *value = strsep_skip_consecutive_separators(&url, "&");
  337. if(!value || !*value) continue;
  338. char *name = strsep_skip_consecutive_separators(&value, "=");
  339. if(!name || !*name) continue;
  340. if(!value || !*value) continue;
  341. // name and value are now the parameters
  342. // they are not null and not empty
  343. if(!strcmp(name, "scope_nodes")) scope_nodes = value;
  344. else if(!strcmp(name, "scope_contexts")) scope_contexts = value;
  345. else if(!strcmp(name, "nodes")) nodes = value;
  346. else if(!strcmp(name, "contexts")) contexts = value;
  347. else if(!strcmp(name, "instances")) instances = value;
  348. else if(!strcmp(name, "dimensions")) dimensions = value;
  349. else if(!strcmp(name, "labels")) labels = value;
  350. else if(!strcmp(name, "alerts")) alerts = value;
  351. else if(!strcmp(name, "after")) after_str = value;
  352. else if(!strcmp(name, "before")) before_str = value;
  353. else if(!strcmp(name, "points")) points_str = value;
  354. else if(!strcmp(name, "timeout")) timeout_str = value;
  355. else if(!strcmp(name, "group_by")) {
  356. group_by[group_by_idx++].group_by = group_by_parse(value);
  357. if(group_by_idx >= MAX_QUERY_GROUP_BY_PASSES)
  358. group_by_idx = MAX_QUERY_GROUP_BY_PASSES - 1;
  359. }
  360. else if(!strcmp(name, "group_by_label")) {
  361. group_by[group_by_label_idx++].group_by_label = value;
  362. if(group_by_label_idx >= MAX_QUERY_GROUP_BY_PASSES)
  363. group_by_label_idx = MAX_QUERY_GROUP_BY_PASSES - 1;
  364. }
  365. else if(!strcmp(name, "aggregation")) {
  366. group_by[aggregation_idx++].aggregation = group_by_aggregate_function_parse(value);
  367. if(aggregation_idx >= MAX_QUERY_GROUP_BY_PASSES)
  368. aggregation_idx = MAX_QUERY_GROUP_BY_PASSES - 1;
  369. }
  370. else if(!strcmp(name, "format")) format = web_client_api_request_v1_data_format(value);
  371. else if(!strcmp(name, "options")) options |= web_client_api_request_v1_data_options(value);
  372. else if(!strcmp(name, "time_group")) time_group = time_grouping_parse(value, RRDR_GROUPING_AVERAGE);
  373. else if(!strcmp(name, "time_group_options")) time_group_options = value;
  374. else if(!strcmp(name, "time_resampling")) resampling_time_str = value;
  375. else if(!strcmp(name, "tier")) tier_str = value;
  376. else if(!strcmp(name, "callback")) responseHandler = value;
  377. else if(!strcmp(name, "filename")) outFileName = value;
  378. else if(!strcmp(name, "tqx")) {
  379. // parse Google Visualization API options
  380. // https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
  381. char *tqx_name, *tqx_value;
  382. while(value) {
  383. tqx_value = strsep_skip_consecutive_separators(&value, ";");
  384. if(!tqx_value || !*tqx_value) continue;
  385. tqx_name = strsep_skip_consecutive_separators(&tqx_value, ":");
  386. if(!tqx_name || !*tqx_name) continue;
  387. if(!tqx_value || !*tqx_value) continue;
  388. if(!strcmp(tqx_name, "version"))
  389. google_version = tqx_value;
  390. else if(!strcmp(tqx_name, "reqId"))
  391. google_reqId = tqx_value;
  392. else if(!strcmp(tqx_name, "sig")) {
  393. google_sig = tqx_value;
  394. google_timestamp = strtoul(google_sig, NULL, 0);
  395. }
  396. else if(!strcmp(tqx_name, "out")) {
  397. google_out = tqx_value;
  398. format = web_client_api_request_v1_data_google_format(google_out);
  399. }
  400. else if(!strcmp(tqx_name, "responseHandler"))
  401. responseHandler = tqx_value;
  402. else if(!strcmp(tqx_name, "outFileName"))
  403. outFileName = tqx_value;
  404. }
  405. }
  406. else {
  407. for(size_t g = 0; g < MAX_QUERY_GROUP_BY_PASSES ;g++) {
  408. if(!strcmp(name, group_by_keys[g].group_by))
  409. group_by[g].group_by = group_by_parse(value);
  410. else if(!strcmp(name, group_by_keys[g].group_by_label))
  411. group_by[g].group_by_label = value;
  412. else if(!strcmp(name, group_by_keys[g].aggregation))
  413. group_by[g].aggregation = group_by_aggregate_function_parse(value);
  414. }
  415. }
  416. }
  417. // validate the google parameters given
  418. fix_google_param(google_out);
  419. fix_google_param(google_sig);
  420. fix_google_param(google_reqId);
  421. fix_google_param(google_version);
  422. fix_google_param(responseHandler);
  423. fix_google_param(outFileName);
  424. for(size_t g = 0; g < MAX_QUERY_GROUP_BY_PASSES ;g++) {
  425. if (group_by[g].group_by_label && *group_by[g].group_by_label)
  426. group_by[g].group_by |= RRDR_GROUP_BY_LABEL;
  427. }
  428. if(group_by[0].group_by == RRDR_GROUP_BY_NONE)
  429. group_by[0].group_by = RRDR_GROUP_BY_DIMENSION;
  430. for(size_t g = 0; g < MAX_QUERY_GROUP_BY_PASSES ;g++) {
  431. if ((group_by[g].group_by & ~(RRDR_GROUP_BY_DIMENSION)) || (options & RRDR_OPTION_PERCENTAGE)) {
  432. options |= RRDR_OPTION_ABSOLUTE;
  433. break;
  434. }
  435. }
  436. if(options & RRDR_OPTION_DEBUG)
  437. options &= ~RRDR_OPTION_MINIFY;
  438. if(tier_str && *tier_str) {
  439. tier = str2ul(tier_str);
  440. if(tier < storage_tiers)
  441. options |= RRDR_OPTION_SELECTED_TIER;
  442. else
  443. tier = 0;
  444. }
  445. time_t before = (before_str && *before_str)?str2l(before_str):0;
  446. time_t after = (after_str && *after_str) ?str2l(after_str):-600;
  447. size_t points = (points_str && *points_str)?str2u(points_str):0;
  448. int timeout = (timeout_str && *timeout_str)?str2i(timeout_str): 0;
  449. time_t resampling_time = (resampling_time_str && *resampling_time_str) ? str2l(resampling_time_str) : 0;
  450. QUERY_TARGET_REQUEST qtr = {
  451. .version = 2,
  452. .scope_nodes = scope_nodes,
  453. .scope_contexts = scope_contexts,
  454. .after = after,
  455. .before = before,
  456. .host = NULL,
  457. .st = NULL,
  458. .nodes = nodes,
  459. .contexts = contexts,
  460. .instances = instances,
  461. .dimensions = dimensions,
  462. .alerts = alerts,
  463. .timeout_ms = timeout,
  464. .points = points,
  465. .format = format,
  466. .options = options,
  467. .time_group_method = time_group,
  468. .time_group_options = time_group_options,
  469. .resampling_time = resampling_time,
  470. .tier = tier,
  471. .chart_label_key = NULL,
  472. .labels = labels,
  473. .query_source = QUERY_SOURCE_API_DATA,
  474. .priority = STORAGE_PRIORITY_NORMAL,
  475. .received_ut = received_ut,
  476. .interrupt_callback = web_client_interrupt_callback,
  477. .interrupt_callback_data = w,
  478. };
  479. for(size_t g = 0; g < MAX_QUERY_GROUP_BY_PASSES ;g++)
  480. qtr.group_by[g] = group_by[g];
  481. QUERY_TARGET *qt = query_target_create(&qtr);
  482. ONEWAYALLOC *owa = NULL;
  483. if(!qt) {
  484. buffer_sprintf(w->response.data, "Failed to prepare the query.");
  485. ret = HTTP_RESP_INTERNAL_SERVER_ERROR;
  486. goto cleanup;
  487. }
  488. web_client_timeout_checkpoint_set(w, timeout);
  489. if(web_client_timeout_checkpoint_and_check(w, NULL)) {
  490. ret = w->response.code;
  491. goto cleanup;
  492. }
  493. if(outFileName && *outFileName) {
  494. buffer_sprintf(w->response.header, "Content-Disposition: attachment; filename=\"%s\"\r\n", outFileName);
  495. netdata_log_debug(D_WEB_CLIENT, "%llu: generating outfilename header: '%s'", w->id, outFileName);
  496. }
  497. if(format == DATASOURCE_DATATABLE_JSONP) {
  498. if(responseHandler == NULL)
  499. responseHandler = "google.visualization.Query.setResponse";
  500. netdata_log_debug(D_WEB_CLIENT_ACCESS, "%llu: GOOGLE JSON/JSONP: version = '%s', reqId = '%s', sig = '%s', out = '%s', responseHandler = '%s', outFileName = '%s'",
  501. w->id, google_version, google_reqId, google_sig, google_out, responseHandler, outFileName
  502. );
  503. buffer_sprintf(
  504. w->response.data,
  505. "%s({version:'%s',reqId:'%s',status:'ok',sig:'%"PRId64"',table:",
  506. responseHandler,
  507. google_version,
  508. google_reqId,
  509. (int64_t)now_realtime_sec());
  510. }
  511. else if(format == DATASOURCE_JSONP) {
  512. if(responseHandler == NULL)
  513. responseHandler = "callback";
  514. buffer_strcat(w->response.data, responseHandler);
  515. buffer_strcat(w->response.data, "(");
  516. }
  517. owa = onewayalloc_create(0);
  518. ret = data_query_execute(owa, w->response.data, qt, &last_timestamp_in_data);
  519. if(format == DATASOURCE_DATATABLE_JSONP) {
  520. if(google_timestamp < last_timestamp_in_data)
  521. buffer_strcat(w->response.data, "});");
  522. else {
  523. // the client already has the latest data
  524. buffer_flush(w->response.data);
  525. buffer_sprintf(w->response.data,
  526. "%s({version:'%s',reqId:'%s',status:'error',errors:[{reason:'not_modified',message:'Data not modified'}]});",
  527. responseHandler, google_version, google_reqId);
  528. }
  529. }
  530. else if(format == DATASOURCE_JSONP)
  531. buffer_strcat(w->response.data, ");");
  532. if(qt->internal.relative)
  533. buffer_no_cacheable(w->response.data);
  534. else
  535. buffer_cacheable(w->response.data);
  536. cleanup:
  537. query_target_release(qt);
  538. onewayalloc_destroy(owa);
  539. return ret;
  540. }
  541. static int web_client_api_request_v2_webrtc(RRDHOST *host __maybe_unused, struct web_client *w, char *url __maybe_unused) {
  542. return webrtc_new_connection(w->post_payload, w->response.data);
  543. }
  544. #define CONFIG_API_V2_URL "/api/v2/config"
  545. static int web_client_api_request_v2_config(RRDHOST *host __maybe_unused, struct web_client *w, char *query __maybe_unused) {
  546. char *url = strdupz(buffer_tostring(w->url_as_received));
  547. char *url_full = url;
  548. buffer_flush(w->response.data);
  549. if (strncmp(url, "/host/", strlen("/host/")) == 0) {
  550. url += strlen("/host/");
  551. char *host_id_end = strchr(url, '/');
  552. if (host_id_end == NULL) {
  553. buffer_sprintf(w->response.data, "Invalid URL");
  554. freez(url_full);
  555. return HTTP_RESP_BAD_REQUEST;
  556. }
  557. url += host_id_end - url;
  558. }
  559. if (strncmp(url, CONFIG_API_V2_URL, strlen(CONFIG_API_V2_URL)) != 0) {
  560. buffer_sprintf(w->response.data, "Invalid URL");
  561. freez(url_full);
  562. return HTTP_RESP_BAD_REQUEST;
  563. }
  564. url += strlen(CONFIG_API_V2_URL);
  565. char *save_ptr = NULL;
  566. char *plugin = strtok_r(url, "/", &save_ptr);
  567. char *module = strtok_r(NULL, "/", &save_ptr);
  568. char *job_id = strtok_r(NULL, "/", &save_ptr);
  569. char *extra = strtok_r(NULL, "/", &save_ptr);
  570. if (extra != NULL) {
  571. buffer_sprintf(w->response.data, "Invalid URL");
  572. freez(url_full);
  573. return HTTP_RESP_BAD_REQUEST;
  574. }
  575. int http_method;
  576. switch (w->mode)
  577. {
  578. case WEB_CLIENT_MODE_GET:
  579. http_method = HTTP_METHOD_GET;
  580. break;
  581. case WEB_CLIENT_MODE_POST:
  582. http_method = HTTP_METHOD_POST;
  583. break;
  584. case WEB_CLIENT_MODE_PUT:
  585. http_method = HTTP_METHOD_PUT;
  586. break;
  587. case WEB_CLIENT_MODE_DELETE:
  588. http_method = HTTP_METHOD_DELETE;
  589. break;
  590. default:
  591. buffer_sprintf(w->response.data, "Invalid HTTP method");
  592. freez(url_full);
  593. return HTTP_RESP_BAD_REQUEST;
  594. }
  595. struct uni_http_response resp = dyn_conf_process_http_request(host->configurable_plugins, http_method, plugin, module, job_id, w->post_payload, w->post_payload_size);
  596. if (resp.content[resp.content_length - 1] != '\0') {
  597. char *con = mallocz(resp.content_length + 1);
  598. memcpy(con, resp.content, resp.content_length);
  599. con[resp.content_length] = '\0';
  600. if (resp.content_free)
  601. resp.content_free(resp.content);
  602. resp.content = con;
  603. resp.content_free = freez_dyncfg;
  604. }
  605. buffer_strcat(w->response.data, resp.content);
  606. if (resp.content_free)
  607. resp.content_free(resp.content);
  608. w->response.data->content_type = resp.content_type;
  609. freez(url_full);
  610. return resp.status;
  611. }
  612. static json_object *job_statuses_grouped() {
  613. json_object *top_obj = json_object_new_object();
  614. json_object *host_vec = json_object_new_array();
  615. RRDHOST *host;
  616. dfe_start_reentrant(rrdhost_root_index, host) {
  617. json_object *host_obj = json_object_new_object();
  618. json_object *host_sub_obj = json_object_new_string(host->machine_guid);
  619. json_object_object_add(host_obj, "host_guid", host_sub_obj);
  620. host_sub_obj = json_object_new_array();
  621. DICTIONARY *plugins_dict = host->configurable_plugins;
  622. struct configurable_plugin *plugin;
  623. dfe_start_read(plugins_dict, plugin) {
  624. json_object *plugin_obj = json_object_new_object();
  625. json_object *plugin_sub_obj = json_object_new_string(plugin->name);
  626. json_object_object_add(plugin_obj, "name", plugin_sub_obj);
  627. plugin_sub_obj = json_object_new_array();
  628. struct module *module;
  629. dfe_start_read(plugin->modules, module) {
  630. json_object *module_obj = json_object_new_object();
  631. json_object *module_sub_obj = json_object_new_string(module->name);
  632. json_object_object_add(module_obj, "name", module_sub_obj);
  633. module_sub_obj = json_object_new_array();
  634. struct job *job;
  635. dfe_start_read(module->jobs, job) {
  636. json_object *job_obj = json_object_new_object();
  637. json_object *job_sub_obj = json_object_new_string(job->name);
  638. json_object_object_add(job_obj, "name", job_sub_obj);
  639. job_sub_obj = job2json(job);
  640. json_object_object_add(job_obj, "job", job_sub_obj);
  641. json_object_array_add(module_sub_obj, job_obj);
  642. } dfe_done(job);
  643. json_object_object_add(module_obj, "jobs", module_sub_obj);
  644. json_object_array_add(plugin_sub_obj, module_obj);
  645. } dfe_done(module);
  646. json_object_object_add(plugin_obj, "modules", plugin_sub_obj);
  647. json_object_array_add(host_sub_obj, plugin_obj);
  648. } dfe_done(plugin);
  649. json_object_object_add(host_obj, "plugins", host_sub_obj);
  650. json_object_array_add(host_vec, host_obj);
  651. }
  652. dfe_done(host);
  653. json_object_object_add(top_obj, "hosts", host_vec);
  654. return top_obj;
  655. }
  656. static json_object *job_statuses_flat() {
  657. RRDHOST *host;
  658. json_object *ret = json_object_new_array();
  659. dfe_start_reentrant(rrdhost_root_index, host) {
  660. DICTIONARY *plugins_dict = host->configurable_plugins;
  661. struct configurable_plugin *plugin;
  662. dfe_start_read(plugins_dict, plugin) {
  663. struct module *module;
  664. dfe_start_read(plugin->modules, module) {
  665. struct job *job;
  666. dfe_start_read(module->jobs, job) {
  667. json_object *job_rich = json_object_new_object();
  668. json_object *obj = json_object_new_string(host->machine_guid);
  669. json_object_object_add(job_rich, "host_guid", obj);
  670. obj = json_object_new_string(plugin->name);
  671. json_object_object_add(job_rich, "plugin_name", obj);
  672. obj = json_object_new_string(module->name);
  673. json_object_object_add(job_rich, "module_name", obj);
  674. obj = job2json(job);
  675. json_object_object_add(job_rich, "job", obj);
  676. json_object_array_add(ret, job_rich);
  677. } dfe_done(job);
  678. } dfe_done(module);
  679. } dfe_done(plugin);
  680. }
  681. dfe_done(host);
  682. return ret;
  683. }
  684. static int web_client_api_request_v2_job_statuses(RRDHOST *host __maybe_unused, struct web_client *w, char *query) {
  685. json_object *json;
  686. if (strstr(query, "grouped") != NULL)
  687. json = job_statuses_grouped();
  688. else
  689. json = job_statuses_flat();
  690. buffer_flush(w->response.data);
  691. buffer_strcat(w->response.data, json_object_to_json_string_ext(json, JSON_C_TO_STRING_PRETTY));
  692. w->response.data->content_type = CT_APPLICATION_JSON;
  693. return HTTP_RESP_OK;
  694. }
  695. static struct web_api_command api_commands_v2[] = {
  696. {"info", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_info, 0},
  697. {"data", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_data, 0},
  698. {"weights", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_weights, 0},
  699. {"contexts", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_contexts, 0},
  700. {"nodes", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_nodes, 0},
  701. {"node_instances", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_node_instances, 0},
  702. {"versions", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_versions, 0},
  703. {"functions", 0, WEB_CLIENT_ACL_ACLK_WEBRTC_DASHBOARD_WITH_BEARER | ACL_DEV_OPEN_ACCESS, web_client_api_request_v2_functions, 0},
  704. {"q", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_q, 0},
  705. {"alerts", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_alerts, 0},
  706. {"alert_transitions", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_alert_transitions, 0},
  707. {"alert_config", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_alert_config, 0},
  708. {"claim", 0, WEB_CLIENT_ACL_NOCHECK, web_client_api_request_v2_claim, 0},
  709. {"rtc_offer", 0, WEB_CLIENT_ACL_ACLK | ACL_DEV_OPEN_ACCESS, web_client_api_request_v2_webrtc, 0},
  710. {"bearer_protection", 0, WEB_CLIENT_ACL_ACLK | ACL_DEV_OPEN_ACCESS, api_v2_bearer_protection, 0},
  711. {"bearer_get_token", 0, WEB_CLIENT_ACL_ACLK | ACL_DEV_OPEN_ACCESS, api_v2_bearer_token, 0},
  712. {"config", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_config, 1},
  713. {"job_statuses", 0, WEB_CLIENT_ACL_DASHBOARD_ACLK_WEBRTC, web_client_api_request_v2_job_statuses, 0},
  714. { "ilove.svg", 0, WEB_CLIENT_ACL_NOCHECK, web_client_api_request_v2_ilove, 0 },
  715. // terminator
  716. {NULL, 0, WEB_CLIENT_ACL_NONE, NULL, 0},
  717. };
  718. inline int web_client_api_request_v2(RRDHOST *host, struct web_client *w, char *url_path_endpoint) {
  719. static int initialized = 0;
  720. if(unlikely(initialized == 0)) {
  721. initialized = 1;
  722. for(int i = 0; api_commands_v2[i].command ; i++)
  723. api_commands_v2[i].hash = simple_hash(api_commands_v2[i].command);
  724. }
  725. return web_client_api_request_vX(host, w, url_path_endpoint, api_commands_v2);
  726. }