You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rspamd.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /*
  2. The MIT License (MIT)
  3. Copyright (C) 2012-2013 Anton Simonov <untone@gmail.com>
  4. Copyright (C) 2014-2017 Vsevolod Stakhov <vsevolod@highsecure.ru>
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. */
  21. /* global jQuery:false, Visibility:false */
  22. define(["jquery", "d3pie", "visibility", "nprogress", "app/stats", "app/graph", "app/config",
  23. "app/symbols", "app/history", "app/upload"],
  24. // eslint-disable-next-line max-params
  25. function ($, D3pie, visibility, NProgress, tab_stat, tab_graph, tab_config,
  26. tab_symbols, tab_history, tab_upload) {
  27. "use strict";
  28. // begin
  29. var graphs = {};
  30. var tables = {};
  31. var neighbours = []; // list of clusters
  32. var checked_server = "All SERVERS";
  33. var ui = {};
  34. var timer_id = [];
  35. var selData = null; // Graph's dataset selector state
  36. NProgress.configure({
  37. minimum: 0.01,
  38. showSpinner: false,
  39. });
  40. function cleanCredentials() {
  41. sessionStorage.clear();
  42. $("#statWidgets").empty();
  43. $("#listMaps").empty();
  44. $("#modalBody").empty();
  45. }
  46. function stopTimers() {
  47. for (var key in timer_id) {
  48. if (!{}.hasOwnProperty.call(timer_id, key)) continue;
  49. Visibility.stop(timer_id[key]);
  50. }
  51. }
  52. function disconnect() {
  53. [graphs, tables].forEach(function (o) {
  54. Object.keys(o).forEach(function (key) {
  55. o[key].destroy();
  56. delete o[key];
  57. });
  58. });
  59. stopTimers();
  60. cleanCredentials();
  61. ui.connect();
  62. }
  63. function tabClick(id) {
  64. var tab_id = id;
  65. if ($(tab_id).attr("disabled")) return;
  66. $(tab_id).attr("disabled", true);
  67. stopTimers();
  68. if (tab_id === "#refresh") {
  69. tab_id = "#" + $(".navbar-nav .active > a").attr("id");
  70. }
  71. switch (tab_id) {
  72. case "#status_nav":
  73. tab_stat.statWidgets(ui, graphs, checked_server);
  74. timer_id.status = Visibility.every(10000, function () {
  75. tab_stat.statWidgets(ui, graphs, checked_server);
  76. });
  77. break;
  78. case "#throughput_nav":
  79. tab_graph.draw(ui, graphs, tables, neighbours, checked_server, selData);
  80. var autoRefresh = {
  81. hourly: 60000,
  82. daily: 300000
  83. };
  84. timer_id.throughput = Visibility.every(autoRefresh[selData] || 3600000, function () {
  85. tab_graph.draw(ui, graphs, tables, neighbours, checked_server, selData);
  86. });
  87. break;
  88. case "#configuration_nav":
  89. tab_config.getActions(ui, checked_server);
  90. tab_config.getMaps(ui, checked_server);
  91. break;
  92. case "#symbols_nav":
  93. tab_symbols.getSymbols(ui, tables, checked_server);
  94. break;
  95. case "#history_nav":
  96. tab_history.getHistory(ui, tables);
  97. tab_history.getErrors(ui, tables);
  98. break;
  99. case "#disconnect":
  100. disconnect();
  101. break;
  102. default:
  103. }
  104. setTimeout(function () {
  105. $(tab_id).removeAttr("disabled");
  106. $("#refresh").removeAttr("disabled");
  107. }, 1000);
  108. }
  109. // @return password
  110. function getPassword() {
  111. return sessionStorage.getItem("Password");
  112. }
  113. // @save credentials
  114. function saveCredentials(password) {
  115. sessionStorage.setItem("Password", password);
  116. }
  117. function displayUI() {
  118. // In many browsers local storage can only store string.
  119. // So when we store the boolean true or false, it actually stores the strings "true" or "false".
  120. ui.read_only = sessionStorage.getItem("read_only") === "true";
  121. if (ui.read_only) {
  122. $("#learning_nav").hide();
  123. $("#resetHistory").attr("disabled", true);
  124. $("#errors-history").hide();
  125. } else {
  126. $("#learning_nav").show();
  127. $("#resetHistory").removeAttr("disabled", true);
  128. $("#errors-history").show();
  129. }
  130. var buttons = $("#navBar .pull-right");
  131. $("#mainUI").show();
  132. $("#progress").show();
  133. $(buttons).show();
  134. tabClick("#refresh");
  135. $("#progress").hide();
  136. }
  137. function alertMessage(alertClass, alertText) {
  138. var a = $("<div class=\"alert " + alertClass + " alert-dismissible fade in show\">" +
  139. "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" title=\"Dismiss\">&times;</button>" +
  140. "<strong>" + alertText + "</strong>");
  141. $(".notification-area").append(a);
  142. setTimeout(function () {
  143. $(a).fadeTo(500, 0).slideUp(500, function () {
  144. $(this).alert("close");
  145. });
  146. }, 5000);
  147. }
  148. function queryServer(neighbours_status, ind, req_url, o) {
  149. neighbours_status[ind].checked = false;
  150. neighbours_status[ind].data = {};
  151. neighbours_status[ind].status = false;
  152. var req_params = {
  153. jsonp: false,
  154. data: o.data,
  155. headers: $.extend({Password:getPassword()}, o.headers),
  156. url: neighbours_status[ind].url + req_url,
  157. xhr: function () {
  158. var xhr = $.ajaxSettings.xhr();
  159. // Download progress
  160. if (req_url !== "neighbours") {
  161. xhr.addEventListener("progress", function (e) {
  162. if (e.lengthComputable) {
  163. neighbours_status[ind].percentComplete = e.loaded / e.total;
  164. var percentComplete = neighbours_status.reduce(function (prev, curr) {
  165. return curr.percentComplete ? curr.percentComplete + prev : prev;
  166. }, 0);
  167. NProgress.set(percentComplete / neighbours_status.length);
  168. }
  169. }, false);
  170. }
  171. return xhr;
  172. },
  173. success: function (json) {
  174. neighbours_status[ind].checked = true;
  175. neighbours_status[ind].status = true;
  176. neighbours_status[ind].data = json;
  177. },
  178. error: function (jqXHR, textStatus, errorThrown) {
  179. neighbours_status[ind].checked = true;
  180. function errorMessage() {
  181. alertMessage("alert-error", neighbours_status[ind].name + " > " +
  182. (o.errorMessage ? o.errorMessage : "Request failed") +
  183. (errorThrown ? ": " + errorThrown : ""));
  184. }
  185. if (o.error) {
  186. o.error(neighbours_status[ind],
  187. jqXHR, textStatus, errorThrown);
  188. } else if (o.errorOnceId) {
  189. var alert_status = o.errorOnceId + neighbours_status[ind].name;
  190. if (!(alert_status in sessionStorage)) {
  191. sessionStorage.setItem(alert_status, true);
  192. errorMessage();
  193. }
  194. } else {
  195. errorMessage();
  196. }
  197. },
  198. complete: function (jqXHR) {
  199. if (neighbours_status.every(function (elt) { return elt.checked; })) {
  200. if (neighbours_status.some(function (elt) { return elt.status; })) {
  201. if (o.success) {
  202. o.success(neighbours_status, jqXHR);
  203. } else {
  204. alertMessage("alert-success", "Request completed");
  205. }
  206. } else {
  207. alertMessage("alert-error", "Request failed");
  208. }
  209. NProgress.done();
  210. }
  211. },
  212. statusCode: o.statusCode
  213. };
  214. if (o.method) {
  215. req_params.method = o.method;
  216. }
  217. if (o.params) {
  218. $.each(o.params, function (k, v) {
  219. req_params[k] = v;
  220. });
  221. }
  222. $.ajax(req_params);
  223. }
  224. // Public functions
  225. ui.alertMessage = alertMessage;
  226. ui.setup = function () {
  227. $("#selData").change(function () {
  228. selData = this.value;
  229. tabClick("#throughput_nav");
  230. });
  231. $.ajaxSetup({
  232. timeout: 20000,
  233. jsonp: false
  234. });
  235. $(document).ajaxStart(function () {
  236. $("#navBar").addClass("loading");
  237. });
  238. $(document).ajaxComplete(function () {
  239. setTimeout(function () {
  240. $("#navBar").removeClass("loading");
  241. }, 1000);
  242. });
  243. $("a[data-toggle=\"tab\"]").on("click", function (e) {
  244. var tab_id = "#" + $(e.target).attr("id");
  245. tabClick(tab_id);
  246. });
  247. $("#selSrv").change(function () {
  248. checked_server = this.value;
  249. $("#selSrv [value=\"" + checked_server + "\"]").prop("checked", true);
  250. tabClick("#" + $("#navBar ul li.active > a").attr("id"));
  251. });
  252. // Radio buttons
  253. $(document).on("click", "input:radio[name=\"clusterName\"]", function () {
  254. if (!this.disabled) {
  255. checked_server = this.value;
  256. tabClick("#status_nav");
  257. }
  258. });
  259. tab_config.setup(ui);
  260. tab_history.setup(ui, tables);
  261. tab_symbols.setup(ui, tables);
  262. tab_upload.setup(ui);
  263. selData = tab_graph.setup();
  264. };
  265. ui.connect = function () {
  266. // Query "/stat" to check if user is already logged in or client ip matches "secure_ip"
  267. $.ajax({
  268. type: "GET",
  269. url: "stat",
  270. async: false,
  271. success: function () {
  272. displayUI();
  273. },
  274. error: function () {
  275. var dialog = $("#connectDialog");
  276. var backdrop = $("#backDrop");
  277. $("#mainUI").hide();
  278. $(dialog).show();
  279. $(backdrop).show();
  280. $("#connectPassword").focus();
  281. $("#connectForm").off("submit");
  282. $("#connectForm").on("submit", function (e) {
  283. e.preventDefault();
  284. var password = $("#connectPassword").val();
  285. if (!(/^[\u0020-\u007e]*$/).test(password)) {
  286. alertMessage("alert-modal alert-error", "Invalid characters in the password");
  287. $("#connectPassword").focus();
  288. return;
  289. }
  290. ui.query("auth", {
  291. headers: {
  292. Password: password
  293. },
  294. success: function (json) {
  295. var data = json[0].data;
  296. $("#connectPassword").val("");
  297. if (data.auth === "ok") {
  298. sessionStorage.setItem("read_only", data.read_only);
  299. saveCredentials(password);
  300. $(dialog).hide();
  301. $(backdrop).hide();
  302. displayUI();
  303. }
  304. },
  305. error: function (jqXHR) {
  306. ui.alertMessage("alert-modal alert-error", jqXHR.statusText);
  307. $("#connectPassword").val("");
  308. $("#connectPassword").focus();
  309. },
  310. params: {
  311. global: false,
  312. },
  313. server: "local"
  314. });
  315. });
  316. }
  317. });
  318. };
  319. ui.drawPie = function (object, id, data, conf) {
  320. var obj = object;
  321. if (obj) {
  322. obj.updateProp("data.content",
  323. data.filter(function (elt) {
  324. return elt.value > 0;
  325. })
  326. );
  327. } else {
  328. obj = new D3pie(id,
  329. $.extend({}, {
  330. header: {
  331. title: {
  332. text: "Rspamd filter stats",
  333. fontSize: 24,
  334. font: "open sans"
  335. },
  336. subtitle: {
  337. color: "#999999",
  338. fontSize: 12,
  339. font: "open sans"
  340. },
  341. titleSubtitlePadding: 9
  342. },
  343. footer: {
  344. color: "#999999",
  345. fontSize: 10,
  346. font: "open sans",
  347. location: "bottom-left"
  348. },
  349. size: {
  350. canvasWidth: 600,
  351. canvasHeight: 400,
  352. pieInnerRadius: "20%",
  353. pieOuterRadius: "85%"
  354. },
  355. data: {
  356. // "sortOrder": "value-desc",
  357. content: data.filter(function (elt) {
  358. return elt.value > 0;
  359. })
  360. },
  361. labels: {
  362. outer: {
  363. hideWhenLessThanPercentage: 1,
  364. pieDistance: 30
  365. },
  366. inner: {
  367. hideWhenLessThanPercentage: 4
  368. },
  369. mainLabel: {
  370. fontSize: 14
  371. },
  372. percentage: {
  373. color: "#eeeeee",
  374. fontSize: 14,
  375. decimalPlaces: 0
  376. },
  377. lines: {
  378. enabled: true
  379. },
  380. truncation: {
  381. enabled: true
  382. }
  383. },
  384. tooltips: {
  385. enabled: true,
  386. type: "placeholder",
  387. string: "{label}: {value} ({percentage}%)"
  388. },
  389. effects: {
  390. pullOutSegmentOnClick: {
  391. effect: "back",
  392. speed: 400,
  393. size: 8
  394. },
  395. load: {
  396. effect: "none"
  397. }
  398. },
  399. misc: {
  400. gradient: {
  401. enabled: true,
  402. percentage: 100
  403. }
  404. }
  405. }, conf));
  406. }
  407. return obj;
  408. };
  409. ui.getPassword = getPassword;
  410. /**
  411. * @param {string} url - A string containing the URL to which the request is sent
  412. * @param {Object} [options] - A set of key/value pairs that configure the Ajax request. All settings are optional.
  413. *
  414. * @param {Object|string|Array} [options.data] - Data to be sent to the server.
  415. * @param {Function} [options.error] - A function to be called if the request fails.
  416. * @param {string} [options.errorMessage] - Text to display in the alert message if the request fails.
  417. * @param {string} [options.errorOnceId] - A prefix of the alert ID to be added to the session storage. If the
  418. * parameter is set, the error for each server will be displayed only once per session.
  419. * @param {Object} [options.headers] - An object of additional header key/value pairs to send along with requests
  420. * using the XMLHttpRequest transport.
  421. * @param {string} [options.method] - The HTTP method to use for the request.
  422. * @param {Object} [options.params] - An object of additional jQuery.ajax() settings key/value pairs.
  423. * @param {string} [options.server] - A server to which send the request.
  424. * @param {Function} [options.success] - A function to be called if the request succeeds.
  425. *
  426. * @returns {undefined}
  427. */
  428. ui.query = function (url, options) {
  429. // Force options to be an object
  430. var o = options || {};
  431. Object.keys(o).forEach(function (option) {
  432. if (["data", "error", "errorMessage", "errorOnceId", "headers", "method", "params", "server", "statusCode",
  433. "success"]
  434. .indexOf(option) < 0) {
  435. throw new Error("Unknown option: " + option);
  436. }
  437. });
  438. var neighbours_status = [{
  439. name: "local",
  440. host: "local",
  441. url: "",
  442. }];
  443. o.server = o.server || checked_server;
  444. if (o.server === "All SERVERS") {
  445. queryServer(neighbours_status, 0, "neighbours", {
  446. success: function (json) {
  447. var data = json[0].data;
  448. if (jQuery.isEmptyObject(data)) {
  449. neighbours = {
  450. local: {
  451. host: window.location.host,
  452. url: window.location.href
  453. }
  454. };
  455. } else {
  456. neighbours = data;
  457. }
  458. neighbours_status = [];
  459. $.each(neighbours, function (ind) {
  460. neighbours_status.push({
  461. name: ind,
  462. host: neighbours[ind].host,
  463. url: neighbours[ind].url,
  464. });
  465. });
  466. $.each(neighbours_status, function (ind) {
  467. queryServer(neighbours_status, ind, url, o);
  468. });
  469. },
  470. errorMessage: "Cannot receive neighbours data"
  471. });
  472. } else {
  473. if (o.server !== "local") {
  474. neighbours_status = [{
  475. name: o.server,
  476. host: neighbours[o.server].host,
  477. url: neighbours[o.server].url,
  478. }];
  479. }
  480. queryServer(neighbours_status, 0, url, o);
  481. }
  482. };
  483. return ui;
  484. });