Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

controller.c 100KB

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