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

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