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

controller.c 101KB

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