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

controller.c 101KB

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