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.

lua_http.c 28KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  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 "lua_common.h"
  17. #include "lua_thread_pool.h"
  18. #include "libserver/http/http_private.h"
  19. #include "ref.h"
  20. #include "unix-std.h"
  21. #include "zlib.h"
  22. /***
  23. * @module rspamd_http
  24. * Rspamd HTTP module represents HTTP asynchronous client available from LUA code.
  25. * This module hides all complexity: DNS resolving, sessions management, zero-copy
  26. * text transfers and so on under the hood.
  27. * @example
  28. local rspamd_http = require "rspamd_http"
  29. local function symbol_callback(task)
  30. local function http_callback(err_message, code, body, headers)
  31. task:insert_result('SYMBOL', 1) -- task is available via closure
  32. end
  33. rspamd_http.request({
  34. task=task,
  35. url='http://example.com/data',
  36. body=task:get_content(),
  37. callback=http_callback,
  38. headers={Header='Value', OtherHeader='Value'},
  39. mime_type='text/plain',
  40. })
  41. end
  42. */
  43. #define MAX_HEADERS_SIZE 8192
  44. static const gchar *M = "rspamd lua http";
  45. LUA_FUNCTION_DEF (http, request);
  46. static const struct luaL_reg httplib_m[] = {
  47. LUA_INTERFACE_DEF (http, request),
  48. {"__tostring", rspamd_lua_class_tostring},
  49. {NULL, NULL}
  50. };
  51. #define RSPAMD_LUA_HTTP_FLAG_TEXT (1 << 0)
  52. #define RSPAMD_LUA_HTTP_FLAG_NOVERIFY (1 << 1)
  53. #define RSPAMD_LUA_HTTP_FLAG_RESOLVED (1 << 2)
  54. #define RSPAMD_LUA_HTTP_FLAG_KEEP_ALIVE (1 << 3)
  55. #define RSPAMD_LUA_HTTP_FLAG_YIELDED (1 << 4)
  56. struct lua_http_cbdata {
  57. struct rspamd_http_connection *conn;
  58. struct rspamd_async_session *session;
  59. struct rspamd_symcache_dynamic_item *item;
  60. struct rspamd_http_message *msg;
  61. struct ev_loop *event_loop;
  62. struct rspamd_config *cfg;
  63. struct rspamd_task *task;
  64. ev_tstamp timeout;
  65. struct rspamd_cryptobox_keypair *local_kp;
  66. struct rspamd_cryptobox_pubkey *peer_pk;
  67. rspamd_inet_addr_t *addr;
  68. gchar *mime_type;
  69. gchar *host;
  70. gchar *auth;
  71. const gchar *url;
  72. gsize max_size;
  73. gint flags;
  74. gint fd;
  75. gint cbref;
  76. struct thread_entry *thread;
  77. ref_entry_t ref;
  78. };
  79. static const gdouble default_http_timeout = 5.0;
  80. static struct rspamd_dns_resolver *
  81. lua_http_global_resolver (struct ev_loop *ev_base)
  82. {
  83. static struct rspamd_dns_resolver *global_resolver;
  84. if (global_resolver == NULL) {
  85. global_resolver = rspamd_dns_resolver_init (NULL, ev_base, NULL);
  86. }
  87. return global_resolver;
  88. }
  89. static void
  90. lua_http_fin (gpointer arg)
  91. {
  92. struct lua_http_cbdata *cbd = (struct lua_http_cbdata *)arg;
  93. if (cbd->cbref != -1) {
  94. luaL_unref (cbd->cfg->lua_state, LUA_REGISTRYINDEX, cbd->cbref);
  95. }
  96. if (cbd->conn) {
  97. /* Here we already have a connection, so we need to unref it */
  98. rspamd_http_connection_unref (cbd->conn);
  99. }
  100. else if (cbd->msg != NULL) {
  101. /* We need to free message */
  102. rspamd_http_message_unref (cbd->msg);
  103. }
  104. if (cbd->fd != -1) {
  105. close (cbd->fd);
  106. }
  107. if (cbd->addr) {
  108. rspamd_inet_address_free (cbd->addr);
  109. }
  110. if (cbd->mime_type) {
  111. g_free (cbd->mime_type);
  112. }
  113. if (cbd->auth) {
  114. g_free (cbd->auth);
  115. }
  116. if (cbd->host) {
  117. g_free (cbd->host);
  118. }
  119. if (cbd->local_kp) {
  120. rspamd_keypair_unref (cbd->local_kp);
  121. }
  122. if (cbd->peer_pk) {
  123. rspamd_pubkey_unref (cbd->peer_pk);
  124. }
  125. g_free (cbd);
  126. }
  127. static void
  128. lua_http_cbd_dtor (struct lua_http_cbdata *cbd)
  129. {
  130. if (cbd->session) {
  131. if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_RESOLVED) {
  132. /* Event is added merely for resolved events */
  133. if (cbd->item) {
  134. rspamd_symcache_item_async_dec_check (cbd->task, cbd->item, M);
  135. }
  136. rspamd_session_remove_event (cbd->session, lua_http_fin, cbd);
  137. }
  138. }
  139. else {
  140. lua_http_fin (cbd);
  141. }
  142. }
  143. static void
  144. lua_http_push_error (struct lua_http_cbdata *cbd, const char *err)
  145. {
  146. struct lua_callback_state lcbd;
  147. lua_State *L;
  148. lua_thread_pool_prepare_callback (cbd->cfg->lua_thread_pool, &lcbd);
  149. L = lcbd.L;
  150. lua_rawgeti (L, LUA_REGISTRYINDEX, cbd->cbref);
  151. lua_pushstring (L, err);
  152. if (cbd->item) {
  153. rspamd_symcache_set_cur_item (cbd->task, cbd->item);
  154. }
  155. if (lua_pcall (L, 1, 0, 0) != 0) {
  156. msg_info ("callback call failed: %s", lua_tostring (L, -1));
  157. lua_pop (L, 1);
  158. }
  159. lua_thread_pool_restore_callback (&lcbd);
  160. }
  161. static void lua_http_resume_handler (struct rspamd_http_connection *conn,
  162. struct rspamd_http_message *msg, const char *err);
  163. static void
  164. lua_http_error_handler (struct rspamd_http_connection *conn, GError *err)
  165. {
  166. struct lua_http_cbdata *cbd = (struct lua_http_cbdata *)conn->ud;
  167. if (cbd->cbref == -1) {
  168. if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_YIELDED) {
  169. cbd->flags &= ~RSPAMD_LUA_HTTP_FLAG_YIELDED;
  170. lua_http_resume_handler (conn, NULL, err->message);
  171. }
  172. else {
  173. /* TODO: kill me please */
  174. msg_info ("lost HTTP error from %s in coroutines mess: %s",
  175. rspamd_inet_address_to_string_pretty (cbd->addr),
  176. err->message);
  177. }
  178. }
  179. else {
  180. lua_http_push_error (cbd, err->message);
  181. }
  182. REF_RELEASE (cbd);
  183. }
  184. static int
  185. lua_http_finish_handler (struct rspamd_http_connection *conn,
  186. struct rspamd_http_message *msg)
  187. {
  188. struct lua_http_cbdata *cbd = (struct lua_http_cbdata *)conn->ud;
  189. struct rspamd_http_header *h;
  190. const gchar *body;
  191. gsize body_len;
  192. struct lua_callback_state lcbd;
  193. lua_State *L;
  194. if (cbd->cbref == -1) {
  195. if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_YIELDED) {
  196. cbd->flags &= ~RSPAMD_LUA_HTTP_FLAG_YIELDED;
  197. lua_http_resume_handler (conn, msg, NULL);
  198. }
  199. else {
  200. /* TODO: kill me please */
  201. msg_err ("lost HTTP data from %s in coroutines mess",
  202. rspamd_inet_address_to_string_pretty (cbd->addr));
  203. }
  204. REF_RELEASE (cbd);
  205. return 0;
  206. }
  207. lua_thread_pool_prepare_callback (cbd->cfg->lua_thread_pool, &lcbd);
  208. L = lcbd.L;
  209. lua_rawgeti (L, LUA_REGISTRYINDEX, cbd->cbref);
  210. /* Error */
  211. lua_pushnil (L);
  212. /* Reply code */
  213. lua_pushinteger (L, msg->code);
  214. /* Body */
  215. body = rspamd_http_message_get_body (msg, &body_len);
  216. if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_TEXT) {
  217. struct rspamd_lua_text *t;
  218. t = lua_newuserdata (L, sizeof (*t));
  219. rspamd_lua_setclass (L, "rspamd{text}", -1);
  220. t->start = body;
  221. t->len = body_len;
  222. t->flags = 0;
  223. }
  224. else {
  225. if (body_len > 0) {
  226. lua_pushlstring (L, body, body_len);
  227. }
  228. else {
  229. lua_pushnil (L);
  230. }
  231. }
  232. /* Headers */
  233. lua_newtable (L);
  234. kh_foreach_value (msg->headers, h, {
  235. /*
  236. * Lowercase header name, as Lua cannot search in caseless matter
  237. */
  238. rspamd_str_lc (h->combined->str, h->name.len);
  239. lua_pushlstring (L, h->name.begin, h->name.len);
  240. lua_pushlstring (L, h->value.begin, h->value.len);
  241. lua_settable (L, -3);
  242. });
  243. if (cbd->item) {
  244. /* Replace watcher to deal with nested calls */
  245. rspamd_symcache_set_cur_item (cbd->task, cbd->item);
  246. }
  247. if (lua_pcall (L, 4, 0, 0) != 0) {
  248. msg_info ("callback call failed: %s", lua_tostring (L, -1));
  249. lua_pop (L, 1);
  250. }
  251. REF_RELEASE (cbd);
  252. lua_thread_pool_restore_callback (&lcbd);
  253. return 0;
  254. }
  255. /*
  256. * resumes yielded thread
  257. */
  258. static void
  259. lua_http_resume_handler (struct rspamd_http_connection *conn,
  260. struct rspamd_http_message *msg, const char *err)
  261. {
  262. struct lua_http_cbdata *cbd = (struct lua_http_cbdata *)conn->ud;
  263. lua_State *L = cbd->thread->lua_state;
  264. const gchar *body;
  265. gsize body_len;
  266. struct rspamd_http_header *h;
  267. if (err) {
  268. lua_pushstring (L, err);
  269. lua_pushnil (L);
  270. }
  271. else {
  272. /*
  273. * 1 - nil (error)
  274. * 2 - table:
  275. * code (int)
  276. * content (string)
  277. * headers (table: header -> value)
  278. */
  279. lua_pushnil (L); // error code
  280. lua_createtable (L, 0, 3);
  281. /* code */
  282. lua_pushliteral (L, "code");
  283. lua_pushinteger (L, msg->code);
  284. lua_settable (L, -3);
  285. /* content */
  286. lua_pushliteral (L, "content");
  287. body = rspamd_http_message_get_body (msg, &body_len);
  288. if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_TEXT) {
  289. struct rspamd_lua_text *t;
  290. t = lua_newuserdata (L, sizeof (*t));
  291. rspamd_lua_setclass (L, "rspamd{text}", -1);
  292. t->start = body;
  293. t->len = body_len;
  294. t->flags = 0;
  295. }
  296. else {
  297. if (body_len > 0) {
  298. lua_pushlstring (L, body, body_len);
  299. }
  300. else {
  301. lua_pushnil (L);
  302. }
  303. }
  304. lua_settable (L, -3);
  305. /* headers */
  306. lua_pushliteral (L, "headers");
  307. lua_newtable (L);
  308. kh_foreach_value (msg->headers, h, {
  309. /*
  310. * Lowercase header name, as Lua cannot search in caseless matter
  311. */
  312. rspamd_str_lc (h->combined->str, h->name.len);
  313. lua_pushlstring (L, h->name.begin, h->name.len);
  314. lua_pushlstring (L, h->value.begin, h->value.len);
  315. lua_settable (L, -3);
  316. });
  317. lua_settable (L, -3);
  318. }
  319. if (cbd->item) {
  320. /* Replace watcher to deal with nested calls */
  321. rspamd_symcache_set_cur_item (cbd->task, cbd->item);
  322. }
  323. lua_thread_resume (cbd->thread, 2);
  324. }
  325. static gboolean
  326. lua_http_make_connection (struct lua_http_cbdata *cbd)
  327. {
  328. rspamd_inet_address_set_port (cbd->addr, cbd->msg->port);
  329. unsigned http_opts = RSPAMD_HTTP_CLIENT_SIMPLE;
  330. if (cbd->msg->flags & RSPAMD_HTTP_FLAG_WANT_SSL) {
  331. http_opts |= RSPAMD_HTTP_CLIENT_SSL;
  332. }
  333. if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_KEEP_ALIVE) {
  334. cbd->fd = -1; /* FD is owned by keepalive connection */
  335. cbd->conn = rspamd_http_connection_new_client_keepalive(
  336. NULL, /* Default context */
  337. NULL,
  338. lua_http_error_handler,
  339. lua_http_finish_handler,
  340. http_opts,
  341. cbd->addr,
  342. cbd->host);
  343. }
  344. else {
  345. cbd->fd = -1;
  346. cbd->conn = rspamd_http_connection_new_client (
  347. NULL, /* Default context */
  348. NULL,
  349. lua_http_error_handler,
  350. lua_http_finish_handler,
  351. http_opts,
  352. cbd->addr);
  353. }
  354. if (cbd->conn) {
  355. if (cbd->local_kp) {
  356. rspamd_http_connection_set_key (cbd->conn, cbd->local_kp);
  357. }
  358. if (cbd->peer_pk) {
  359. rspamd_http_message_set_peer_key (cbd->msg, cbd->peer_pk);
  360. }
  361. if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_NOVERIFY) {
  362. cbd->msg->flags |= RSPAMD_HTTP_FLAG_SSL_NOVERIFY;
  363. }
  364. if (cbd->max_size) {
  365. rspamd_http_connection_set_max_size (cbd->conn, cbd->max_size);
  366. }
  367. if (cbd->auth) {
  368. rspamd_http_message_add_header (cbd->msg, "Authorization",
  369. cbd->auth);
  370. }
  371. if (cbd->session) {
  372. if (cbd->item) {
  373. rspamd_session_add_event_full (cbd->session,
  374. (event_finalizer_t) lua_http_fin, cbd,
  375. M,
  376. rspamd_symcache_dyn_item_name (cbd->task, cbd->item));
  377. }
  378. else {
  379. rspamd_session_add_event (cbd->session,
  380. (event_finalizer_t) lua_http_fin, cbd,
  381. M);
  382. }
  383. cbd->flags |= RSPAMD_LUA_HTTP_FLAG_RESOLVED;
  384. }
  385. if (cbd->task) {
  386. cbd->conn->log_tag = cbd->task->task_pool->tag.uid;
  387. if (cbd->item) {
  388. rspamd_symcache_item_async_inc (cbd->task, cbd->item, M);
  389. }
  390. }
  391. else if (cbd->cfg) {
  392. cbd->conn->log_tag = cbd->cfg->cfg_pool->tag.uid;
  393. }
  394. struct rspamd_http_message *msg = cbd->msg;
  395. /* Message is now owned by a connection object */
  396. cbd->msg = NULL;
  397. return rspamd_http_connection_write_message (cbd->conn, msg,
  398. cbd->host, cbd->mime_type, cbd,
  399. cbd->timeout);
  400. }
  401. return FALSE;
  402. }
  403. static void
  404. lua_http_dns_handler (struct rdns_reply *reply, gpointer ud)
  405. {
  406. struct lua_http_cbdata *cbd = (struct lua_http_cbdata *)ud;
  407. struct rspamd_symcache_dynamic_item *item;
  408. struct rspamd_task *task;
  409. task = cbd->task;
  410. item = cbd->item;
  411. if (reply->code != RDNS_RC_NOERROR) {
  412. lua_http_push_error (cbd, "unable to resolve host");
  413. REF_RELEASE (cbd);
  414. }
  415. else {
  416. if (reply->entries->type == RDNS_REQUEST_A) {
  417. cbd->addr = rspamd_inet_address_new (AF_INET,
  418. &reply->entries->content.a.addr);
  419. }
  420. else if (reply->entries->type == RDNS_REQUEST_AAAA) {
  421. cbd->addr = rspamd_inet_address_new (AF_INET6,
  422. &reply->entries->content.aaa.addr);
  423. }
  424. REF_RETAIN (cbd);
  425. if (!lua_http_make_connection (cbd)) {
  426. lua_http_push_error (cbd, "unable to make connection to the host");
  427. if (cbd->ref.refcount > 1) {
  428. REF_RELEASE (cbd);
  429. }
  430. REF_RELEASE (cbd);
  431. return;
  432. }
  433. REF_RELEASE (cbd);
  434. }
  435. if (item) {
  436. rspamd_symcache_item_async_dec_check (task, item, M);
  437. }
  438. }
  439. static void
  440. lua_http_push_headers (lua_State *L, struct rspamd_http_message *msg)
  441. {
  442. const char *name, *value;
  443. gint i, sz;
  444. lua_pushnil (L);
  445. while (lua_next (L, -2) != 0) {
  446. lua_pushvalue (L, -2);
  447. name = lua_tostring (L, -1);
  448. sz = rspamd_lua_table_size (L, -2);
  449. if (sz != 0 && name != NULL) {
  450. for (i = 1; i <= sz ; i++) {
  451. lua_rawgeti (L, -2, i);
  452. value = lua_tostring (L, -1);
  453. if (value != NULL) {
  454. rspamd_http_message_add_header (msg, name, value);
  455. }
  456. lua_pop (L, 1);
  457. }
  458. } else {
  459. value = lua_tostring (L, -2);
  460. if (name != NULL && value != NULL) {
  461. rspamd_http_message_add_header (msg, name, value);
  462. }
  463. }
  464. lua_pop (L, 2);
  465. }
  466. }
  467. /***
  468. * @function rspamd_http.request({params...})
  469. * This function creates HTTP request and accepts several parameters as a table using key=value syntax.
  470. * Required params are:
  471. *
  472. * - `url`
  473. * - `task`
  474. *
  475. * In taskless mode, instead of `task` required are:
  476. *
  477. * - `ev_base`
  478. * - `config`
  479. *
  480. * @param {string} url specifies URL for a request in the standard URI form (e.g. 'http://example.com/path')
  481. * @param {function} callback specifies callback function in format `function (err_message, code, body, headers)` that is called on HTTP request completion. if this parameter is missing, the function performs "pseudo-synchronous" call (see [Synchronous and Asynchronous API overview](/doc/lua/sync_async.html#API-example-http-module)
  482. * @param {task} task if called from symbol handler it is generally a good idea to use the common task objects: event base, DNS resolver and events session
  483. * @param {table} headers optional headers in form `[name='value', name='value']`
  484. * @param {string} mime_type MIME type of the HTTP content (for example, `text/html`)
  485. * @param {string/text} body full body content, can be opaque `rspamd{text}` to avoid data copying
  486. * @param {number} timeout floating point request timeout value in seconds (default is 5.0 seconds)
  487. * @param {resolver} resolver to perform DNS-requests. Usually got from either `task` or `config`
  488. * @param {boolean} gzip if true, body of the requests will be compressed
  489. * @param {boolean} no_ssl_verify disable SSL peer checks
  490. * @param {boolean} keepalive enable keep-alive pool
  491. * @param {string} user for HTTP authentication
  492. * @param {string} password for HTTP authentication, only if "user" present
  493. * @return {boolean} `true`, in **async** mode, if a request has been successfully scheduled. If this value is `false` then some error occurred, the callback thus will not be called.
  494. * @return In **sync** mode `string|nil, nil|table` In sync mode error message if any and response as table: `int` _code_, `string` _content_ and `table` _headers_ (header -> value)
  495. */
  496. static gint
  497. lua_http_request (lua_State *L)
  498. {
  499. LUA_TRACE_POINT;
  500. struct ev_loop *ev_base;
  501. struct rspamd_http_message *msg;
  502. struct lua_http_cbdata *cbd;
  503. struct rspamd_dns_resolver *resolver;
  504. struct rspamd_async_session *session = NULL;
  505. struct rspamd_lua_text *t;
  506. struct rspamd_task *task = NULL;
  507. struct rspamd_config *cfg = NULL;
  508. struct rspamd_cryptobox_pubkey *peer_key = NULL;
  509. struct rspamd_cryptobox_keypair *local_kp = NULL;
  510. const gchar *url, *lua_body;
  511. rspamd_fstring_t *body = NULL;
  512. gint cbref = -1;
  513. gsize bodylen;
  514. gdouble timeout = default_http_timeout;
  515. gint flags = 0;
  516. gchar *mime_type = NULL;
  517. gchar *auth = NULL;
  518. gsize max_size = 0;
  519. gboolean gzip = FALSE;
  520. if (lua_gettop (L) >= 2) {
  521. /* url, callback and event_base format */
  522. url = luaL_checkstring (L, 1);
  523. if (url == NULL || lua_type (L, 2) != LUA_TFUNCTION) {
  524. msg_err ("http request has bad params");
  525. lua_pushboolean (L, FALSE);
  526. return 1;
  527. }
  528. lua_pushvalue (L, 2);
  529. cbref = luaL_ref (L, LUA_REGISTRYINDEX);
  530. if (lua_gettop (L) >= 3 && rspamd_lua_check_udata_maybe (L, 3, "rspamd{ev_base}")) {
  531. ev_base = *(struct ev_loop **)lua_touserdata (L, 3);
  532. }
  533. else {
  534. ev_base = NULL;
  535. }
  536. if (lua_gettop (L) >= 4 && rspamd_lua_check_udata_maybe (L, 4, "rspamd{resolver}")) {
  537. resolver = *(struct rspamd_dns_resolver **)lua_touserdata (L, 4);
  538. }
  539. else {
  540. resolver = lua_http_global_resolver (ev_base);
  541. }
  542. if (lua_gettop (L) >= 5 && rspamd_lua_check_udata_maybe (L, 5, "rspamd{session}")) {
  543. session = *(struct rspamd_async_session **)lua_touserdata (L, 5);
  544. }
  545. else {
  546. session = NULL;
  547. }
  548. msg = rspamd_http_message_from_url (url);
  549. if (msg == NULL) {
  550. lua_pushboolean (L, FALSE);
  551. return 1;
  552. }
  553. }
  554. else if (lua_type (L, 1) == LUA_TTABLE) {
  555. lua_pushstring (L, "url");
  556. lua_gettable (L, 1);
  557. url = luaL_checkstring (L, -1);
  558. lua_pop (L, 1);
  559. lua_pushstring (L, "callback");
  560. lua_gettable (L, 1);
  561. if (url == NULL || lua_type (L, -1) != LUA_TFUNCTION) {
  562. lua_pop (L, 1);
  563. } else {
  564. cbref = luaL_ref (L, LUA_REGISTRYINDEX);
  565. }
  566. lua_pushstring (L, "task");
  567. lua_gettable (L, 1);
  568. if (lua_type (L, -1) == LUA_TUSERDATA) {
  569. task = lua_check_task (L, -1);
  570. if (task) {
  571. ev_base = task->event_loop;
  572. resolver = task->resolver;
  573. session = task->s;
  574. cfg = task->cfg;
  575. }
  576. }
  577. lua_pop (L, 1);
  578. if (task == NULL) {
  579. lua_pushstring (L, "ev_base");
  580. lua_gettable (L, 1);
  581. if (rspamd_lua_check_udata_maybe (L, -1, "rspamd{ev_base}")) {
  582. ev_base = *(struct ev_loop **)lua_touserdata (L, -1);
  583. }
  584. else {
  585. ev_base = NULL;
  586. }
  587. lua_pop (L, 1);
  588. lua_pushstring (L, "session");
  589. lua_gettable (L, 1);
  590. if (rspamd_lua_check_udata_maybe (L, -1, "rspamd{session}")) {
  591. session = *(struct rspamd_async_session **)lua_touserdata (L, -1);
  592. }
  593. else {
  594. session = NULL;
  595. }
  596. lua_pop (L, 1);
  597. lua_pushstring (L, "config");
  598. lua_gettable (L, 1);
  599. if (rspamd_lua_check_udata_maybe (L, -1, "rspamd{config}")) {
  600. cfg = *(struct rspamd_config **)lua_touserdata (L, -1);
  601. }
  602. else {
  603. cfg = NULL;
  604. }
  605. lua_pop (L, 1);
  606. lua_pushstring (L, "resolver");
  607. lua_gettable (L, 1);
  608. if (rspamd_lua_check_udata_maybe (L, -1, "rspamd{resolver}")) {
  609. resolver = *(struct rspamd_dns_resolver **)lua_touserdata (L, -1);
  610. }
  611. else {
  612. if (cfg && cfg->dns_resolver) {
  613. resolver = cfg->dns_resolver;
  614. }
  615. else {
  616. resolver = lua_http_global_resolver (ev_base);
  617. }
  618. }
  619. lua_pop (L, 1);
  620. }
  621. msg = rspamd_http_message_from_url (url);
  622. if (msg == NULL) {
  623. msg_err ("cannot create HTTP message from url %s", url);
  624. lua_pushboolean (L, FALSE);
  625. return 1;
  626. }
  627. lua_pushstring (L, "headers");
  628. lua_gettable (L, 1);
  629. if (lua_type (L, -1) == LUA_TTABLE) {
  630. lua_http_push_headers (L, msg);
  631. }
  632. lua_pop (L, 1);
  633. lua_pushstring (L, "timeout");
  634. lua_gettable (L, 1);
  635. if (lua_type (L, -1) == LUA_TNUMBER) {
  636. timeout = lua_tonumber (L, -1);
  637. }
  638. lua_pop (L, 1);
  639. lua_pushstring (L, "mime_type");
  640. lua_gettable (L, 1);
  641. if (lua_type (L, -1) == LUA_TSTRING) {
  642. mime_type = g_strdup (lua_tostring (L, -1));
  643. }
  644. lua_pop (L, 1);
  645. lua_pushstring (L, "body");
  646. lua_gettable (L, 1);
  647. if (lua_type (L, -1) == LUA_TSTRING) {
  648. lua_body = lua_tolstring (L, -1, &bodylen);
  649. body = rspamd_fstring_new_init (lua_body, bodylen);
  650. }
  651. else if (lua_type (L, -1) == LUA_TUSERDATA) {
  652. t = lua_check_text (L, -1);
  653. /* TODO: think about zero-copy possibilities */
  654. if (t) {
  655. body = rspamd_fstring_new_init (t->start, t->len);
  656. }
  657. else {
  658. rspamd_http_message_unref (msg);
  659. g_free (mime_type);
  660. return luaL_error (L, "invalid body argument type: %s",
  661. lua_typename (L, lua_type (L, -1)));
  662. }
  663. }
  664. else if (lua_type (L, -1) == LUA_TTABLE) {
  665. gsize total_len = 0, nelts = rspamd_lua_table_size (L, -1);
  666. /* Calculate length and check types */
  667. for (gsize i = 0; i < nelts; i ++) {
  668. lua_rawgeti (L, -1, i + 1);
  669. if (lua_type (L, -1) == LUA_TSTRING) {
  670. #if LUA_VERSION_NUM >= 502
  671. total_len += lua_rawlen (L, -1);
  672. #else
  673. total_len += lua_objlen (L, -1);
  674. #endif
  675. }
  676. else if (lua_type (L, -1) == LUA_TUSERDATA) {
  677. t = lua_check_text (L, -1);
  678. if (t) {
  679. total_len += t->len;
  680. }
  681. else {
  682. rspamd_http_message_unref (msg);
  683. if (mime_type) {
  684. g_free (mime_type);
  685. }
  686. return luaL_error (L, "invalid body argument: %s",
  687. lua_typename (L, lua_type (L, -1)));
  688. }
  689. }
  690. else {
  691. rspamd_http_message_unref (msg);
  692. if (mime_type) {
  693. g_free (mime_type);
  694. }
  695. return luaL_error (L, "invalid body argument type: %s",
  696. lua_typename (L, lua_type (L, -1)));
  697. }
  698. lua_pop (L, 1);
  699. }
  700. /* Preallocate body */
  701. if (total_len > 0) {
  702. body = rspamd_fstring_sized_new (total_len);
  703. }
  704. else {
  705. rspamd_http_message_unref (msg);
  706. if (mime_type) {
  707. g_free (mime_type);
  708. }
  709. return luaL_error (L, "empty body specified");
  710. }
  711. /* Fill elements */
  712. for (gsize i = 0; i < nelts; i ++) {
  713. lua_rawgeti (L, -1, i + 1);
  714. if (lua_type (L, -1) == LUA_TSTRING) {
  715. lua_body = lua_tolstring (L, -1, &bodylen);
  716. body = rspamd_fstring_append (body, lua_body, bodylen);
  717. }
  718. else {
  719. t = lua_check_text (L, -1);
  720. if (t) {
  721. body = rspamd_fstring_append(body, t->start, t->len);
  722. }
  723. }
  724. lua_pop (L, 1);
  725. }
  726. }
  727. else if (lua_type (L, -1) != LUA_TNONE && lua_type (L, -1) != LUA_TNIL) {
  728. rspamd_http_message_unref (msg);
  729. return luaL_error (L, "invalid body argument type: %s",
  730. lua_typename (L, lua_type (L, -1)));
  731. }
  732. lua_pop (L, 1);
  733. lua_pushstring (L, "peer_key");
  734. lua_gettable (L, 1);
  735. if (lua_type (L, -1) == LUA_TSTRING) {
  736. const gchar *in;
  737. gsize inlen;
  738. in = lua_tolstring (L, -1, &inlen);
  739. peer_key = rspamd_pubkey_from_base32 (in, inlen,
  740. RSPAMD_KEYPAIR_KEX, RSPAMD_CRYPTOBOX_MODE_25519);
  741. }
  742. lua_pop (L, 1);
  743. lua_pushstring (L, "keypair");
  744. lua_gettable (L, 1);
  745. if (lua_type (L, -1) == LUA_TTABLE) {
  746. ucl_object_t *kp_ucl = ucl_object_lua_import (L, -1);
  747. local_kp = rspamd_keypair_from_ucl (kp_ucl);
  748. ucl_object_unref (kp_ucl);
  749. }
  750. lua_pop (L, 1);
  751. lua_pushstring (L, "opaque_body");
  752. lua_gettable (L, 1);
  753. if (!!lua_toboolean (L, -1)) {
  754. flags |= RSPAMD_LUA_HTTP_FLAG_TEXT;
  755. }
  756. lua_pop (L, 1);
  757. lua_pushstring (L, "gzip");
  758. lua_gettable (L, 1);
  759. if (!!lua_toboolean (L, -1)) {
  760. gzip = TRUE;
  761. }
  762. lua_pop (L, 1);
  763. lua_pushstring (L, "no_ssl_verify");
  764. lua_gettable (L, 1);
  765. if (!!lua_toboolean (L, -1)) {
  766. flags |= RSPAMD_LUA_HTTP_FLAG_NOVERIFY;
  767. }
  768. lua_pop (L, 1);
  769. lua_pushstring (L, "keepalive");
  770. lua_gettable (L, 1);
  771. if (!!lua_toboolean (L, -1)) {
  772. flags |= RSPAMD_LUA_HTTP_FLAG_KEEP_ALIVE;
  773. }
  774. lua_pop (L, 1);
  775. lua_pushstring (L, "max_size");
  776. lua_gettable (L, 1);
  777. if (lua_type (L, -1) == LUA_TNUMBER) {
  778. max_size = lua_tointeger (L, -1);
  779. }
  780. lua_pop (L, 1);
  781. lua_pushstring (L, "method");
  782. lua_gettable (L, 1);
  783. if (lua_type (L, -1) == LUA_TSTRING) {
  784. rspamd_http_message_set_method (msg, lua_tostring (L, -1));
  785. }
  786. lua_pop (L, 1);
  787. lua_pushstring (L, "user");
  788. lua_gettable (L, 1);
  789. if (lua_type (L, -1) == LUA_TSTRING) {
  790. const gchar *user = lua_tostring (L, -1);
  791. lua_pushstring (L, "password");
  792. lua_gettable (L, 1);
  793. if (lua_type (L, -1) == LUA_TSTRING) {
  794. const gchar *password = lua_tostring (L, -1);
  795. gchar *tmpbuf;
  796. gsize tlen;
  797. tlen = strlen (user) + strlen (password) + 1;
  798. tmpbuf = g_malloc (tlen + 1);
  799. rspamd_snprintf (tmpbuf, tlen + 1, "%s:%s", user, password);
  800. tlen *= 2;
  801. tlen += sizeof ("Basic ") - 1;
  802. auth = g_malloc (tlen + 1);
  803. rspamd_snprintf (auth, tlen + 1, "Basic %Bs", tmpbuf);
  804. g_free (tmpbuf);
  805. }
  806. else {
  807. msg_warn ("HTTP user must have password, disabling auth");
  808. }
  809. lua_pop (L, 1); /* password */
  810. }
  811. lua_pop (L, 1); /* username */
  812. }
  813. else {
  814. msg_err ("http request has bad params");
  815. lua_pushboolean (L, FALSE);
  816. return 1;
  817. }
  818. if (session && rspamd_session_blocked (session)) {
  819. lua_pushboolean (L, FALSE);
  820. g_free (auth);
  821. rspamd_http_message_unref (msg);
  822. if (body) {
  823. rspamd_fstring_free (body);
  824. }
  825. if (local_kp) {
  826. rspamd_keypair_unref (local_kp);
  827. }
  828. return 1;
  829. }
  830. if (task == NULL && cfg == NULL) {
  831. g_free (auth);
  832. rspamd_http_message_unref (msg);
  833. if (body) {
  834. rspamd_fstring_free (body);
  835. }
  836. if (local_kp) {
  837. rspamd_keypair_unref (local_kp);
  838. }
  839. return luaL_error (L,
  840. "Bad params to rspamd_http:request(): either task or config should be set");
  841. }
  842. if (ev_base == NULL) {
  843. g_free (auth);
  844. rspamd_http_message_unref (msg);
  845. if (body) {
  846. rspamd_fstring_free (body);
  847. }
  848. if (local_kp) {
  849. rspamd_keypair_unref (local_kp);
  850. }
  851. return luaL_error (L,
  852. "Bad params to rspamd_http:request(): ev_base isn't passed");
  853. }
  854. cbd = g_malloc0 (sizeof (*cbd));
  855. cbd->cbref = cbref;
  856. cbd->msg = msg;
  857. cbd->event_loop = ev_base;
  858. cbd->mime_type = mime_type;
  859. cbd->timeout = timeout;
  860. cbd->fd = -1;
  861. cbd->cfg = cfg;
  862. cbd->peer_pk = peer_key;
  863. cbd->local_kp = local_kp;
  864. cbd->flags = flags;
  865. cbd->max_size = max_size;
  866. cbd->url = url;
  867. cbd->auth = auth;
  868. cbd->task = task;
  869. if (cbd->cbref == -1) {
  870. cbd->thread = lua_thread_pool_get_running_entry (cfg->lua_thread_pool);
  871. }
  872. REF_INIT_RETAIN (cbd, lua_http_cbd_dtor);
  873. if (task) {
  874. cbd->item = rspamd_symcache_get_cur_item (task);
  875. }
  876. if (body) {
  877. if (gzip) {
  878. if (rspamd_fstring_gzip (&body)) {
  879. rspamd_http_message_add_header (msg, "Content-Encoding", "gzip");
  880. }
  881. }
  882. rspamd_http_message_set_body_from_fstring_steal (msg, body);
  883. }
  884. if (session) {
  885. cbd->session = session;
  886. }
  887. bool numeric_ip = false;
  888. /* Check if we can skip resolving */
  889. gsize hostlen = 0;
  890. const gchar *host = rspamd_http_message_get_http_host (msg, &hostlen);
  891. if (host) {
  892. cbd->host = g_malloc (hostlen + 1);
  893. rspamd_strlcpy (cbd->host, host, hostlen + 1);
  894. if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_KEEP_ALIVE) {
  895. const rspamd_inet_addr_t *ka_addr = rspamd_http_context_has_keepalive(NULL,
  896. cbd->host,
  897. msg->port,
  898. msg->flags & RSPAMD_HTTP_FLAG_WANT_SSL);
  899. if (ka_addr) {
  900. cbd->addr = rspamd_inet_address_copy(ka_addr, NULL);
  901. numeric_ip = true;
  902. }
  903. }
  904. if (!cbd->addr) {
  905. /* We use msg->host here, not cbd->host ! */
  906. if (rspamd_parse_inet_address (&cbd->addr,
  907. msg->host->str, msg->host->len,
  908. RSPAMD_INET_ADDRESS_PARSE_DEFAULT)) {
  909. numeric_ip = true;
  910. }
  911. }
  912. }
  913. else {
  914. cbd->host = NULL;
  915. }
  916. if (numeric_ip) {
  917. /* Host is numeric IP, no need to resolve */
  918. gboolean ret;
  919. REF_RETAIN (cbd);
  920. ret = lua_http_make_connection (cbd);
  921. if (!ret) {
  922. if (cbd->ref.refcount > 1) {
  923. /* Not released by make_connection */
  924. REF_RELEASE (cbd);
  925. }
  926. REF_RELEASE (cbd);
  927. lua_pushboolean (L, FALSE);
  928. return 1;
  929. }
  930. REF_RELEASE (cbd);
  931. }
  932. else {
  933. if (!cbd->host) {
  934. REF_RELEASE (cbd);
  935. return luaL_error (L, "no host has been specified");
  936. }
  937. if (task == NULL) {
  938. REF_RETAIN (cbd);
  939. if (!rspamd_dns_resolver_request (resolver, session, NULL, lua_http_dns_handler, cbd,
  940. RDNS_REQUEST_A,
  941. cbd->host)) {
  942. if (cbd->ref.refcount > 1) {
  943. /* Not released by make_connection */
  944. REF_RELEASE (cbd);
  945. }
  946. REF_RELEASE (cbd);
  947. lua_pushboolean (L, FALSE);
  948. return 1;
  949. }
  950. REF_RELEASE (cbd);
  951. }
  952. else {
  953. REF_RETAIN (cbd);
  954. if (!rspamd_dns_resolver_request_task_forced (task, lua_http_dns_handler, cbd,
  955. RDNS_REQUEST_A, cbd->host)) {
  956. if (cbd->ref.refcount > 1) {
  957. /* Not released by make_connection */
  958. REF_RELEASE (cbd);
  959. }
  960. REF_RELEASE (cbd);
  961. lua_pushboolean (L, FALSE);
  962. return 1;
  963. }
  964. else if (cbd->item) {
  965. rspamd_symcache_item_async_inc (cbd->task, cbd->item, M);
  966. }
  967. REF_RELEASE (cbd);
  968. }
  969. }
  970. if (cbd->cbref == -1) {
  971. cbd->thread = lua_thread_pool_get_running_entry (cfg->lua_thread_pool);
  972. cbd->flags |= RSPAMD_LUA_HTTP_FLAG_YIELDED;
  973. return lua_thread_yield (cbd->thread, 0);
  974. }
  975. else {
  976. lua_pushboolean (L, TRUE);
  977. }
  978. return 1;
  979. }
  980. static gint
  981. lua_load_http (lua_State * L)
  982. {
  983. lua_newtable (L);
  984. luaL_register (L, NULL, httplib_m);
  985. return 1;
  986. }
  987. void
  988. luaopen_http (lua_State * L)
  989. {
  990. rspamd_lua_add_preload (L, "rspamd_http", lua_load_http);
  991. }