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

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