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 99KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877
  1. /*-
  2. * Copyright 2016 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "config.h"
  17. #include "libserver/dynamic_cfg.h"
  18. #include "libutil/rrd.h"
  19. #include "libutil/map.h"
  20. #include "libutil/map_helpers.h"
  21. #include "libutil/map_private.h"
  22. #include "libutil/http_private.h"
  23. #include "libstat/stat_api.h"
  24. #include "rspamd.h"
  25. #include "libserver/worker_util.h"
  26. #include "lua/lua_common.h"
  27. #include "cryptobox.h"
  28. #include "ottery.h"
  29. #include "fuzzy_wire.h"
  30. #include "unix-std.h"
  31. #include "utlist.h"
  32. #include "libmime/lang_detection.h"
  33. #include <math.h>
  34. /* 60 seconds for worker's IO */
  35. #define DEFAULT_WORKER_IO_TIMEOUT 60000
  36. #define DEFAULT_STATS_PATH RSPAMD_DBDIR "/stats.ucl"
  37. /* HTTP paths */
  38. #define PATH_AUTH "/auth"
  39. #define PATH_SYMBOLS "/symbols"
  40. #define PATH_ACTIONS "/actions"
  41. #define PATH_MAPS "/maps"
  42. #define PATH_GET_MAP "/getmap"
  43. #define PATH_GRAPH "/graph"
  44. #define PATH_PIE_CHART "/pie"
  45. #define PATH_HISTORY "/history"
  46. #define PATH_HISTORY_RESET "/historyreset"
  47. #define PATH_LEARN_SPAM "/learnspam"
  48. #define PATH_LEARN_HAM "/learnham"
  49. #define PATH_SAVE_ACTIONS "/saveactions"
  50. #define PATH_SAVE_SYMBOLS "/savesymbols"
  51. #define PATH_SAVE_MAP "/savemap"
  52. #define PATH_SCAN "/scan"
  53. #define PATH_CHECK "/check"
  54. #define PATH_CHECKV2 "/checkv2"
  55. #define PATH_STAT "/stat"
  56. #define PATH_STAT_RESET "/statreset"
  57. #define PATH_COUNTERS "/counters"
  58. #define PATH_ERRORS "/errors"
  59. #define PATH_NEIGHBOURS "/neighbours"
  60. #define PATH_PLUGINS "/plugins"
  61. #define PATH_PING "/ping"
  62. #define msg_err_session(...) rspamd_default_log_function(G_LOG_LEVEL_CRITICAL, \
  63. session->pool->tag.tagname, session->pool->tag.uid, \
  64. G_STRFUNC, \
  65. __VA_ARGS__)
  66. #define msg_warn_session(...) rspamd_default_log_function (G_LOG_LEVEL_WARNING, \
  67. session->pool->tag.tagname, session->pool->tag.uid, \
  68. G_STRFUNC, \
  69. __VA_ARGS__)
  70. #define msg_info_session(...) rspamd_default_log_function (G_LOG_LEVEL_INFO, \
  71. session->pool->tag.tagname, session->pool->tag.uid, \
  72. G_STRFUNC, \
  73. __VA_ARGS__)
  74. #define msg_err_ctx(...) rspamd_default_log_function(G_LOG_LEVEL_CRITICAL, \
  75. "controller", ctx->cfg->cfg_pool->tag.uid, \
  76. G_STRFUNC, \
  77. __VA_ARGS__)
  78. #define msg_warn_ctx(...) rspamd_default_log_function (G_LOG_LEVEL_WARNING, \
  79. "controller", ctx->cfg->cfg_pool->tag.uid, \
  80. G_STRFUNC, \
  81. __VA_ARGS__)
  82. #define msg_info_ctx(...) rspamd_default_log_function (G_LOG_LEVEL_INFO, \
  83. "controller", ctx->cfg->cfg_pool->tag.uid, \
  84. G_STRFUNC, \
  85. __VA_ARGS__)
  86. #define msg_debug_session(...) rspamd_conditional_debug_fast (NULL, session->from_addr, \
  87. rspamd_controller_log_id, "controller", session->pool->tag.uid, \
  88. G_STRFUNC, \
  89. __VA_ARGS__)
  90. INIT_LOG_MODULE(controller)
  91. /* Graph colors */
  92. #define COLOR_CLEAN "#58A458"
  93. #define COLOR_PROBABLE_SPAM "#D67E7E"
  94. #define COLOR_GREYLIST "#A0A0A0"
  95. #define COLOR_REJECT "#CB4B4B"
  96. #define COLOR_TOTAL "#9440ED"
  97. const struct timeval rrd_update_time = {
  98. .tv_sec = 1,
  99. .tv_usec = 0
  100. };
  101. const guint64 rspamd_controller_ctx_magic = 0xf72697805e6941faULL;
  102. extern void fuzzy_stat_command (struct rspamd_task *task);
  103. gpointer init_controller_worker (struct rspamd_config *cfg);
  104. void start_controller_worker (struct rspamd_worker *worker);
  105. worker_t controller_worker = {
  106. "controller", /* Name */
  107. init_controller_worker, /* Init function */
  108. start_controller_worker, /* Start function */
  109. RSPAMD_WORKER_HAS_SOCKET | RSPAMD_WORKER_KILLABLE |
  110. RSPAMD_WORKER_SCANNER | RSPAMD_WORKER_CONTROLLER,
  111. RSPAMD_WORKER_SOCKET_TCP, /* TCP socket */
  112. RSPAMD_WORKER_VER /* Version info */
  113. };
  114. /*
  115. * Worker's context
  116. */
  117. struct rspamd_controller_worker_ctx {
  118. guint64 magic;
  119. /* Events base */
  120. struct event_base *ev_base;
  121. /* DNS resolver */
  122. struct rspamd_dns_resolver *resolver;
  123. /* Config */
  124. struct rspamd_config *cfg;
  125. /* END OF COMMON PART */
  126. guint32 timeout;
  127. struct timeval io_tv;
  128. /* Whether we use ssl for this server */
  129. gboolean use_ssl;
  130. /* Webui password */
  131. gchar *password;
  132. /* Privilleged password */
  133. gchar *enable_password;
  134. /* Cached versions of the passwords */
  135. rspamd_ftok_t cached_password;
  136. rspamd_ftok_t cached_enable_password;
  137. /* HTTP server */
  138. struct rspamd_http_connection_router *http;
  139. /* Server's start time */
  140. time_t start_time;
  141. /* Main server */
  142. struct rspamd_main *srv;
  143. /* SSL cert */
  144. gchar *ssl_cert;
  145. /* SSL private key */
  146. gchar *ssl_key;
  147. /* A map of secure IP */
  148. const ucl_object_t *secure_ip;
  149. struct rspamd_radix_map_helper *secure_map;
  150. /* Static files dir */
  151. gchar *static_files_dir;
  152. /* Saved statistics path */
  153. gchar *saved_stats_path;
  154. /* Custom commands registered by plugins */
  155. GHashTable *custom_commands;
  156. /* Plugins registered from lua */
  157. GHashTable *plugins;
  158. /* Worker */
  159. struct rspamd_worker *worker;
  160. /* Local keypair */
  161. gpointer key;
  162. struct event *rrd_event;
  163. struct rspamd_rrd_file *rrd;
  164. struct event save_stats_event;
  165. struct rspamd_lang_detector *lang_det;
  166. };
  167. struct rspamd_controller_plugin_cbdata {
  168. lua_State *L;
  169. struct rspamd_controller_worker_ctx *ctx;
  170. gchar *plugin;
  171. struct ucl_lua_funcdata *handler;
  172. ucl_object_t *obj;
  173. gboolean is_enable;
  174. gboolean need_task;
  175. guint version;
  176. };
  177. static gboolean
  178. rspamd_is_encrypted_password (const gchar *password,
  179. struct rspamd_controller_pbkdf const **pbkdf)
  180. {
  181. const gchar *start, *end;
  182. gint64 id;
  183. gsize size, i;
  184. gboolean ret = FALSE;
  185. const struct rspamd_controller_pbkdf *p;
  186. if (password[0] == '$') {
  187. /* Parse id */
  188. start = password + 1;
  189. end = start;
  190. size = 0;
  191. while (*end != '\0' && g_ascii_isdigit (*end)) {
  192. size++;
  193. end++;
  194. }
  195. if (size > 0) {
  196. gchar *endptr;
  197. id = strtoul (start, &endptr, 10);
  198. if ((endptr == NULL || *endptr == *end)) {
  199. for (i = 0; i < RSPAMD_PBKDF_ID_MAX - 1; i ++) {
  200. p = &pbkdf_list[i];
  201. if (p->id == id) {
  202. ret = TRUE;
  203. if (pbkdf != NULL) {
  204. *pbkdf = &pbkdf_list[i];
  205. }
  206. break;
  207. }
  208. }
  209. }
  210. }
  211. }
  212. return ret;
  213. }
  214. static const gchar *
  215. rspamd_encrypted_password_get_str (const gchar * password, gsize skip,
  216. gsize * length)
  217. {
  218. const gchar *str, *start, *end;
  219. gsize size;
  220. start = password + skip;
  221. end = start;
  222. size = 0;
  223. while (*end != '\0' && g_ascii_isalnum (*end)) {
  224. size++;
  225. end++;
  226. }
  227. if (size) {
  228. str = start;
  229. *length = size;
  230. }
  231. else {
  232. str = NULL;
  233. }
  234. return str;
  235. }
  236. static gboolean
  237. rspamd_check_encrypted_password (struct rspamd_controller_worker_ctx *ctx,
  238. const rspamd_ftok_t * password, const gchar * check,
  239. const struct rspamd_controller_pbkdf *pbkdf,
  240. gboolean is_enable)
  241. {
  242. const gchar *salt, *hash;
  243. gchar *salt_decoded, *key_decoded;
  244. gsize salt_len = 0, key_len = 0;
  245. gboolean ret = TRUE;
  246. guchar *local_key;
  247. rspamd_ftok_t *cache;
  248. gpointer m;
  249. /* First of all check cached versions to save resources */
  250. if (is_enable && ctx->cached_enable_password.len != 0) {
  251. if (password->len != ctx->cached_enable_password.len ||
  252. !rspamd_constant_memcmp (password->begin,
  253. ctx->cached_enable_password.begin, password->len)) {
  254. msg_info_ctx ("incorrect or absent enable password has been specified");
  255. return FALSE;
  256. }
  257. return TRUE;
  258. }
  259. else if (!is_enable && ctx->cached_password.len != 0) {
  260. if (password->len != ctx->cached_password.len ||
  261. !rspamd_constant_memcmp (password->begin,
  262. ctx->cached_password.begin, password->len)) {
  263. /* We still need to check enable password here */
  264. if (ctx->cached_enable_password.len != 0) {
  265. if (password->len != ctx->cached_enable_password.len ||
  266. !rspamd_constant_memcmp (password->begin,
  267. ctx->cached_enable_password.begin,
  268. password->len)) {
  269. msg_info_ctx (
  270. "incorrect or absent password has been specified");
  271. return FALSE;
  272. }
  273. else {
  274. /* Cached matched */
  275. return TRUE;
  276. }
  277. }
  278. else {
  279. /* We might want to check uncached version */
  280. goto check_uncached;
  281. }
  282. }
  283. else {
  284. /* Cached matched */
  285. return TRUE;
  286. }
  287. }
  288. check_uncached:
  289. g_assert (pbkdf != NULL);
  290. /* get salt */
  291. salt = rspamd_encrypted_password_get_str (check, 3, &salt_len);
  292. /* get hash */
  293. hash = rspamd_encrypted_password_get_str (check, 3 + salt_len + 1,
  294. &key_len);
  295. if (salt != NULL && hash != NULL) {
  296. /* decode salt */
  297. salt_decoded = rspamd_decode_base32 (salt, salt_len, &salt_len);
  298. if (salt_decoded == NULL || salt_len != pbkdf->salt_len) {
  299. /* We have some unknown salt here */
  300. msg_info_ctx ("incorrect salt: %z, while %z expected",
  301. salt_len, pbkdf->salt_len);
  302. return FALSE;
  303. }
  304. key_decoded = rspamd_decode_base32 (hash, key_len, &key_len);
  305. if (key_decoded == NULL || key_len != pbkdf->key_len) {
  306. /* We have some unknown salt here */
  307. msg_info_ctx ("incorrect key: %z, while %z expected",
  308. key_len, pbkdf->key_len);
  309. return FALSE;
  310. }
  311. local_key = g_alloca (pbkdf->key_len);
  312. rspamd_cryptobox_pbkdf (password->begin, password->len,
  313. salt_decoded, salt_len,
  314. local_key, pbkdf->key_len, pbkdf->complexity,
  315. pbkdf->type);
  316. if (!rspamd_constant_memcmp (key_decoded, local_key, pbkdf->key_len)) {
  317. msg_info_ctx ("incorrect or absent password has been specified");
  318. ret = FALSE;
  319. }
  320. g_free (salt_decoded);
  321. g_free (key_decoded);
  322. }
  323. if (ret) {
  324. /* Save cached version */
  325. cache = is_enable ? &ctx->cached_enable_password : &ctx->cached_password;
  326. if (cache->len == 0) {
  327. /* Mmap region */
  328. #ifdef MAP_NOCORE
  329. m = mmap (NULL, password->len, PROT_WRITE,
  330. MAP_PRIVATE | MAP_ANON | MAP_NOCORE, -1, 0);
  331. #else
  332. m = mmap (NULL, password->len, PROT_WRITE,
  333. MAP_PRIVATE | MAP_ANON, -1, 0);
  334. #endif
  335. if (m != MAP_FAILED) {
  336. memcpy (m, password->begin, password->len);
  337. (void)mprotect (m, password->len, PROT_READ);
  338. (void)mlock (m, password->len);
  339. cache->begin = m;
  340. cache->len = password->len;
  341. }
  342. else {
  343. msg_err_ctx ("cannot store cached password, mmap failed: %s",
  344. strerror (errno));
  345. }
  346. }
  347. }
  348. return ret;
  349. }
  350. /**
  351. * Checks for X-Forwarded-For header and update client's address if needed
  352. *
  353. * This function is intended to be called for a trusted client to ensure that
  354. * a request is not proxied through it
  355. * @return 0 if no forwarded found, 1 if forwarded found and it is yet trusted
  356. * and -1 if forwarded is denied
  357. */
  358. static gint
  359. rspamd_controller_check_forwarded (struct rspamd_controller_session *session,
  360. struct rspamd_http_message *msg,
  361. struct rspamd_controller_worker_ctx *ctx)
  362. {
  363. const rspamd_ftok_t *hdr;
  364. const gchar *comma;
  365. const char *hdr_name = "X-Forwarded-For", *alt_hdr_name = "X-Real-IP";
  366. char ip_buf[INET6_ADDRSTRLEN + 1];
  367. rspamd_inet_addr_t *addr = NULL;
  368. gint ret = 0;
  369. hdr = rspamd_http_message_find_header (msg, hdr_name);
  370. if (hdr) {
  371. /*
  372. * We need to parse and update the header
  373. * X-Forwarded-For: client, proxy1, proxy2
  374. */
  375. comma = rspamd_memrchr (hdr->begin, ',', hdr->len);
  376. if (comma != NULL) {
  377. while (comma < hdr->begin + hdr->len &&
  378. (*comma == ',' || g_ascii_isspace (*comma))) {
  379. comma ++;
  380. }
  381. }
  382. else {
  383. comma = hdr->begin;
  384. }
  385. if (rspamd_parse_inet_address (&addr, comma,
  386. (hdr->begin + hdr->len) - comma)) {
  387. /* We have addr now, so check if it is still trusted */
  388. if (ctx->secure_map &&
  389. rspamd_match_radix_map_addr (ctx->secure_map, addr) != NULL) {
  390. /* rspamd_inet_address_to_string is not reentrant */
  391. rspamd_strlcpy (ip_buf, rspamd_inet_address_to_string (addr),
  392. sizeof (ip_buf));
  393. msg_info_session ("allow unauthorized proxied connection "
  394. "from a trusted IP %s via %s",
  395. ip_buf,
  396. rspamd_inet_address_to_string (session->from_addr));
  397. ret = 1;
  398. }
  399. else {
  400. ret = -1;
  401. }
  402. rspamd_inet_address_free (addr);
  403. }
  404. else {
  405. msg_warn_session ("cannot parse forwarded IP: %T", hdr);
  406. ret = -1;
  407. }
  408. }
  409. else {
  410. /* Try also X-Real-IP */
  411. hdr = rspamd_http_message_find_header (msg, alt_hdr_name);
  412. if (hdr) {
  413. if (rspamd_parse_inet_address (&addr, hdr->begin, hdr->len)) {
  414. /* We have addr now, so check if it is still trusted */
  415. if (ctx->secure_map &&
  416. rspamd_match_radix_map_addr (ctx->secure_map, addr) != NULL) {
  417. /* rspamd_inet_address_to_string is not reentrant */
  418. rspamd_strlcpy (ip_buf, rspamd_inet_address_to_string (addr),
  419. sizeof (ip_buf));
  420. msg_info_session ("allow unauthorized proxied connection "
  421. "from a trusted IP %s via %s",
  422. ip_buf,
  423. rspamd_inet_address_to_string (session->from_addr));
  424. ret = 1;
  425. }
  426. else {
  427. ret = -1;
  428. }
  429. rspamd_inet_address_free (addr);
  430. }
  431. else {
  432. msg_warn_session ("cannot parse real IP: %T", hdr);
  433. ret = -1;
  434. }
  435. }
  436. }
  437. return ret;
  438. }
  439. /* Check for password if it is required by configuration */
  440. static gboolean
  441. rspamd_controller_check_password (struct rspamd_http_connection_entry *entry,
  442. struct rspamd_controller_session *session,
  443. struct rspamd_http_message *msg, gboolean is_enable)
  444. {
  445. const gchar *check;
  446. const rspamd_ftok_t *password;
  447. rspamd_ftok_t lookup;
  448. GHashTable *query_args = NULL;
  449. struct rspamd_controller_worker_ctx *ctx = session->ctx;
  450. gboolean check_normal = TRUE, check_enable = TRUE, ret = TRUE,
  451. use_enable = FALSE;
  452. const struct rspamd_controller_pbkdf *pbkdf = NULL;
  453. /* Access list logic */
  454. if (rspamd_inet_address_get_af (session->from_addr) == AF_UNIX) {
  455. ret = rspamd_controller_check_forwarded (session, msg, ctx);
  456. if (ret == 1) {
  457. session->is_enable = TRUE;
  458. return TRUE;
  459. }
  460. else if (ret == 0) {
  461. /* No forwarded found */
  462. msg_info_session ("allow unauthorized connection from a unix socket");
  463. session->is_enable = TRUE;
  464. return TRUE;
  465. }
  466. }
  467. else if (ctx->secure_map
  468. && rspamd_match_radix_map_addr (ctx->secure_map, session->from_addr)
  469. != NULL) {
  470. ret = rspamd_controller_check_forwarded (session, msg, ctx);
  471. if (ret == 1) {
  472. session->is_enable = TRUE;
  473. return TRUE;
  474. }
  475. else if (ret == 0) {
  476. /* No forwarded found */
  477. msg_info_session ("allow unauthorized connection from a trusted IP %s",
  478. rspamd_inet_address_to_string (session->from_addr));
  479. session->is_enable = TRUE;
  480. return TRUE;
  481. }
  482. }
  483. /* Password logic */
  484. password = rspamd_http_message_find_header (msg, "Password");
  485. if (password == NULL) {
  486. /* Try to get password from query args */
  487. query_args = rspamd_http_message_parse_query (msg);
  488. lookup.begin = (gchar *)"password";
  489. lookup.len = sizeof ("password") - 1;
  490. password = g_hash_table_lookup (query_args, &lookup);
  491. }
  492. if (password == NULL) {
  493. if (ctx->secure_map == NULL) {
  494. if (ctx->password == NULL && !is_enable) {
  495. return TRUE;
  496. }
  497. else if (is_enable && (ctx->password == NULL &&
  498. ctx->enable_password == NULL)) {
  499. session->is_enable = TRUE;
  500. return TRUE;
  501. }
  502. }
  503. msg_info_session ("absent password has been specified");
  504. ret = FALSE;
  505. }
  506. else {
  507. if (rspamd_ftok_cstr_equal (password, "q1", FALSE) ||
  508. rspamd_ftok_cstr_equal (password, "q2", FALSE)) {
  509. msg_info_session ("deny default password for remote access");
  510. ret = FALSE;
  511. goto end;
  512. }
  513. if (is_enable) {
  514. /* For privileged commands we strictly require enable password */
  515. if (ctx->enable_password != NULL) {
  516. check = ctx->enable_password;
  517. use_enable = TRUE;
  518. }
  519. else {
  520. /* Use just a password (legacy mode) */
  521. msg_info(
  522. "using password as enable_password for a privileged command");
  523. check = ctx->password;
  524. }
  525. if (check != NULL) {
  526. if (!rspamd_is_encrypted_password (check, &pbkdf)) {
  527. ret = FALSE;
  528. if (strlen (check) == password->len) {
  529. ret = rspamd_constant_memcmp (password->begin, check,
  530. password->len);
  531. }
  532. }
  533. else {
  534. ret = rspamd_check_encrypted_password (ctx, password, check,
  535. pbkdf, use_enable);
  536. }
  537. }
  538. else {
  539. msg_warn_session (
  540. "no password to check while executing a privileged command");
  541. ret = FALSE;
  542. }
  543. if (ret) {
  544. session->is_enable = TRUE;
  545. }
  546. }
  547. else {
  548. /* Accept both normal and enable passwords */
  549. if (ctx->password != NULL) {
  550. check = ctx->password;
  551. if (!rspamd_is_encrypted_password (check, &pbkdf)) {
  552. check_normal = FALSE;
  553. if (strlen (check) == password->len) {
  554. check_normal = rspamd_constant_memcmp (password->begin,
  555. check,
  556. password->len);
  557. }
  558. }
  559. else {
  560. check_normal = rspamd_check_encrypted_password (ctx,
  561. password,
  562. check, pbkdf, FALSE);
  563. }
  564. }
  565. else {
  566. check_normal = FALSE;
  567. }
  568. if (ctx->enable_password != NULL) {
  569. check = ctx->enable_password;
  570. if (!rspamd_is_encrypted_password (check, &pbkdf)) {
  571. check_enable = FALSE;
  572. if (strlen (check) == password->len) {
  573. check_enable = rspamd_constant_memcmp (password->begin,
  574. check,
  575. password->len);
  576. }
  577. }
  578. else {
  579. check_enable = rspamd_check_encrypted_password (ctx,
  580. password,
  581. check, pbkdf, TRUE);
  582. }
  583. if (check_enable) {
  584. session->is_enable = TRUE;
  585. }
  586. }
  587. else {
  588. check_enable = FALSE;
  589. if (check_normal) {
  590. /*
  591. * If no enable password is specified use normal password as
  592. * enable password
  593. */
  594. session->is_enable = TRUE;
  595. }
  596. }
  597. }
  598. }
  599. if (check_normal == FALSE && check_enable == FALSE) {
  600. msg_info ("absent or incorrect password has been specified");
  601. ret = FALSE;
  602. }
  603. end:
  604. if (query_args != NULL) {
  605. g_hash_table_unref (query_args);
  606. }
  607. if (!ret) {
  608. rspamd_controller_send_error (entry, 403, "Unauthorized");
  609. }
  610. return ret;
  611. }
  612. /* Command handlers */
  613. /*
  614. * Auth command handler:
  615. * request: /auth
  616. * headers: Password
  617. * reply: json {"auth": "ok", "version": "0.5.2", "uptime": "some uptime", "error": "none"}
  618. */
  619. static int
  620. rspamd_controller_handle_auth (struct rspamd_http_connection_entry *conn_ent,
  621. struct rspamd_http_message *msg)
  622. {
  623. struct rspamd_controller_session *session = conn_ent->ud;
  624. struct rspamd_stat *st;
  625. int64_t uptime;
  626. gulong data[5];
  627. ucl_object_t *obj;
  628. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  629. return 0;
  630. }
  631. obj = ucl_object_typed_new (UCL_OBJECT);
  632. st = session->ctx->srv->stat;
  633. data[0] = st->actions_stat[METRIC_ACTION_NOACTION];
  634. data[1] = st->actions_stat[METRIC_ACTION_ADD_HEADER] +
  635. st->actions_stat[METRIC_ACTION_REWRITE_SUBJECT];
  636. data[2] = st->actions_stat[METRIC_ACTION_GREYLIST];
  637. data[3] = st->actions_stat[METRIC_ACTION_REJECT];
  638. data[4] = st->actions_stat[METRIC_ACTION_SOFT_REJECT];
  639. /* Get uptime */
  640. uptime = time (NULL) - session->ctx->start_time;
  641. ucl_object_insert_key (obj, ucl_object_fromstring (
  642. RVERSION), "version", 0, false);
  643. ucl_object_insert_key (obj, ucl_object_fromstring (
  644. "ok"), "auth", 0, false);
  645. ucl_object_insert_key (obj, ucl_object_fromint (
  646. uptime), "uptime", 0, false);
  647. ucl_object_insert_key (obj, ucl_object_fromint (
  648. data[0]), "clean", 0, false);
  649. ucl_object_insert_key (obj, ucl_object_fromint (
  650. data[1]), "probable", 0, false);
  651. ucl_object_insert_key (obj, ucl_object_fromint (
  652. data[2]), "greylist", 0, false);
  653. ucl_object_insert_key (obj, ucl_object_fromint (
  654. data[3]), "reject", 0, false);
  655. ucl_object_insert_key (obj, ucl_object_fromint (
  656. data[4]), "soft_reject", 0, false);
  657. ucl_object_insert_key (obj, ucl_object_fromint (
  658. st->messages_scanned), "scanned", 0, false);
  659. ucl_object_insert_key (obj, ucl_object_fromint (
  660. st->messages_learned), "learned", 0, false);
  661. ucl_object_insert_key (obj, ucl_object_frombool (!session->is_enable),
  662. "read_only", 0, false);
  663. ucl_object_insert_key (obj, ucl_object_fromstring (session->ctx->cfg->checksum),
  664. "config_id", 0, false);
  665. rspamd_controller_send_ucl (conn_ent, obj);
  666. ucl_object_unref (obj);
  667. return 0;
  668. }
  669. /*
  670. * Symbols command handler:
  671. * request: /symbols
  672. * reply: json [{
  673. * "name": "group_name",
  674. * "symbols": [
  675. * {
  676. * "name": "name",
  677. * "weight": 0.1,
  678. * "description": "description of symbol"
  679. * },
  680. * {...}
  681. * },
  682. * {...}]
  683. */
  684. static int
  685. rspamd_controller_handle_symbols (struct rspamd_http_connection_entry *conn_ent,
  686. struct rspamd_http_message *msg)
  687. {
  688. struct rspamd_controller_session *session = conn_ent->ud;
  689. GHashTableIter it, sit;
  690. struct rspamd_symbols_group *gr;
  691. struct rspamd_symbol *sym;
  692. ucl_object_t *obj, *top, *sym_obj, *group_symbols;
  693. gpointer k, v;
  694. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  695. return 0;
  696. }
  697. top = ucl_object_typed_new (UCL_ARRAY);
  698. /* Go through all symbols groups in the default metric */
  699. g_hash_table_iter_init (&it, session->cfg->groups);
  700. while (g_hash_table_iter_next (&it, &k, &v)) {
  701. gr = v;
  702. obj = ucl_object_typed_new (UCL_OBJECT);
  703. ucl_object_insert_key (obj, ucl_object_fromstring (
  704. gr->name), "group", 0, false);
  705. /* Iterate through all symbols */
  706. g_hash_table_iter_init (&sit, gr->symbols);
  707. group_symbols = ucl_object_typed_new (UCL_ARRAY);
  708. while (g_hash_table_iter_next (&sit, &k, &v)) {
  709. gdouble tm = 0.0, freq = 0, freq_dev = 0;
  710. sym = v;
  711. sym_obj = ucl_object_typed_new (UCL_OBJECT);
  712. ucl_object_insert_key (sym_obj, ucl_object_fromstring (sym->name),
  713. "symbol", 0, false);
  714. ucl_object_insert_key (sym_obj,
  715. ucl_object_fromdouble (*sym->weight_ptr),
  716. "weight", 0, false);
  717. if (sym->description) {
  718. ucl_object_insert_key (sym_obj,
  719. ucl_object_fromstring (sym->description),
  720. "description", 0, false);
  721. }
  722. if (rspamd_symcache_stat_symbol (session->ctx->cfg->cache,
  723. sym->name, &freq, &freq_dev, &tm, NULL)) {
  724. ucl_object_insert_key (sym_obj,
  725. ucl_object_fromdouble (freq),
  726. "frequency", 0, false);
  727. ucl_object_insert_key (sym_obj,
  728. ucl_object_fromdouble (freq_dev),
  729. "frequency_stddev", 0, false);
  730. ucl_object_insert_key (sym_obj,
  731. ucl_object_fromdouble (tm),
  732. "time", 0, false);
  733. }
  734. ucl_array_append (group_symbols, sym_obj);
  735. }
  736. ucl_object_insert_key (obj, group_symbols, "rules", 0, false);
  737. ucl_array_append (top, obj);
  738. }
  739. rspamd_controller_send_ucl (conn_ent, top);
  740. ucl_object_unref (top);
  741. return 0;
  742. }
  743. /*
  744. * Actions command handler:
  745. * request: /actions
  746. * reply: json [{
  747. * "action": "no action",
  748. * "value": 1.1
  749. * },
  750. * {...}]
  751. */
  752. static int
  753. rspamd_controller_handle_actions (struct rspamd_http_connection_entry *conn_ent,
  754. struct rspamd_http_message *msg)
  755. {
  756. struct rspamd_controller_session *session = conn_ent->ud;
  757. struct rspamd_action *act;
  758. gint i;
  759. ucl_object_t *obj, *top;
  760. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  761. return 0;
  762. }
  763. top = ucl_object_typed_new (UCL_ARRAY);
  764. /* Get actions for default metric */
  765. for (i = METRIC_ACTION_REJECT; i < METRIC_ACTION_MAX; i++) {
  766. act = &session->cfg->actions[i];
  767. obj = ucl_object_typed_new (UCL_OBJECT);
  768. ucl_object_insert_key (obj,
  769. ucl_object_fromstring (rspamd_action_to_str (
  770. act->action)), "action", 0, false);
  771. ucl_object_insert_key (obj, ucl_object_fromdouble (
  772. act->score), "value", 0, false);
  773. ucl_array_append (top, obj);
  774. }
  775. rspamd_controller_send_ucl (conn_ent, top);
  776. ucl_object_unref (top);
  777. return 0;
  778. }
  779. static gboolean
  780. rspamd_controller_can_edit_map (struct rspamd_map_backend *bk)
  781. {
  782. gchar *fpath;
  783. if (access (bk->uri, W_OK) == 0) {
  784. return TRUE;
  785. }
  786. else if (access (bk->uri, R_OK) == -1 && errno == ENOENT) {
  787. fpath = g_path_get_dirname (bk->uri);
  788. if (fpath) {
  789. if (access (fpath, W_OK) == 0) {
  790. g_free (fpath);
  791. return TRUE;
  792. }
  793. g_free (fpath);
  794. }
  795. }
  796. return FALSE;
  797. }
  798. /*
  799. * Maps command handler:
  800. * request: /maps
  801. * headers: Password
  802. * reply: json [
  803. * {
  804. * "map": "name",
  805. * "description": "description",
  806. * "editable": true
  807. * },
  808. * {...}
  809. * ]
  810. */
  811. static int
  812. rspamd_controller_handle_maps (struct rspamd_http_connection_entry *conn_ent,
  813. struct rspamd_http_message *msg)
  814. {
  815. struct rspamd_controller_session *session = conn_ent->ud;
  816. GList *cur;
  817. struct rspamd_map *map;
  818. struct rspamd_map_backend *bk;
  819. guint i;
  820. gboolean editable;
  821. ucl_object_t *obj, *top;
  822. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  823. return 0;
  824. }
  825. top = ucl_object_typed_new (UCL_ARRAY);
  826. /* Iterate over all maps */
  827. cur = session->ctx->cfg->maps;
  828. while (cur) {
  829. map = cur->data;
  830. PTR_ARRAY_FOREACH (map->backends, i, bk) {
  831. if (bk->protocol == MAP_PROTO_FILE) {
  832. editable = rspamd_controller_can_edit_map (bk);
  833. if (!editable && access (bk->uri, R_OK) == -1) {
  834. /* Skip unreadable and non-existing maps */
  835. continue;
  836. }
  837. obj = ucl_object_typed_new (UCL_OBJECT);
  838. ucl_object_insert_key (obj, ucl_object_fromint (bk->id),
  839. "map", 0, false);
  840. if (map->description) {
  841. ucl_object_insert_key (obj, ucl_object_fromstring (map->description),
  842. "description", 0, false);
  843. }
  844. ucl_object_insert_key (obj, ucl_object_fromstring (bk->uri),
  845. "uri", 0, false);
  846. ucl_object_insert_key (obj, ucl_object_frombool (editable),
  847. "editable", 0, false);
  848. ucl_array_append (top, obj);
  849. }
  850. }
  851. cur = g_list_next (cur);
  852. }
  853. rspamd_controller_send_ucl (conn_ent, top);
  854. ucl_object_unref (top);
  855. return 0;
  856. }
  857. /*
  858. * Get map command handler:
  859. * request: /getmap
  860. * headers: Password, Map
  861. * reply: plain-text
  862. */
  863. static int
  864. rspamd_controller_handle_get_map (struct rspamd_http_connection_entry *conn_ent,
  865. struct rspamd_http_message *msg)
  866. {
  867. struct rspamd_controller_session *session = conn_ent->ud;
  868. GList *cur;
  869. struct rspamd_map *map;
  870. struct rspamd_map_backend *bk;
  871. const rspamd_ftok_t *idstr;
  872. struct stat st;
  873. gint fd;
  874. gulong id, i;
  875. gboolean found = FALSE;
  876. struct rspamd_http_message *reply;
  877. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  878. return 0;
  879. }
  880. idstr = rspamd_http_message_find_header (msg, "Map");
  881. if (idstr == NULL) {
  882. msg_info_session ("absent map id");
  883. rspamd_controller_send_error (conn_ent, 400, "Id header missing");
  884. return 0;
  885. }
  886. if (!rspamd_strtoul (idstr->begin, idstr->len, &id)) {
  887. msg_info_session ("invalid map id");
  888. rspamd_controller_send_error (conn_ent, 400, "Invalid map id");
  889. return 0;
  890. }
  891. /* Now let's be sure that we have map defined in configuration */
  892. cur = session->ctx->cfg->maps;
  893. while (cur && !found) {
  894. map = cur->data;
  895. PTR_ARRAY_FOREACH (map->backends, i, bk) {
  896. if (bk->id == id && bk->protocol == MAP_PROTO_FILE) {
  897. found = TRUE;
  898. break;
  899. }
  900. }
  901. cur = g_list_next (cur);
  902. }
  903. if (!found) {
  904. msg_info_session ("map not found");
  905. rspamd_controller_send_error (conn_ent, 404, "Map not found");
  906. return 0;
  907. }
  908. if (stat (bk->uri, &st) == -1 || (fd = open (bk->uri, O_RDONLY)) == -1) {
  909. reply = rspamd_http_new_message (HTTP_RESPONSE);
  910. reply->date = time (NULL);
  911. reply->code = 200;
  912. }
  913. else {
  914. reply = rspamd_http_new_message (HTTP_RESPONSE);
  915. reply->date = time (NULL);
  916. reply->code = 200;
  917. if (st.st_size > 0) {
  918. if (!rspamd_http_message_set_body_from_fd (reply, fd)) {
  919. close (fd);
  920. rspamd_http_message_unref (reply);
  921. msg_err_session ("cannot read map %s: %s", bk->uri, strerror (errno));
  922. rspamd_controller_send_error (conn_ent, 500, "Map read error");
  923. return 0;
  924. }
  925. }
  926. else {
  927. rspamd_fstring_t *empty_body = rspamd_fstring_new_init ("", 0);
  928. rspamd_http_message_set_body_from_fstring_steal (reply, empty_body);
  929. }
  930. close (fd);
  931. }
  932. rspamd_http_connection_reset (conn_ent->conn);
  933. rspamd_http_router_insert_headers (conn_ent->rt, reply);
  934. rspamd_http_connection_write_message (conn_ent->conn, reply, NULL,
  935. "text/plain", conn_ent, conn_ent->conn->fd,
  936. conn_ent->rt->ptv, conn_ent->rt->ev_base);
  937. conn_ent->is_reply = TRUE;
  938. return 0;
  939. }
  940. static ucl_object_t *
  941. rspamd_controller_pie_element (enum rspamd_action_type action,
  942. const char *label, gdouble data)
  943. {
  944. ucl_object_t *res = ucl_object_typed_new (UCL_OBJECT);
  945. const char *colors[METRIC_ACTION_MAX] = {
  946. [METRIC_ACTION_REJECT] = "#FF0000",
  947. [METRIC_ACTION_SOFT_REJECT] = "#cc9966",
  948. [METRIC_ACTION_REWRITE_SUBJECT] = "#ff6600",
  949. [METRIC_ACTION_ADD_HEADER] = "#FFD700",
  950. [METRIC_ACTION_GREYLIST] = "#436EEE",
  951. [METRIC_ACTION_NOACTION] = "#66cc00"
  952. };
  953. ucl_object_insert_key (res, ucl_object_fromstring (colors[action]),
  954. "color", 0, false);
  955. ucl_object_insert_key (res, ucl_object_fromstring (label), "label", 0, false);
  956. ucl_object_insert_key (res, ucl_object_fromdouble (data), "data", 0, false);
  957. ucl_object_insert_key (res, ucl_object_fromdouble (data), "value", 0, false);
  958. return res;
  959. }
  960. /*
  961. * Pie chart command handler:
  962. * request: /pie
  963. * headers: Password
  964. * reply: json [
  965. * { label: "Foo", data: 11 },
  966. * { label: "Bar", data: 20 },
  967. * {...}
  968. * ]
  969. */
  970. static int
  971. rspamd_controller_handle_pie_chart (
  972. struct rspamd_http_connection_entry *conn_ent,
  973. struct rspamd_http_message *msg)
  974. {
  975. struct rspamd_controller_session *session = conn_ent->ud;
  976. struct rspamd_controller_worker_ctx *ctx;
  977. gdouble data[5], total;
  978. ucl_object_t *top;
  979. ctx = session->ctx;
  980. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  981. return 0;
  982. }
  983. top = ucl_object_typed_new (UCL_ARRAY);
  984. total = ctx->srv->stat->messages_scanned;
  985. if (total != 0) {
  986. data[0] = ctx->srv->stat->actions_stat[METRIC_ACTION_NOACTION];
  987. data[1] = ctx->srv->stat->actions_stat[METRIC_ACTION_SOFT_REJECT];
  988. data[2] = (ctx->srv->stat->actions_stat[METRIC_ACTION_ADD_HEADER] +
  989. ctx->srv->stat->actions_stat[METRIC_ACTION_REWRITE_SUBJECT]);
  990. data[3] = ctx->srv->stat->actions_stat[METRIC_ACTION_GREYLIST];
  991. data[4] = ctx->srv->stat->actions_stat[METRIC_ACTION_REJECT];
  992. }
  993. else {
  994. memset (data, 0, sizeof (data));
  995. }
  996. ucl_array_append (top, rspamd_controller_pie_element (
  997. METRIC_ACTION_NOACTION, "Clean", data[0]));
  998. ucl_array_append (top, rspamd_controller_pie_element (
  999. METRIC_ACTION_SOFT_REJECT, "Temporarily rejected", data[1]));
  1000. ucl_array_append (top, rspamd_controller_pie_element (
  1001. METRIC_ACTION_ADD_HEADER, "Probable spam", data[2]));
  1002. ucl_array_append (top, rspamd_controller_pie_element (
  1003. METRIC_ACTION_GREYLIST, "Greylisted", data[3]));
  1004. ucl_array_append (top, rspamd_controller_pie_element (
  1005. METRIC_ACTION_REJECT, "Rejected", data[4]));
  1006. rspamd_controller_send_ucl (conn_ent, top);
  1007. ucl_object_unref (top);
  1008. return 0;
  1009. }
  1010. void
  1011. rspamd_controller_graph_point (gulong t, gulong step,
  1012. struct rspamd_rrd_query_result* rrd_result,
  1013. gdouble *acc,
  1014. ucl_object_t **elt)
  1015. {
  1016. guint nan_cnt;
  1017. gdouble sum = 0.0, yval;
  1018. ucl_object_t* data_elt;
  1019. guint i, j;
  1020. for (i = 0; i < rrd_result->ds_count; i++) {
  1021. sum = 0.0;
  1022. nan_cnt = 0;
  1023. data_elt = ucl_object_typed_new (UCL_OBJECT);
  1024. ucl_object_insert_key (data_elt, ucl_object_fromint (t), "x", 1, false);
  1025. for (j = 0; j < step; j++) {
  1026. yval = acc[i + j * rrd_result->ds_count];
  1027. if (!isfinite (yval)) {
  1028. nan_cnt++;
  1029. }
  1030. else {
  1031. sum += yval;
  1032. }
  1033. }
  1034. if (nan_cnt == step) {
  1035. ucl_object_insert_key (data_elt, ucl_object_typed_new (UCL_NULL),
  1036. "y", 1, false);
  1037. }
  1038. else {
  1039. ucl_object_insert_key (data_elt,
  1040. ucl_object_fromdouble (sum / (gdouble) step), "y", 1,
  1041. false);
  1042. }
  1043. ucl_array_append (elt[i], data_elt);
  1044. }
  1045. }
  1046. /*
  1047. * Graph command handler:
  1048. * request: /graph?type=<hourly|daily|weekly|monthly>
  1049. * headers: Password
  1050. * reply: json [
  1051. * { label: "Foo", data: 11 },
  1052. * { label: "Bar", data: 20 },
  1053. * {...}
  1054. * ]
  1055. */
  1056. static int
  1057. rspamd_controller_handle_graph (
  1058. struct rspamd_http_connection_entry *conn_ent,
  1059. struct rspamd_http_message *msg)
  1060. {
  1061. GHashTable *query;
  1062. struct rspamd_controller_session *session = conn_ent->ud;
  1063. struct rspamd_controller_worker_ctx *ctx;
  1064. rspamd_ftok_t srch, *value;
  1065. struct rspamd_rrd_query_result *rrd_result;
  1066. gulong i, k, start_row, cnt, t, ts, step;
  1067. gdouble *acc;
  1068. ucl_object_t *res, *elt[METRIC_ACTION_MAX];
  1069. enum {
  1070. rra_hourly = 0,
  1071. rra_daily,
  1072. rra_weekly,
  1073. rra_monthly,
  1074. rra_invalid
  1075. } rra_num = rra_invalid;
  1076. /* How many points are we going to send to display */
  1077. static const guint desired_points = 500;
  1078. ctx = session->ctx;
  1079. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  1080. return 0;
  1081. }
  1082. if (ctx->rrd == NULL) {
  1083. msg_err_session ("no rrd configured");
  1084. rspamd_controller_send_error (conn_ent, 404, "No rrd configured for graphs");
  1085. return 0;
  1086. }
  1087. query = rspamd_http_message_parse_query (msg);
  1088. srch.begin = (gchar *)"type";
  1089. srch.len = 4;
  1090. if (query == NULL || (value = g_hash_table_lookup (query, &srch)) == NULL) {
  1091. msg_err_session ("absent graph type query");
  1092. rspamd_controller_send_error (conn_ent, 400, "Absent graph type");
  1093. if (query) {
  1094. g_hash_table_unref (query);
  1095. }
  1096. return 0;
  1097. }
  1098. if (value->len == 6 && rspamd_lc_cmp (value->begin, "hourly", value->len) == 0) {
  1099. rra_num = rra_hourly;
  1100. }
  1101. else if (value->len == 5 && rspamd_lc_cmp (value->begin, "daily", value->len) == 0) {
  1102. rra_num = rra_daily;
  1103. }
  1104. else if (value->len == 6 && rspamd_lc_cmp (value->begin, "weekly", value->len) == 0) {
  1105. rra_num = rra_weekly;
  1106. }
  1107. else if (value->len == 7 && rspamd_lc_cmp (value->begin, "monthly", value->len) == 0) {
  1108. rra_num = rra_monthly;
  1109. }
  1110. g_hash_table_unref (query);
  1111. if (rra_num == rra_invalid) {
  1112. msg_err_session ("invalid graph type query");
  1113. rspamd_controller_send_error (conn_ent, 400, "Invalid graph type");
  1114. return 0;
  1115. }
  1116. rrd_result = rspamd_rrd_query (ctx->rrd, rra_num);
  1117. if (rrd_result == NULL) {
  1118. msg_err_session ("cannot query rrd");
  1119. rspamd_controller_send_error (conn_ent, 500, "Cannot query rrd");
  1120. return 0;
  1121. }
  1122. g_assert (rrd_result->ds_count == G_N_ELEMENTS (elt));
  1123. res = ucl_object_typed_new (UCL_ARRAY);
  1124. /* How much full updates happened since the last update */
  1125. ts = rrd_result->last_update / rrd_result->pdp_per_cdp - rrd_result->rra_rows;
  1126. for (i = 0; i < rrd_result->ds_count; i ++) {
  1127. elt[i] = ucl_object_typed_new (UCL_ARRAY);
  1128. }
  1129. start_row = rrd_result->cur_row == rrd_result->rra_rows - 1 ?
  1130. 0 : rrd_result->cur_row;
  1131. t = ts * rrd_result->pdp_per_cdp;
  1132. k = 0;
  1133. /* Create window */
  1134. step = ceil (((gdouble)rrd_result->rra_rows) / desired_points);
  1135. g_assert (step >= 1);
  1136. acc = g_malloc0 (sizeof (double) * rrd_result->ds_count * step);
  1137. for (i = start_row, cnt = 0; cnt < rrd_result->rra_rows;
  1138. cnt ++) {
  1139. memcpy (&acc[k * rrd_result->ds_count],
  1140. &rrd_result->data[i * rrd_result->ds_count],
  1141. sizeof (gdouble) * rrd_result->ds_count);
  1142. if (k < step - 1) {
  1143. k ++;
  1144. }
  1145. else {
  1146. t = ts * rrd_result->pdp_per_cdp;
  1147. /* Need a fresh point */
  1148. rspamd_controller_graph_point (t, step, rrd_result, acc, elt);
  1149. k = 0;
  1150. }
  1151. if (i == rrd_result->rra_rows - 1) {
  1152. i = 0;
  1153. }
  1154. else {
  1155. i ++;
  1156. }
  1157. ts ++;
  1158. }
  1159. if (k > 0) {
  1160. rspamd_controller_graph_point (t, k, rrd_result, acc, elt);
  1161. }
  1162. for (i = 0; i < rrd_result->ds_count; i++) {
  1163. ucl_array_append (res, elt[i]);
  1164. }
  1165. rspamd_controller_send_ucl (conn_ent, res);
  1166. ucl_object_unref (res);
  1167. g_free (acc);
  1168. return 0;
  1169. }
  1170. static void
  1171. rspamd_controller_handle_legacy_history (
  1172. struct rspamd_controller_session *session,
  1173. struct rspamd_controller_worker_ctx *ctx,
  1174. struct rspamd_http_connection_entry *conn_ent,
  1175. struct rspamd_http_message *msg)
  1176. {
  1177. struct roll_history_row *row, *copied_rows;
  1178. guint i, rows_proc, row_num;
  1179. struct tm tm;
  1180. gchar timebuf[32], **syms;
  1181. ucl_object_t *top, *obj;
  1182. top = ucl_object_typed_new (UCL_ARRAY);
  1183. /* Set lock on history */
  1184. copied_rows = g_malloc (sizeof (*copied_rows) * ctx->srv->history->nrows);
  1185. memcpy (copied_rows, ctx->srv->history->rows,
  1186. sizeof (*copied_rows) * ctx->srv->history->nrows);
  1187. /* Go through all rows */
  1188. row_num = ctx->srv->history->cur_row;
  1189. for (i = 0, rows_proc = 0; i < ctx->srv->history->nrows; i++, row_num++) {
  1190. if (row_num == ctx->srv->history->nrows) {
  1191. row_num = 0;
  1192. }
  1193. row = &copied_rows[row_num];
  1194. /* Get only completed rows */
  1195. if (row->completed) {
  1196. rspamd_localtime (row->tv.tv_sec, &tm);
  1197. strftime (timebuf, sizeof (timebuf) - 1, "%Y-%m-%d %H:%M:%S", &tm);
  1198. obj = ucl_object_typed_new (UCL_OBJECT);
  1199. ucl_object_insert_key (obj, ucl_object_fromstring (
  1200. timebuf), "time", 0, false);
  1201. ucl_object_insert_key (obj, ucl_object_fromint (
  1202. row->tv.tv_sec), "unix_time", 0, false);
  1203. ucl_object_insert_key (obj, ucl_object_fromstring (
  1204. row->message_id), "id", 0, false);
  1205. ucl_object_insert_key (obj, ucl_object_fromstring (row->from_addr),
  1206. "ip", 0, false);
  1207. ucl_object_insert_key (obj,
  1208. ucl_object_fromstring (rspamd_action_to_str (
  1209. row->action)), "action", 0, false);
  1210. if (!isnan (row->score)) {
  1211. ucl_object_insert_key (obj, ucl_object_fromdouble (
  1212. row->score), "score", 0, false);
  1213. }
  1214. else {
  1215. ucl_object_insert_key (obj,
  1216. ucl_object_fromdouble (0.0), "score", 0, false);
  1217. }
  1218. if (!isnan (row->required_score)) {
  1219. ucl_object_insert_key (obj,
  1220. ucl_object_fromdouble (
  1221. row->required_score), "required_score", 0, false);
  1222. }
  1223. else {
  1224. ucl_object_insert_key (obj,
  1225. ucl_object_fromdouble (0.0), "required_score", 0, false);
  1226. }
  1227. syms = g_strsplit_set (row->symbols, ", ", -1);
  1228. if (syms) {
  1229. guint nelts = g_strv_length (syms);
  1230. ucl_object_t *syms_obj = ucl_object_typed_new (UCL_OBJECT);
  1231. ucl_object_reserve (syms_obj, nelts);
  1232. for (guint j = 0; j < nelts; j++) {
  1233. g_strstrip (syms[j]);
  1234. if (strlen (syms[j]) == 0) {
  1235. /* Empty garbadge */
  1236. continue;
  1237. }
  1238. ucl_object_t *cur = ucl_object_typed_new (UCL_OBJECT);
  1239. ucl_object_insert_key (cur, ucl_object_fromdouble (0.0),
  1240. "score", 0, false);
  1241. ucl_object_insert_key (syms_obj, cur, syms[j], 0, true);
  1242. }
  1243. ucl_object_insert_key (obj, syms_obj, "symbols", 0, false);
  1244. g_strfreev (syms);
  1245. }
  1246. ucl_object_insert_key (obj, ucl_object_fromint (row->len),
  1247. "size", 0, false);
  1248. ucl_object_insert_key (obj,
  1249. ucl_object_fromdouble (row->scan_time),
  1250. "scan_time", 0, false);
  1251. if (row->user[0] != '\0') {
  1252. ucl_object_insert_key (obj, ucl_object_fromstring (row->user),
  1253. "user", 0, false);
  1254. }
  1255. if (row->from_addr[0] != '\0') {
  1256. ucl_object_insert_key (obj, ucl_object_fromstring (
  1257. row->from_addr), "from", 0, false);
  1258. }
  1259. ucl_array_append (top, obj);
  1260. rows_proc++;
  1261. }
  1262. }
  1263. rspamd_controller_send_ucl (conn_ent, top);
  1264. ucl_object_unref (top);
  1265. g_free (copied_rows);
  1266. }
  1267. static gboolean
  1268. rspamd_controller_history_lua_fin_task (void *ud)
  1269. {
  1270. return TRUE;
  1271. }
  1272. static void
  1273. rspamd_controller_handle_lua_history (lua_State *L,
  1274. struct rspamd_controller_session *session,
  1275. struct rspamd_controller_worker_ctx *ctx,
  1276. struct rspamd_http_connection_entry *conn_ent,
  1277. struct rspamd_http_message *msg,
  1278. gboolean reset)
  1279. {
  1280. struct rspamd_task *task, **ptask;
  1281. struct rspamd_http_connection_entry **pconn_ent;
  1282. GHashTable *params;
  1283. rspamd_ftok_t srch, *found;
  1284. glong from = 0, to = -1;
  1285. params = rspamd_http_message_parse_query (msg);
  1286. if (params) {
  1287. /* Check from and to */
  1288. RSPAMD_FTOK_ASSIGN (&srch, "from");
  1289. found = g_hash_table_lookup (params, &srch);
  1290. if (found) {
  1291. rspamd_strtol (found->begin, found->len, &from);
  1292. }
  1293. RSPAMD_FTOK_ASSIGN (&srch, "to");
  1294. found = g_hash_table_lookup (params, &srch);
  1295. if (found) {
  1296. rspamd_strtol (found->begin, found->len, &to);
  1297. }
  1298. g_hash_table_unref (params);
  1299. }
  1300. lua_getglobal (L, "rspamd_plugins");
  1301. if (lua_istable (L, -1)) {
  1302. lua_pushstring (L, "history");
  1303. lua_gettable (L, -2);
  1304. if (lua_istable (L, -1)) {
  1305. lua_pushstring (L, "handler");
  1306. lua_gettable (L, -2);
  1307. if (lua_isfunction (L, -1)) {
  1308. task = rspamd_task_new (session->ctx->worker, session->cfg,
  1309. session->pool, ctx->lang_det, ctx->ev_base);
  1310. task->resolver = ctx->resolver;
  1311. task->s = rspamd_session_create (session->pool,
  1312. rspamd_controller_history_lua_fin_task,
  1313. NULL,
  1314. (event_finalizer_t )rspamd_task_free,
  1315. task);
  1316. task->fin_arg = conn_ent;
  1317. ptask = lua_newuserdata (L, sizeof (*ptask));
  1318. *ptask = task;
  1319. rspamd_lua_setclass (L, "rspamd{task}", -1);
  1320. pconn_ent = lua_newuserdata (L, sizeof (*pconn_ent));
  1321. *pconn_ent = conn_ent;
  1322. rspamd_lua_setclass (L, "rspamd{csession}", -1);
  1323. lua_pushinteger (L, from);
  1324. lua_pushinteger (L, to);
  1325. lua_pushboolean (L, reset);
  1326. if (lua_pcall (L, 5, 0, 0) != 0) {
  1327. msg_err_session ("call to history function failed: %s",
  1328. lua_tostring (L, -1));
  1329. lua_settop (L, 0);
  1330. rspamd_task_free (task);
  1331. goto err;
  1332. }
  1333. task->http_conn = rspamd_http_connection_ref (conn_ent->conn);;
  1334. task->sock = -1;
  1335. session->task = task;
  1336. rspamd_session_pending (task->s);
  1337. }
  1338. else {
  1339. msg_err_session ("rspamd_plugins.history.handler is not a function");
  1340. lua_settop (L, 0);
  1341. goto err;
  1342. }
  1343. }
  1344. else {
  1345. msg_err_session ("rspamd_plugins.history is not a table");
  1346. lua_settop (L, 0);
  1347. goto err;
  1348. }
  1349. }
  1350. else {
  1351. msg_err_session ("rspamd_plugins is absent or has incorrect type");
  1352. lua_settop (L, 0);
  1353. goto err;
  1354. }
  1355. lua_settop (L, 0);
  1356. return;
  1357. err:
  1358. rspamd_controller_send_error (conn_ent, 500, "Internal error");
  1359. }
  1360. /*
  1361. * History command handler:
  1362. * request: /history
  1363. * headers: Password
  1364. * reply: json [
  1365. * { label: "Foo", data: 11 },
  1366. * { label: "Bar", data: 20 },
  1367. * {...}
  1368. * ]
  1369. */
  1370. static int
  1371. rspamd_controller_handle_history (struct rspamd_http_connection_entry *conn_ent,
  1372. struct rspamd_http_message *msg)
  1373. {
  1374. struct rspamd_controller_session *session = conn_ent->ud;
  1375. struct rspamd_controller_worker_ctx *ctx;
  1376. lua_State *L;
  1377. ctx = session->ctx;
  1378. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  1379. return 0;
  1380. }
  1381. L = ctx->cfg->lua_state;
  1382. if (!ctx->srv->history->disabled) {
  1383. rspamd_controller_handle_legacy_history (session, ctx, conn_ent, msg);
  1384. }
  1385. else {
  1386. rspamd_controller_handle_lua_history (L, session, ctx, conn_ent, msg,
  1387. FALSE);
  1388. }
  1389. return 0;
  1390. }
  1391. /*
  1392. * Errors command handler:
  1393. * request: /errors
  1394. * headers: Password
  1395. * reply: json [
  1396. * { ts: 100500, type: normal, pid: 100, module: lua, message: bad things },
  1397. * {...}
  1398. * ]
  1399. */
  1400. static int
  1401. rspamd_controller_handle_errors (struct rspamd_http_connection_entry *conn_ent,
  1402. struct rspamd_http_message *msg)
  1403. {
  1404. struct rspamd_controller_session *session = conn_ent->ud;
  1405. struct rspamd_controller_worker_ctx *ctx;
  1406. ucl_object_t *top;
  1407. ctx = session->ctx;
  1408. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  1409. return 0;
  1410. }
  1411. top = rspamd_log_errorbuf_export (ctx->worker->srv->logger);
  1412. rspamd_controller_send_ucl (conn_ent, top);
  1413. ucl_object_unref (top);
  1414. return 0;
  1415. }
  1416. /*
  1417. * Neighbours command handler:
  1418. * request: /neighbours
  1419. * headers: Password
  1420. * reply: json {name: {url: "http://...", host: "host"}}
  1421. */
  1422. static int
  1423. rspamd_controller_handle_neighbours (struct rspamd_http_connection_entry *conn_ent,
  1424. struct rspamd_http_message *msg)
  1425. {
  1426. struct rspamd_controller_session *session = conn_ent->ud;
  1427. struct rspamd_controller_worker_ctx *ctx;
  1428. ctx = session->ctx;
  1429. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  1430. return 0;
  1431. }
  1432. rspamd_controller_send_ucl (conn_ent, ctx->cfg->neighbours);
  1433. return 0;
  1434. }
  1435. static int
  1436. rspamd_controller_handle_history_reset (struct rspamd_http_connection_entry *conn_ent,
  1437. struct rspamd_http_message *msg)
  1438. {
  1439. struct rspamd_controller_session *session = conn_ent->ud;
  1440. struct rspamd_controller_worker_ctx *ctx;
  1441. struct roll_history_row *row;
  1442. guint start_row, i, t;
  1443. lua_State *L;
  1444. ctx = session->ctx;
  1445. L = ctx->cfg->lua_state;
  1446. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  1447. return 0;
  1448. }
  1449. if (!ctx->srv->history->disabled) {
  1450. /* Clean from start to the current row */
  1451. start_row = g_atomic_int_get (&ctx->srv->history->cur_row);
  1452. for (i = 0; i < start_row; i ++) {
  1453. t = g_atomic_int_get (&ctx->srv->history->cur_row);
  1454. /* We somehow come to the race condition */
  1455. if (i >= t) {
  1456. break;
  1457. }
  1458. row = &ctx->srv->history->rows[i];
  1459. memset (row, 0, sizeof (*row));
  1460. }
  1461. start_row = g_atomic_int_get (&ctx->srv->history->cur_row);
  1462. /* Optimistically set all bytes to zero (might cause race) */
  1463. memset (ctx->srv->history->rows,
  1464. 0,
  1465. sizeof (*row) * (ctx->srv->history->nrows - start_row));
  1466. msg_info_session ("<%s> reset history",
  1467. rspamd_inet_address_to_string (session->from_addr));
  1468. rspamd_controller_send_string (conn_ent, "{\"success\":true}");
  1469. }
  1470. else {
  1471. rspamd_controller_handle_lua_history (L, session, ctx, conn_ent, msg,
  1472. TRUE);
  1473. }
  1474. return 0;
  1475. }
  1476. static gboolean
  1477. rspamd_controller_lua_fin_task (void *ud)
  1478. {
  1479. struct rspamd_task *task = ud;
  1480. struct rspamd_http_connection_entry *conn_ent;
  1481. conn_ent = task->fin_arg;
  1482. if (task->err != NULL) {
  1483. rspamd_controller_send_error (conn_ent, task->err->code, "%s",
  1484. task->err->message);
  1485. }
  1486. return TRUE;
  1487. }
  1488. static int
  1489. rspamd_controller_handle_lua (struct rspamd_http_connection_entry *conn_ent,
  1490. struct rspamd_http_message *msg)
  1491. {
  1492. struct rspamd_controller_session *session = conn_ent->ud;
  1493. struct rspamd_task *task, **ptask;
  1494. struct rspamd_http_connection_entry **pconn;
  1495. struct rspamd_controller_worker_ctx *ctx;
  1496. gchar filebuf[PATH_MAX], realbuf[PATH_MAX];
  1497. struct http_parser_url u;
  1498. rspamd_ftok_t lookup;
  1499. struct stat st;
  1500. lua_State *L;
  1501. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  1502. return 0;
  1503. }
  1504. ctx = session->ctx;
  1505. L = ctx->cfg->lua_state;
  1506. /* Find lua script */
  1507. if (msg->url != NULL && msg->url->len != 0) {
  1508. http_parser_parse_url (RSPAMD_FSTRING_DATA (msg->url),
  1509. RSPAMD_FSTRING_LEN (msg->url), TRUE, &u);
  1510. if (u.field_set & (1 << UF_PATH)) {
  1511. lookup.begin = RSPAMD_FSTRING_DATA (msg->url) +
  1512. u.field_data[UF_PATH].off;
  1513. lookup.len = u.field_data[UF_PATH].len;
  1514. }
  1515. else {
  1516. lookup.begin = RSPAMD_FSTRING_DATA (msg->url);
  1517. lookup.len = RSPAMD_FSTRING_LEN (msg->url);
  1518. }
  1519. rspamd_snprintf (filebuf, sizeof (filebuf), "%s%c%T",
  1520. ctx->static_files_dir, G_DIR_SEPARATOR, &lookup);
  1521. if (realpath (filebuf, realbuf) == NULL ||
  1522. lstat (realbuf, &st) == -1) {
  1523. rspamd_controller_send_error (conn_ent, 404, "Cannot find path: %s",
  1524. strerror (errno));
  1525. return 0;
  1526. }
  1527. /* TODO: add caching here, should be trivial */
  1528. /* Now we load and execute the code fragment, which should return a function */
  1529. if (luaL_loadfile (L, realbuf) != 0) {
  1530. rspamd_controller_send_error (conn_ent, 500, "Cannot load path: %s",
  1531. lua_tostring (L, -1));
  1532. lua_settop (L, 0);
  1533. return 0;
  1534. }
  1535. if (lua_pcall (L, 0, 1, 0) != 0) {
  1536. rspamd_controller_send_error (conn_ent, 501, "Cannot run path: %s",
  1537. lua_tostring (L, -1));
  1538. lua_settop (L, 0);
  1539. return 0;
  1540. }
  1541. if (lua_type (L, -1) != LUA_TFUNCTION) {
  1542. rspamd_controller_send_error (conn_ent, 502, "Bad return type: %s",
  1543. lua_typename (L, lua_type (L, -1)));
  1544. lua_settop (L, 0);
  1545. return 0;
  1546. }
  1547. }
  1548. else {
  1549. rspamd_controller_send_error (conn_ent, 404, "Empty path is not permitted");
  1550. return 0;
  1551. }
  1552. task = rspamd_task_new (session->ctx->worker, session->cfg, session->pool,
  1553. ctx->lang_det, ctx->ev_base);
  1554. task->resolver = ctx->resolver;
  1555. task->s = rspamd_session_create (session->pool,
  1556. rspamd_controller_lua_fin_task,
  1557. NULL,
  1558. (event_finalizer_t )rspamd_task_free,
  1559. task);
  1560. task->fin_arg = conn_ent;
  1561. task->http_conn = rspamd_http_connection_ref (conn_ent->conn);;
  1562. task->sock = -1;
  1563. session->task = task;
  1564. if (msg->body_buf.len > 0) {
  1565. if (!rspamd_task_load_message (task, msg, msg->body_buf.begin, msg->body_buf.len)) {
  1566. rspamd_controller_send_error (conn_ent, task->err->code, "%s",
  1567. task->err->message);
  1568. return 0;
  1569. }
  1570. }
  1571. ptask = lua_newuserdata (L, sizeof (*ptask));
  1572. rspamd_lua_setclass (L, "rspamd{task}", -1);
  1573. *ptask = task;
  1574. pconn = lua_newuserdata (L, sizeof (*pconn));
  1575. rspamd_lua_setclass (L, "rspamd{csession}", -1);
  1576. *pconn = conn_ent;
  1577. if (lua_pcall (L, 2, 0, 0) != 0) {
  1578. rspamd_controller_send_error (conn_ent, 503, "Cannot run callback: %s",
  1579. lua_tostring (L, -1));
  1580. lua_settop (L, 0);
  1581. return 0;
  1582. }
  1583. rspamd_session_pending (task->s);
  1584. return 0;
  1585. }
  1586. static gboolean
  1587. rspamd_controller_learn_fin_task (void *ud)
  1588. {
  1589. struct rspamd_task *task = ud;
  1590. struct rspamd_controller_session *session;
  1591. struct rspamd_http_connection_entry *conn_ent;
  1592. conn_ent = task->fin_arg;
  1593. session = conn_ent->ud;
  1594. if (task->err != NULL) {
  1595. msg_info_session ("cannot learn <%s>: %e", task->message_id, task->err);
  1596. rspamd_controller_send_error (conn_ent, task->err->code, "%s",
  1597. task->err->message);
  1598. return TRUE;
  1599. }
  1600. if (RSPAMD_TASK_IS_PROCESSED (task)) {
  1601. /* Successful learn */
  1602. msg_info_task ("<%s> learned message as %s: %s",
  1603. rspamd_inet_address_to_string (session->from_addr),
  1604. session->is_spam ? "spam" : "ham",
  1605. task->message_id);
  1606. rspamd_controller_send_string (conn_ent, "{\"success\":true}");
  1607. return TRUE;
  1608. }
  1609. if (!rspamd_task_process (task, RSPAMD_TASK_PROCESS_LEARN)) {
  1610. msg_info_task ("cannot learn <%s>: %e", task->message_id, task->err);
  1611. if (task->err) {
  1612. rspamd_controller_send_error (conn_ent, task->err->code, "%s",
  1613. task->err->message);
  1614. }
  1615. else {
  1616. rspamd_controller_send_error (conn_ent, 500,
  1617. "Internal error");
  1618. }
  1619. }
  1620. if (RSPAMD_TASK_IS_PROCESSED (task)) {
  1621. if (task->err) {
  1622. rspamd_controller_send_error (conn_ent, task->err->code, "%s",
  1623. task->err->message);
  1624. }
  1625. else {
  1626. msg_info_task ("<%s> learned message as %s: %s",
  1627. rspamd_inet_address_to_string (session->from_addr),
  1628. session->is_spam ? "spam" : "ham",
  1629. task->message_id);
  1630. rspamd_controller_send_string (conn_ent, "{\"success\":true}");
  1631. }
  1632. return TRUE;
  1633. }
  1634. /* One more iteration */
  1635. return FALSE;
  1636. }
  1637. static void
  1638. rspamd_controller_scan_reply (struct rspamd_task *task)
  1639. {
  1640. struct rspamd_http_message *msg;
  1641. struct rspamd_http_connection_entry *conn_ent;
  1642. conn_ent = task->fin_arg;
  1643. msg = rspamd_http_new_message (HTTP_RESPONSE);
  1644. msg->date = time (NULL);
  1645. msg->code = 200;
  1646. rspamd_protocol_http_reply (msg, task, NULL);
  1647. rspamd_http_connection_reset (conn_ent->conn);
  1648. rspamd_http_router_insert_headers (conn_ent->rt, msg);
  1649. rspamd_http_connection_write_message (conn_ent->conn, msg, NULL,
  1650. "application/json", conn_ent, conn_ent->conn->fd, conn_ent->rt->ptv,
  1651. conn_ent->rt->ev_base);
  1652. conn_ent->is_reply = TRUE;
  1653. }
  1654. static gboolean
  1655. rspamd_controller_check_fin_task (void *ud)
  1656. {
  1657. struct rspamd_task *task = ud;
  1658. struct rspamd_http_connection_entry *conn_ent;
  1659. msg_debug_task ("finish task");
  1660. conn_ent = task->fin_arg;
  1661. if (task->err) {
  1662. msg_info_task ("cannot check <%s>: %e", task->message_id, task->err);
  1663. rspamd_controller_send_error (conn_ent, task->err->code, "%s",
  1664. task->err->message);
  1665. return TRUE;
  1666. }
  1667. if (RSPAMD_TASK_IS_PROCESSED (task)) {
  1668. rspamd_controller_scan_reply (task);
  1669. return TRUE;
  1670. }
  1671. if (!rspamd_task_process (task, RSPAMD_TASK_PROCESS_ALL)) {
  1672. rspamd_controller_scan_reply (task);
  1673. return TRUE;
  1674. }
  1675. if (RSPAMD_TASK_IS_PROCESSED (task)) {
  1676. rspamd_controller_scan_reply (task);
  1677. return TRUE;
  1678. }
  1679. /* One more iteration */
  1680. return FALSE;
  1681. }
  1682. static int
  1683. rspamd_controller_handle_learn_common (
  1684. struct rspamd_http_connection_entry *conn_ent,
  1685. struct rspamd_http_message *msg,
  1686. gboolean is_spam)
  1687. {
  1688. struct rspamd_controller_session *session = conn_ent->ud;
  1689. struct rspamd_controller_worker_ctx *ctx;
  1690. struct rspamd_task *task;
  1691. const rspamd_ftok_t *cl_header;
  1692. ctx = session->ctx;
  1693. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  1694. return 0;
  1695. }
  1696. if (rspamd_http_message_get_body (msg, NULL) == NULL) {
  1697. msg_err_session ("got zero length body, cannot continue");
  1698. rspamd_controller_send_error (conn_ent,
  1699. 400,
  1700. "Empty body is not permitted");
  1701. return 0;
  1702. }
  1703. task = rspamd_task_new (session->ctx->worker, session->cfg, session->pool,
  1704. session->ctx->lang_det, ctx->ev_base);
  1705. task->resolver = ctx->resolver;
  1706. task->s = rspamd_session_create (session->pool,
  1707. rspamd_controller_learn_fin_task,
  1708. NULL,
  1709. (event_finalizer_t )rspamd_task_free,
  1710. task);
  1711. task->fin_arg = conn_ent;
  1712. task->http_conn = rspamd_http_connection_ref (conn_ent->conn);;
  1713. task->sock = -1;
  1714. session->task = task;
  1715. cl_header = rspamd_http_message_find_header (msg, "classifier");
  1716. if (cl_header) {
  1717. session->classifier = rspamd_mempool_ftokdup (session->pool, cl_header);
  1718. }
  1719. else {
  1720. session->classifier = NULL;
  1721. }
  1722. if (!rspamd_task_load_message (task, msg, msg->body_buf.begin, msg->body_buf.len)) {
  1723. goto end;
  1724. }
  1725. rspamd_learn_task_spam (task, is_spam, session->classifier, NULL);
  1726. if (!rspamd_task_process (task, RSPAMD_TASK_PROCESS_LEARN)) {
  1727. msg_warn_session ("<%s> message cannot be processed", task->message_id);
  1728. goto end;
  1729. }
  1730. end:
  1731. session->is_spam = is_spam;
  1732. rspamd_session_pending (task->s);
  1733. return 0;
  1734. }
  1735. /*
  1736. * Learn spam command handler:
  1737. * request: /learnspam
  1738. * headers: Password
  1739. * input: plaintext data
  1740. * reply: json {"success":true} or {"error":"error message"}
  1741. */
  1742. static int
  1743. rspamd_controller_handle_learnspam (
  1744. struct rspamd_http_connection_entry *conn_ent,
  1745. struct rspamd_http_message *msg)
  1746. {
  1747. return rspamd_controller_handle_learn_common (conn_ent, msg, TRUE);
  1748. }
  1749. /*
  1750. * Learn ham command handler:
  1751. * request: /learnham
  1752. * headers: Password
  1753. * input: plaintext data
  1754. * reply: json {"success":true} or {"error":"error message"}
  1755. */
  1756. static int
  1757. rspamd_controller_handle_learnham (
  1758. struct rspamd_http_connection_entry *conn_ent,
  1759. struct rspamd_http_message *msg)
  1760. {
  1761. return rspamd_controller_handle_learn_common (conn_ent, msg, FALSE);
  1762. }
  1763. /*
  1764. * Scan command handler:
  1765. * request: /scan
  1766. * headers: Password
  1767. * input: plaintext data
  1768. * reply: json {scan data} or {"error":"error message"}
  1769. */
  1770. static int
  1771. rspamd_controller_handle_scan (struct rspamd_http_connection_entry *conn_ent,
  1772. struct rspamd_http_message *msg)
  1773. {
  1774. struct rspamd_controller_session *session = conn_ent->ud;
  1775. struct rspamd_controller_worker_ctx *ctx;
  1776. struct rspamd_task *task;
  1777. ctx = session->ctx;
  1778. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  1779. return 0;
  1780. }
  1781. if (rspamd_http_message_get_body (msg, NULL) == NULL) {
  1782. msg_err_session ("got zero length body, cannot continue");
  1783. rspamd_controller_send_error (conn_ent,
  1784. 400,
  1785. "Empty body is not permitted");
  1786. return 0;
  1787. }
  1788. task = rspamd_task_new (session->ctx->worker, session->cfg, session->pool,
  1789. ctx->lang_det, ctx->ev_base);
  1790. task->resolver = ctx->resolver;
  1791. task->s = rspamd_session_create (session->pool,
  1792. rspamd_controller_check_fin_task,
  1793. NULL,
  1794. (event_finalizer_t )rspamd_task_free,
  1795. task);
  1796. task->fin_arg = conn_ent;
  1797. task->http_conn = rspamd_http_connection_ref (conn_ent->conn);
  1798. task->sock = conn_ent->conn->fd;
  1799. task->flags |= RSPAMD_TASK_FLAG_MIME;
  1800. task->resolver = ctx->resolver;
  1801. if (!rspamd_protocol_handle_request (task, msg)) {
  1802. goto end;
  1803. }
  1804. if (!rspamd_task_load_message (task, msg, msg->body_buf.begin, msg->body_buf.len)) {
  1805. goto end;
  1806. }
  1807. if (!rspamd_task_process (task, RSPAMD_TASK_PROCESS_ALL)) {
  1808. goto end;
  1809. }
  1810. end:
  1811. session->task = task;
  1812. rspamd_session_pending (task->s);
  1813. return 0;
  1814. }
  1815. /*
  1816. * Save actions command handler:
  1817. * request: /saveactions
  1818. * headers: Password
  1819. * input: json array [<spam>,<probable spam>,<greylist>]
  1820. * reply: json {"success":true} or {"error":"error message"}
  1821. */
  1822. static int
  1823. rspamd_controller_handle_saveactions (
  1824. struct rspamd_http_connection_entry *conn_ent,
  1825. struct rspamd_http_message *msg)
  1826. {
  1827. struct rspamd_controller_session *session = conn_ent->ud;
  1828. struct ucl_parser *parser;
  1829. ucl_object_t *obj;
  1830. const ucl_object_t *cur;
  1831. struct rspamd_controller_worker_ctx *ctx;
  1832. const gchar *error;
  1833. gdouble score;
  1834. gint i, added = 0;
  1835. enum rspamd_action_type act;
  1836. ucl_object_iter_t it = NULL;
  1837. ctx = session->ctx;
  1838. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  1839. return 0;
  1840. }
  1841. if (rspamd_http_message_get_body (msg, NULL) == NULL) {
  1842. msg_err_session ("got zero length body, cannot continue");
  1843. rspamd_controller_send_error (conn_ent,
  1844. 400,
  1845. "Empty body is not permitted");
  1846. return 0;
  1847. }
  1848. parser = ucl_parser_new (0);
  1849. if (!ucl_parser_add_chunk (parser, msg->body_buf.begin, msg->body_buf.len)) {
  1850. if ((error = ucl_parser_get_error (parser)) != NULL) {
  1851. msg_err_session ("cannot parse input: %s", error);
  1852. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  1853. ucl_parser_free (parser);
  1854. return 0;
  1855. }
  1856. msg_err_session ("cannot parse input: unknown error");
  1857. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  1858. ucl_parser_free (parser);
  1859. return 0;
  1860. }
  1861. obj = ucl_parser_get_object (parser);
  1862. ucl_parser_free (parser);
  1863. if (obj->type != UCL_ARRAY || obj->len != 4) {
  1864. msg_err_session ("input is not an array of 4 elements");
  1865. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  1866. ucl_object_unref (obj);
  1867. return 0;
  1868. }
  1869. it = ucl_object_iterate_new (obj);
  1870. for (i = 0; i < 4; i++) {
  1871. cur = ucl_object_iterate_safe (it, TRUE);
  1872. switch (i) {
  1873. case 0:
  1874. act = METRIC_ACTION_REJECT;
  1875. break;
  1876. case 1:
  1877. act = METRIC_ACTION_REWRITE_SUBJECT;
  1878. break;
  1879. case 2:
  1880. act = METRIC_ACTION_ADD_HEADER;
  1881. break;
  1882. case 3:
  1883. act = METRIC_ACTION_GREYLIST;
  1884. break;
  1885. }
  1886. if (ucl_object_type (cur) == UCL_NULL) {
  1887. /* Assume NaN */
  1888. score = NAN;
  1889. }
  1890. else {
  1891. score = ucl_object_todouble (cur);
  1892. }
  1893. if ((isnan (session->cfg->actions[act].score) != isnan (score)) ||
  1894. (session->cfg->actions[act].score != score)) {
  1895. add_dynamic_action (ctx->cfg, DEFAULT_METRIC, act, score);
  1896. added ++;
  1897. }
  1898. else {
  1899. if (remove_dynamic_action (ctx->cfg, DEFAULT_METRIC, act)) {
  1900. added ++;
  1901. }
  1902. }
  1903. }
  1904. ucl_object_iterate_free (it);
  1905. if (dump_dynamic_config (ctx->cfg)) {
  1906. msg_info_session ("<%s> modified %d actions",
  1907. rspamd_inet_address_to_string (session->from_addr),
  1908. added);
  1909. rspamd_controller_send_string (conn_ent, "{\"success\":true}");
  1910. }
  1911. else {
  1912. rspamd_controller_send_error (conn_ent, 500, "Save error");
  1913. }
  1914. ucl_object_unref (obj);
  1915. return 0;
  1916. }
  1917. /*
  1918. * Save symbols command handler:
  1919. * request: /savesymbols
  1920. * headers: Password
  1921. * input: json data
  1922. * reply: json {"success":true} or {"error":"error message"}
  1923. */
  1924. static int
  1925. rspamd_controller_handle_savesymbols (
  1926. struct rspamd_http_connection_entry *conn_ent,
  1927. struct rspamd_http_message *msg)
  1928. {
  1929. struct rspamd_controller_session *session = conn_ent->ud;
  1930. struct ucl_parser *parser;
  1931. ucl_object_t *obj;
  1932. const ucl_object_t *cur, *jname, *jvalue;
  1933. ucl_object_iter_t iter = NULL;
  1934. struct rspamd_controller_worker_ctx *ctx;
  1935. const gchar *error;
  1936. gdouble val;
  1937. struct rspamd_symbol *sym;
  1938. int added = 0;
  1939. ctx = session->ctx;
  1940. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  1941. return 0;
  1942. }
  1943. if (rspamd_http_message_get_body (msg, NULL) == NULL) {
  1944. msg_err_session ("got zero length body, cannot continue");
  1945. rspamd_controller_send_error (conn_ent,
  1946. 400,
  1947. "Empty body is not permitted");
  1948. return 0;
  1949. }
  1950. parser = ucl_parser_new (0);
  1951. if (!ucl_parser_add_chunk (parser, msg->body_buf.begin, msg->body_buf.len)) {
  1952. if ((error = ucl_parser_get_error (parser)) != NULL) {
  1953. msg_err_session ("cannot parse input: %s", error);
  1954. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  1955. ucl_parser_free (parser);
  1956. return 0;
  1957. }
  1958. msg_err_session ("cannot parse input: unknown error");
  1959. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  1960. ucl_parser_free (parser);
  1961. return 0;
  1962. }
  1963. obj = ucl_parser_get_object (parser);
  1964. ucl_parser_free (parser);
  1965. if (obj->type != UCL_ARRAY) {
  1966. msg_err_session ("input is not an array");
  1967. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  1968. ucl_object_unref (obj);
  1969. return 0;
  1970. }
  1971. iter = ucl_object_iterate_new (obj);
  1972. while ((cur = ucl_object_iterate_safe (iter, true))) {
  1973. if (cur->type != UCL_OBJECT) {
  1974. msg_err_session ("json array data error");
  1975. rspamd_controller_send_error (conn_ent, 400, "Cannot parse input");
  1976. ucl_object_unref (obj);
  1977. ucl_object_iterate_free (iter);
  1978. return 0;
  1979. }
  1980. jname = ucl_object_lookup (cur, "name");
  1981. jvalue = ucl_object_lookup (cur, "value");
  1982. val = ucl_object_todouble (jvalue);
  1983. sym = g_hash_table_lookup (session->cfg->symbols, ucl_object_tostring (jname));
  1984. if (sym && fabs (*sym->weight_ptr - val) > 0.01) {
  1985. if (!add_dynamic_symbol (ctx->cfg, DEFAULT_METRIC,
  1986. ucl_object_tostring (jname), val)) {
  1987. msg_err_session ("add symbol failed for %s",
  1988. ucl_object_tostring (jname));
  1989. rspamd_controller_send_error (conn_ent, 506,
  1990. "Add symbol failed");
  1991. ucl_object_unref (obj);
  1992. ucl_object_iterate_free (iter);
  1993. return 0;
  1994. }
  1995. added ++;
  1996. }
  1997. else if (sym && ctx->cfg->dynamic_conf) {
  1998. if (remove_dynamic_symbol (ctx->cfg, DEFAULT_METRIC,
  1999. ucl_object_tostring (jname))) {
  2000. added ++;
  2001. }
  2002. }
  2003. }
  2004. ucl_object_iterate_free (iter);
  2005. if (added > 0) {
  2006. if (ctx->cfg->dynamic_conf) {
  2007. if (dump_dynamic_config (ctx->cfg)) {
  2008. msg_info_session ("<%s> modified %d symbols",
  2009. rspamd_inet_address_to_string (session->from_addr),
  2010. added);
  2011. rspamd_controller_send_string (conn_ent, "{\"success\":true}");
  2012. }
  2013. else {
  2014. rspamd_controller_send_error (conn_ent, 500, "Save error");
  2015. }
  2016. }
  2017. else {
  2018. rspamd_controller_send_string (conn_ent, "{\"success\":true}");
  2019. }
  2020. }
  2021. else {
  2022. msg_err_session ("no symbols to save");
  2023. rspamd_controller_send_error (conn_ent, 404, "No symbols to save");
  2024. }
  2025. ucl_object_unref (obj);
  2026. return 0;
  2027. }
  2028. /*
  2029. * Save map command handler:
  2030. * request: /savemap
  2031. * headers: Password, Map
  2032. * input: plaintext data
  2033. * reply: json {"success":true} or {"error":"error message"}
  2034. */
  2035. static int
  2036. rspamd_controller_handle_savemap (struct rspamd_http_connection_entry *conn_ent,
  2037. struct rspamd_http_message *msg)
  2038. {
  2039. struct rspamd_controller_session *session = conn_ent->ud;
  2040. GList *cur;
  2041. struct rspamd_map *map;
  2042. struct rspamd_map_backend *bk;
  2043. struct rspamd_controller_worker_ctx *ctx;
  2044. const rspamd_ftok_t *idstr;
  2045. gulong id, i, ntries = 0;
  2046. gboolean found = FALSE;
  2047. gint fd;
  2048. ctx = session->ctx;
  2049. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  2050. return 0;
  2051. }
  2052. if (rspamd_http_message_get_body (msg, NULL) == NULL) {
  2053. msg_err_session ("got zero length body, cannot continue");
  2054. rspamd_controller_send_error (conn_ent,
  2055. 400,
  2056. "Empty body is not permitted");
  2057. return 0;
  2058. }
  2059. idstr = rspamd_http_message_find_header (msg, "Map");
  2060. if (idstr == NULL) {
  2061. msg_info_session ("absent map id");
  2062. rspamd_controller_send_error (conn_ent, 400, "Map id not specified");
  2063. return 0;
  2064. }
  2065. if (!rspamd_strtoul (idstr->begin, idstr->len, &id)) {
  2066. msg_info_session ("invalid map id: %T", idstr);
  2067. rspamd_controller_send_error (conn_ent, 400, "Map id is invalid");
  2068. return 0;
  2069. }
  2070. /* Now let's be sure that we have map defined in configuration */
  2071. cur = ctx->cfg->maps;
  2072. while (cur && !found) {
  2073. map = cur->data;
  2074. PTR_ARRAY_FOREACH (map->backends, i, bk) {
  2075. if (bk->id == id && bk->protocol == MAP_PROTO_FILE) {
  2076. found = TRUE;
  2077. break;
  2078. }
  2079. }
  2080. cur = g_list_next (cur);
  2081. }
  2082. if (!found) {
  2083. msg_info_session ("map not found: %L", id);
  2084. rspamd_controller_send_error (conn_ent, 404, "Map id not found");
  2085. return 0;
  2086. }
  2087. while (g_atomic_int_compare_and_exchange (map->locked, 0, 1)) {
  2088. struct timespec sleep_ts = {
  2089. .tv_sec = 0,
  2090. .tv_nsec = 100000000ULL,
  2091. };
  2092. if (ntries > 5) {
  2093. msg_info_session ("map locked: %s", bk->uri);
  2094. rspamd_controller_send_error (conn_ent, 404, "Map is locked");
  2095. return 0;
  2096. }
  2097. ntries ++;
  2098. nanosleep (&sleep_ts, NULL);
  2099. }
  2100. /* Set lock */
  2101. fd = open (bk->uri, O_WRONLY | O_TRUNC | O_CREAT, 00644);
  2102. if (fd == -1) {
  2103. g_atomic_int_set (map->locked, 0);
  2104. msg_info_session ("map %s open error: %s", bk->uri, strerror (errno));
  2105. rspamd_controller_send_error (conn_ent, 404, "Cannot open map: %s",
  2106. strerror (errno));
  2107. return 0;
  2108. }
  2109. if (write (fd, msg->body_buf.begin, msg->body_buf.len) == -1) {
  2110. msg_info_session ("map %s write error: %s", bk->uri, strerror (errno));
  2111. close (fd);
  2112. g_atomic_int_set (map->locked, 0);
  2113. rspamd_controller_send_error (conn_ent, 500, "Map write error: %s",
  2114. strerror (errno));
  2115. return 0;
  2116. }
  2117. msg_info_session ("<%s>, map %s saved",
  2118. rspamd_inet_address_to_string (session->from_addr),
  2119. bk->uri);
  2120. /* Close and unlock */
  2121. close (fd);
  2122. g_atomic_int_set (map->locked, 0);
  2123. rspamd_controller_send_string (conn_ent, "{\"success\":true}");
  2124. return 0;
  2125. }
  2126. struct rspamd_stat_cbdata {
  2127. struct rspamd_http_connection_entry *conn_ent;
  2128. ucl_object_t *top;
  2129. ucl_object_t *stat;
  2130. struct rspamd_task *task;
  2131. guint64 learned;
  2132. };
  2133. static gboolean
  2134. rspamd_controller_stat_fin_task (void *ud)
  2135. {
  2136. struct rspamd_stat_cbdata *cbdata = ud;
  2137. struct rspamd_http_connection_entry *conn_ent;
  2138. ucl_object_t *top, *ar;
  2139. GList *fuzzy_elts, *cur;
  2140. struct rspamd_fuzzy_stat_entry *entry;
  2141. conn_ent = cbdata->conn_ent;
  2142. top = cbdata->top;
  2143. ucl_object_insert_key (top,
  2144. ucl_object_fromint (cbdata->learned), "total_learns", 0, false);
  2145. if (cbdata->stat) {
  2146. ucl_object_insert_key (top, cbdata->stat, "statfiles", 0, false);
  2147. }
  2148. fuzzy_elts = rspamd_mempool_get_variable (cbdata->task->task_pool, "fuzzy_stat");
  2149. if (fuzzy_elts) {
  2150. ar = ucl_object_typed_new (UCL_OBJECT);
  2151. for (cur = fuzzy_elts; cur != NULL; cur = g_list_next (cur)) {
  2152. entry = cur->data;
  2153. if (entry->name) {
  2154. ucl_object_insert_key (ar, ucl_object_fromint (entry->fuzzy_cnt),
  2155. entry->name, 0, true);
  2156. }
  2157. }
  2158. ucl_object_insert_key (top, ar, "fuzzy_hashes", 0, false);
  2159. }
  2160. rspamd_controller_send_ucl (conn_ent, top);
  2161. return TRUE;
  2162. }
  2163. static void
  2164. rspamd_controller_stat_cleanup_task (void *ud)
  2165. {
  2166. struct rspamd_stat_cbdata *cbdata = ud;
  2167. rspamd_task_free (cbdata->task);
  2168. ucl_object_unref (cbdata->top);
  2169. }
  2170. /*
  2171. * Stat command handler:
  2172. * request: /stat (/resetstat)
  2173. * headers: Password
  2174. * reply: json data
  2175. */
  2176. static int
  2177. rspamd_controller_handle_stat_common (
  2178. struct rspamd_http_connection_entry *conn_ent,
  2179. struct rspamd_http_message *msg,
  2180. gboolean do_reset)
  2181. {
  2182. struct rspamd_controller_session *session = conn_ent->ud;
  2183. ucl_object_t *top, *sub;
  2184. gint i;
  2185. guint64 spam = 0, ham = 0;
  2186. rspamd_mempool_stat_t mem_st;
  2187. struct rspamd_stat *stat, stat_copy;
  2188. struct rspamd_controller_worker_ctx *ctx;
  2189. struct rspamd_task *task;
  2190. struct rspamd_stat_cbdata *cbdata;
  2191. memset (&mem_st, 0, sizeof (mem_st));
  2192. rspamd_mempool_stat (&mem_st);
  2193. memcpy (&stat_copy, session->ctx->worker->srv->stat, sizeof (stat_copy));
  2194. stat = &stat_copy;
  2195. ctx = session->ctx;
  2196. task = rspamd_task_new (session->ctx->worker, session->cfg, session->pool,
  2197. ctx->lang_det, ctx->ev_base);
  2198. task->resolver = ctx->resolver;
  2199. cbdata = rspamd_mempool_alloc0 (session->pool, sizeof (*cbdata));
  2200. cbdata->conn_ent = conn_ent;
  2201. cbdata->task = task;
  2202. top = ucl_object_typed_new (UCL_OBJECT);
  2203. cbdata->top = top;
  2204. task->s = rspamd_session_create (session->pool,
  2205. rspamd_controller_stat_fin_task,
  2206. NULL,
  2207. rspamd_controller_stat_cleanup_task,
  2208. cbdata);
  2209. task->fin_arg = cbdata;
  2210. task->http_conn = rspamd_http_connection_ref (conn_ent->conn);;
  2211. task->sock = conn_ent->conn->fd;
  2212. ucl_object_insert_key (top, ucl_object_frombool (!session->is_enable),
  2213. "read_only", 0, false);
  2214. ucl_object_insert_key (top, ucl_object_fromint (
  2215. stat->messages_scanned), "scanned", 0, false);
  2216. ucl_object_insert_key (top, ucl_object_fromint (
  2217. stat->messages_learned), "learned", 0, false);
  2218. if (stat->messages_scanned > 0) {
  2219. sub = ucl_object_typed_new (UCL_OBJECT);
  2220. for (i = METRIC_ACTION_REJECT; i <= METRIC_ACTION_NOACTION; i++) {
  2221. ucl_object_insert_key (sub,
  2222. ucl_object_fromint (stat->actions_stat[i]),
  2223. rspamd_action_to_str (i), 0, false);
  2224. if (i < METRIC_ACTION_GREYLIST) {
  2225. spam += stat->actions_stat[i];
  2226. }
  2227. else {
  2228. ham += stat->actions_stat[i];
  2229. }
  2230. if (do_reset) {
  2231. #ifndef HAVE_ATOMIC_BUILTINS
  2232. session->ctx->worker->srv->stat->actions_stat[i] = 0;
  2233. #else
  2234. __atomic_store_n(&session->ctx->worker->srv->stat->actions_stat[i],
  2235. 0, __ATOMIC_RELEASE);
  2236. #endif
  2237. }
  2238. }
  2239. ucl_object_insert_key (top, sub, "actions", 0, false);
  2240. }
  2241. ucl_object_insert_key (top, ucl_object_fromint (
  2242. spam), "spam_count", 0, false);
  2243. ucl_object_insert_key (top, ucl_object_fromint (
  2244. ham), "ham_count", 0, false);
  2245. ucl_object_insert_key (top,
  2246. ucl_object_fromint (stat->connections_count), "connections", 0, false);
  2247. ucl_object_insert_key (top,
  2248. ucl_object_fromint (stat->control_connections_count),
  2249. "control_connections", 0, false);
  2250. ucl_object_insert_key (top,
  2251. ucl_object_fromint (mem_st.pools_allocated), "pools_allocated", 0,
  2252. false);
  2253. ucl_object_insert_key (top,
  2254. ucl_object_fromint (mem_st.pools_freed), "pools_freed", 0, false);
  2255. ucl_object_insert_key (top,
  2256. ucl_object_fromint (mem_st.bytes_allocated), "bytes_allocated", 0,
  2257. false);
  2258. ucl_object_insert_key (top,
  2259. ucl_object_fromint (
  2260. mem_st.chunks_allocated), "chunks_allocated", 0, false);
  2261. ucl_object_insert_key (top,
  2262. ucl_object_fromint (mem_st.shared_chunks_allocated),
  2263. "shared_chunks_allocated", 0, false);
  2264. ucl_object_insert_key (top,
  2265. ucl_object_fromint (mem_st.chunks_freed), "chunks_freed", 0, false);
  2266. ucl_object_insert_key (top,
  2267. ucl_object_fromint (
  2268. mem_st.oversized_chunks), "chunks_oversized", 0, false);
  2269. ucl_object_insert_key (top,
  2270. ucl_object_fromint (mem_st.fragmented_size), "fragmented", 0, false);
  2271. if (do_reset) {
  2272. session->ctx->srv->stat->messages_scanned = 0;
  2273. session->ctx->srv->stat->messages_learned = 0;
  2274. session->ctx->srv->stat->connections_count = 0;
  2275. session->ctx->srv->stat->control_connections_count = 0;
  2276. rspamd_mempool_stat_reset ();
  2277. }
  2278. fuzzy_stat_command (task);
  2279. /* Now write statistics for each statfile */
  2280. rspamd_stat_statistics (task, session->ctx->cfg, &cbdata->learned,
  2281. &cbdata->stat);
  2282. session->task = task;
  2283. rspamd_session_pending (task->s);
  2284. return 0;
  2285. }
  2286. static int
  2287. rspamd_controller_handle_stat (struct rspamd_http_connection_entry *conn_ent,
  2288. struct rspamd_http_message *msg)
  2289. {
  2290. struct rspamd_controller_session *session = conn_ent->ud;
  2291. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  2292. return 0;
  2293. }
  2294. return rspamd_controller_handle_stat_common (conn_ent, msg, FALSE);
  2295. }
  2296. static int
  2297. rspamd_controller_handle_statreset (
  2298. struct rspamd_http_connection_entry *conn_ent,
  2299. struct rspamd_http_message *msg)
  2300. {
  2301. struct rspamd_controller_session *session = conn_ent->ud;
  2302. if (!rspamd_controller_check_password (conn_ent, session, msg, TRUE)) {
  2303. return 0;
  2304. }
  2305. msg_info_session ("<%s> reset stat",
  2306. rspamd_inet_address_to_string (session->from_addr));
  2307. return rspamd_controller_handle_stat_common (conn_ent, msg, TRUE);
  2308. }
  2309. /*
  2310. * Counters command handler:
  2311. * request: /counters
  2312. * headers: Password
  2313. * reply: json array of all counters
  2314. */
  2315. static int
  2316. rspamd_controller_handle_counters (
  2317. struct rspamd_http_connection_entry *conn_ent,
  2318. struct rspamd_http_message *msg)
  2319. {
  2320. struct rspamd_controller_session *session = conn_ent->ud;
  2321. ucl_object_t *top;
  2322. struct rspamd_symcache *cache;
  2323. if (!rspamd_controller_check_password (conn_ent, session, msg, FALSE)) {
  2324. return 0;
  2325. }
  2326. cache = session->ctx->cfg->cache;
  2327. if (cache != NULL) {
  2328. top = rspamd_symcache_counters (cache);
  2329. rspamd_controller_send_ucl (conn_ent, top);
  2330. ucl_object_unref (top);
  2331. }
  2332. else {
  2333. rspamd_controller_send_error (conn_ent, 500, "Invalid cache");
  2334. }
  2335. return 0;
  2336. }
  2337. static int
  2338. rspamd_controller_handle_custom (struct rspamd_http_connection_entry *conn_ent,
  2339. struct rspamd_http_message *msg)
  2340. {
  2341. struct rspamd_controller_session *session = conn_ent->ud;
  2342. struct rspamd_custom_controller_command *cmd;
  2343. gchar *url_str;
  2344. url_str = rspamd_fstring_cstr (msg->url);
  2345. cmd = g_hash_table_lookup (session->ctx->custom_commands, url_str);
  2346. g_free (url_str);
  2347. if (cmd == NULL || cmd->handler == NULL) {
  2348. msg_err_session ("custom command %V has not been found", msg->url);
  2349. rspamd_controller_send_error (conn_ent, 404, "No command associated");
  2350. return 0;
  2351. }
  2352. if (!rspamd_controller_check_password (conn_ent, session, msg,
  2353. cmd->privilleged)) {
  2354. return 0;
  2355. }
  2356. if (cmd->require_message && (rspamd_http_message_get_body (msg, NULL) == NULL)) {
  2357. msg_err_session ("got zero length body, cannot continue");
  2358. rspamd_controller_send_error (conn_ent,
  2359. 400,
  2360. "Empty body is not permitted");
  2361. return 0;
  2362. }
  2363. return cmd->handler (conn_ent, msg, cmd->ctx);
  2364. }
  2365. static int
  2366. rspamd_controller_handle_plugins (struct rspamd_http_connection_entry *conn_ent,
  2367. struct rspamd_http_message *msg)
  2368. {
  2369. struct rspamd_controller_session *session = conn_ent->ud;
  2370. struct rspamd_controller_plugin_cbdata *cbd;
  2371. GHashTableIter it;
  2372. gpointer k, v;
  2373. ucl_object_t *plugins;
  2374. if (!rspamd_controller_check_password (conn_ent, session, msg,
  2375. FALSE)) {
  2376. return 0;
  2377. }
  2378. plugins = ucl_object_typed_new (UCL_OBJECT);
  2379. g_hash_table_iter_init (&it, session->ctx->plugins);
  2380. while (g_hash_table_iter_next (&it, &k, &v)) {
  2381. ucl_object_t *elt, *npath;
  2382. cbd = v;
  2383. elt = (ucl_object_t *)ucl_object_lookup (plugins, cbd->plugin);
  2384. if (elt == NULL) {
  2385. elt = ucl_object_typed_new (UCL_OBJECT);
  2386. ucl_object_insert_key (elt, ucl_object_fromint (cbd->version),
  2387. "version", 0, false);
  2388. npath = ucl_object_typed_new (UCL_ARRAY);
  2389. ucl_object_insert_key (elt, npath, "paths", 0, false);
  2390. ucl_object_insert_key (plugins, elt, cbd->plugin, 0, false);
  2391. }
  2392. else {
  2393. npath = (ucl_object_t *)ucl_object_lookup (elt, "paths");
  2394. }
  2395. g_assert (npath != NULL);
  2396. ucl_array_append (npath, ucl_object_fromstring (k));
  2397. }
  2398. rspamd_controller_send_ucl (conn_ent, plugins);
  2399. ucl_object_unref (plugins);
  2400. return 0;
  2401. }
  2402. static int
  2403. rspamd_controller_handle_ping (struct rspamd_http_connection_entry *conn_ent,
  2404. struct rspamd_http_message *msg)
  2405. {
  2406. struct rspamd_http_message *rep_msg;
  2407. rspamd_fstring_t *reply;
  2408. rep_msg = rspamd_http_new_message (HTTP_RESPONSE);
  2409. rep_msg->date = time (NULL);
  2410. rep_msg->code = 200;
  2411. rep_msg->status = rspamd_fstring_new_init ("OK", 2);
  2412. reply = rspamd_fstring_new_init ("pong" CRLF, strlen ("pong" CRLF));
  2413. rspamd_http_message_set_body_from_fstring_steal (rep_msg, reply);
  2414. rspamd_http_connection_reset (conn_ent->conn);
  2415. rspamd_http_router_insert_headers (conn_ent->rt, rep_msg);
  2416. rspamd_http_connection_write_message (conn_ent->conn,
  2417. rep_msg,
  2418. NULL,
  2419. "text/plain",
  2420. conn_ent,
  2421. conn_ent->conn->fd,
  2422. conn_ent->rt->ptv,
  2423. conn_ent->rt->ev_base);
  2424. conn_ent->is_reply = TRUE;
  2425. return 0;
  2426. }
  2427. /*
  2428. * Called on unknown methods and is used to deal with CORS as per
  2429. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  2430. */
  2431. static int
  2432. rspamd_controller_handle_unknown (struct rspamd_http_connection_entry *conn_ent,
  2433. struct rspamd_http_message *msg)
  2434. {
  2435. struct rspamd_http_message *rep;
  2436. if (msg->method == HTTP_OPTIONS) {
  2437. /* Assume CORS request */
  2438. rep = rspamd_http_new_message (HTTP_RESPONSE);
  2439. rep->date = time (NULL);
  2440. rep->code = 200;
  2441. rep->status = rspamd_fstring_new_init ("OK", 2);
  2442. rspamd_http_message_add_header (rep, "Access-Control-Allow-Methods",
  2443. "POST, GET, OPTIONS");
  2444. rspamd_http_message_add_header (rep, "Access-Control-Allow-Headers",
  2445. "Content-Type,Password,Map,Weight,Flag");
  2446. rspamd_http_connection_reset (conn_ent->conn);
  2447. rspamd_http_router_insert_headers (conn_ent->rt, rep);
  2448. rspamd_http_connection_write_message (conn_ent->conn,
  2449. rep,
  2450. NULL,
  2451. "text/plain",
  2452. conn_ent,
  2453. conn_ent->conn->fd,
  2454. conn_ent->rt->ptv,
  2455. conn_ent->rt->ev_base);
  2456. conn_ent->is_reply = TRUE;
  2457. }
  2458. else {
  2459. rep = rspamd_http_new_message (HTTP_RESPONSE);
  2460. rep->date = time (NULL);
  2461. rep->code = 500;
  2462. rep->status = rspamd_fstring_new_init ("Invalid method",
  2463. strlen ("Invalid method"));
  2464. rspamd_http_connection_reset (conn_ent->conn);
  2465. rspamd_http_router_insert_headers (conn_ent->rt, rep);
  2466. rspamd_http_connection_write_message (conn_ent->conn,
  2467. rep,
  2468. NULL,
  2469. "text/plain",
  2470. conn_ent,
  2471. conn_ent->conn->fd,
  2472. conn_ent->rt->ptv,
  2473. conn_ent->rt->ev_base);
  2474. conn_ent->is_reply = TRUE;
  2475. }
  2476. return 0;
  2477. }
  2478. static int
  2479. rspamd_controller_handle_lua_plugin (struct rspamd_http_connection_entry *conn_ent,
  2480. struct rspamd_http_message *msg)
  2481. {
  2482. struct rspamd_controller_session *session = conn_ent->ud;
  2483. struct rspamd_controller_plugin_cbdata *cbd;
  2484. struct rspamd_task *task, **ptask;
  2485. struct rspamd_http_connection_entry **pconn;
  2486. struct rspamd_controller_worker_ctx *ctx;
  2487. lua_State *L;
  2488. gchar *url_str;
  2489. url_str = rspamd_fstring_cstr (msg->url);
  2490. cbd = g_hash_table_lookup (session->ctx->plugins, url_str);
  2491. g_free (url_str);
  2492. if (cbd == NULL || cbd->handler == NULL) {
  2493. msg_err_session ("plugin handler %V has not been found", msg->url);
  2494. rspamd_controller_send_error (conn_ent, 404, "No command associated");
  2495. return 0;
  2496. }
  2497. L = cbd->L;
  2498. ctx = cbd->ctx;
  2499. if (!rspamd_controller_check_password (conn_ent, session, msg,
  2500. cbd->is_enable)) {
  2501. return 0;
  2502. }
  2503. if (cbd->need_task && (rspamd_http_message_get_body (msg, NULL) == NULL)) {
  2504. msg_err_session ("got zero length body, cannot continue");
  2505. rspamd_controller_send_error (conn_ent,
  2506. 400,
  2507. "Empty body is not permitted");
  2508. return 0;
  2509. }
  2510. task = rspamd_task_new (session->ctx->worker, session->cfg, session->pool,
  2511. ctx->lang_det, ctx->ev_base);
  2512. task->resolver = ctx->resolver;
  2513. task->s = rspamd_session_create (session->pool,
  2514. rspamd_controller_lua_fin_task,
  2515. NULL,
  2516. (event_finalizer_t )rspamd_task_free,
  2517. task);
  2518. task->fin_arg = conn_ent;
  2519. task->http_conn = rspamd_http_connection_ref (conn_ent->conn);;
  2520. task->sock = -1;
  2521. session->task = task;
  2522. if (msg->body_buf.len > 0) {
  2523. if (!rspamd_task_load_message (task, msg, msg->body_buf.begin, msg->body_buf.len)) {
  2524. rspamd_controller_send_error (conn_ent, task->err->code, "%s",
  2525. task->err->message);
  2526. return 0;
  2527. }
  2528. }
  2529. /* Callback */
  2530. lua_rawgeti (L, LUA_REGISTRYINDEX, cbd->handler->idx);
  2531. ptask = lua_newuserdata (L, sizeof (*ptask));
  2532. rspamd_lua_setclass (L, "rspamd{task}", -1);
  2533. *ptask = task;
  2534. pconn = lua_newuserdata (L, sizeof (*pconn));
  2535. rspamd_lua_setclass (L, "rspamd{csession}", -1);
  2536. *pconn = conn_ent;
  2537. if (lua_pcall (L, 2, 0, 0) != 0) {
  2538. rspamd_controller_send_error (conn_ent, 503, "Cannot run callback: %s",
  2539. lua_tostring (L, -1));
  2540. lua_settop (L, 0);
  2541. return 0;
  2542. }
  2543. rspamd_session_pending (task->s);
  2544. return 0;
  2545. }
  2546. static void
  2547. rspamd_controller_error_handler (struct rspamd_http_connection_entry *conn_ent,
  2548. GError *err)
  2549. {
  2550. struct rspamd_controller_session *session = conn_ent->ud;
  2551. msg_err_session ("http error occurred: %s", err->message);
  2552. }
  2553. static void
  2554. rspamd_controller_finish_handler (struct rspamd_http_connection_entry *conn_ent)
  2555. {
  2556. struct rspamd_controller_session *session = conn_ent->ud;
  2557. session->ctx->worker->srv->stat->control_connections_count++;
  2558. if (session->task != NULL) {
  2559. rspamd_session_destroy (session->task->s);
  2560. }
  2561. session->wrk->nconns --;
  2562. rspamd_inet_address_free (session->from_addr);
  2563. REF_RELEASE (session->cfg);
  2564. if (session->pool) {
  2565. msg_debug_session ("destroy session %p", session);
  2566. rspamd_mempool_delete (session->pool);
  2567. }
  2568. g_free (session);
  2569. }
  2570. static void
  2571. rspamd_controller_accept_socket (gint fd, short what, void *arg)
  2572. {
  2573. struct rspamd_worker *worker = (struct rspamd_worker *) arg;
  2574. struct rspamd_controller_worker_ctx *ctx;
  2575. struct rspamd_controller_session *session;
  2576. rspamd_inet_addr_t *addr;
  2577. gint nfd;
  2578. ctx = worker->ctx;
  2579. if ((nfd =
  2580. rspamd_accept_from_socket (fd, &addr, worker->accept_events)) == -1) {
  2581. msg_warn_ctx ("accept failed: %s", strerror (errno));
  2582. return;
  2583. }
  2584. /* Check for EAGAIN */
  2585. if (nfd == 0) {
  2586. return;
  2587. }
  2588. session = g_malloc0 (sizeof (struct rspamd_controller_session));
  2589. session->pool = rspamd_mempool_new (rspamd_mempool_suggest_size (),
  2590. "csession");
  2591. session->ctx = ctx;
  2592. session->cfg = ctx->cfg;
  2593. session->lang_det = ctx->lang_det;
  2594. REF_RETAIN (session->cfg);
  2595. session->from_addr = addr;
  2596. session->wrk = worker;
  2597. worker->nconns ++;
  2598. rspamd_http_router_handle_socket (ctx->http, nfd, session);
  2599. }
  2600. static void
  2601. rspamd_controller_rrd_update (gint fd, short what, void *arg)
  2602. {
  2603. struct rspamd_controller_worker_ctx *ctx = arg;
  2604. struct rspamd_stat *stat;
  2605. GArray ar;
  2606. gdouble points[METRIC_ACTION_MAX];
  2607. GError *err = NULL;
  2608. guint i;
  2609. g_assert (ctx->rrd != NULL);
  2610. stat = ctx->srv->stat;
  2611. for (i = METRIC_ACTION_REJECT; i < METRIC_ACTION_MAX; i ++) {
  2612. points[i] = stat->actions_stat[i];
  2613. }
  2614. ar.data = (gchar *)points;
  2615. ar.len = sizeof (points);
  2616. if (!rspamd_rrd_add_record (ctx->rrd, &ar, rspamd_get_calendar_ticks (),
  2617. &err)) {
  2618. msg_err_ctx ("cannot update rrd file: %e", err);
  2619. g_error_free (err);
  2620. }
  2621. /* Plan new event */
  2622. event_del (ctx->rrd_event);
  2623. evtimer_add (ctx->rrd_event, &rrd_update_time);
  2624. }
  2625. static void
  2626. rspamd_controller_load_saved_stats (struct rspamd_controller_worker_ctx *ctx)
  2627. {
  2628. struct ucl_parser *parser;
  2629. ucl_object_t *obj;
  2630. const ucl_object_t *elt, *subelt;
  2631. struct rspamd_stat *stat, stat_copy;
  2632. gint i;
  2633. g_assert (ctx->saved_stats_path != NULL);
  2634. if (access (ctx->saved_stats_path, R_OK) == -1) {
  2635. msg_err_ctx ("cannot load controller stats from %s: %s",
  2636. ctx->saved_stats_path, strerror (errno));
  2637. return;
  2638. }
  2639. parser = ucl_parser_new (0);
  2640. if (!ucl_parser_add_file (parser, ctx->saved_stats_path)) {
  2641. msg_err_ctx ("cannot parse controller stats from %s: %s",
  2642. ctx->saved_stats_path, ucl_parser_get_error (parser));
  2643. ucl_parser_free (parser);
  2644. return;
  2645. }
  2646. obj = ucl_parser_get_object (parser);
  2647. ucl_parser_free (parser);
  2648. stat = ctx->srv->stat;
  2649. memcpy (&stat_copy, stat, sizeof (stat_copy));
  2650. elt = ucl_object_lookup (obj, "scanned");
  2651. if (elt != NULL && ucl_object_type (elt) == UCL_INT) {
  2652. stat_copy.messages_scanned = ucl_object_toint (elt);
  2653. }
  2654. elt = ucl_object_lookup (obj, "learned");
  2655. if (elt != NULL && ucl_object_type (elt) == UCL_INT) {
  2656. stat_copy.messages_learned = ucl_object_toint (elt);
  2657. }
  2658. elt = ucl_object_lookup (obj, "actions");
  2659. if (elt != NULL) {
  2660. for (i = METRIC_ACTION_REJECT; i <= METRIC_ACTION_NOACTION; i++) {
  2661. subelt = ucl_object_lookup (elt, rspamd_action_to_str (i));
  2662. if (subelt && ucl_object_type (subelt) == UCL_INT) {
  2663. stat_copy.actions_stat[i] = ucl_object_toint (subelt);
  2664. }
  2665. }
  2666. }
  2667. elt = ucl_object_lookup (obj, "connections_count");
  2668. if (elt != NULL && ucl_object_type (elt) == UCL_INT) {
  2669. stat_copy.connections_count = ucl_object_toint (elt);
  2670. }
  2671. elt = ucl_object_lookup (obj, "control_connections_count");
  2672. if (elt != NULL && ucl_object_type (elt) == UCL_INT) {
  2673. stat_copy.control_connections_count = ucl_object_toint (elt);
  2674. }
  2675. ucl_object_unref (obj);
  2676. memcpy (stat, &stat_copy, sizeof (stat_copy));
  2677. }
  2678. static void
  2679. rspamd_controller_store_saved_stats (struct rspamd_controller_worker_ctx *ctx)
  2680. {
  2681. struct rspamd_stat *stat;
  2682. ucl_object_t *top, *sub;
  2683. struct ucl_emitter_functions *efuncs;
  2684. gint i, fd;
  2685. g_assert (ctx->saved_stats_path != NULL);
  2686. fd = open (ctx->saved_stats_path, O_WRONLY|O_CREAT|O_TRUNC, 00644);
  2687. if (fd == -1) {
  2688. msg_err_ctx ("cannot open for writing controller stats from %s: %s",
  2689. ctx->saved_stats_path, strerror (errno));
  2690. return;
  2691. }
  2692. if (rspamd_file_lock (fd, FALSE) == -1) {
  2693. msg_err_ctx ("cannot lock controller stats in %s: %s",
  2694. ctx->saved_stats_path, strerror (errno));
  2695. close (fd);
  2696. return;
  2697. }
  2698. stat = ctx->srv->stat;
  2699. top = ucl_object_typed_new (UCL_OBJECT);
  2700. ucl_object_insert_key (top, ucl_object_fromint (
  2701. stat->messages_scanned), "scanned", 0, false);
  2702. ucl_object_insert_key (top, ucl_object_fromint (
  2703. stat->messages_learned), "learned", 0, false);
  2704. if (stat->messages_scanned > 0) {
  2705. sub = ucl_object_typed_new (UCL_OBJECT);
  2706. for (i = METRIC_ACTION_REJECT; i <= METRIC_ACTION_NOACTION; i++) {
  2707. ucl_object_insert_key (sub,
  2708. ucl_object_fromint (stat->actions_stat[i]),
  2709. rspamd_action_to_str (i), 0, false);
  2710. }
  2711. ucl_object_insert_key (top, sub, "actions", 0, false);
  2712. }
  2713. ucl_object_insert_key (top,
  2714. ucl_object_fromint (stat->connections_count), "connections", 0, false);
  2715. ucl_object_insert_key (top,
  2716. ucl_object_fromint (stat->control_connections_count),
  2717. "control_connections", 0, false);
  2718. efuncs = ucl_object_emit_fd_funcs (fd);
  2719. ucl_object_emit_full (top, UCL_EMIT_JSON_COMPACT,
  2720. efuncs, NULL);
  2721. ucl_object_unref (top);
  2722. rspamd_file_unlock (fd, FALSE);
  2723. close (fd);
  2724. ucl_object_emit_funcs_free (efuncs);
  2725. }
  2726. static void
  2727. rspamd_controller_stats_save_periodic (int fd, short what, gpointer ud)
  2728. {
  2729. struct rspamd_controller_worker_ctx *ctx = ud;
  2730. rspamd_controller_store_saved_stats (ctx);
  2731. }
  2732. static void
  2733. rspamd_controller_password_sane (struct rspamd_controller_worker_ctx *ctx,
  2734. const gchar *password, const gchar *type)
  2735. {
  2736. const struct rspamd_controller_pbkdf *pbkdf = &pbkdf_list[0];
  2737. if (password == NULL) {
  2738. msg_warn_ctx ("%s is not set, so you should filter controller "
  2739. "availability "
  2740. "by using of firewall or `secure_ip` option", type);
  2741. return;
  2742. }
  2743. g_assert (pbkdf != NULL);
  2744. if (!rspamd_is_encrypted_password (password, NULL)) {
  2745. /* Suggest encryption to a user */
  2746. msg_warn_ctx ("your %s is not encrypted, we strongly "
  2747. "recommend to replace it with the encrypted one", type);
  2748. }
  2749. }
  2750. gpointer
  2751. init_controller_worker (struct rspamd_config *cfg)
  2752. {
  2753. struct rspamd_controller_worker_ctx *ctx;
  2754. GQuark type;
  2755. type = g_quark_try_string ("controller");
  2756. ctx = rspamd_mempool_alloc0 (cfg->cfg_pool,
  2757. sizeof (struct rspamd_controller_worker_ctx));
  2758. ctx->magic = rspamd_controller_ctx_magic;
  2759. ctx->timeout = DEFAULT_WORKER_IO_TIMEOUT;
  2760. rspamd_rcl_register_worker_option (cfg,
  2761. type,
  2762. "password",
  2763. rspamd_rcl_parse_struct_string,
  2764. ctx,
  2765. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, password),
  2766. 0,
  2767. "Password for read-only commands");
  2768. rspamd_rcl_register_worker_option (cfg,
  2769. type,
  2770. "enable_password",
  2771. rspamd_rcl_parse_struct_string,
  2772. ctx,
  2773. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx,
  2774. enable_password),
  2775. 0,
  2776. "Password for read and write commands");
  2777. rspamd_rcl_register_worker_option (cfg,
  2778. type,
  2779. "ssl",
  2780. rspamd_rcl_parse_struct_boolean,
  2781. ctx,
  2782. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, use_ssl),
  2783. 0,
  2784. "Unimplemented");
  2785. rspamd_rcl_register_worker_option (cfg,
  2786. type,
  2787. "ssl_cert",
  2788. rspamd_rcl_parse_struct_string,
  2789. ctx,
  2790. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, ssl_cert),
  2791. 0,
  2792. "Unimplemented");
  2793. rspamd_rcl_register_worker_option (cfg,
  2794. type,
  2795. "ssl_key",
  2796. rspamd_rcl_parse_struct_string,
  2797. ctx,
  2798. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, ssl_key),
  2799. 0,
  2800. "Unimplemented");
  2801. rspamd_rcl_register_worker_option (cfg,
  2802. type,
  2803. "timeout",
  2804. rspamd_rcl_parse_struct_time,
  2805. ctx,
  2806. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx,
  2807. timeout),
  2808. RSPAMD_CL_FLAG_TIME_INTEGER,
  2809. "Protocol timeout");
  2810. rspamd_rcl_register_worker_option (cfg,
  2811. type,
  2812. "secure_ip",
  2813. rspamd_rcl_parse_struct_ucl,
  2814. ctx,
  2815. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, secure_ip),
  2816. 0,
  2817. "List of IP addresses that are allowed for password-less access");
  2818. rspamd_rcl_register_worker_option (cfg,
  2819. type,
  2820. "trusted_ips",
  2821. rspamd_rcl_parse_struct_ucl,
  2822. ctx,
  2823. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx, secure_ip),
  2824. 0,
  2825. "List of IP addresses that are allowed for password-less access");
  2826. rspamd_rcl_register_worker_option (cfg,
  2827. type,
  2828. "static_dir",
  2829. rspamd_rcl_parse_struct_string,
  2830. ctx,
  2831. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx,
  2832. static_files_dir),
  2833. 0,
  2834. "Directory for static files served by controller's HTTP server");
  2835. rspamd_rcl_register_worker_option (cfg,
  2836. type,
  2837. "keypair",
  2838. rspamd_rcl_parse_struct_keypair,
  2839. ctx,
  2840. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx,
  2841. key),
  2842. 0,
  2843. "Encryption keypair");
  2844. rspamd_rcl_register_worker_option (cfg,
  2845. type,
  2846. "stats_path",
  2847. rspamd_rcl_parse_struct_string,
  2848. ctx,
  2849. G_STRUCT_OFFSET (struct rspamd_controller_worker_ctx,
  2850. saved_stats_path),
  2851. 0,
  2852. "Directory where controller saves server's statistics between restarts");
  2853. return ctx;
  2854. }
  2855. /* Lua bindings */
  2856. LUA_FUNCTION_DEF (csession, get_ev_base);
  2857. LUA_FUNCTION_DEF (csession, get_cfg);
  2858. LUA_FUNCTION_DEF (csession, send_ucl);
  2859. LUA_FUNCTION_DEF (csession, send_string);
  2860. LUA_FUNCTION_DEF (csession, send_error);
  2861. static const struct luaL_reg lua_csessionlib_m[] = {
  2862. LUA_INTERFACE_DEF (csession, get_ev_base),
  2863. LUA_INTERFACE_DEF (csession, get_cfg),
  2864. LUA_INTERFACE_DEF (csession, send_ucl),
  2865. LUA_INTERFACE_DEF (csession, send_string),
  2866. LUA_INTERFACE_DEF (csession, send_error),
  2867. {"__tostring", rspamd_lua_class_tostring},
  2868. {NULL, NULL}
  2869. };
  2870. /* Basic functions of LUA API for worker object */
  2871. static void
  2872. luaopen_controller (lua_State * L)
  2873. {
  2874. rspamd_lua_new_class (L, "rspamd{csession}", lua_csessionlib_m);
  2875. lua_pop (L, 1);
  2876. }
  2877. struct rspamd_http_connection_entry *
  2878. lua_check_controller_entry (lua_State * L, gint pos)
  2879. {
  2880. void *ud = luaL_checkudata (L, pos, "rspamd{csession}");
  2881. luaL_argcheck (L, ud != NULL, pos, "'csession' expected");
  2882. return ud ? *((struct rspamd_http_connection_entry **)ud) : NULL;
  2883. }
  2884. static int
  2885. lua_csession_get_ev_base (lua_State *L)
  2886. {
  2887. struct rspamd_http_connection_entry *c = lua_check_controller_entry (L, 1);
  2888. struct event_base **pbase;
  2889. struct rspamd_controller_session *s;
  2890. if (c) {
  2891. s = c->ud;
  2892. pbase = lua_newuserdata (L, sizeof (struct event_base *));
  2893. rspamd_lua_setclass (L, "rspamd{ev_base}", -1);
  2894. *pbase = s->ctx->ev_base;
  2895. }
  2896. else {
  2897. return luaL_error (L, "invalid arguments");
  2898. }
  2899. return 1;
  2900. }
  2901. static int
  2902. lua_csession_get_cfg (lua_State *L)
  2903. {
  2904. struct rspamd_http_connection_entry *c = lua_check_controller_entry (L, 1);
  2905. struct rspamd_config **pcfg;
  2906. struct rspamd_controller_session *s;
  2907. if (c) {
  2908. s = c->ud;
  2909. pcfg = lua_newuserdata (L, sizeof (gpointer));
  2910. rspamd_lua_setclass (L, "rspamd{config}", -1);
  2911. *pcfg = s->ctx->cfg;
  2912. }
  2913. else {
  2914. return luaL_error (L, "invalid arguments");
  2915. }
  2916. return 1;
  2917. }
  2918. static int
  2919. lua_csession_send_ucl (lua_State *L)
  2920. {
  2921. struct rspamd_http_connection_entry *c = lua_check_controller_entry (L, 1);
  2922. ucl_object_t *obj = ucl_object_lua_import_escape (L, 2);
  2923. if (c) {
  2924. rspamd_controller_send_ucl (c, obj);
  2925. }
  2926. else {
  2927. ucl_object_unref (obj);
  2928. return luaL_error (L, "invalid arguments");
  2929. }
  2930. ucl_object_unref (obj);
  2931. return 0;
  2932. }
  2933. static int
  2934. lua_csession_send_error (lua_State *L)
  2935. {
  2936. struct rspamd_http_connection_entry *c = lua_check_controller_entry (L, 1);
  2937. guint err_code = lua_tonumber (L, 2);
  2938. const gchar *err_str = lua_tostring (L, 3);
  2939. if (c) {
  2940. rspamd_controller_send_error (c, err_code, "%s", err_str);
  2941. }
  2942. else {
  2943. return luaL_error (L, "invalid arguments");
  2944. }
  2945. return 0;
  2946. }
  2947. static int
  2948. lua_csession_send_string (lua_State *L)
  2949. {
  2950. struct rspamd_http_connection_entry *c = lua_check_controller_entry (L, 1);
  2951. const gchar *str = lua_tostring (L, 2);
  2952. if (c) {
  2953. rspamd_controller_send_string (c, str);
  2954. }
  2955. else {
  2956. return luaL_error (L, "invalid arguments");
  2957. }
  2958. return 0;
  2959. }
  2960. static gboolean
  2961. rspamd_controller_on_terminate (struct rspamd_worker *worker)
  2962. {
  2963. struct rspamd_controller_worker_ctx *ctx = worker->ctx;
  2964. rspamd_controller_store_saved_stats (ctx);
  2965. if (ctx->rrd) {
  2966. msg_info ("closing rrd file: %s", ctx->rrd->filename);
  2967. event_del (ctx->rrd_event);
  2968. rspamd_rrd_close (ctx->rrd);
  2969. }
  2970. return FALSE;
  2971. }
  2972. static void
  2973. rspamd_plugin_cbdata_dtor (gpointer p)
  2974. {
  2975. struct rspamd_controller_plugin_cbdata *cbd = p;
  2976. g_free (cbd->plugin);
  2977. ucl_object_unref (cbd->obj); /* This also releases lua references */
  2978. g_free (cbd);
  2979. }
  2980. static void
  2981. rspamd_controller_register_plugin_path (lua_State *L,
  2982. struct rspamd_controller_worker_ctx *ctx,
  2983. const ucl_object_t *webui_data,
  2984. const ucl_object_t *handler,
  2985. const gchar *path,
  2986. const gchar *plugin_name)
  2987. {
  2988. struct rspamd_controller_plugin_cbdata *cbd;
  2989. const ucl_object_t *elt;
  2990. GString *full_path;
  2991. cbd = g_malloc0 (sizeof (*cbd));
  2992. cbd->L = L;
  2993. cbd->ctx = ctx;
  2994. cbd->handler = ucl_object_toclosure (handler);
  2995. cbd->plugin = g_strdup (plugin_name);
  2996. cbd->obj = ucl_object_ref (webui_data);
  2997. elt = ucl_object_lookup (webui_data, "version");
  2998. if (elt) {
  2999. cbd->version = ucl_object_toint (elt);
  3000. }
  3001. elt = ucl_object_lookup (webui_data, "enable");
  3002. if (elt && ucl_object_toboolean (elt)) {
  3003. cbd->is_enable = TRUE;
  3004. }
  3005. elt = ucl_object_lookup (webui_data, "need_task");
  3006. if (elt && !!ucl_object_toboolean (elt)) {
  3007. cbd->need_task = TRUE;
  3008. }
  3009. full_path = g_string_new ("/plugins/");
  3010. rspamd_printf_gstring (full_path, "%s/%s",
  3011. plugin_name, path);
  3012. rspamd_http_router_add_path (ctx->http,
  3013. full_path->str,
  3014. rspamd_controller_handle_lua_plugin);
  3015. g_hash_table_insert (ctx->plugins, full_path->str, cbd);
  3016. g_string_free (full_path, FALSE); /* Do not free data */
  3017. }
  3018. static void
  3019. rspamd_controller_register_plugins_paths (struct rspamd_controller_worker_ctx *ctx)
  3020. {
  3021. lua_State *L = ctx->cfg->lua_state;
  3022. ucl_object_t *webui_data;
  3023. const ucl_object_t *handler_obj, *cur;
  3024. ucl_object_iter_t it = NULL;
  3025. lua_getglobal (L, "rspamd_plugins");
  3026. if (lua_istable (L, -1)) {
  3027. for (lua_pushnil (L); lua_next (L, -2); lua_pop (L, 2)) {
  3028. lua_pushvalue (L, -2); /* Store key */
  3029. lua_pushstring (L, "webui");
  3030. lua_gettable (L, -3); /* value is at -3 index */
  3031. if (lua_istable (L, -1)) {
  3032. webui_data = ucl_object_lua_import_escape (L, -1);
  3033. while ((cur = ucl_object_iterate (webui_data, &it, true)) != NULL) {
  3034. handler_obj = ucl_object_lookup (cur, "handler");
  3035. if (handler_obj && ucl_object_key (cur)) {
  3036. rspamd_controller_register_plugin_path (L, ctx,
  3037. cur, handler_obj, ucl_object_key (cur),
  3038. lua_tostring (L, -2));
  3039. }
  3040. else {
  3041. msg_err_ctx ("bad webui definition for plugin: %s",
  3042. lua_tostring (L, -2));
  3043. }
  3044. }
  3045. ucl_object_unref (webui_data);
  3046. }
  3047. lua_pop (L, 1); /* remove table value */
  3048. }
  3049. }
  3050. lua_pop (L, 1); /* rspamd_plugins global */
  3051. }
  3052. /*
  3053. * Start worker process
  3054. */
  3055. void
  3056. start_controller_worker (struct rspamd_worker *worker)
  3057. {
  3058. struct rspamd_controller_worker_ctx *ctx = worker->ctx;
  3059. struct module_ctx *mctx;
  3060. GHashTableIter iter;
  3061. gpointer key, value;
  3062. guint i;
  3063. struct rspamd_keypair_cache *cache;
  3064. struct timeval stv;
  3065. const guint save_stats_interval = 60 * 1000; /* 1 minute */
  3066. gpointer m;
  3067. ctx->ev_base = rspamd_prepare_worker (worker,
  3068. "controller",
  3069. rspamd_controller_accept_socket);
  3070. msec_to_tv (ctx->timeout, &ctx->io_tv);
  3071. ctx->start_time = time (NULL);
  3072. ctx->worker = worker;
  3073. ctx->cfg = worker->srv->cfg;
  3074. ctx->srv = worker->srv;
  3075. ctx->custom_commands = g_hash_table_new (rspamd_strcase_hash,
  3076. rspamd_strcase_equal);
  3077. ctx->plugins = g_hash_table_new_full (rspamd_strcase_hash,
  3078. rspamd_strcase_equal, g_free,
  3079. rspamd_plugin_cbdata_dtor);
  3080. if (ctx->secure_ip != NULL) {
  3081. rspamd_config_radix_from_ucl (ctx->cfg, ctx->secure_ip,
  3082. "Allow unauthenticated requests from these addresses",
  3083. &ctx->secure_map, NULL);
  3084. }
  3085. if (ctx->saved_stats_path == NULL) {
  3086. /* Assume default path */
  3087. ctx->saved_stats_path = rspamd_mempool_strdup (worker->srv->cfg->cfg_pool,
  3088. DEFAULT_STATS_PATH);
  3089. }
  3090. g_ptr_array_add (worker->finish_actions,
  3091. (gpointer)rspamd_controller_on_terminate);
  3092. rspamd_controller_load_saved_stats (ctx);
  3093. ctx->lang_det = ctx->cfg->lang_det;
  3094. /* RRD collector */
  3095. if (ctx->cfg->rrd_file && worker->index == 0) {
  3096. GError *rrd_err = NULL;
  3097. ctx->rrd = rspamd_rrd_file_default (ctx->cfg->rrd_file, &rrd_err);
  3098. if (ctx->rrd) {
  3099. ctx->rrd_event = g_malloc0 (sizeof (*ctx->rrd_event));
  3100. evtimer_set (ctx->rrd_event, rspamd_controller_rrd_update, ctx);
  3101. event_base_set (ctx->ev_base, ctx->rrd_event);
  3102. event_add (ctx->rrd_event, &rrd_update_time);
  3103. }
  3104. else if (rrd_err) {
  3105. msg_err ("cannot load rrd from %s: %e", ctx->cfg->rrd_file,
  3106. rrd_err);
  3107. g_error_free (rrd_err);
  3108. }
  3109. else {
  3110. msg_err ("cannot load rrd from %s: unknown error", ctx->cfg->rrd_file);
  3111. }
  3112. }
  3113. else {
  3114. ctx->rrd = NULL;
  3115. }
  3116. rspamd_controller_password_sane (ctx, ctx->password, "normal password");
  3117. rspamd_controller_password_sane (ctx, ctx->enable_password, "enable "
  3118. "password");
  3119. /* Accept event */
  3120. cache = rspamd_keypair_cache_new (256);
  3121. ctx->http = rspamd_http_router_new (rspamd_controller_error_handler,
  3122. rspamd_controller_finish_handler, &ctx->io_tv, ctx->ev_base,
  3123. ctx->static_files_dir, cache);
  3124. /* Add callbacks for different methods */
  3125. rspamd_http_router_add_path (ctx->http,
  3126. PATH_AUTH,
  3127. rspamd_controller_handle_auth);
  3128. rspamd_http_router_add_path (ctx->http,
  3129. PATH_SYMBOLS,
  3130. rspamd_controller_handle_symbols);
  3131. rspamd_http_router_add_path (ctx->http,
  3132. PATH_ACTIONS,
  3133. rspamd_controller_handle_actions);
  3134. rspamd_http_router_add_path (ctx->http,
  3135. PATH_MAPS,
  3136. rspamd_controller_handle_maps);
  3137. rspamd_http_router_add_path (ctx->http,
  3138. PATH_GET_MAP,
  3139. rspamd_controller_handle_get_map);
  3140. rspamd_http_router_add_path (ctx->http,
  3141. PATH_PIE_CHART,
  3142. rspamd_controller_handle_pie_chart);
  3143. rspamd_http_router_add_path (ctx->http,
  3144. PATH_GRAPH,
  3145. rspamd_controller_handle_graph);
  3146. rspamd_http_router_add_path (ctx->http,
  3147. PATH_HISTORY,
  3148. rspamd_controller_handle_history);
  3149. rspamd_http_router_add_path (ctx->http,
  3150. PATH_HISTORY_RESET,
  3151. rspamd_controller_handle_history_reset);
  3152. rspamd_http_router_add_path (ctx->http,
  3153. PATH_LEARN_SPAM,
  3154. rspamd_controller_handle_learnspam);
  3155. rspamd_http_router_add_path (ctx->http,
  3156. PATH_LEARN_HAM,
  3157. rspamd_controller_handle_learnham);
  3158. rspamd_http_router_add_path (ctx->http,
  3159. PATH_SAVE_ACTIONS,
  3160. rspamd_controller_handle_saveactions);
  3161. rspamd_http_router_add_path (ctx->http,
  3162. PATH_SAVE_SYMBOLS,
  3163. rspamd_controller_handle_savesymbols);
  3164. rspamd_http_router_add_path (ctx->http,
  3165. PATH_SAVE_MAP,
  3166. rspamd_controller_handle_savemap);
  3167. rspamd_http_router_add_path (ctx->http,
  3168. PATH_SCAN,
  3169. rspamd_controller_handle_scan);
  3170. rspamd_http_router_add_path (ctx->http,
  3171. PATH_CHECK,
  3172. rspamd_controller_handle_scan);
  3173. rspamd_http_router_add_path (ctx->http,
  3174. PATH_CHECKV2,
  3175. rspamd_controller_handle_scan);
  3176. rspamd_http_router_add_path (ctx->http,
  3177. PATH_STAT,
  3178. rspamd_controller_handle_stat);
  3179. rspamd_http_router_add_path (ctx->http,
  3180. PATH_STAT_RESET,
  3181. rspamd_controller_handle_statreset);
  3182. rspamd_http_router_add_path (ctx->http,
  3183. PATH_COUNTERS,
  3184. rspamd_controller_handle_counters);
  3185. rspamd_http_router_add_path (ctx->http,
  3186. PATH_ERRORS,
  3187. rspamd_controller_handle_errors);
  3188. rspamd_http_router_add_path (ctx->http,
  3189. PATH_NEIGHBOURS,
  3190. rspamd_controller_handle_neighbours);
  3191. rspamd_http_router_add_path (ctx->http,
  3192. PATH_PLUGINS,
  3193. rspamd_controller_handle_plugins);
  3194. rspamd_http_router_add_path (ctx->http,
  3195. PATH_PING,
  3196. rspamd_controller_handle_ping);
  3197. rspamd_controller_register_plugins_paths (ctx);
  3198. #if 0
  3199. rspamd_regexp_t *lua_re = rspamd_regexp_new ("^/.*/.*\\.lua$", NULL, NULL);
  3200. rspamd_http_router_add_regexp (ctx->http, lua_re,
  3201. rspamd_controller_handle_lua);
  3202. rspamd_regexp_unref (lua_re);
  3203. #endif
  3204. luaopen_controller (ctx->cfg->lua_state);
  3205. if (ctx->key) {
  3206. rspamd_http_router_set_key (ctx->http, ctx->key);
  3207. }
  3208. PTR_ARRAY_FOREACH (ctx->cfg->c_modules, i, mctx) {
  3209. if (mctx->mod->module_attach_controller_func != NULL) {
  3210. mctx->mod->module_attach_controller_func (mctx,
  3211. ctx->custom_commands);
  3212. }
  3213. }
  3214. g_hash_table_iter_init (&iter, ctx->custom_commands);
  3215. while (g_hash_table_iter_next (&iter, &key, &value)) {
  3216. rspamd_http_router_add_path (ctx->http,
  3217. key,
  3218. rspamd_controller_handle_custom);
  3219. }
  3220. if (worker->srv->cfg->neighbours && worker->srv->cfg->neighbours->len > 0) {
  3221. rspamd_http_router_add_header (ctx->http,
  3222. "Access-Control-Allow-Origin", "*");
  3223. }
  3224. rspamd_http_router_set_unknown_handler (ctx->http,
  3225. rspamd_controller_handle_unknown);
  3226. ctx->resolver = dns_resolver_init (worker->srv->logger,
  3227. ctx->ev_base,
  3228. worker->srv->cfg);
  3229. rspamd_upstreams_library_config (worker->srv->cfg, worker->srv->cfg->ups_ctx,
  3230. ctx->ev_base, ctx->resolver->r);
  3231. rspamd_symcache_start_refresh (worker->srv->cfg->cache, ctx->ev_base,
  3232. worker);
  3233. rspamd_stat_init (worker->srv->cfg, ctx->ev_base);
  3234. if (worker->index == 0) {
  3235. if (!ctx->cfg->disable_monitored) {
  3236. rspamd_worker_init_monitored (worker, ctx->ev_base, ctx->resolver);
  3237. }
  3238. rspamd_map_watch (worker->srv->cfg, ctx->ev_base,
  3239. ctx->resolver, worker, TRUE);
  3240. }
  3241. else {
  3242. rspamd_map_watch (worker->srv->cfg, ctx->ev_base,
  3243. ctx->resolver, worker, FALSE);
  3244. }
  3245. rspamd_lua_run_postloads (ctx->cfg->lua_state, ctx->cfg, ctx->ev_base, worker);
  3246. /* Schedule periodic stats saving, see #1823 */
  3247. evtimer_set (&ctx->save_stats_event, rspamd_controller_stats_save_periodic,
  3248. ctx);
  3249. event_base_set (ctx->ev_base, &ctx->save_stats_event);
  3250. msec_to_tv (save_stats_interval, &stv);
  3251. evtimer_add (&ctx->save_stats_event, &stv);
  3252. /* Start event loop */
  3253. event_base_loop (ctx->ev_base, 0);
  3254. rspamd_worker_block_signals ();
  3255. rspamd_stat_close ();
  3256. rspamd_http_router_free (ctx->http);
  3257. if (ctx->cached_password.len > 0) {
  3258. m = (gpointer)ctx->cached_password.begin;
  3259. munmap (m, ctx->cached_password.len);
  3260. }
  3261. if (ctx->cached_enable_password.len > 0) {
  3262. m = (gpointer) ctx->cached_enable_password.begin;
  3263. munmap (m, ctx->cached_enable_password.len);
  3264. }
  3265. g_hash_table_unref (ctx->plugins);
  3266. g_hash_table_unref (ctx->custom_commands);
  3267. REF_RELEASE (ctx->cfg);
  3268. rspamd_log_close (worker->srv->logger, TRUE);
  3269. exit (EXIT_SUCCESS);
  3270. }