1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
|
/*
* Copyright 2025 Vsevolod Stakhov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "lua_common.h"
#include "lua_caseless_table.h"
#include "lua_thread_pool.h"
#include "libserver/http/http_private.h"
#include "libutil/upstream.h"
#include "ref.h"
#include "unix-std.h"
#include "zlib.h"
#include "utlist.h"
#include "libserver/protocol_internal.h"
/* HTTP-specific caseless table builder (defined in lua_caseless_table.c) */
extern void rspamd_lua_caseless_table_push_from_http(lua_State *L,
khash_t(rspamd_http_headers_hash) * headers);
/***
* @module rspamd_http
* Rspamd HTTP module represents HTTP asynchronous client available from LUA code.
* This module hides all complexity: DNS resolving, sessions management, zero-copy
* text transfers and so on under the hood.
* @example
-- Basic GET request with callback
local rspamd_http = require "rspamd_http"
local function symbol_callback(task)
local function http_callback(err_message, code, body, headers)
task:insert_result('SYMBOL', 1) -- task is available via closure
if err_message then
-- Handle error
return
end
-- Process response
if code == 200 then
-- Process body and headers (caseless table)
-- Lookup is case-insensitive: headers['Content-Type'] == headers['content-type']
for name, value in headers:each() do
-- Original header case is preserved
end
end
end
rspamd_http.request({
task=task,
url='http://example.com/data',
body=task:get_content(),
callback=http_callback,
headers={Header='Value', OtherHeader='Value', DuplicatedHeader={'Multiple', 'Values'}},
mime_type='text/plain',
})
end
-- POST request with JSON body
local function post_json_example(task)
local ucl = require "ucl"
local data = {
id = task:get_queue_id(),
sender = task:get_from()[1].addr
}
local json_data = ucl.to_json(data)
rspamd_http.request({
task = task,
url = "http://example.com/api/submit",
method = "POST",
body = json_data,
headers = {['Content-Type'] = 'application/json'},
callback = function(err, code, body, headers)
if not err and code == 200 then
-- Success
end
end
})
end
-- Synchronous HTTP request (using coroutines)
local function sync_http_example(task)
-- No callback makes this a synchronous call
local err, response = rspamd_http.request({
task = task,
url = "http://example.com/api/data",
method = "GET",
timeout = 10.0
})
if not err then
-- Response is a table with code, content, and headers
if response.code == 200 then
-- Process response.content
return true
end
end
return false
end
-- Using authentication
local function auth_example(task)
rspamd_http.request({
task = task,
url = "https://example.com/api/protected",
method = "GET",
user = "username",
password = "secret",
callback = function(err, code, body, headers)
-- Process authenticated response
end
})
end
-- Using HTTPS with SSL options
local function https_example(task)
rspamd_http.request({
task = task,
url = "https://example.com/api/secure",
method = "GET",
no_ssl_verify = false, -- Verify SSL (default)
callback = function(err, code, body, headers)
-- Process secure response
end
})
end
-- Using keep-alive and gzip
local function advanced_example(task)
rspamd_http.request({
task = task,
url = "http://example.com/api/data",
method = "POST",
body = task:get_content(),
gzip = true, -- Compress request body
keepalive = true, -- Use keep-alive connection
max_size = 1024 * 1024, -- Limit response to 1MB
callback = function(err, code, body, headers)
-- Process response
end
})
end
*/
#define MAX_HEADERS_SIZE 8192
static const char *M = "rspamd lua http";
LUA_FUNCTION_DEF(http, request);
static const struct luaL_reg httplib_m[] = {
LUA_INTERFACE_DEF(http, request),
{"__tostring", rspamd_lua_class_tostring},
{NULL, NULL}};
#define RSPAMD_LUA_HTTP_FLAG_TEXT (1 << 0)
#define RSPAMD_LUA_HTTP_FLAG_NOVERIFY (1 << 1)
#define RSPAMD_LUA_HTTP_FLAG_RESOLVED (1 << 2)
#define RSPAMD_LUA_HTTP_FLAG_KEEP_ALIVE (1 << 3)
#define RSPAMD_LUA_HTTP_FLAG_YIELDED (1 << 4)
#define RSPAMD_LUA_HTTP_FLAG_NO_LOCAL (1 << 5)
/* Per-request connection tuning was read from the request table */
#define RSPAMD_LUA_HTTP_FLAG_TUNED (1 << 6)
struct lua_http_cbdata {
struct rspamd_http_connection *conn;
struct rspamd_async_session *session;
struct rspamd_symcache_dynamic_item *item;
struct rspamd_http_message *msg;
struct ev_loop *event_loop;
struct rspamd_config *cfg;
struct rspamd_task *task;
ev_tstamp timeout;
/* optional per-request tuning */
double connect_timeout;
double ssl_timeout;
double write_timeout;
double read_timeout;
double connection_ttl;
double idle_timeout;
unsigned int max_reuse;
struct rspamd_cryptobox_keypair *local_kp;
struct rspamd_cryptobox_pubkey *peer_pk;
rspamd_inet_addr_t *addr;
char *mime_type;
char *host;
char *auth;
struct upstream *up;
const char *url;
gsize max_size;
int flags;
int fd;
int cbref;
struct thread_entry *thread;
guint64 thread_generation;
ref_entry_t ref;
};
static const double default_http_timeout = 5.0;
static struct rspamd_dns_resolver *
lua_http_global_resolver(struct ev_loop *ev_base)
{
static struct rspamd_dns_resolver *global_resolver;
if (global_resolver == NULL) {
global_resolver = rspamd_dns_resolver_init(NULL, ev_base, NULL);
}
return global_resolver;
}
static void
lua_http_read_tuning(lua_State *L, int idx, struct lua_http_cbdata *cbd)
{
static const struct {
const char *name;
gsize offset;
} fields[] = {
{"connect_timeout", G_STRUCT_OFFSET(struct lua_http_cbdata, connect_timeout)},
{"ssl_timeout", G_STRUCT_OFFSET(struct lua_http_cbdata, ssl_timeout)},
{"write_timeout", G_STRUCT_OFFSET(struct lua_http_cbdata, write_timeout)},
{"read_timeout", G_STRUCT_OFFSET(struct lua_http_cbdata, read_timeout)},
{"connection_ttl", G_STRUCT_OFFSET(struct lua_http_cbdata, connection_ttl)},
{"idle_timeout", G_STRUCT_OFFSET(struct lua_http_cbdata, idle_timeout)},
};
for (unsigned int i = 0; i < G_N_ELEMENTS(fields); i++) {
lua_getfield(L, idx, fields[i].name);
if (lua_type(L, -1) == LUA_TNUMBER) {
G_STRUCT_MEMBER(double, cbd, fields[i].offset) = lua_tonumber(L, -1);
}
lua_pop(L, 1);
}
lua_getfield(L, idx, "max_reuse");
if (lua_type(L, -1) == LUA_TNUMBER) {
cbd->max_reuse = lua_tointeger(L, -1);
}
lua_pop(L, 1);
cbd->flags |= RSPAMD_LUA_HTTP_FLAG_TUNED;
}
static void
lua_http_fin(gpointer arg)
{
struct lua_http_cbdata *cbd = (struct lua_http_cbdata *) arg;
if (cbd->thread) {
/*
* A cancelled session finalises the request directly, without
* lua_http_cbd_dtor, which releases the entry otherwise
*/
lua_thread_pool_release_entry(cbd->thread);
cbd->thread = NULL;
}
if (cbd->cbref != -1) {
luaL_unref(cbd->cfg->lua_state, LUA_REGISTRYINDEX, cbd->cbref);
}
if (cbd->conn) {
/* Here we already have a connection, so we need to unref it */
rspamd_http_connection_unref(cbd->conn);
}
else if (cbd->msg != NULL) {
/* We need to free message */
rspamd_http_message_unref(cbd->msg);
}
if (cbd->fd != -1) {
close(cbd->fd);
}
if (cbd->addr) {
rspamd_inet_address_free(cbd->addr);
}
if (cbd->up) {
rspamd_upstream_unref(cbd->up);
}
if (cbd->mime_type) {
g_free(cbd->mime_type);
}
if (cbd->auth) {
g_free(cbd->auth);
}
if (cbd->host) {
g_free(cbd->host);
}
if (cbd->local_kp) {
rspamd_keypair_unref(cbd->local_kp);
}
if (cbd->peer_pk) {
rspamd_pubkey_unref(cbd->peer_pk);
}
g_free(cbd);
}
static void
lua_http_cbd_dtor(struct lua_http_cbdata *cbd)
{
if (cbd->thread) {
/* Balances the retain taken when the coroutine yielded on this request */
lua_thread_pool_release_entry(cbd->thread);
cbd->thread = NULL;
}
if (cbd->session) {
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_RESOLVED) {
/* Event is added merely for resolved events */
if (cbd->item) {
rspamd_symcache_item_async_dec_check(cbd->task, cbd->item, M);
}
rspamd_session_remove_event(cbd->session, lua_http_fin, cbd);
}
else {
/* Failed before its session event was added, e.g. in DNS */
lua_http_fin(cbd);
}
}
else {
lua_http_fin(cbd);
}
}
static void
lua_http_push_error(struct lua_http_cbdata *cbd, const char *err)
{
struct lua_callback_state lcbd;
lua_State *L;
if (cbd->cbref == -1) {
/* Coroutine-style call: resume the yielded thread with (err, nil) */
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_YIELDED) {
cbd->flags &= ~RSPAMD_LUA_HTTP_FLAG_YIELDED;
L = cbd->thread->lua_state;
lua_pushstring(L, err);
lua_pushnil(L);
if (cbd->item) {
rspamd_symcache_set_cur_item(cbd->task, cbd->item);
}
lua_thread_resume_checked(cbd->thread, cbd->thread_generation, 2);
}
else {
msg_info("lost HTTP error for %s in coroutines mess: %s",
cbd->host ? cbd->host : "unknown host", err);
}
return;
}
lua_thread_pool_prepare_callback(cbd->cfg->lua_thread_pool, &lcbd);
L = lcbd.L;
lua_rawgeti(L, LUA_REGISTRYINDEX, cbd->cbref);
lua_pushstring(L, err);
if (cbd->item) {
rspamd_symcache_set_cur_item(cbd->task, cbd->item);
}
if (lua_pcall(L, 1, 0, 0) != 0) {
msg_info("callback call failed: %s", lua_tostring(L, -1));
lua_pop(L, 1);
}
lua_thread_pool_restore_callback(&lcbd);
}
static void lua_http_resume_handler(struct rspamd_http_connection *conn,
struct rspamd_http_message *msg, const char *err);
static void
lua_http_error_handler(struct rspamd_http_connection *conn, GError *err)
{
struct lua_http_cbdata *cbd = (struct lua_http_cbdata *) conn->ud;
if (cbd->up) {
rspamd_upstream_fail(cbd->up, false, err ? err->message : "unknown error");
}
if (cbd->cbref == -1) {
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_YIELDED) {
cbd->flags &= ~RSPAMD_LUA_HTTP_FLAG_YIELDED;
lua_http_resume_handler(conn, NULL, err->message);
}
else {
/* TODO: kill me please */
msg_info("lost HTTP error from %s in coroutines mess: %s",
rspamd_inet_address_to_string_pretty(cbd->addr),
err->message);
}
}
else {
lua_http_push_error(cbd, err->message);
}
REF_RELEASE(cbd);
}
static int
lua_http_finish_handler(struct rspamd_http_connection *conn,
struct rspamd_http_message *msg)
{
struct lua_http_cbdata *cbd = (struct lua_http_cbdata *) conn->ud;
const char *body;
gsize body_len;
struct lua_callback_state lcbd;
lua_State *L;
if (cbd->cbref == -1) {
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_YIELDED) {
cbd->flags &= ~RSPAMD_LUA_HTTP_FLAG_YIELDED;
lua_http_resume_handler(conn, msg, NULL);
}
else {
/* TODO: kill me please */
msg_err("lost HTTP data from %s in coroutines mess",
rspamd_inet_address_to_string_pretty(cbd->addr));
}
REF_RELEASE(cbd);
return 0;
}
lua_thread_pool_prepare_callback(cbd->cfg->lua_thread_pool, &lcbd);
if (cbd->up) {
rspamd_upstream_ok(cbd->up);
}
L = lcbd.L;
lua_pushcfunction(L, &rspamd_lua_traceback);
int err_idx = lua_gettop(L);
lua_rawgeti(L, LUA_REGISTRYINDEX, cbd->cbref);
/* Error */
lua_pushnil(L);
/* Reply code */
lua_pushinteger(L, msg->code);
/* Body */
body = rspamd_http_message_get_body(msg, &body_len);
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_TEXT) {
struct rspamd_lua_text *t;
t = lua_newuserdata(L, sizeof(*t));
rspamd_lua_setclass(L, rspamd_text_classname, -1);
t->start = body;
t->len = body_len;
t->flags = 0;
}
else {
if (body_len > 0) {
lua_pushlstring(L, body, body_len);
}
else {
lua_pushnil(L);
}
}
/* Headers as caseless table */
rspamd_lua_caseless_table_push_from_http(L, msg->headers);
if (cbd->item) {
/* Replace watcher to deal with nested calls */
rspamd_symcache_set_cur_item(cbd->task, cbd->item);
}
if (lua_pcall(L, 4, 0, err_idx) != 0) {
msg_info("callback call failed: %s", lua_tostring(L, -1));
lua_pop(L, 1);
}
lua_pop(L, 1); /* Remove traceback function */
REF_RELEASE(cbd);
lua_thread_pool_restore_callback(&lcbd);
return 0;
}
/*
* resumes yielded thread
*/
static void
lua_http_resume_handler(struct rspamd_http_connection *conn,
struct rspamd_http_message *msg, const char *err)
{
struct lua_http_cbdata *cbd = (struct lua_http_cbdata *) conn->ud;
lua_State *L = cbd->thread->lua_state;
const char *body;
gsize body_len;
if (err) {
lua_pushstring(L, err);
lua_pushnil(L);
}
else {
/*
* 1 - nil (error)
* 2 - table:
* code (int)
* content (string)
* headers (table: header -> value)
*/
lua_pushnil(L);// error code
lua_createtable(L, 0, 3);
/* code */
lua_pushliteral(L, "code");
lua_pushinteger(L, msg->code);
lua_settable(L, -3);
/* content */
lua_pushliteral(L, "content");
body = rspamd_http_message_get_body(msg, &body_len);
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_TEXT) {
struct rspamd_lua_text *t;
t = lua_newuserdata(L, sizeof(*t));
rspamd_lua_setclass(L, rspamd_text_classname, -1);
t->start = body;
t->len = body_len;
t->flags = 0;
}
else {
if (body_len > 0) {
lua_pushlstring(L, body, body_len);
}
else {
lua_pushnil(L);
}
}
lua_settable(L, -3);
/* headers as caseless table */
lua_pushliteral(L, "headers");
rspamd_lua_caseless_table_push_from_http(L, msg->headers);
lua_settable(L, -3);
}
if (cbd->item) {
/* Replace watcher to deal with nested calls */
rspamd_symcache_set_cur_item(cbd->task, cbd->item);
}
lua_thread_resume_checked(cbd->thread, cbd->thread_generation, 2);
}
/*
* IPv4 destinations that are not hosts of the public network: "this network"
* (0.0.0.0 is the local host for a connect), shared address space, link-local
* addresses (whatever `local_addrs` is set to), protocol assignments, benchmarking, multicast and the reserved top of the space
*/
static gboolean
lua_http_ip4_is_special(uint32_t ip)
{
return (ip & 0xff000000U) == 0x00000000U || /* 0.0.0.0/8 */
(ip & 0xffc00000U) == 0x64400000U || /* 100.64.0.0/10 */
(ip & 0xffff0000U) == 0xa9fe0000U || /* 169.254.0.0/16, link-local */
(ip & 0xffffff00U) == 0xc0000000U || /* 192.0.0.0/24 */
(ip & 0xfffe0000U) == 0xc6120000U || /* 198.18.0.0/15 */
(ip & 0xf0000000U) == 0xe0000000U || /* 224.0.0.0/4 */
(ip & 0xf0000000U) == 0xf0000000U; /* 240.0.0.0/4 */
}
/*
* What `forbid_local` refuses: the addresses that are local by the
* configuration, and those that lead to this host or to an internal network
* without being listed there. An IPv4 address inside of an IPv6 one, mapped or
* behind the well known NAT64 prefix, is judged as that IPv4 address.
*/
static gboolean
lua_http_addr_is_forbidden(struct rspamd_config *cfg, const rspamd_inet_addr_t *addr)
{
if (rspamd_ip_is_local_cfg(cfg, addr)) {
return TRUE;
}
int af = rspamd_inet_address_get_af(addr);
unsigned int klen = 0;
const unsigned char *key = rspamd_inet_address_get_hash_key(addr, &klen);
if (af == AF_INET && klen == 4) {
uint32_t ip = ((uint32_t) key[0] << 24) | ((uint32_t) key[1] << 16) |
((uint32_t) key[2] << 8) | key[3];
return lua_http_ip4_is_special(ip);
}
else if (af == AF_INET6 && klen == 16) {
static const unsigned char unspecified[16] = {0};
static const unsigned char v4mapped[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
static const unsigned char nat64[12] = {0, 0x64, 0xff, 0x9b, 0, 0, 0, 0, 0, 0, 0, 0};
if (memcmp(key, unspecified, sizeof(unspecified)) == 0) {
/* The local host for a connect */
return TRUE;
}
if ((key[0] & 0xfe) == 0xfc || key[0] == 0xff) {
/* Unique local fc00::/7 and multicast ff00::/8 */
return TRUE;
}
if (memcmp(key, v4mapped, sizeof(v4mapped)) == 0 ||
memcmp(key, nat64, sizeof(nat64)) == 0) {
struct in_addr in4;
gboolean forbidden;
memcpy(&in4, key + 12, sizeof(in4));
rspamd_inet_addr_t *embedded = rspamd_inet_address_new(AF_INET, &in4);
forbidden = lua_http_addr_is_forbidden(cfg, embedded);
rspamd_inet_address_free(embedded);
return forbidden;
}
}
return FALSE;
}
static gboolean
lua_http_make_connection(struct lua_http_cbdata *cbd)
{
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_NO_LOCAL) {
struct rspamd_config *cfg = cbd->cfg;
if (cfg == NULL && cbd->task) {
cfg = cbd->task->cfg;
}
if (lua_http_addr_is_forbidden(cfg, cbd->addr)) {
msg_info("forbid HTTP request to local address %s (host: %s) as 'forbid_local' is set",
rspamd_inet_address_to_string(cbd->addr),
cbd->host ? cbd->host : "unknown");
return FALSE;
}
}
rspamd_inet_address_set_port(cbd->addr, cbd->msg->port);
unsigned http_opts = RSPAMD_HTTP_CLIENT_SIMPLE;
if (cbd->msg->flags & RSPAMD_HTTP_FLAG_WANT_SSL) {
http_opts |= RSPAMD_HTTP_CLIENT_SSL;
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_NOVERIFY) {
/* Not to be given a connection that was verified, nor the reverse */
http_opts |= RSPAMD_HTTP_CLIENT_SSL_NOVERIFY;
}
}
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_KEEP_ALIVE) {
cbd->fd = -1; /* FD is owned by keepalive connection */
cbd->conn = rspamd_http_connection_new_client_keepalive(
NULL, /* Default context */
NULL,
lua_http_error_handler,
lua_http_finish_handler,
http_opts,
cbd->addr,
cbd->host);
}
else {
cbd->fd = -1;
cbd->conn = rspamd_http_connection_new_client(
NULL, /* Default context */
NULL,
lua_http_error_handler,
lua_http_finish_handler,
http_opts,
cbd->addr);
}
if (cbd->conn) {
if (cbd->local_kp) {
rspamd_http_connection_set_key(cbd->conn, cbd->local_kp);
}
if (cbd->peer_pk) {
rspamd_http_message_set_peer_key(cbd->msg, cbd->peer_pk);
}
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_NOVERIFY) {
cbd->msg->flags |= RSPAMD_HTTP_FLAG_SSL_NOVERIFY;
}
if (cbd->max_size) {
rspamd_http_connection_set_max_size(cbd->conn, cbd->max_size);
}
if (cbd->auth) {
rspamd_http_message_add_header(cbd->msg, "Authorization",
cbd->auth);
}
if (cbd->session) {
rspamd_session_add_event_full(cbd->session,
(event_finalizer_t) lua_http_fin, cbd, M,
cbd->host);
cbd->flags |= RSPAMD_LUA_HTTP_FLAG_RESOLVED;
}
/* Optional per-request tuning, read from the request table */
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_TUNED) {
rspamd_http_connection_set_timeouts(cbd->conn, cbd->connect_timeout,
cbd->ssl_timeout, cbd->write_timeout,
cbd->read_timeout);
rspamd_http_connection_set_keepalive_tuning(cbd->conn, cbd->connection_ttl,
cbd->idle_timeout, cbd->max_reuse);
}
if (cbd->task) {
cbd->conn->log_tag = cbd->task->task_pool->tag.uid;
if (cbd->item) {
rspamd_symcache_item_async_inc(cbd->task, cbd->item, M);
}
}
else if (cbd->cfg) {
cbd->conn->log_tag = cbd->cfg->cfg_pool->tag.uid;
}
struct rspamd_http_message *msg = cbd->msg;
/* Message is now owned by a connection object */
cbd->msg = NULL;
return rspamd_http_connection_write_message(cbd->conn, msg,
cbd->host, cbd->mime_type, cbd,
cbd->timeout);
}
return FALSE;
}
static void
lua_http_dns_handler(struct rdns_reply *reply, gpointer ud)
{
struct lua_http_cbdata *cbd = (struct lua_http_cbdata *) ud;
struct rspamd_symcache_dynamic_item *item;
struct rspamd_task *task;
task = cbd->task;
item = cbd->item;
if (reply->code != RDNS_RC_NOERROR) {
lua_http_push_error(cbd, "unable to resolve host");
REF_RELEASE(cbd);
}
else {
struct rdns_reply_entry *entry;
DL_FOREACH(reply->entries, entry)
{
if (entry->type == RDNS_REQUEST_A) {
cbd->addr = rspamd_inet_address_new(AF_INET,
&entry->content.a.addr);
break;
}
else if (entry->type == RDNS_REQUEST_AAAA) {
cbd->addr = rspamd_inet_address_new(AF_INET6,
&entry->content.aaa.addr);
break;
}
}
if (cbd->addr == NULL) {
lua_http_push_error(cbd, "unable to resolve host: no records with such name");
REF_RELEASE(cbd);
}
else {
REF_RETAIN(cbd);
if (!lua_http_make_connection(cbd)) {
/*
* E.g. the resolved address is denied by `forbid_local`; the
* symbol's async counter taken for the DNS request is released
* below as in the other error paths
*/
lua_http_push_error(cbd, "unable to make connection to the host");
if (cbd->ref.refcount > 1) {
REF_RELEASE(cbd);
}
}
REF_RELEASE(cbd);
}
}
if (item) {
rspamd_symcache_item_async_dec_check(task, item, M);
}
}
static void
lua_http_push_headers(lua_State *L, struct rspamd_http_message *msg)
{
const char *name, *value;
int i, sz;
int tbl = lua_gettop(L);
/*
* Two accepted shapes for the headers table:
* - map: { ['Name'] = 'value', ['Name'] = {'v1', 'v2'} } -- order undefined
* - list: { {'Name', 'value'}, {'Name', {'v1', 'v2'}} } -- order preserved
* The list shape sets RSPAMD_HTTP_FLAG_ORDERED_HEADERS so the HTTP client
* emits headers on the wire in exactly the order they are listed (used to
* mimic a real browser's header order). It is detected by a non-nil
* integer key 1 whose value is itself a table.
*/
lua_rawgeti(L, tbl, 1);
if (lua_type(L, -1) == LUA_TTABLE) {
lua_pop(L, 1);
msg->flags |= RSPAMD_HTTP_FLAG_ORDERED_HEADERS;
sz = rspamd_lua_table_size(L, tbl);
for (i = 1; i <= sz; i++) {
lua_rawgeti(L, tbl, i); /* pair { name, value } */
if (lua_type(L, -1) == LUA_TTABLE) {
int pair = lua_gettop(L);
int vsz, j;
lua_rawgeti(L, pair, 1);
name = lua_tostring(L, -1);
lua_pop(L, 1);
lua_rawgeti(L, pair, 2);
vsz = rspamd_lua_table_size(L, -1);
if (name != NULL) {
if (vsz != 0) {
/* Duplicated header: value is a list of strings */
for (j = 1; j <= vsz; j++) {
lua_rawgeti(L, -1, j);
value = lua_tostring(L, -1);
if (value != NULL) {
rspamd_http_message_add_header(msg, name, value);
}
lua_pop(L, 1);
}
}
else {
value = lua_tostring(L, -1);
if (value != NULL) {
rspamd_http_message_add_header(msg, name, value);
}
}
}
lua_pop(L, 1); /* value */
}
lua_pop(L, 1); /* pair */
}
}
else {
lua_pop(L, 1);
lua_pushnil(L);
while (lua_next(L, tbl) != 0) {
lua_pushvalue(L, -2);
name = lua_tostring(L, -1);
sz = rspamd_lua_table_size(L, -2);
if (sz != 0 && name != NULL) {
for (i = 1; i <= sz; i++) {
lua_rawgeti(L, -2, i);
value = lua_tostring(L, -1);
if (value != NULL) {
rspamd_http_message_add_header(msg, name, value);
}
lua_pop(L, 1);
}
}
else {
value = lua_tostring(L, -2);
if (name != NULL && value != NULL) {
rspamd_http_message_add_header(msg, name, value);
}
}
lua_pop(L, 2);
}
}
}
/***
* @function rspamd_http.request({params...})
* This function creates HTTP request and accepts several parameters as a table using key=value syntax.
* Required params are:
*
* - `url`
* - `task`
*
* In taskless mode, instead of `task` required are:
*
* - `ev_base`
* - `config`
*
* @param {string} url specifies URL for a request in the standard URI form (e.g. 'http://example.com/path')
* @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/developers/sync_async.html#API-example-http-module)
* @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
* @param {table} headers optional headers in form `[name='value']` or `[name=['value1', 'value2']]` to duplicate a header with multiple values. A list form `{{'name', 'value'}, {'name', {'value1', 'value2'}}}` is also accepted and preserves the header order on the wire
* @param {string} mime_type MIME type of the HTTP content (for example, `text/html`)
* @param {string/text} body full body content, can be opaque `rspamd{text}` to avoid data copying
* @param {number} timeout floating point request timeout value in seconds (default is 5.0 seconds)
* @param {number} max_size maximum size of the reply body in bytes (default is the `max_lua_http_response` global option, 256Mb; 0 disables the limit)
* @param {resolver} resolver to perform DNS-requests. Usually got from either `task` or `config`
* @param {boolean} gzip if true, body of the requests will be compressed
* @param {boolean} no_ssl_verify disable SSL peer checks
* @param {boolean} forbid_local refuse to connect when the destination resolves to a loopback, unspecified, link-local, unique local, shared (100.64/10), multicast, reserved or `local_addrs` address, also when it is an IPv4 address of these inside of an IPv6 one (SSRF protection for requests to untrusted URLs)
* @param {boolean} keepalive enable keep-alive pool
* @param {string} user for HTTP authentication
* @param {string} password for HTTP authentication, only if "user" present
* @param {number} connect_timeout optional TCP connect timeout (seconds)
* @param {number} ssl_timeout optional SSL handshake timeout (seconds)
* @param {number} write_timeout optional request write timeout (seconds)
* @param {number} read_timeout optional response read timeout (seconds)
* @param {number} connection_ttl optional absolute keep-alive connection TTL (seconds)
* @param {number} idle_timeout optional keep-alive idle timeout override (seconds)
* @param {number} max_reuse optional keep-alive max reuse count per connection
* @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.
* @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)
*/
static int
lua_http_request(lua_State *L)
{
LUA_TRACE_POINT;
struct ev_loop *ev_base;
struct rspamd_http_message *msg;
struct lua_http_cbdata *cbd;
struct rspamd_dns_resolver *resolver;
struct rspamd_async_session *session = NULL;
struct rspamd_lua_text *t;
struct rspamd_task *task = NULL;
struct rspamd_config *cfg = NULL;
struct rspamd_cryptobox_pubkey *peer_key = NULL;
struct rspamd_cryptobox_keypair *local_kp = NULL;
struct upstream *up = NULL;
const char *url, *lua_body;
rspamd_fstring_t *body = NULL;
int cbref = -1;
gsize bodylen;
double timeout = default_http_timeout;
int flags = 0;
char *mime_type = NULL;
char *auth = NULL;
gssize max_size = -1; /* -1 = use the global default; 0 = unlimited */
gboolean gzip = FALSE;
if (lua_gettop(L) >= 2) {
/* url, callback and event_base format */
url = luaL_checkstring(L, 1);
if (url == NULL || lua_type(L, 2) != LUA_TFUNCTION) {
msg_err("http request has bad params");
lua_pushboolean(L, FALSE);
return 1;
}
lua_pushvalue(L, 2);
cbref = luaL_ref(L, LUA_REGISTRYINDEX);
if (lua_gettop(L) >= 3 && rspamd_lua_check_udata_maybe(L, 3, rspamd_ev_base_classname)) {
ev_base = *(struct ev_loop **) lua_touserdata(L, 3);
}
else {
ev_base = NULL;
}
if (lua_gettop(L) >= 4 && rspamd_lua_check_udata_maybe(L, 4, rspamd_resolver_classname)) {
resolver = *(struct rspamd_dns_resolver **) lua_touserdata(L, 4);
}
else {
resolver = lua_http_global_resolver(ev_base);
}
if (lua_gettop(L) >= 5 && rspamd_lua_check_udata_maybe(L, 5, rspamd_session_classname)) {
session = *(struct rspamd_async_session **) lua_touserdata(L, 5);
}
else {
session = NULL;
}
msg = rspamd_http_message_from_url(url);
if (msg == NULL) {
luaL_unref(L, LUA_REGISTRYINDEX, cbref);
msg_err("cannot create HTTP message from url %s", url);
lua_pushboolean(L, FALSE);
return 1;
}
}
else if (lua_type(L, 1) == LUA_TTABLE) {
lua_pushstring(L, "url");
lua_gettable(L, 1);
url = luaL_checkstring(L, -1);
lua_pop(L, 1);
if (url == NULL) {
msg_err("cannot create HTTP message without url");
lua_pushboolean(L, FALSE);
return 1;
}
lua_pushstring(L, "callback");
lua_gettable(L, 1);
if (url == NULL || lua_type(L, -1) != LUA_TFUNCTION) {
lua_pop(L, 1);
}
else {
cbref = luaL_ref(L, LUA_REGISTRYINDEX);
}
lua_pushstring(L, "task");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TUSERDATA) {
task = lua_check_task(L, -1);
if (task) {
ev_base = task->event_loop;
resolver = task->resolver;
session = task->s;
cfg = task->cfg;
}
}
lua_pop(L, 1);
if (task == NULL) {
lua_pushstring(L, "ev_base");
lua_gettable(L, 1);
if (rspamd_lua_check_udata_maybe(L, -1, rspamd_ev_base_classname)) {
ev_base = *(struct ev_loop **) lua_touserdata(L, -1);
}
else {
ev_base = NULL;
}
lua_pop(L, 1);
lua_pushstring(L, "session");
lua_gettable(L, 1);
if (rspamd_lua_check_udata_maybe(L, -1, rspamd_session_classname)) {
session = *(struct rspamd_async_session **) lua_touserdata(L, -1);
}
else {
session = NULL;
}
lua_pop(L, 1);
lua_pushstring(L, "config");
lua_gettable(L, 1);
if (rspamd_lua_check_udata_maybe(L, -1, rspamd_config_classname)) {
cfg = *(struct rspamd_config **) lua_touserdata(L, -1);
}
else {
cfg = NULL;
}
lua_pop(L, 1);
lua_pushstring(L, "resolver");
lua_gettable(L, 1);
if (rspamd_lua_check_udata_maybe(L, -1, rspamd_resolver_classname)) {
resolver = *(struct rspamd_dns_resolver **) lua_touserdata(L, -1);
}
else {
if (cfg && cfg->dns_resolver) {
resolver = cfg->dns_resolver;
}
else {
resolver = lua_http_global_resolver(ev_base);
}
}
lua_pop(L, 1);
}
msg = rspamd_http_message_from_url(url);
if (msg == NULL) {
msg_err_task_check("cannot create HTTP message from url %s", url);
if (cbref == -1) {
/* Coroutine callers expect (err, response), not a bare false */
lua_pushstring(L, "cannot create HTTP message from url");
lua_pushnil(L);
return 2;
}
lua_pushboolean(L, FALSE);
return 1;
}
lua_pushstring(L, "headers");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TTABLE) {
lua_http_push_headers(L, msg);
}
lua_pop(L, 1);
lua_pushstring(L, "timeout");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TNUMBER) {
timeout = lua_tonumber(L, -1);
}
lua_pop(L, 1);
lua_pushstring(L, "mime_type");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TSTRING) {
mime_type = g_strdup(lua_tostring(L, -1));
}
lua_pop(L, 1);
lua_pushstring(L, "body");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TSTRING) {
lua_body = lua_tolstring(L, -1, &bodylen);
body = rspamd_fstring_new_init(lua_body, bodylen);
}
else if (lua_type(L, -1) == LUA_TUSERDATA) {
t = lua_check_text(L, -1);
/* TODO: think about zero-copy possibilities */
if (t) {
body = rspamd_fstring_new_init(t->start, t->len);
}
else {
rspamd_http_message_unref(msg);
g_free(mime_type);
return luaL_error(L, "invalid body argument type: %s",
lua_typename(L, lua_type(L, -1)));
}
}
else if (lua_type(L, -1) == LUA_TTABLE) {
gsize total_len = 0, nelts = rspamd_lua_table_size(L, -1);
/* Calculate length and check types */
for (gsize i = 0; i < nelts; i++) {
lua_rawgeti(L, -1, i + 1);
if (lua_type(L, -1) == LUA_TSTRING) {
#if LUA_VERSION_NUM >= 502
total_len += lua_rawlen(L, -1);
#else
total_len += lua_objlen(L, -1);
#endif
}
else if (lua_type(L, -1) == LUA_TUSERDATA) {
t = lua_check_text(L, -1);
if (t) {
total_len += t->len;
}
else {
rspamd_http_message_unref(msg);
if (mime_type) {
g_free(mime_type);
}
return luaL_error(L, "invalid body argument: %s",
lua_typename(L, lua_type(L, -1)));
}
}
else {
rspamd_http_message_unref(msg);
if (mime_type) {
g_free(mime_type);
}
return luaL_error(L, "invalid body argument type: %s",
lua_typename(L, lua_type(L, -1)));
}
lua_pop(L, 1);
}
/* Preallocate body */
if (total_len > 0) {
body = rspamd_fstring_sized_new(total_len);
}
else {
rspamd_http_message_unref(msg);
if (mime_type) {
g_free(mime_type);
}
return luaL_error(L, "empty body specified");
}
/* Fill elements */
for (gsize i = 0; i < nelts; i++) {
lua_rawgeti(L, -1, i + 1);
if (lua_type(L, -1) == LUA_TSTRING) {
lua_body = lua_tolstring(L, -1, &bodylen);
body = rspamd_fstring_append(body, lua_body, bodylen);
}
else {
t = lua_check_text(L, -1);
if (t) {
body = rspamd_fstring_append(body, t->start, t->len);
}
}
lua_pop(L, 1);
}
}
else if (lua_type(L, -1) != LUA_TNONE && lua_type(L, -1) != LUA_TNIL) {
rspamd_http_message_unref(msg);
return luaL_error(L, "invalid body argument type: %s",
lua_typename(L, lua_type(L, -1)));
}
lua_pop(L, 1);
lua_pushstring(L, "peer_key");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TSTRING) {
const char *in;
gsize inlen;
in = lua_tolstring(L, -1, &inlen);
peer_key = rspamd_pubkey_from_base32(in, inlen, RSPAMD_KEYPAIR_KEX);
}
lua_pop(L, 1);
lua_pushstring(L, "keypair");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TTABLE) {
ucl_object_t *kp_ucl = ucl_object_lua_import(L, -1);
local_kp = rspamd_keypair_from_ucl(kp_ucl);
ucl_object_unref(kp_ucl);
}
lua_pop(L, 1);
lua_pushstring(L, "opaque_body");
lua_gettable(L, 1);
if (!!lua_toboolean(L, -1)) {
flags |= RSPAMD_LUA_HTTP_FLAG_TEXT;
}
lua_pop(L, 1);
lua_pushstring(L, "gzip");
lua_gettable(L, 1);
if (!!lua_toboolean(L, -1)) {
gzip = TRUE;
}
lua_pop(L, 1);
lua_pushstring(L, "no_ssl_verify");
lua_gettable(L, 1);
if (!!lua_toboolean(L, -1)) {
flags |= RSPAMD_LUA_HTTP_FLAG_NOVERIFY;
}
lua_pop(L, 1);
lua_pushstring(L, "forbid_local");
lua_gettable(L, 1);
if (!!lua_toboolean(L, -1)) {
flags |= RSPAMD_LUA_HTTP_FLAG_NO_LOCAL;
}
lua_pop(L, 1);
lua_pushstring(L, "keepalive");
lua_gettable(L, 1);
if (!!lua_toboolean(L, -1)) {
flags |= RSPAMD_LUA_HTTP_FLAG_KEEP_ALIVE;
}
lua_pop(L, 1);
lua_pushstring(L, "max_size");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TNUMBER) {
lua_Integer i = lua_tointeger(L, -1);
if (i >= 0) {
max_size = i;
}
else {
msg_err_task_check("ignore negative max_size %L in HTTP request to %s",
(int64_t) i, url);
}
}
lua_pop(L, 1);
lua_pushstring(L, "method");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TSTRING) {
rspamd_http_message_set_method(msg, lua_tostring(L, -1));
}
lua_pop(L, 1);
lua_pushstring(L, "upstream");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TUSERDATA) {
struct rspamd_lua_upstream *lup = lua_check_upstream(L, -1);
if (lup) {
/* Preserve pointer in case if lup is destructed */
up = lup->up;
}
}
lua_pop(L, 1);
lua_pushstring(L, "user");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TSTRING) {
const char *user = lua_tostring(L, -1);
lua_pushstring(L, "password");
lua_gettable(L, 1);
if (lua_type(L, -1) == LUA_TSTRING) {
const char *password = lua_tostring(L, -1);
char *tmpbuf;
gsize tlen;
tlen = strlen(user) + strlen(password) + 1;
tmpbuf = g_malloc(tlen + 1);
rspamd_snprintf(tmpbuf, tlen + 1, "%s:%s", user, password);
tlen *= 2;
tlen += sizeof("Basic ") - 1;
auth = g_malloc(tlen + 1);
rspamd_snprintf(auth, tlen + 1, "Basic %Bs", tmpbuf);
g_free(tmpbuf);
}
else {
msg_warn("HTTP user must have password, disabling auth");
}
lua_pop(L, 1); /* password */
}
lua_pop(L, 1); /* username */
}
else {
msg_err("http request has bad params");
lua_pushboolean(L, FALSE);
return 1;
}
if (session && rspamd_session_blocked(session)) {
g_free(auth);
rspamd_http_message_unref(msg);
if (body) {
rspamd_fstring_free(body);
}
if (local_kp) {
rspamd_keypair_unref(local_kp);
}
if (cbref == -1) {
/* Coroutine callers expect (err, response), not a bare false */
lua_pushstring(L, "session is terminating");
lua_pushnil(L);
return 2;
}
lua_pushboolean(L, FALSE);
return 1;
}
if (task == NULL && cfg == NULL) {
g_free(auth);
rspamd_http_message_unref(msg);
if (body) {
rspamd_fstring_free(body);
}
if (local_kp) {
rspamd_keypair_unref(local_kp);
}
return luaL_error(L,
"Bad params to rspamd_http:request(): either task or config should be set");
}
if (ev_base == NULL) {
g_free(auth);
rspamd_http_message_unref(msg);
if (body) {
rspamd_fstring_free(body);
}
if (local_kp) {
rspamd_keypair_unref(local_kp);
}
return luaL_error(L,
"Bad params to rspamd_http:request(): ev_base isn't passed");
}
cbd = g_malloc0(sizeof(*cbd));
cbd->cbref = cbref;
cbd->msg = msg;
cbd->event_loop = ev_base;
cbd->mime_type = mime_type;
cbd->timeout = timeout;
cbd->fd = -1;
cbd->cfg = cfg;
cbd->peer_pk = peer_key;
cbd->local_kp = local_kp;
cbd->flags = flags;
if (max_size >= 0) {
cbd->max_size = max_size;
}
else {
cbd->max_size = cfg ? cfg->max_lua_http_response : 0;
}
cbd->url = url;
cbd->auth = auth;
cbd->task = task;
/*
* Per-request tuning is read now: the connection may be made from the
* DNS reply callback, when this call frame and its arguments are gone
*/
if (lua_type(L, 1) == LUA_TTABLE) {
lua_http_read_tuning(L, 1, cbd);
}
if (up) {
cbd->up = rspamd_upstream_ref(up);
}
if (cbd->cbref == -1) {
cbd->thread = lua_thread_pool_get_running_entry(cfg->lua_thread_pool);
cbd->thread_generation = cbd->thread->generation;
/* Held for the lifetime of cbd, released in lua_http_cbd_dtor() */
lua_thread_pool_retain_entry(cbd->thread);
}
REF_INIT_RETAIN(cbd, lua_http_cbd_dtor);
if (task) {
cbd->item = rspamd_symcache_get_cur_item(task);
}
if (body) {
if (gzip) {
if (rspamd_fstring_gzip(&body)) {
rspamd_http_message_add_header(msg, CONTENT_ENCODING_HEADER, "gzip");
}
}
rspamd_http_message_set_body_from_fstring_steal(msg, body);
}
if (session) {
cbd->session = session;
}
bool numeric_ip = false;
/* Check if we can skip resolving */
gsize hostlen = 0;
const char *host = rspamd_http_message_get_http_host(msg, &hostlen);
if (host) {
cbd->host = g_malloc(hostlen + 1);
rspamd_strlcpy(cbd->host, host, hostlen + 1);
/*
* The address is the one of an upstream, or the one that the URL
* names. A pooled connection tells an address only for a name that
* would be resolved otherwise: a request to an address goes to that
* address, whatever its Host header shares with other requests
*/
if (cbd->up) {
numeric_ip = true;
cbd->addr = rspamd_inet_address_copy(rspamd_upstream_addr_next(cbd->up), NULL);
}
else {
/* We use msg->host here, not cbd->host ! */
if (rspamd_parse_inet_address(&cbd->addr,
msg->host->str, msg->host->len,
RSPAMD_INET_ADDRESS_PARSE_DEFAULT)) {
numeric_ip = true;
}
}
/* Keep-alive entry is available */
if (!cbd->addr && (cbd->flags & RSPAMD_LUA_HTTP_FLAG_KEEP_ALIVE)) {
unsigned int ssl_flags = 0;
if (msg->flags & RSPAMD_HTTP_FLAG_WANT_SSL) {
ssl_flags |= RSPAMD_HTTP_KEEPALIVE_SSL;
if (cbd->flags & RSPAMD_LUA_HTTP_FLAG_NOVERIFY) {
ssl_flags |= RSPAMD_HTTP_KEEPALIVE_SSL_NOVERIFY;
}
}
const rspamd_inet_addr_t *ka_addr = rspamd_http_context_has_keepalive(NULL,
cbd->host,
msg->port,
ssl_flags);
if (ka_addr) {
cbd->addr = rspamd_inet_address_copy(ka_addr, NULL);
numeric_ip = true;
}
}
}
else {
if (cbd->up) {
numeric_ip = true;
cbd->addr = rspamd_inet_address_copy(rspamd_upstream_addr_next(cbd->up), NULL);
}
cbd->host = NULL;
}
if (numeric_ip) {
/* Host is numeric IP, no need to resolve */
gboolean ret;
REF_RETAIN(cbd);
ret = lua_http_make_connection(cbd);
if (!ret) {
if (cbd->up) {
rspamd_upstream_fail(cbd->up, true, "HTTP connection failed");
}
if (cbd->ref.refcount > 1) {
/* Not released by make_connection */
REF_RELEASE(cbd);
}
REF_RELEASE(cbd);
if (cbref == -1) {
/* Coroutine callers expect (err, response), not a bare false */
lua_pushstring(L, "cannot make HTTP connection");
lua_pushnil(L);
return 2;
}
lua_pushboolean(L, FALSE);
return 1;
}
REF_RELEASE(cbd);
}
else {
if (!cbd->host) {
REF_RELEASE(cbd);
return luaL_error(L, "no host has been specified");
}
if (task == NULL) {
REF_RETAIN(cbd);
if (!rspamd_dns_resolver_request(resolver, session, NULL, lua_http_dns_handler, cbd,
RDNS_REQUEST_A,
cbd->host)) {
if (cbd->ref.refcount > 1) {
/* Not released by make_connection */
REF_RELEASE(cbd);
}
REF_RELEASE(cbd);
if (cbref == -1) {
/* Coroutine callers expect (err, response), not a bare false */
lua_pushstring(L, "cannot make DNS request");
lua_pushnil(L);
return 2;
}
lua_pushboolean(L, FALSE);
return 1;
}
REF_RELEASE(cbd);
}
else {
REF_RETAIN(cbd);
if (!rspamd_dns_resolver_request_task_forced(task, lua_http_dns_handler, cbd,
RDNS_REQUEST_A, cbd->host)) {
if (cbd->ref.refcount > 1) {
/* Not released by make_connection */
REF_RELEASE(cbd);
}
REF_RELEASE(cbd);
if (cbref == -1) {
/* Coroutine callers expect (err, response), not a bare false */
lua_pushstring(L, "cannot make DNS request");
lua_pushnil(L);
return 2;
}
lua_pushboolean(L, FALSE);
return 1;
}
else if (cbd->item) {
rspamd_symcache_item_async_inc(cbd->task, cbd->item, M);
}
REF_RELEASE(cbd);
}
}
if (cbd->cbref == -1) {
cbd->thread = lua_thread_pool_get_running_entry(cfg->lua_thread_pool);
cbd->thread_generation = cbd->thread->generation;
cbd->flags |= RSPAMD_LUA_HTTP_FLAG_YIELDED;
return lua_thread_yield(cbd->thread, 0);
}
else {
lua_pushboolean(L, TRUE);
}
return 1;
}
static int
lua_load_http(lua_State *L)
{
lua_newtable(L);
luaL_register(L, NULL, httplib_m);
return 1;
}
void luaopen_http(lua_State *L)
{
rspamd_lua_add_preload(L, "rspamd_http", lua_load_http);
}
|