You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

controller.c 115KB

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