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

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