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.

controller.c 46KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711
  1. /* Copyright (c) 2010-2012, Vsevolod Stakhov
  2. * All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. * * Redistributions of source code must retain the above copyright
  7. * notice, this list of conditions and the following disclaimer.
  8. * * Redistributions in binary form must reproduce the above copyright
  9. * notice, this list of conditions and the following disclaimer in the
  10. * documentation and/or other materials provided with the distribution.
  11. *
  12. * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
  13. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  14. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  15. * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY
  16. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  17. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  18. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  19. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  20. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  21. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22. */
  23. #include "config.h"
  24. #include "libserver/dynamic_cfg.h"
  25. #include "libutil/rrd.h"
  26. #include "libutil/map.h"
  27. #include "libstat/stat_api.h"
  28. #include "main.h"
  29. #ifdef WITH_GPERF_TOOLS
  30. # include <glib/gprintf.h>
  31. #endif
  32. /* 60 seconds for worker's IO */
  33. #define DEFAULT_WORKER_IO_TIMEOUT 60000
  34. /* HTTP paths */
  35. #define PATH_AUTH "/auth"
  36. #define PATH_SYMBOLS "/symbols"
  37. #define PATH_ACTIONS "/actions"
  38. #define PATH_MAPS "/maps"
  39. #define PATH_GET_MAP "/getmap"
  40. #define PATH_GRAPH "/graph"
  41. #define PATH_PIE_CHART "/pie"
  42. #define PATH_HISTORY "/history"
  43. #define PATH_LEARN_SPAM "/learnspam"
  44. #define PATH_LEARN_HAM "/learnham"
  45. #define PATH_SAVE_ACTIONS "/saveactions"
  46. #define PATH_SAVE_SYMBOLS "/savesymbols"
  47. #define PATH_SAVE_MAP "/savemap"
  48. #define PATH_SCAN "/scan"
  49. #define PATH_CHECK "/check"
  50. #define PATH_STAT "/stat"
  51. #define PATH_STAT_RESET "/statreset"
  52. #define PATH_COUNTERS "/counters"
  53. /* Graph colors */
  54. #define COLOR_CLEAN "#58A458"
  55. #define COLOR_PROBABLE_SPAM "#D67E7E"
  56. #define COLOR_GREYLIST "#A0A0A0"
  57. #define COLOR_REJECT "#CB4B4B"
  58. #define COLOR_TOTAL "#9440ED"
  59. gpointer init_controller_worker (struct rspamd_config *cfg);
  60. void start_controller_worker (struct rspamd_worker *worker);
  61. worker_t controller_worker = {
  62. "controller", /* Name */
  63. init_controller_worker, /* Init function */
  64. start_controller_worker, /* Start function */
  65. TRUE, /* Has socket */
  66. TRUE, /* Non unique */
  67. FALSE, /* Non threaded */
  68. TRUE, /* Killable */
  69. SOCK_STREAM /* TCP socket */
  70. };
  71. /*
  72. * Worker's context
  73. */
  74. struct rspamd_controller_worker_ctx {
  75. guint32 timeout;
  76. struct timeval io_tv;
  77. /* DNS resolver */
  78. struct rspamd_dns_resolver *resolver;
  79. /* Events base */
  80. struct event_base *ev_base;
  81. /* Whether we use ssl for this server */
  82. gboolean use_ssl;
  83. /* Webui password */
  84. gchar *password;
  85. /* Privilleged password */
  86. gchar *enable_password;
  87. /* HTTP server */
  88. struct rspamd_http_connection_router *http;
  89. /* Server's start time */
  90. time_t start_time;
  91. /* Main server */
  92. struct rspamd_main *srv;
  93. /* Configuration */
  94. struct rspamd_config *cfg;
  95. /* SSL cert */
  96. gchar *ssl_cert;
  97. /* SSL private key */
  98. gchar *ssl_key;
  99. /* A map of secure IP */
  100. gchar *secure_ip;
  101. radix_compressed_t *secure_map;
  102. /* Static files dir */
  103. gchar *static_files_dir;
  104. /* Custom commands registered by plugins */
  105. GHashTable *custom_commands;
  106. /* Worker */
  107. struct rspamd_worker *worker;
  108. /* Local keypair */
  109. gpointer key;
  110. };
  111. struct rspamd_controller_session {
  112. struct rspamd_controller_worker_ctx *ctx;
  113. rspamd_mempool_t *pool;
  114. struct rspamd_task *task;
  115. struct rspamd_classifier_config *cl;
  116. rspamd_inet_addr_t from_addr;
  117. gboolean is_spam;
  118. };
  119. /* Check for password if it is required by configuration */
  120. static gboolean
  121. rspamd_controller_check_password (struct rspamd_http_connection_entry *entry,
  122. struct rspamd_controller_session *session, struct rspamd_http_message *msg,
  123. gboolean is_enable)
  124. {
  125. const gchar *password, *check;
  126. struct rspamd_controller_worker_ctx *ctx = session->ctx;
  127. gboolean ret = TRUE;
  128. /* Access list logic */
  129. if (!session->from_addr.af == AF_UNIX) {
  130. msg_info ("allow unauthorized connection from a unix socket");
  131. return TRUE;
  132. }
  133. else if (ctx->secure_map && radix_find_compressed_addr (ctx->secure_map,
  134. &session->from_addr) != RADIX_NO_VALUE) {
  135. msg_info ("allow unauthorized connection from a trusted IP %s",
  136. rspamd_inet_address_to_string (&session->from_addr));
  137. return TRUE;
  138. }
  139. /* Password logic */
  140. if (is_enable) {
  141. /* For privileged commands we strictly require enable password */
  142. password = rspamd_http_message_find_header (msg, "Password");
  143. if (ctx->enable_password == NULL) {
  144. /* Use just a password (legacy mode) */
  145. msg_info (
  146. "using password as enable_password for a privileged command");
  147. check = ctx->password;
  148. }
  149. else {
  150. check = ctx->enable_password;
  151. }
  152. if (check != NULL) {
  153. if (password == NULL || strcmp (password, check) != 0) {
  154. msg_info ("incorrect or absent password has been specified");
  155. ret = FALSE;
  156. }
  157. }
  158. else {
  159. msg_warn (
  160. "no password to check while executing a privileged command");
  161. if (ctx->secure_map) {
  162. msg_info ("deny unauthorized connection");
  163. ret = FALSE;
  164. }
  165. }
  166. }
  167. else {
  168. password = rspamd_http_message_find_header (msg, "Password");
  169. if (ctx->password != NULL) {
  170. /* Accept both normal and enable passwords */
  171. check = ctx->password;
  172. if (password == NULL) {
  173. msg_info ("absent password has been specified");
  174. ret = FALSE;
  175. }
  176. else if (strcmp (password, check) != 0) {
  177. if (ctx->enable_password != NULL) {
  178. check = ctx->enable_password;
  179. if (strcmp (password, check) != 0) {
  180. msg_info ("incorrect password has been specified");
  181. ret = FALSE;
  182. }
  183. }
  184. else {
  185. msg_info ("incorrect or absent password has been specified");
  186. ret = FALSE;
  187. }
  188. }
  189. }
  190. /* No password specified, allowing this command */
  191. }
  192. if (!ret) {
  193. rspamd_controller_send_error (entry, 403, "Unauthorized");
  194. }
  195. return ret;
  196. }
  197. /* Command handlers */
  198. /*
  199. * Auth command handler:
  200. * request: /auth
  201. * headers: Password
  202. * reply: json {"auth": "ok", "version": "0.5.2", "uptime": "some uptime", "error": "none"}
  203. */
  204. static int
  205. rspamd_controller_handle_auth (struct rspamd_http_connection_entry *conn_ent,
  206. struct rspamd_http_message *msg)
  207. {
  208. struct rspamd_controller_session *session = conn_ent->ud;
  209. struct rspamd_stat *st;
  210. int64_t uptime;
  211. gulong data[4];
  212. ucl_object_t *obj;
  213. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  214. return 0;
  215. }
  216. obj = ucl_object_typed_new (UCL_OBJECT);
  217. st = session->ctx->srv->stat;
  218. data[0] = st->actions_stat[METRIC_ACTION_NOACTION];
  219. data[1] = st->actions_stat[METRIC_ACTION_ADD_HEADER] +
  220. st->actions_stat[METRIC_ACTION_REWRITE_SUBJECT];
  221. data[2] = st->actions_stat[METRIC_ACTION_GREYLIST];
  222. data[3] = st->actions_stat[METRIC_ACTION_REJECT];
  223. /* Get uptime */
  224. uptime = time (NULL) - session->ctx->start_time;
  225. ucl_object_insert_key (obj, ucl_object_fromstring (
  226. RVERSION), "version", 0, false);
  227. ucl_object_insert_key (obj, ucl_object_fromstring (
  228. "ok"), "auth", 0, false);
  229. ucl_object_insert_key (obj, ucl_object_fromint (
  230. uptime), "uptime", 0, false);
  231. ucl_object_insert_key (obj, ucl_object_fromint (
  232. data[0]), "clean", 0, false);
  233. ucl_object_insert_key (obj, ucl_object_fromint (
  234. data[1]), "probable", 0, false);
  235. ucl_object_insert_key (obj, ucl_object_fromint (
  236. data[2]), "greylist", 0, false);
  237. ucl_object_insert_key (obj, ucl_object_fromint (
  238. data[3]), "reject", 0, false);
  239. ucl_object_insert_key (obj, ucl_object_fromint (
  240. st->messages_scanned), "scanned", 0, false);
  241. ucl_object_insert_key (obj, ucl_object_fromint (
  242. st->messages_learned), "learned", 0, false);
  243. rspamd_controller_send_ucl (conn_ent, obj);
  244. ucl_object_unref (obj);
  245. return 0;
  246. }
  247. /*
  248. * Symbols command handler:
  249. * request: /symbols
  250. * reply: json [{
  251. * "name": "group_name",
  252. * "symbols": [
  253. * {
  254. * "name": "name",
  255. * "weight": 0.1,
  256. * "description": "description of symbol"
  257. * },
  258. * {...}
  259. * },
  260. * {...}]
  261. */
  262. static int
  263. rspamd_controller_handle_symbols (struct rspamd_http_connection_entry *conn_ent,
  264. struct rspamd_http_message *msg)
  265. {
  266. struct rspamd_controller_session *session = conn_ent->ud;
  267. GList *cur_gr, *cur_sym;
  268. struct rspamd_symbols_group *gr;
  269. struct rspamd_symbol_def *sym;
  270. ucl_object_t *obj, *top, *sym_obj;
  271. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  272. return 0;
  273. }
  274. top = ucl_object_typed_new (UCL_ARRAY);
  275. /* Go through all symbols groups */
  276. cur_gr = session->ctx->cfg->symbols_groups;
  277. while (cur_gr) {
  278. gr = cur_gr->data;
  279. obj = ucl_object_typed_new (UCL_OBJECT);
  280. ucl_object_insert_key (obj, ucl_object_fromstring (
  281. gr->name), "group", 0, false);
  282. /* Iterate through all symbols */
  283. cur_sym = gr->symbols;
  284. while (cur_sym) {
  285. sym_obj = ucl_object_typed_new (UCL_OBJECT);
  286. sym = cur_sym->data;
  287. ucl_object_insert_key (sym_obj, ucl_object_fromstring (sym->name),
  288. "symbol", 0, false);
  289. ucl_object_insert_key (sym_obj,
  290. ucl_object_fromdouble (*sym->weight_ptr),
  291. "weight", 0, false);
  292. if (sym->description) {
  293. ucl_object_insert_key (sym_obj,
  294. ucl_object_fromstring (sym->description),
  295. "description", 0, false);
  296. }
  297. ucl_object_insert_key (obj, sym_obj, "rules", 0, false);
  298. cur_sym = g_list_next (cur_sym);
  299. }
  300. cur_gr = g_list_next (cur_gr);
  301. ucl_array_append (top, obj);
  302. }
  303. rspamd_controller_send_ucl (conn_ent, top);
  304. ucl_object_unref (top);
  305. return 0;
  306. }
  307. /*
  308. * Actions command handler:
  309. * request: /actions
  310. * reply: json [{
  311. * "action": "no action",
  312. * "value": 1.1
  313. * },
  314. * {...}]
  315. */
  316. static int
  317. rspamd_controller_handle_actions (struct rspamd_http_connection_entry *conn_ent,
  318. struct rspamd_http_message *msg)
  319. {
  320. struct rspamd_controller_session *session = conn_ent->ud;
  321. struct metric *metric;
  322. struct metric_action *act;
  323. gint i;
  324. ucl_object_t *obj, *top;
  325. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  326. return 0;
  327. }
  328. top = ucl_object_typed_new (UCL_ARRAY);
  329. /* Get actions for default metric */
  330. metric = g_hash_table_lookup (session->ctx->cfg->metrics, DEFAULT_METRIC);
  331. if (metric != NULL) {
  332. for (i = METRIC_ACTION_REJECT; i < METRIC_ACTION_MAX; i++) {
  333. act = &metric->actions[i];
  334. if (act->score >= 0) {
  335. obj = ucl_object_typed_new (UCL_OBJECT);
  336. ucl_object_insert_key (obj,
  337. ucl_object_fromstring (rspamd_action_to_str (
  338. act->action)), "action", 0, false);
  339. ucl_object_insert_key (obj, ucl_object_fromdouble (
  340. act->score), "value", 0, false);
  341. ucl_array_append (top, obj);
  342. }
  343. }
  344. }
  345. rspamd_controller_send_ucl (conn_ent, top);
  346. ucl_object_unref (top);
  347. return 0;
  348. }
  349. /*
  350. * Maps command handler:
  351. * request: /maps
  352. * headers: Password
  353. * reply: json [
  354. * {
  355. * "map": "name",
  356. * "description": "description",
  357. * "editable": true
  358. * },
  359. * {...}
  360. * ]
  361. */
  362. static int
  363. rspamd_controller_handle_maps (struct rspamd_http_connection_entry *conn_ent,
  364. struct rspamd_http_message *msg)
  365. {
  366. struct rspamd_controller_session *session = conn_ent->ud;
  367. GList *cur, *tmp = NULL;
  368. struct rspamd_map *map;
  369. gboolean editable;
  370. ucl_object_t *obj, *top;
  371. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  372. return 0;
  373. }
  374. top = ucl_object_typed_new (UCL_ARRAY);
  375. /* Iterate over all maps */
  376. cur = session->ctx->cfg->maps;
  377. while (cur) {
  378. map = cur->data;
  379. if (map->protocol == MAP_PROTO_FILE) {
  380. if (access (map->uri, R_OK) == 0) {
  381. tmp = g_list_prepend (tmp, map);
  382. }
  383. }
  384. cur = g_list_next (cur);
  385. }
  386. /* Iterate over selected maps */
  387. cur = tmp;
  388. while (cur) {
  389. map = cur->data;
  390. editable = (access (map->uri, W_OK) == 0);
  391. obj = ucl_object_typed_new (UCL_OBJECT);
  392. ucl_object_insert_key (obj, ucl_object_fromint (map->id),
  393. "map", 0, false);
  394. if (map->description) {
  395. ucl_object_insert_key (obj, ucl_object_fromstring (map->description),
  396. "description", 0, false);
  397. }
  398. ucl_object_insert_key (obj, ucl_object_frombool (editable),
  399. "editable", 0, false);
  400. ucl_array_append (top, obj);
  401. cur = g_list_next (cur);
  402. }
  403. if (tmp) {
  404. g_list_free (tmp);
  405. }
  406. rspamd_controller_send_ucl (conn_ent, top);
  407. ucl_object_unref (top);
  408. return 0;
  409. }
  410. /*
  411. * Get map command handler:
  412. * request: /getmap
  413. * headers: Password, Map
  414. * reply: plain-text
  415. */
  416. static int
  417. rspamd_controller_handle_get_map (struct rspamd_http_connection_entry *conn_ent,
  418. struct rspamd_http_message *msg)
  419. {
  420. struct rspamd_controller_session *session = conn_ent->ud;
  421. GList *cur;
  422. struct rspamd_map *map;
  423. const gchar *idstr;
  424. gchar *errstr;
  425. struct stat st;
  426. gint fd;
  427. guint32 id;
  428. gboolean found = FALSE;
  429. struct rspamd_http_message *reply;
  430. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  431. return 0;
  432. }
  433. idstr = rspamd_http_message_find_header (msg, "Map");
  434. if (idstr == NULL) {
  435. msg_info ("absent map id");
  436. rspamd_controller_send_error (conn_ent, 400, "400 id header missing");
  437. return 0;
  438. }
  439. id = strtoul (idstr, &errstr, 10);
  440. if (*errstr != '\0') {
  441. msg_info ("invalid map id");
  442. rspamd_controller_send_error (conn_ent, 400, "400 invalid map id");
  443. return 0;
  444. }
  445. /* Now let's be sure that we have map defined in configuration */
  446. cur = session->ctx->cfg->maps;
  447. while (cur) {
  448. map = cur->data;
  449. if (map->id == id && map->protocol == MAP_PROTO_FILE) {
  450. found = TRUE;
  451. break;
  452. }
  453. cur = g_list_next (cur);
  454. }
  455. if (!found) {
  456. msg_info ("map not found");
  457. rspamd_controller_send_error (conn_ent, 404, "404 map not found");
  458. return 0;
  459. }
  460. if (stat (map->uri, &st) == -1 || (fd = open (map->uri, O_RDONLY)) == -1) {
  461. msg_err ("cannot open map %s: %s", map->uri, strerror (errno));
  462. rspamd_controller_send_error (conn_ent, 500, "500 map open error");
  463. return 0;
  464. }
  465. reply = rspamd_http_new_message (HTTP_RESPONSE);
  466. reply->date = time (NULL);
  467. reply->code = 200;
  468. reply->body = g_string_sized_new (st.st_size);
  469. /* Read the whole buffer */
  470. if (read (fd, reply->body->str, st.st_size) == -1) {
  471. close (fd);
  472. rspamd_http_message_free (reply);
  473. msg_err ("cannot read map %s: %s", map->uri, strerror (errno));
  474. rspamd_controller_send_error (conn_ent, 500, "500 map read error");
  475. return 0;
  476. }
  477. reply->body->len = st.st_size;
  478. reply->body->str[reply->body->len] = '\0';
  479. close (fd);
  480. rspamd_http_connection_reset (conn_ent->conn);
  481. rspamd_http_connection_write_message (conn_ent->conn, reply, NULL,
  482. "text/plain", conn_ent, conn_ent->conn->fd,
  483. conn_ent->rt->ptv, conn_ent->rt->ev_base);
  484. conn_ent->is_reply = TRUE;
  485. return 0;
  486. }
  487. static ucl_object_t *
  488. rspamd_controller_pie_element (enum rspamd_metric_action action,
  489. const char *label, gdouble data)
  490. {
  491. ucl_object_t *res = ucl_object_typed_new (UCL_OBJECT);
  492. const char *colors[METRIC_ACTION_MAX] = {
  493. [METRIC_ACTION_REJECT] = "#993300",
  494. [METRIC_ACTION_SOFT_REJECT] = "#cc9966",
  495. [METRIC_ACTION_REWRITE_SUBJECT] = "#ff6600",
  496. [METRIC_ACTION_ADD_HEADER] = "#ffcc66",
  497. [METRIC_ACTION_GREYLIST] = "#6666cc",
  498. [METRIC_ACTION_NOACTION] = "#66cc00"
  499. };
  500. ucl_object_insert_key (res, ucl_object_fromstring (colors[action]),
  501. "color", 0, false);
  502. ucl_object_insert_key (res, ucl_object_fromstring (label), "label", 0, false);
  503. ucl_object_insert_key (res, ucl_object_fromdouble (data), "data", 0, false);
  504. return res;
  505. }
  506. /*
  507. * Pie chart command handler:
  508. * request: /pie
  509. * headers: Password
  510. * reply: json [
  511. * { label: "Foo", data: 11 },
  512. * { label: "Bar", data: 20 },
  513. * {...}
  514. * ]
  515. */
  516. static int
  517. rspamd_controller_handle_pie_chart (
  518. struct rspamd_http_connection_entry *conn_ent,
  519. struct rspamd_http_message *msg)
  520. {
  521. struct rspamd_controller_session *session = conn_ent->ud;
  522. struct rspamd_controller_worker_ctx *ctx;
  523. gdouble data[5], total;
  524. ucl_object_t *top;
  525. ctx = session->ctx;
  526. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  527. return 0;
  528. }
  529. top = ucl_object_typed_new (UCL_ARRAY);
  530. total = ctx->srv->stat->messages_scanned;
  531. if (total != 0) {
  532. data[0] = ctx->srv->stat->actions_stat[METRIC_ACTION_NOACTION] / total *
  533. 100.;
  534. data[1] = ctx->srv->stat->actions_stat[METRIC_ACTION_SOFT_REJECT] / total *
  535. 100.;
  536. data[2] = (ctx->srv->stat->actions_stat[METRIC_ACTION_ADD_HEADER] +
  537. ctx->srv->stat->actions_stat[METRIC_ACTION_REWRITE_SUBJECT]) /
  538. total * 100.;
  539. data[3] = ctx->srv->stat->actions_stat[METRIC_ACTION_GREYLIST] / total *
  540. 100.;
  541. data[4] = ctx->srv->stat->actions_stat[METRIC_ACTION_REJECT] / total *
  542. 100.;
  543. }
  544. else {
  545. memset (data, 0, sizeof (data));
  546. }
  547. ucl_array_append (top, rspamd_controller_pie_element (
  548. METRIC_ACTION_NOACTION, "Clean", data[0]));
  549. ucl_array_append (top, rspamd_controller_pie_element (
  550. METRIC_ACTION_SOFT_REJECT, "Temporary rejected", data[1]));
  551. ucl_array_append (top, rspamd_controller_pie_element (
  552. METRIC_ACTION_ADD_HEADER, "Probable spam", data[2]));
  553. ucl_array_append (top, rspamd_controller_pie_element (
  554. METRIC_ACTION_GREYLIST, "Greylisted", data[3]));
  555. ucl_array_append (top, rspamd_controller_pie_element (
  556. METRIC_ACTION_REJECT, "Rejected", data[4]));
  557. rspamd_controller_send_ucl (conn_ent, top);
  558. ucl_object_unref (top);
  559. return 0;
  560. }
  561. /*
  562. * History command handler:
  563. * request: /history
  564. * headers: Password
  565. * reply: json [
  566. * { label: "Foo", data: 11 },
  567. * { label: "Bar", data: 20 },
  568. * {...}
  569. * ]
  570. */
  571. static int
  572. rspamd_controller_handle_history (struct rspamd_http_connection_entry *conn_ent,
  573. struct rspamd_http_message *msg)
  574. {
  575. struct rspamd_controller_session *session = conn_ent->ud;
  576. struct rspamd_controller_worker_ctx *ctx;
  577. struct roll_history_row *row;
  578. struct roll_history copied_history;
  579. gint i, rows_proc, row_num;
  580. struct tm *tm;
  581. gchar timebuf[32];
  582. ucl_object_t *top, *obj;
  583. ctx = session->ctx;
  584. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  585. return 0;
  586. }
  587. top = ucl_object_typed_new (UCL_ARRAY);
  588. /* Set lock on history */
  589. rspamd_mempool_lock_mutex (ctx->srv->history->mtx);
  590. ctx->srv->history->need_lock = TRUE;
  591. /* Copy locked */
  592. memcpy (&copied_history, ctx->srv->history, sizeof (copied_history));
  593. rspamd_mempool_unlock_mutex (ctx->srv->history->mtx);
  594. /* Go through all rows */
  595. row_num = copied_history.cur_row;
  596. for (i = 0, rows_proc = 0; i < HISTORY_MAX_ROWS; i++, row_num++) {
  597. if (row_num == HISTORY_MAX_ROWS) {
  598. row_num = 0;
  599. }
  600. row = &copied_history.rows[row_num];
  601. /* Get only completed rows */
  602. if (row->completed) {
  603. tm = localtime (&row->tv.tv_sec);
  604. strftime (timebuf, sizeof (timebuf) - 1, "%Y-%m-%d %H:%M:%S", tm);
  605. obj = ucl_object_typed_new (UCL_OBJECT);
  606. ucl_object_insert_key (obj, ucl_object_fromstring (
  607. timebuf), "time", 0, false);
  608. ucl_object_insert_key (obj, ucl_object_fromstring (
  609. row->message_id), "id", 0, false);
  610. ucl_object_insert_key (obj, ucl_object_fromstring (
  611. rspamd_inet_address_to_string (&row->from_addr)),
  612. "ip", 0, false);
  613. ucl_object_insert_key (obj,
  614. ucl_object_fromstring (rspamd_action_to_str (
  615. row->action)), "action", 0, false);
  616. ucl_object_insert_key (obj, ucl_object_fromdouble (
  617. row->score), "score", 0, false);
  618. ucl_object_insert_key (obj,
  619. ucl_object_fromdouble (
  620. row->required_score), "required_score", 0, false);
  621. ucl_object_insert_key (obj, ucl_object_fromstring (
  622. row->symbols), "symbols", 0, false);
  623. ucl_object_insert_key (obj, ucl_object_fromint (
  624. row->len), "size", 0, false);
  625. ucl_object_insert_key (obj, ucl_object_fromint (
  626. row->scan_time), "scan_time", 0, false);
  627. if (row->user[0] != '\0') {
  628. ucl_object_insert_key (obj, ucl_object_fromstring (
  629. row->user), "user", 0, false);
  630. }
  631. ucl_array_append (top, obj);
  632. rows_proc++;
  633. }
  634. }
  635. rspamd_controller_send_ucl (conn_ent, top);
  636. ucl_object_unref (top);
  637. return 0;
  638. }
  639. static gboolean
  640. rspamd_controller_learn_fin_task (void *ud)
  641. {
  642. struct rspamd_task *task = ud;
  643. struct rspamd_controller_session *session;
  644. struct rspamd_http_connection_entry *conn_ent;
  645. GError *err = NULL;
  646. conn_ent = task->fin_arg;
  647. session = conn_ent->ud;
  648. if (!rspamd_learn_task_spam (session->cl, task, session->is_spam, &err)) {
  649. rspamd_controller_send_error (conn_ent, 500 + err->code, err->message);
  650. return TRUE;
  651. }
  652. /* Successful learn */
  653. msg_info ("<%s> learned message: %s",
  654. rspamd_inet_address_to_string (&session->from_addr),
  655. task->message_id);
  656. rspamd_controller_send_string (conn_ent, "{\"success\":true}");
  657. return TRUE;
  658. }
  659. static gboolean
  660. rspamd_controller_check_fin_task (void *ud)
  661. {
  662. struct rspamd_task *task = ud;
  663. struct rspamd_http_connection_entry *conn_ent;
  664. struct rspamd_http_message *msg;
  665. rspamd_process_statistics (task);
  666. conn_ent = task->fin_arg;
  667. msg = rspamd_http_new_message (HTTP_RESPONSE);
  668. msg->date = time (NULL);
  669. msg->code = 200;
  670. rspamd_protocol_http_reply (msg, task);
  671. rspamd_http_connection_reset (conn_ent->conn);
  672. rspamd_http_connection_write_message (conn_ent->conn, msg, NULL,
  673. "application/json", conn_ent, conn_ent->conn->fd, conn_ent->rt->ptv,
  674. conn_ent->rt->ev_base);
  675. conn_ent->is_reply = TRUE;
  676. return TRUE;
  677. }
  678. static int
  679. rspamd_controller_handle_learn_common (
  680. struct rspamd_http_connection_entry *conn_ent,
  681. struct rspamd_http_message *msg,
  682. gboolean is_spam)
  683. {
  684. struct rspamd_controller_session *session = conn_ent->ud;
  685. struct rspamd_controller_worker_ctx *ctx;
  686. struct rspamd_classifier_config *cl;
  687. struct rspamd_task *task;
  688. const gchar *classifier;
  689. ctx = session->ctx;
  690. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  691. return 0;
  692. }
  693. if (msg->body == NULL || msg->body->len == 0) {
  694. msg_err ("got zero length body, cannot continue");
  695. rspamd_controller_send_error (conn_ent,
  696. 400,
  697. "Empty body is not permitted");
  698. return 0;
  699. }
  700. if ((classifier =
  701. rspamd_http_message_find_header (msg, "Classifier")) == NULL) {
  702. classifier = "bayes";
  703. }
  704. cl = rspamd_config_find_classifier (ctx->cfg, classifier);
  705. if (cl == NULL) {
  706. rspamd_controller_send_error (conn_ent, 400, "Classifier not found");
  707. return 0;
  708. }
  709. task = rspamd_task_new (session->ctx->worker);
  710. task->resolver = ctx->resolver;
  711. task->ev_base = ctx->ev_base;
  712. task->s = new_async_session (session->pool,
  713. rspamd_controller_learn_fin_task,
  714. NULL,
  715. rspamd_task_free_hard,
  716. task);
  717. task->s->wanna_die = TRUE;
  718. task->fin_arg = conn_ent;
  719. task->http_conn = rspamd_http_connection_ref (conn_ent->conn);;
  720. task->sock = conn_ent->conn->fd;
  721. /* XXX: Handle encrypted messages */
  722. if (!rspamd_task_process (task, msg, msg->body->str, msg->body->len, NULL, FALSE)) {
  723. msg_warn ("filters cannot be processed for %s", task->message_id);
  724. rspamd_controller_send_error (conn_ent, 500, task->last_error);
  725. destroy_session (task->s);
  726. return 0;
  727. }
  728. session->task = task;
  729. session->cl = cl;
  730. session->is_spam = is_spam;
  731. check_session_pending (task->s);
  732. return 0;
  733. }
  734. /*
  735. * Learn spam command handler:
  736. * request: /learnspam
  737. * headers: Password
  738. * input: plaintext data
  739. * reply: json {"success":true} or {"error":"error message"}
  740. */
  741. static int
  742. rspamd_controller_handle_learnspam (
  743. struct rspamd_http_connection_entry *conn_ent,
  744. struct rspamd_http_message *msg)
  745. {
  746. return rspamd_controller_handle_learn_common (conn_ent, msg, TRUE);
  747. }
  748. /*
  749. * Learn ham command handler:
  750. * request: /learnham
  751. * headers: Password
  752. * input: plaintext data
  753. * reply: json {"success":true} or {"error":"error message"}
  754. */
  755. static int
  756. rspamd_controller_handle_learnham (
  757. struct rspamd_http_connection_entry *conn_ent,
  758. struct rspamd_http_message *msg)
  759. {
  760. return rspamd_controller_handle_learn_common (conn_ent, msg, FALSE);
  761. }
  762. /*
  763. * Scan command handler:
  764. * request: /scan
  765. * headers: Password
  766. * input: plaintext data
  767. * reply: json {scan data} or {"error":"error message"}
  768. */
  769. static int
  770. rspamd_controller_handle_scan (struct rspamd_http_connection_entry *conn_ent,
  771. struct rspamd_http_message *msg)
  772. {
  773. struct rspamd_controller_session *session = conn_ent->ud;
  774. struct rspamd_controller_worker_ctx *ctx;
  775. struct rspamd_task *task;
  776. ctx = session->ctx;
  777. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  778. return 0;
  779. }
  780. if (msg->body == NULL || msg->body->len == 0) {
  781. msg_err ("got zero length body, cannot continue");
  782. rspamd_controller_send_error (conn_ent,
  783. 400,
  784. "Empty body is not permitted");
  785. return 0;
  786. }
  787. task = rspamd_task_new (session->ctx->worker);
  788. task->ev_base = session->ctx->ev_base;
  789. task->resolver = ctx->resolver;
  790. task->ev_base = ctx->ev_base;
  791. task->s = new_async_session (session->pool,
  792. rspamd_controller_check_fin_task,
  793. NULL,
  794. rspamd_task_free_hard,
  795. task);
  796. task->s->wanna_die = TRUE;
  797. task->fin_arg = conn_ent;
  798. task->http_conn = rspamd_http_connection_ref (conn_ent->conn);
  799. task->sock = conn_ent->conn->fd;
  800. /* XXX: handle encrypted messages */
  801. if (!rspamd_task_process (task, msg, msg->body->str, msg->body->len, NULL, FALSE)) {
  802. msg_warn ("filters cannot be processed for %s", task->message_id);
  803. rspamd_controller_send_error (conn_ent, 500, task->last_error);
  804. destroy_session (task->s);
  805. return 0;
  806. }
  807. session->task = task;
  808. check_session_pending (task->s);
  809. return 0;
  810. }
  811. /*
  812. * Save actions command handler:
  813. * request: /saveactions
  814. * headers: Password
  815. * input: json array [<spam>,<probable spam>,<greylist>]
  816. * reply: json {"success":true} or {"error":"error message"}
  817. */
  818. static int
  819. rspamd_controller_handle_saveactions (
  820. struct rspamd_http_connection_entry *conn_ent,
  821. struct rspamd_http_message *msg)
  822. {
  823. struct rspamd_controller_session *session = conn_ent->ud;
  824. struct ucl_parser *parser;
  825. struct metric *metric;
  826. ucl_object_t *obj;
  827. const ucl_object_t *cur;
  828. struct rspamd_controller_worker_ctx *ctx;
  829. const gchar *error;
  830. gdouble score;
  831. gint i, added = 0;
  832. enum rspamd_metric_action act;
  833. ucl_object_iter_t it = NULL;
  834. ctx = session->ctx;
  835. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  836. return 0;
  837. }
  838. if (msg->body == NULL || msg->body->len == 0) {
  839. msg_err ("got zero length body, cannot continue");
  840. rspamd_controller_send_error (conn_ent,
  841. 400,
  842. "Empty body is not permitted");
  843. return 0;
  844. }
  845. metric = g_hash_table_lookup (ctx->cfg->metrics, DEFAULT_METRIC);
  846. if (metric == NULL) {
  847. msg_err ("cannot find default metric");
  848. rspamd_controller_send_error (conn_ent, 500,
  849. "Default metric is absent");
  850. return 0;
  851. }
  852. /* Now check for dynamic config */
  853. if (!ctx->cfg->dynamic_conf) {
  854. msg_err ("dynamic conf has not been defined");
  855. rspamd_controller_send_error (conn_ent,
  856. 500,
  857. "No dynamic_rules setting defined");
  858. return 0;
  859. }
  860. parser = ucl_parser_new (0);
  861. ucl_parser_add_chunk (parser, msg->body->str, msg->body->len);
  862. if ((error = ucl_parser_get_error (parser)) != NULL) {
  863. msg_err ("cannot parse input: %s", error);
  864. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  865. ucl_parser_free (parser);
  866. return 0;
  867. }
  868. obj = ucl_parser_get_object (parser);
  869. ucl_parser_free (parser);
  870. if (obj->type != UCL_ARRAY || obj->len != 3) {
  871. msg_err ("input is not an array of 3 elements");
  872. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  873. ucl_object_unref (obj);
  874. return 0;
  875. }
  876. for (i = 0; i < 3; i++) {
  877. cur = ucl_iterate_object (obj, &it, TRUE);
  878. if (cur == NULL) {
  879. break;
  880. }
  881. switch (i) {
  882. case 0:
  883. act = METRIC_ACTION_REJECT;
  884. break;
  885. case 1:
  886. act = METRIC_ACTION_ADD_HEADER;
  887. break;
  888. case 2:
  889. act = METRIC_ACTION_GREYLIST;
  890. break;
  891. }
  892. score = ucl_object_todouble (cur);
  893. if (metric->actions[act].score != score) {
  894. add_dynamic_action (ctx->cfg, DEFAULT_METRIC, act, score);
  895. added ++;
  896. }
  897. }
  898. dump_dynamic_config (ctx->cfg);
  899. msg_info ("<%s> modified %d actions",
  900. rspamd_inet_address_to_string (&session->from_addr),
  901. added);
  902. rspamd_controller_send_string (conn_ent, "{\"success\":true}");
  903. return 0;
  904. }
  905. /*
  906. * Save symbols command handler:
  907. * request: /savesymbols
  908. * headers: Password
  909. * input: json data
  910. * reply: json {"success":true} or {"error":"error message"}
  911. */
  912. static int
  913. rspamd_controller_handle_savesymbols (
  914. struct rspamd_http_connection_entry *conn_ent,
  915. struct rspamd_http_message *msg)
  916. {
  917. struct rspamd_controller_session *session = conn_ent->ud;
  918. struct ucl_parser *parser;
  919. struct metric *metric;
  920. ucl_object_t *obj;
  921. const ucl_object_t *cur, *jname, *jvalue;
  922. ucl_object_iter_t iter = NULL;
  923. struct rspamd_controller_worker_ctx *ctx;
  924. const gchar *error;
  925. gdouble val;
  926. struct rspamd_symbol_def *sym;
  927. int added = 0;
  928. ctx = session->ctx;
  929. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  930. return 0;
  931. }
  932. if (msg->body == NULL || msg->body->len == 0) {
  933. msg_err ("got zero length body, cannot continue");
  934. rspamd_controller_send_error (conn_ent,
  935. 400,
  936. "Empty body is not permitted");
  937. return 0;
  938. }
  939. metric = g_hash_table_lookup (ctx->cfg->metrics, DEFAULT_METRIC);
  940. if (metric == NULL) {
  941. msg_err ("cannot find default metric");
  942. rspamd_controller_send_error (conn_ent, 500,
  943. "Default metric is absent");
  944. return 0;
  945. }
  946. /* Now check for dynamic config */
  947. if (!ctx->cfg->dynamic_conf) {
  948. msg_err ("dynamic conf has not been defined");
  949. rspamd_controller_send_error (conn_ent,
  950. 500,
  951. "No dynamic_rules setting defined");
  952. return 0;
  953. }
  954. parser = ucl_parser_new (0);
  955. ucl_parser_add_chunk (parser, msg->body->str, msg->body->len);
  956. if ((error = ucl_parser_get_error (parser)) != NULL) {
  957. msg_err ("cannot parse input: %s", error);
  958. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  959. ucl_parser_free (parser);
  960. return 0;
  961. }
  962. obj = ucl_parser_get_object (parser);
  963. ucl_parser_free (parser);
  964. if (obj->type != UCL_ARRAY) {
  965. msg_err ("input is not an array");
  966. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  967. ucl_object_unref (obj);
  968. return 0;
  969. }
  970. while ((cur = ucl_iterate_object (obj, &iter, true))) {
  971. if (cur->type != UCL_OBJECT) {
  972. msg_err ("json array data error");
  973. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  974. ucl_object_unref (obj);
  975. return 0;
  976. }
  977. jname = ucl_object_find_key (cur, "name");
  978. jvalue = ucl_object_find_key (cur, "value");
  979. val = ucl_object_todouble (jvalue);
  980. sym =
  981. g_hash_table_lookup (metric->symbols, ucl_object_tostring (jname));
  982. if (sym && fabs (*sym->weight_ptr - val) > 0.01) {
  983. if (!add_dynamic_symbol (ctx->cfg, DEFAULT_METRIC,
  984. ucl_object_tostring (jname), val)) {
  985. msg_err ("add symbol failed for %s",
  986. ucl_object_tostring (jname));
  987. rspamd_controller_send_error (conn_ent, 506,
  988. "Add symbol failed");
  989. ucl_object_unref (obj);
  990. return 0;
  991. }
  992. added ++;
  993. }
  994. }
  995. dump_dynamic_config (ctx->cfg);
  996. msg_info ("<%s> modified %d symbols",
  997. rspamd_inet_address_to_string (&session->from_addr),
  998. added);
  999. rspamd_controller_send_string (conn_ent, "{\"success\":true}");
  1000. return 0;
  1001. }
  1002. /*
  1003. * Save map command handler:
  1004. * request: /savemap
  1005. * headers: Password, Map
  1006. * input: plaintext data
  1007. * reply: json {"success":true} or {"error":"error message"}
  1008. */
  1009. static int
  1010. rspamd_controller_handle_savemap (struct rspamd_http_connection_entry *conn_ent,
  1011. struct rspamd_http_message *msg)
  1012. {
  1013. struct rspamd_controller_session *session = conn_ent->ud;
  1014. GList *cur;
  1015. struct rspamd_map *map;
  1016. struct rspamd_controller_worker_ctx *ctx;
  1017. const gchar *idstr;
  1018. gchar *errstr;
  1019. guint32 id;
  1020. gboolean found = FALSE;
  1021. gint fd;
  1022. ctx = session->ctx;
  1023. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  1024. return 0;
  1025. }
  1026. if (msg->body == NULL || msg->body->len == 0) {
  1027. msg_err ("got zero length body, cannot continue");
  1028. rspamd_controller_send_error (conn_ent,
  1029. 400,
  1030. "Empty body is not permitted");
  1031. return 0;
  1032. }
  1033. idstr = rspamd_http_message_find_header (msg, "Map");
  1034. if (idstr == NULL) {
  1035. msg_info ("absent map id");
  1036. rspamd_controller_send_error (conn_ent, 400, "Map id not specified");
  1037. return 0;
  1038. }
  1039. id = strtoul (idstr, &errstr, 10);
  1040. if (*errstr != '\0') {
  1041. msg_info ("invalid map id");
  1042. rspamd_controller_send_error (conn_ent, 400, "Map id is invalid");
  1043. return 0;
  1044. }
  1045. /* Now let's be sure that we have map defined in configuration */
  1046. cur = ctx->cfg->maps;
  1047. while (cur) {
  1048. map = cur->data;
  1049. if (map->id == id && map->protocol == MAP_PROTO_FILE) {
  1050. found = TRUE;
  1051. break;
  1052. }
  1053. cur = g_list_next (cur);
  1054. }
  1055. if (!found) {
  1056. msg_info ("map not found: %d", id);
  1057. rspamd_controller_send_error (conn_ent, 404, "Map id not found");
  1058. return 0;
  1059. }
  1060. if (g_atomic_int_get (map->locked)) {
  1061. msg_info ("map locked: %s", map->uri);
  1062. rspamd_controller_send_error (conn_ent, 404, "Map is locked");
  1063. return 0;
  1064. }
  1065. /* Set lock */
  1066. g_atomic_int_set (map->locked, 1);
  1067. fd = open (map->uri, O_WRONLY | O_TRUNC);
  1068. if (fd == -1) {
  1069. g_atomic_int_set (map->locked, 0);
  1070. msg_info ("map %s open error: %s", map->uri, strerror (errno));
  1071. rspamd_controller_send_error (conn_ent, 404, "Map id not found");
  1072. return 0;
  1073. }
  1074. if (write (fd, msg->body->str, msg->body->len) == -1) {
  1075. msg_info ("map %s write error: %s", map->uri, strerror (errno));
  1076. close (fd);
  1077. g_atomic_int_set (map->locked, 0);
  1078. rspamd_controller_send_error (conn_ent, 500, "Map write error");
  1079. return 0;
  1080. }
  1081. msg_info ("<%s>, map %s saved",
  1082. rspamd_inet_address_to_string (&session->from_addr),
  1083. map->uri);
  1084. /* Close and unlock */
  1085. close (fd);
  1086. g_atomic_int_set (map->locked, 0);
  1087. rspamd_controller_send_string (conn_ent, "{\"success\":true}");
  1088. return 0;
  1089. }
  1090. /*
  1091. * Stat command handler:
  1092. * request: /stat (/resetstat)
  1093. * headers: Password
  1094. * reply: json data
  1095. */
  1096. static int
  1097. rspamd_controller_handle_stat_common (
  1098. struct rspamd_http_connection_entry *conn_ent,
  1099. struct rspamd_http_message *msg,
  1100. gboolean do_reset)
  1101. {
  1102. struct rspamd_controller_session *session = conn_ent->ud;
  1103. ucl_object_t *top, *sub;
  1104. gint i;
  1105. guint64 learned = 0, spam = 0, ham = 0;
  1106. rspamd_mempool_stat_t mem_st;
  1107. struct rspamd_stat *stat, stat_copy;
  1108. rspamd_mempool_stat (&mem_st);
  1109. memcpy (&stat_copy, session->ctx->worker->srv->stat, sizeof (stat_copy));
  1110. stat = &stat_copy;
  1111. top = ucl_object_typed_new (UCL_OBJECT);
  1112. ucl_object_insert_key (top, ucl_object_fromint (
  1113. stat->messages_scanned), "scanned", 0, false);
  1114. if (stat->messages_scanned > 0) {
  1115. sub = ucl_object_typed_new (UCL_OBJECT);
  1116. for (i = METRIC_ACTION_REJECT; i <= METRIC_ACTION_NOACTION; i++) {
  1117. ucl_object_insert_key (sub,
  1118. ucl_object_fromint (stat->actions_stat[i]),
  1119. rspamd_action_to_str (i), 0, false);
  1120. if (i < METRIC_ACTION_GREYLIST) {
  1121. spam += stat->actions_stat[i];
  1122. }
  1123. else {
  1124. ham += stat->actions_stat[i];
  1125. }
  1126. if (do_reset) {
  1127. session->ctx->worker->srv->stat->actions_stat[i] = 0;
  1128. }
  1129. }
  1130. ucl_object_insert_key (top, sub, "actions", 0, false);
  1131. }
  1132. ucl_object_insert_key (top, ucl_object_fromint (
  1133. spam), "spam_count", 0, false);
  1134. ucl_object_insert_key (top, ucl_object_fromint (
  1135. ham), "ham_count", 0, false);
  1136. ucl_object_insert_key (top,
  1137. ucl_object_fromint (stat->connections_count), "connections", 0, false);
  1138. ucl_object_insert_key (top,
  1139. ucl_object_fromint (stat->control_connections_count),
  1140. "control_connections", 0, false);
  1141. ucl_object_insert_key (top,
  1142. ucl_object_fromint (mem_st.pools_allocated), "pools_allocated", 0,
  1143. false);
  1144. ucl_object_insert_key (top,
  1145. ucl_object_fromint (mem_st.pools_freed), "pools_freed", 0, false);
  1146. ucl_object_insert_key (top,
  1147. ucl_object_fromint (mem_st.bytes_allocated), "bytes_allocated", 0,
  1148. false);
  1149. ucl_object_insert_key (top,
  1150. ucl_object_fromint (
  1151. mem_st.chunks_allocated), "chunks_allocated", 0, false);
  1152. ucl_object_insert_key (top,
  1153. ucl_object_fromint (mem_st.shared_chunks_allocated),
  1154. "shared_chunks_allocated", 0, false);
  1155. ucl_object_insert_key (top,
  1156. ucl_object_fromint (mem_st.chunks_freed), "chunks_freed", 0, false);
  1157. ucl_object_insert_key (top,
  1158. ucl_object_fromint (
  1159. mem_st.oversized_chunks), "chunks_oversized", 0, false);
  1160. ucl_object_insert_key (top,
  1161. ucl_object_fromint (stat->fuzzy_hashes), "fuzzy_stored", 0, false);
  1162. ucl_object_insert_key (top,
  1163. ucl_object_fromint (
  1164. stat->fuzzy_hashes_expired), "fuzzy_expired", 0, false);
  1165. /* Now write statistics for each statfile */
  1166. sub = rspamd_stat_statistics (session->ctx->cfg, &learned);
  1167. ucl_object_insert_key (top, sub, "statfiles", 0, false);
  1168. ucl_object_insert_key (top,
  1169. ucl_object_fromint (learned), "total_learns", 0, false);
  1170. if (do_reset) {
  1171. session->ctx->srv->stat->messages_scanned = 0;
  1172. session->ctx->srv->stat->messages_learned = 0;
  1173. session->ctx->srv->stat->connections_count = 0;
  1174. session->ctx->srv->stat->control_connections_count = 0;
  1175. rspamd_mempool_stat_reset ();
  1176. }
  1177. rspamd_controller_send_ucl (conn_ent, top);
  1178. ucl_object_unref (top);
  1179. return 0;
  1180. }
  1181. static int
  1182. rspamd_controller_handle_stat (struct rspamd_http_connection_entry *conn_ent,
  1183. struct rspamd_http_message *msg)
  1184. {
  1185. struct rspamd_controller_session *session = conn_ent->ud;
  1186. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  1187. return 0;
  1188. }
  1189. return rspamd_controller_handle_stat_common (conn_ent, msg, FALSE);
  1190. }
  1191. static int
  1192. rspamd_controller_handle_statreset (
  1193. struct rspamd_http_connection_entry *conn_ent,
  1194. struct rspamd_http_message *msg)
  1195. {
  1196. struct rspamd_controller_session *session = conn_ent->ud;
  1197. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  1198. return 0;
  1199. }
  1200. msg_info ("<%s> reset stat",
  1201. rspamd_inet_address_to_string (&session->from_addr));
  1202. return rspamd_controller_handle_stat_common (conn_ent, msg, TRUE);
  1203. }
  1204. static ucl_object_t *
  1205. rspamd_controller_cache_item_to_ucl (struct cache_item *item)
  1206. {
  1207. ucl_object_t *obj;
  1208. obj = ucl_object_typed_new (UCL_OBJECT);
  1209. ucl_object_insert_key (obj, ucl_object_fromstring (item->s->symbol),
  1210. "symbol", 0, false);
  1211. ucl_object_insert_key (obj, ucl_object_fromdouble (item->s->weight),
  1212. "weight", 0, false);
  1213. ucl_object_insert_key (obj, ucl_object_fromint (item->s->frequency),
  1214. "frequency", 0, false);
  1215. ucl_object_insert_key (obj, ucl_object_fromdouble (item->s->avg_time),
  1216. "time", 0, false);
  1217. return obj;
  1218. }
  1219. /*
  1220. * Counters command handler:
  1221. * request: /counters
  1222. * headers: Password
  1223. * reply: json array of all counters
  1224. */
  1225. static int
  1226. rspamd_controller_handle_counters (
  1227. struct rspamd_http_connection_entry *conn_ent,
  1228. struct rspamd_http_message *msg)
  1229. {
  1230. struct rspamd_controller_session *session = conn_ent->ud;
  1231. ucl_object_t *top;
  1232. GList *cur;
  1233. struct cache_item *item;
  1234. struct symbols_cache *cache;
  1235. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  1236. return 0;
  1237. }
  1238. cache = session->ctx->cfg->cache;
  1239. top = ucl_object_typed_new (UCL_ARRAY);
  1240. if (cache != NULL) {
  1241. cur = cache->negative_items;
  1242. while (cur) {
  1243. item = cur->data;
  1244. if (!item->is_callback) {
  1245. ucl_array_append (top, rspamd_controller_cache_item_to_ucl (
  1246. item));
  1247. }
  1248. cur = g_list_next (cur);
  1249. }
  1250. cur = cache->static_items;
  1251. while (cur) {
  1252. item = cur->data;
  1253. if (!item->is_callback) {
  1254. ucl_array_append (top, rspamd_controller_cache_item_to_ucl (
  1255. item));
  1256. }
  1257. cur = g_list_next (cur);
  1258. }
  1259. }
  1260. rspamd_controller_send_ucl (conn_ent, top);
  1261. ucl_object_unref (top);
  1262. return 0;
  1263. }
  1264. static int
  1265. rspamd_controller_handle_custom (struct rspamd_http_connection_entry *conn_ent,
  1266. struct rspamd_http_message *msg)
  1267. {
  1268. struct rspamd_controller_session *session = conn_ent->ud;
  1269. struct rspamd_custom_controller_command *cmd;
  1270. cmd = g_hash_table_lookup (session->ctx->custom_commands, msg->url->str);
  1271. if (cmd == NULL || cmd->handler == NULL) {
  1272. msg_err ("custom command %V has not been found", msg->url);
  1273. rspamd_controller_send_error (conn_ent, 404, "No command associated");
  1274. return 0;
  1275. }
  1276. if (!rspamd_controller_check_password (conn_ent, session, msg,
  1277. cmd->privilleged)) {
  1278. return 0;
  1279. }
  1280. if (cmd->require_message && (msg->body == NULL || msg->body->len == 0)) {
  1281. msg_err ("got zero length body, cannot continue");
  1282. rspamd_controller_send_error (conn_ent,
  1283. 400,
  1284. "Empty body is not permitted");
  1285. return 0;
  1286. }
  1287. return cmd->handler (conn_ent, msg, cmd->ctx);
  1288. }
  1289. static void
  1290. rspamd_controller_error_handler (struct rspamd_http_connection_entry *conn_ent,
  1291. GError *err)
  1292. {
  1293. msg_err ("http error occurred: %s", err->message);
  1294. }
  1295. static void
  1296. rspamd_controller_finish_handler (struct rspamd_http_connection_entry *conn_ent)
  1297. {
  1298. struct rspamd_controller_session *session = conn_ent->ud;
  1299. session->ctx->worker->srv->stat->control_connections_count++;
  1300. if (session->task != NULL) {
  1301. destroy_session (session->task->s);
  1302. }
  1303. if (session->pool) {
  1304. rspamd_mempool_delete (session->pool);
  1305. }
  1306. g_slice_free1 (sizeof (struct rspamd_controller_session), session);
  1307. }
  1308. static void
  1309. rspamd_controller_accept_socket (gint fd, short what, void *arg)
  1310. {
  1311. struct rspamd_worker *worker = (struct rspamd_worker *) arg;
  1312. struct rspamd_controller_worker_ctx *ctx;
  1313. struct rspamd_controller_session *nsession;
  1314. rspamd_inet_addr_t addr;
  1315. gint nfd;
  1316. ctx = worker->ctx;
  1317. if ((nfd =
  1318. rspamd_accept_from_socket (fd, &addr)) == -1) {
  1319. msg_warn ("accept failed: %s", strerror (errno));
  1320. return;
  1321. }
  1322. /* Check for EAGAIN */
  1323. if (nfd == 0) {
  1324. return;
  1325. }
  1326. nsession = g_slice_alloc0 (sizeof (struct rspamd_controller_session));
  1327. nsession->pool = rspamd_mempool_new (rspamd_mempool_suggest_size ());
  1328. nsession->ctx = ctx;
  1329. memcpy (&nsession->from_addr, &addr, sizeof (addr));
  1330. rspamd_http_router_handle_socket (ctx->http, nfd, nsession);
  1331. }
  1332. gpointer
  1333. init_controller_worker (struct rspamd_config *cfg)
  1334. {
  1335. struct rspamd_controller_worker_ctx *ctx;
  1336. GQuark type;
  1337. type = g_quark_try_string ("controller");
  1338. ctx = g_malloc0 (sizeof (struct rspamd_controller_worker_ctx));
  1339. ctx->timeout = DEFAULT_WORKER_IO_TIMEOUT;
  1340. rspamd_rcl_register_worker_option (cfg, type, "password",
  1341. rspamd_rcl_parse_struct_string, ctx,
  1342. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, password), 0);
  1343. rspamd_rcl_register_worker_option (cfg, type, "enable_password",
  1344. rspamd_rcl_parse_struct_string, ctx,
  1345. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, password), 0);
  1346. rspamd_rcl_register_worker_option (cfg, type, "ssl",
  1347. rspamd_rcl_parse_struct_boolean, ctx,
  1348. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, use_ssl), 0);
  1349. rspamd_rcl_register_worker_option (cfg, type, "ssl_cert",
  1350. rspamd_rcl_parse_struct_string, ctx,
  1351. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, ssl_cert), 0);
  1352. rspamd_rcl_register_worker_option (cfg, type, "ssl_key",
  1353. rspamd_rcl_parse_struct_string, ctx,
  1354. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, ssl_key), 0);
  1355. rspamd_rcl_register_worker_option (cfg, type, "timeout",
  1356. rspamd_rcl_parse_struct_time, ctx,
  1357. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx,
  1358. timeout), RSPAMD_CL_FLAG_TIME_INTEGER);
  1359. rspamd_rcl_register_worker_option (cfg, type, "secure_ip",
  1360. rspamd_rcl_parse_struct_string, ctx,
  1361. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, secure_ip), 0);
  1362. rspamd_rcl_register_worker_option (cfg, type, "static_dir",
  1363. rspamd_rcl_parse_struct_string, ctx,
  1364. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx,
  1365. static_files_dir), 0);
  1366. rspamd_rcl_register_worker_option (cfg, type, "keypair",
  1367. rspamd_rcl_parse_struct_keypair, ctx,
  1368. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx,
  1369. key), 0);
  1370. return ctx;
  1371. }
  1372. /*
  1373. * Start worker process
  1374. */
  1375. void
  1376. start_controller_worker (struct rspamd_worker *worker)
  1377. {
  1378. struct rspamd_controller_worker_ctx *ctx = worker->ctx;
  1379. GList *cur;
  1380. struct filter *f;
  1381. struct module_ctx *mctx;
  1382. GHashTableIter iter;
  1383. gpointer key, value;
  1384. ctx->ev_base = rspamd_prepare_worker (worker,
  1385. "controller",
  1386. rspamd_controller_accept_socket);
  1387. msec_to_tv (ctx->timeout, &ctx->io_tv);
  1388. ctx->start_time = time (NULL);
  1389. ctx->worker = worker;
  1390. ctx->cfg = worker->srv->cfg;
  1391. ctx->srv = worker->srv;
  1392. ctx->custom_commands = g_hash_table_new (rspamd_strcase_hash,
  1393. rspamd_strcase_equal);
  1394. if (ctx->secure_ip != NULL) {
  1395. if (!rspamd_map_add (worker->srv->cfg, ctx->secure_ip,
  1396. "Allow webui access from the specified IP",
  1397. rspamd_radix_read, rspamd_radix_fin, (void **)&ctx->secure_map)) {
  1398. if (!radix_add_generic_iplist (ctx->secure_ip,
  1399. &ctx->secure_map)) {
  1400. msg_warn ("cannot load or parse ip list from '%s'",
  1401. ctx->secure_ip);
  1402. }
  1403. }
  1404. }
  1405. /* Accept event */
  1406. ctx->http = rspamd_http_router_new (rspamd_controller_error_handler,
  1407. rspamd_controller_finish_handler, &ctx->io_tv, ctx->ev_base,
  1408. ctx->static_files_dir);
  1409. /* Add callbacks for different methods */
  1410. rspamd_http_router_add_path (ctx->http,
  1411. PATH_AUTH,
  1412. rspamd_controller_handle_auth);
  1413. rspamd_http_router_add_path (ctx->http,
  1414. PATH_SYMBOLS,
  1415. rspamd_controller_handle_symbols);
  1416. rspamd_http_router_add_path (ctx->http,
  1417. PATH_ACTIONS,
  1418. rspamd_controller_handle_actions);
  1419. rspamd_http_router_add_path (ctx->http,
  1420. PATH_MAPS,
  1421. rspamd_controller_handle_maps);
  1422. rspamd_http_router_add_path (ctx->http,
  1423. PATH_GET_MAP,
  1424. rspamd_controller_handle_get_map);
  1425. rspamd_http_router_add_path (ctx->http,
  1426. PATH_PIE_CHART,
  1427. rspamd_controller_handle_pie_chart);
  1428. rspamd_http_router_add_path (ctx->http,
  1429. PATH_HISTORY,
  1430. rspamd_controller_handle_history);
  1431. rspamd_http_router_add_path (ctx->http,
  1432. PATH_LEARN_SPAM,
  1433. rspamd_controller_handle_learnspam);
  1434. rspamd_http_router_add_path (ctx->http,
  1435. PATH_LEARN_HAM,
  1436. rspamd_controller_handle_learnham);
  1437. rspamd_http_router_add_path (ctx->http,
  1438. PATH_SAVE_ACTIONS,
  1439. rspamd_controller_handle_saveactions);
  1440. rspamd_http_router_add_path (ctx->http,
  1441. PATH_SAVE_SYMBOLS,
  1442. rspamd_controller_handle_savesymbols);
  1443. rspamd_http_router_add_path (ctx->http,
  1444. PATH_SAVE_MAP,
  1445. rspamd_controller_handle_savemap);
  1446. rspamd_http_router_add_path (ctx->http,
  1447. PATH_SCAN,
  1448. rspamd_controller_handle_scan);
  1449. rspamd_http_router_add_path (ctx->http,
  1450. PATH_CHECK,
  1451. rspamd_controller_handle_scan);
  1452. rspamd_http_router_add_path (ctx->http,
  1453. PATH_STAT,
  1454. rspamd_controller_handle_stat);
  1455. rspamd_http_router_add_path (ctx->http,
  1456. PATH_STAT_RESET,
  1457. rspamd_controller_handle_statreset);
  1458. rspamd_http_router_add_path (ctx->http,
  1459. PATH_COUNTERS,
  1460. rspamd_controller_handle_counters);
  1461. if (ctx->key) {
  1462. rspamd_http_router_set_key (ctx->http, ctx->key);
  1463. }
  1464. /* Attach plugins */
  1465. cur = g_list_first (ctx->cfg->filters);
  1466. while (cur) {
  1467. f = cur->data;
  1468. mctx = g_hash_table_lookup (ctx->cfg->c_modules, f->module->name);
  1469. if (mctx != NULL && f->module->module_attach_controller_func != NULL) {
  1470. f->module->module_attach_controller_func (mctx,
  1471. ctx->custom_commands);
  1472. }
  1473. cur = g_list_next (cur);
  1474. }
  1475. g_hash_table_iter_init (&iter, ctx->custom_commands);
  1476. while (g_hash_table_iter_next (&iter, &key, &value)) {
  1477. rspamd_http_router_add_path (ctx->http,
  1478. key,
  1479. rspamd_controller_handle_custom);
  1480. }
  1481. ctx->resolver = dns_resolver_init (worker->srv->logger,
  1482. ctx->ev_base,
  1483. worker->srv->cfg);
  1484. rspamd_upstreams_library_init (ctx->resolver->r, ctx->ev_base);
  1485. rspamd_upstreams_library_config (worker->srv->cfg);
  1486. /* Maps events */
  1487. rspamd_map_watch (worker->srv->cfg, ctx->ev_base);
  1488. event_base_loop (ctx->ev_base, 0);
  1489. g_mime_shutdown ();
  1490. rspamd_log_close (rspamd_main->logger);
  1491. exit (EXIT_SUCCESS);
  1492. }