Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

controller.c 101KB

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