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

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