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 83KB

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