summaryrefslogtreecommitdiffstats
path: root/src/rspamd_proxy.c
blob: a2521fec10e768c050046e5af2a7ded4d787f9de (plain)
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
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
/*-
 * Copyright 2016 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 "config.h"
#include "libutil/util.h"
#include "libutil/map.h"
#include "libutil/upstream.h"
#include "libutil/http.h"
#include "libutil/http_private.h"
#include "libserver/protocol.h"
#include "libserver/cfg_file.h"
#include "libserver/url.h"
#include "libserver/dns.h"
#include "libmime/message.h"
#include "rspamd.h"
#include "libserver/worker_util.h"
#include "worker_private.h"
#include "lua/lua_common.h"
#include "keypairs_cache.h"
#include "libstat/stat_api.h"
#include "ottery.h"
#include "unix-std.h"
#include "libserver/milter.h"
#include "contrib/zstd/zstd.h"

/* Rotate keys each minute by default */
#define DEFAULT_ROTATION_TIME 60.0
#define DEFAULT_RETRIES 5

#define msg_err_session(...) rspamd_default_log_function (G_LOG_LEVEL_CRITICAL, \
        session->pool->tag.tagname, session->pool->tag.uid, \
        G_STRFUNC, \
        __VA_ARGS__)
#define msg_warn_session(...)   rspamd_default_log_function (G_LOG_LEVEL_WARNING, \
        session->pool->tag.tagname, session->pool->tag.uid, \
        G_STRFUNC, \
        __VA_ARGS__)
#define msg_info_session(...)   rspamd_default_log_function (G_LOG_LEVEL_INFO, \
        session->pool->tag.tagname, session->pool->tag.uid, \
        G_STRFUNC, \
        __VA_ARGS__)
#define msg_debug_session(...)  rspamd_default_log_function (G_LOG_LEVEL_DEBUG, \
        session->pool->tag.tagname, session->pool->tag.uid, \
        G_STRFUNC, \
        __VA_ARGS__)

gpointer init_rspamd_proxy (struct rspamd_config *cfg);
void start_rspamd_proxy (struct rspamd_worker *worker);

worker_t rspamd_proxy_worker = {
	"rspamd_proxy",               /* Name */
	init_rspamd_proxy,            /* Init function */
	start_rspamd_proxy,           /* Start function */
	RSPAMD_WORKER_HAS_SOCKET | RSPAMD_WORKER_KILLABLE,
	RSPAMD_WORKER_SOCKET_TCP,    /* TCP socket */
	RSPAMD_WORKER_VER
};

struct rspamd_http_upstream {
	gchar *name;
	struct upstream_list *u;
	struct rspamd_cryptobox_pubkey *key;
	gdouble timeout;
	struct timeval io_tv;
	gint parser_from_ref;
	gint parser_to_ref;
	gboolean local;
	gboolean self_scan;
	gboolean compress;
};

struct rspamd_http_mirror {
	gchar *name;
	gchar *settings_id;
	struct upstream_list *u;
	struct rspamd_cryptobox_pubkey *key;
	gdouble prob;
	gdouble timeout;
	struct timeval io_tv;
	gint parser_from_ref;
	gint parser_to_ref;
	gboolean local;
	gboolean compress;
};

static const guint64 rspamd_rspamd_proxy_magic = 0xcdeb4fd1fc351980ULL;

struct rspamd_proxy_ctx {
	guint64 magic;
	/* Events base */
	struct event_base *ev_base;
	/* DNS resolver */
	struct rspamd_dns_resolver *resolver;
	/* Config */
	struct rspamd_config *cfg;
	/* END OF COMMON PART */
	gdouble timeout;
	struct timeval io_tv;
	/* Encryption key for clients */
	struct rspamd_cryptobox_keypair *key;
	/* Keys cache */
	struct rspamd_keypair_cache *keys_cache;
	/* Upstreams to use */
	GHashTable *upstreams;
	/* Mirrors to send traffic to */
	GPtrArray *mirrors;
	/* Default upstream */
	struct rspamd_http_upstream *default_upstream;
	/* Local rotating keypair for upstreams */
	struct rspamd_cryptobox_keypair *local_key;
	struct event rotate_ev;
	gdouble rotate_tm;
	lua_State *lua_state;
	/* Array of callback functions called on end of scan to compare results */
	GArray *cmp_refs;
	/* Maximum count for retries */
	guint max_retries;
	/* If we have self_scanning backends, we need to work as a normal worker */
	gboolean has_self_scan;
	/* It is not HTTP but milter proxy */
	gboolean milter;
	/* Discard messages instead of rejecting them */
	gboolean discard_on_reject;
	/* Milter spam header */
	gchar *spam_header;
	/* Sessions cache */
	void *sessions_cache;
};

enum rspamd_backend_flags {
	RSPAMD_BACKEND_REPLIED = 1 << 0,
	RSPAMD_BACKEND_CLOSED = 1 << 1,
	RSPAMD_BACKEND_PARSED = 1 << 2,
};

struct rspamd_proxy_session;

struct rspamd_proxy_backend_connection {
	const gchar *name;
	struct rspamd_cryptobox_keypair *local_key;
	struct rspamd_cryptobox_pubkey *remote_key;
	struct upstream *up;
	struct rspamd_http_connection *backend_conn;
	ucl_object_t *results;
	const gchar *err;
	struct rspamd_proxy_session *s;
	struct timeval *io_tv;
	gint backend_sock;
	enum rspamd_backend_flags flags;
	gint parser_from_ref;
	gint parser_to_ref;
	struct rspamd_task *task;
};

enum rspamd_proxy_legacy_support {
	LEGACY_SUPPORT_NO = 0,
	LEGACY_SUPPORT_RSPAMC,
	LEGACY_SUPPORT_SPAMC
};

struct rspamd_proxy_session {
	struct rspamd_worker *worker;
	rspamd_mempool_t *pool;
	struct rspamd_proxy_ctx *ctx;
	rspamd_inet_addr_t *client_addr;
	struct rspamd_http_connection *client_conn;
	struct rspamd_milter_session *client_milter_conn;
	gpointer map;
	gchar *fname;
	gpointer shmem_ref;
	struct rspamd_proxy_backend_connection *master_conn;
	struct rspamd_http_message *client_message;
	GPtrArray *mirror_conns;
	gsize map_len;
	gint client_sock;
	enum rspamd_proxy_legacy_support legacy_support;
	gint retries;
	ref_entry_t ref;
};

static gboolean proxy_send_master_message (struct rspamd_proxy_session *session);

static GQuark
rspamd_proxy_quark (void)
{
	return g_quark_from_static_string ("rspamd-proxy");
}

static gboolean
rspamd_proxy_parse_lua_parser (lua_State *L, const ucl_object_t *obj,
		gint *ref_from, gint *ref_to, GError **err)
{
	const gchar *lua_script;
	gsize slen;
	gint err_idx, ref_idx;
	GString *tb = NULL;
	gboolean has_ref = FALSE;

	g_assert (obj != NULL);
	g_assert (ref_from != NULL);
	g_assert (ref_to != NULL);

	*ref_from = -1;
	*ref_to = -1;

	lua_script = ucl_object_tolstring (obj, &slen);
	lua_pushcfunction (L, &rspamd_lua_traceback);
	err_idx = lua_gettop (L);

	/* Load data */
	if (luaL_loadbuffer (L, lua_script, slen, "proxy parser") != 0) {
		g_set_error (err,
				rspamd_proxy_quark (),
				EINVAL,
				"cannot load lua parser script: %s",
				lua_tostring (L, -1));
		lua_settop (L, 0); /* Error function */

		return FALSE;
	}

	/* Now do it */
	if (lua_pcall (L, 0, 1, err_idx) != 0) {
		tb = lua_touserdata (L, -1);
		g_set_error (err,
				rspamd_proxy_quark (),
				EINVAL,
				"cannot init lua parser script: %s",
				tb->str);
		g_string_free (tb, TRUE);
		lua_settop (L, 0);

		return FALSE;
	}

	if (lua_istable (L, -1)) {
		/*
		 * We have a table, so we check for two keys:
		 * 'from' -> function
		 * 'to' -> function
		 *
		 * From converts parent request to a client one
		 * To converts client request to a parent one
		 */
		lua_pushstring (L, "from");
		lua_gettable (L, -2);

		if (lua_isfunction (L, -1)) {
			ref_idx = luaL_ref (L, LUA_REGISTRYINDEX);
			*ref_from = ref_idx;
			has_ref = TRUE;
		}

		lua_pushstring (L, "to");
		lua_gettable (L, -2);

		if (lua_isfunction (L, -1)) {
			ref_idx = luaL_ref (L, LUA_REGISTRYINDEX);
			*ref_to = ref_idx;
			has_ref = TRUE;
		}
	}
	else if (!lua_isfunction (L, -1)) {
		g_set_error (err,
				rspamd_proxy_quark (),
				EINVAL,
				"cannot init lua parser script: "
				"must return function");
		lua_settop (L, 0);

		return FALSE;
	}
	else {
		/* Just parser from protocol */
		ref_idx = luaL_ref (L, LUA_REGISTRYINDEX);
		*ref_from = ref_idx;
		lua_settop (L, 0);
		has_ref = TRUE;
	}

	return has_ref;
}

static gboolean
rspamd_proxy_parse_upstream (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	const ucl_object_t *elt;
	struct rspamd_http_upstream *up = NULL;
	struct rspamd_proxy_ctx *ctx;
	struct rspamd_rcl_struct_parser *pd = ud;
	lua_State *L;

	ctx = pd->user_struct;
	L = ctx->lua_state;

	if (ucl_object_type (obj) != UCL_OBJECT) {
		g_set_error (err, rspamd_proxy_quark (), 100,
				"upstream option must be an object");

		return FALSE;
	}

	up = rspamd_mempool_alloc0 (pool, sizeof (*up));

	elt = ucl_object_lookup (obj, "name");
	if (elt == NULL) {

		if (ucl_object_key (obj)) {
			if (strcmp (ucl_object_key (obj), "upstream") == 0) {
				/* Iterate over the object and find upstream elements */
				ucl_object_iter_t it = NULL;
				const ucl_object_t *cur;
				gboolean ret = TRUE;

				while ((cur = ucl_object_iterate (obj, &it, true)) != NULL) {
					if (!rspamd_proxy_parse_upstream (pool, cur, ud,
							section, err)) {
						ret = FALSE;
					}
				}

				return ret;
			}
			else {
				/* Inside upstream */
				up->name = rspamd_mempool_strdup (pool, ucl_object_key (obj));
			}
		}
		else {
			g_set_error (err, rspamd_proxy_quark (), 100,
					"upstream option must have some name definition");

			return FALSE;
		}
	}
	else {
		up->name = rspamd_mempool_strdup (pool, ucl_object_tostring (elt));
	}

	up->parser_from_ref = -1;
	up->parser_to_ref = -1;
	up->timeout = ctx->timeout;

	elt = ucl_object_lookup (obj, "key");
	if (elt != NULL) {
		up->key = rspamd_pubkey_from_base32 (ucl_object_tostring (elt), 0,
				RSPAMD_KEYPAIR_KEX, RSPAMD_CRYPTOBOX_MODE_25519);

		if (up->key == NULL) {
			g_set_error (err, rspamd_proxy_quark (), 100,
					"cannot read upstream key");

			goto err;
		}

		rspamd_mempool_add_destructor (pool,
				(rspamd_mempool_destruct_t)rspamd_pubkey_unref, up->key);
	}

	elt = ucl_object_lookup (obj, "self_scan");
	if (elt && ucl_object_toboolean (elt)) {
		up->self_scan = TRUE;
		ctx->has_self_scan = TRUE;
	}

	elt = ucl_object_lookup_any (obj, "compress", "compression", NULL);
	if (elt && ucl_object_toboolean (elt)) {
		up->compress = TRUE;
	}

	elt = ucl_object_lookup (obj, "hosts");

	if (elt == NULL && !up->self_scan) {
		g_set_error (err, rspamd_proxy_quark (), 100,
				"upstream option must have some hosts definition");

		goto err;
	}

	if (elt) {
		up->u = rspamd_upstreams_create (ctx->cfg->ups_ctx);
		if (!rspamd_upstreams_from_ucl (up->u, elt, 11333, NULL)) {
			g_set_error (err, rspamd_proxy_quark (), 100,
					"upstream has bad hosts definition");

			goto err;
		}

		rspamd_mempool_add_destructor (pool,
				(rspamd_mempool_destruct_t)rspamd_upstreams_destroy, up->u);
	}

	elt = ucl_object_lookup (obj, "default");
	if (elt) {
		if (ucl_object_toboolean (elt)) {
			ctx->default_upstream = up;
		}
	}
	else if (up->self_scan) {
		ctx->default_upstream = up;
	}


	elt = ucl_object_lookup (obj, "local");
	if (elt && ucl_object_toboolean (elt)) {
		up->local = TRUE;
	}

	elt = ucl_object_lookup (obj, "timeout");
	if (elt) {
		ucl_object_todouble_safe (elt, &up->timeout);
	}

	/*
	 * Accept lua function here in form
	 * fun :: String -> UCL
	 */
	elt = ucl_object_lookup (obj, "parser");
	if (elt) {
		if (!rspamd_proxy_parse_lua_parser (L, elt, &up->parser_from_ref,
				&up->parser_to_ref, err)) {
			goto err;
		}

		rspamd_lua_add_ref_dtor (L, pool, up->parser_from_ref);
		rspamd_lua_add_ref_dtor (L, pool, up->parser_to_ref);
	}

	double_to_tv (up->timeout, &up->io_tv);

	g_hash_table_insert (ctx->upstreams, up->name, up);

	return TRUE;

err:
	return FALSE;
}

static gboolean
rspamd_proxy_parse_mirror (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	const ucl_object_t *elt;
	struct rspamd_http_mirror *up = NULL;
	struct rspamd_proxy_ctx *ctx;
	struct rspamd_rcl_struct_parser *pd = ud;
	lua_State *L;

	ctx = pd->user_struct;
	L = ctx->lua_state;

	if (ucl_object_type (obj) != UCL_OBJECT) {
		g_set_error (err, rspamd_proxy_quark (), 100,
				"mirror option must be an object");

		return FALSE;
	}

	up = rspamd_mempool_alloc0 (pool, sizeof (*up));

	elt = ucl_object_lookup (obj, "name");
	if (elt == NULL) {

		if (ucl_object_key (obj)) {
			if (strcmp (ucl_object_key (obj), "mirror") == 0) {
				/* Iterate over the object and find upstream elements */
				ucl_object_iter_t it = NULL;
				const ucl_object_t *cur;
				gboolean ret = TRUE;

				while ((cur = ucl_object_iterate (obj, &it, true)) != NULL) {
					if (!rspamd_proxy_parse_mirror (pool, cur, ud,
							section, err)) {
						ret = FALSE;
					}
				}

				return ret;
			}
			else {
				/* Inside upstream */
				up->name = rspamd_mempool_strdup (pool, ucl_object_key (obj));
			}
		}
		else {
			g_set_error (err, rspamd_proxy_quark (), 100,
					"mirror option must have some name definition");

			return FALSE;
		}
	}
	else {
		up->name = rspamd_mempool_strdup (pool, ucl_object_tostring (elt));
	}

	up->parser_to_ref = -1;
	up->parser_from_ref = -1;
	up->timeout = ctx->timeout;

	elt = ucl_object_lookup (obj, "key");
	if (elt != NULL) {
		up->key = rspamd_pubkey_from_base32 (ucl_object_tostring (elt), 0,
				RSPAMD_KEYPAIR_KEX, RSPAMD_CRYPTOBOX_MODE_25519);

		if (up->key == NULL) {
			g_set_error (err, rspamd_proxy_quark (), 100,
					"cannot read mirror key");

			goto err;
		}

		rspamd_mempool_add_destructor (pool,
				(rspamd_mempool_destruct_t)rspamd_pubkey_unref, up->key);
	}

	elt = ucl_object_lookup (obj, "hosts");

	if (elt == NULL) {
		g_set_error (err, rspamd_proxy_quark (), 100,
				"mirror option must have some hosts definition");

		goto err;
	}

	up->u = rspamd_upstreams_create (ctx->cfg->ups_ctx);
	if (!rspamd_upstreams_from_ucl (up->u, elt, 11333, NULL)) {
		g_set_error (err, rspamd_proxy_quark (), 100,
				"mirror has bad hosts definition");

		goto err;
	}

	rspamd_mempool_add_destructor (pool,
			(rspamd_mempool_destruct_t)rspamd_upstreams_destroy, up->u);

	elt = ucl_object_lookup_any (obj, "probability", "prob", NULL);
	if (elt) {
		up->prob = ucl_object_todouble (elt);
	}
	else {
		up->prob = 1.0;
	}

	elt = ucl_object_lookup (obj, "local");
	if (elt && ucl_object_toboolean (elt)) {
		up->local = TRUE;
	}

	elt = ucl_object_lookup_any (obj, "compress", "compression", NULL);
	if (elt && ucl_object_toboolean (elt)) {
		up->compress = TRUE;
	}

	elt = ucl_object_lookup (obj, "timeout");
	if (elt) {
		ucl_object_todouble_safe (elt, &up->timeout);
	}

	/*
	 * Accept lua function here in form
	 * fun :: String -> UCL
	 */
	elt = ucl_object_lookup (obj, "parser");
	if (elt) {
		if (!rspamd_proxy_parse_lua_parser (L, elt, &up->parser_from_ref,
				&up->parser_to_ref, err)) {
			goto err;
		}

		rspamd_lua_add_ref_dtor (L, pool, up->parser_from_ref);
		rspamd_lua_add_ref_dtor (L, pool, up->parser_to_ref);
	}

	elt = ucl_object_lookup_any (obj, "settings", "settings_id", NULL);
	if (elt && ucl_object_type (elt) == UCL_STRING) {
		up->settings_id = rspamd_mempool_strdup (pool, ucl_object_tostring (elt));
	}

	double_to_tv (up->timeout, &up->io_tv);

	g_ptr_array_add (ctx->mirrors, up);

	return TRUE;

err:

	return FALSE;
}

static gboolean
rspamd_proxy_parse_script (rspamd_mempool_t *pool,
	const ucl_object_t *obj,
	gpointer ud,
	struct rspamd_rcl_section *section,
	GError **err)
{
	struct rspamd_proxy_ctx *ctx;
	struct rspamd_rcl_struct_parser *pd = ud;
	lua_State *L;
	const gchar *lua_script;
	gsize slen;
	gint err_idx, ref_idx;
	GString *tb = NULL;
	struct stat st;

	ctx = pd->user_struct;
	L = ctx->lua_state;

	if (ucl_object_type (obj) != UCL_STRING) {
		g_set_error (err, rspamd_proxy_quark (), 100,
				"script option must be a string with file or lua chunk");

		return FALSE;
	}

	lua_script = ucl_object_tolstring (obj, &slen);
	lua_pushcfunction (L, &rspamd_lua_traceback);
	err_idx = lua_gettop (L);

	if (stat (lua_script, &st) != -1) {
		/* Load file */
		if (luaL_loadfile (L, lua_script) != 0) {
			g_set_error (err,
					rspamd_proxy_quark (),
					EINVAL,
					"cannot load lua parser script: %s",
					lua_tostring (L, -1));
			lua_settop (L, 0); /* Error function */

			goto err;
		}
	}
	else {
		/* Load data directly */
		if (luaL_loadbuffer (L, lua_script, slen, "proxy parser") != 0) {
			g_set_error (err,
					rspamd_proxy_quark (),
					EINVAL,
					"cannot load lua parser script: %s",
					lua_tostring (L, -1));
			lua_settop (L, 0); /* Error function */

			goto err;
		}
	}

	/* Now do it */
	if (lua_pcall (L, 0, 1, err_idx) != 0) {
		tb = lua_touserdata (L, -1);
		g_set_error (err,
				rspamd_proxy_quark (),
				EINVAL,
				"cannot init lua parser script: %s",
				tb->str);
		g_string_free (tb, TRUE);
		lua_settop (L, 0);

		goto err;
	}

	if (!lua_isfunction (L, -1)) {
		g_set_error (err,
				rspamd_proxy_quark (),
				EINVAL,
				"cannot init lua parser script: "
				"must return function, %s returned",
				lua_typename (L, lua_type (L, -1)));
		lua_settop (L, 0);

		goto err;
	}

	ref_idx = luaL_ref (L, LUA_REGISTRYINDEX);
	lua_settop (L, 0);
	g_array_append_val (ctx->cmp_refs, ref_idx);

	return TRUE;

err:
	return FALSE;
}

gpointer
init_rspamd_proxy (struct rspamd_config *cfg)
{
	struct rspamd_proxy_ctx *ctx;
	GQuark type;

	type = g_quark_try_string ("rspamd_proxy");

	ctx = rspamd_mempool_alloc0 (cfg->cfg_pool,
			sizeof (struct rspamd_proxy_ctx));
	ctx->magic = rspamd_rspamd_proxy_magic;
	ctx->timeout = 120.0;
	ctx->upstreams = g_hash_table_new (rspamd_strcase_hash, rspamd_strcase_equal);
	rspamd_mempool_add_destructor (cfg->cfg_pool,
			(rspamd_mempool_destruct_t)g_hash_table_unref, ctx->upstreams);
	ctx->mirrors = g_ptr_array_new ();
	rspamd_mempool_add_destructor (cfg->cfg_pool,
			(rspamd_mempool_destruct_t)rspamd_ptr_array_free_hard, ctx->mirrors);
	ctx->rotate_tm = DEFAULT_ROTATION_TIME;
	ctx->cfg = cfg;
	ctx->lua_state = cfg->lua_state;
	ctx->cmp_refs = g_array_new (FALSE, FALSE, sizeof (gint));
	rspamd_mempool_add_destructor (cfg->cfg_pool,
			(rspamd_mempool_destruct_t)rspamd_array_free_hard, ctx->cmp_refs);
	ctx->max_retries = DEFAULT_RETRIES;

	rspamd_rcl_register_worker_option (cfg,
			type,
			"timeout",
			rspamd_rcl_parse_struct_time,
			ctx,
			G_STRUCT_OFFSET (struct rspamd_proxy_ctx, timeout),
			RSPAMD_CL_FLAG_TIME_FLOAT,
			"IO timeout");
	rspamd_rcl_register_worker_option (cfg,
			type,
			"rotate",
			rspamd_rcl_parse_struct_time,
			ctx,
			G_STRUCT_OFFSET (struct rspamd_proxy_ctx, rotate_tm),
			RSPAMD_CL_FLAG_TIME_FLOAT,
			"Rotation keys time, default: "
			G_STRINGIFY (DEFAULT_ROTATION_TIME) " seconds");
	rspamd_rcl_register_worker_option (cfg,
			type,
			"keypair",
			rspamd_rcl_parse_struct_keypair,
			ctx,
			G_STRUCT_OFFSET (struct rspamd_proxy_ctx, key),
			0,
			"Server's keypair");
	rspamd_rcl_register_worker_option (cfg,
			type,
			"upstream",
			rspamd_proxy_parse_upstream,
			ctx,
			0,
			0,
			"List of upstreams");
	rspamd_rcl_register_worker_option (cfg,
			type,
			"mirror",
			rspamd_proxy_parse_mirror,
			ctx,
			0,
			RSPAMD_CL_FLAG_MULTIPLE,
			"List of mirrors");

	rspamd_rcl_register_worker_option (cfg,
			type,
			"script",
			rspamd_proxy_parse_script,
			ctx,
			0,
			RSPAMD_CL_FLAG_MULTIPLE,
			"Compare script to be executed");
	rspamd_rcl_register_worker_option (cfg,
			type,
			"max_retries",
			rspamd_rcl_parse_struct_integer,
			ctx,
			G_STRUCT_OFFSET (struct rspamd_proxy_ctx, max_retries),
			RSPAMD_CL_FLAG_UINT,
			"Maximum number of retries for master connection");
	rspamd_rcl_register_worker_option (cfg,
			type,
			"milter",
			rspamd_rcl_parse_struct_boolean,
			ctx,
			G_STRUCT_OFFSET (struct rspamd_proxy_ctx, milter),
			0,
			"Accept milter connections, not HTTP");
	rspamd_rcl_register_worker_option (cfg,
			type,
			"discard_on_reject",
			rspamd_rcl_parse_struct_boolean,
			ctx,
			G_STRUCT_OFFSET (struct rspamd_proxy_ctx, discard_on_reject),
			0,
			"Tell MTA to discard rejected messages silently");
	rspamd_rcl_register_worker_option (cfg,
			type,
			"spam_header",
			rspamd_rcl_parse_struct_string,
			ctx,
			G_STRUCT_OFFSET (struct rspamd_proxy_ctx, spam_header),
			0,
			"Use the specific spam header instead of X-Spam");

	return ctx;
}

static void
proxy_backend_close_connection (struct rspamd_proxy_backend_connection *conn)
{
	if (conn && !(conn->flags & RSPAMD_BACKEND_CLOSED)) {
		if (conn->backend_conn) {
			rspamd_http_connection_reset (conn->backend_conn);
			rspamd_http_connection_unref (conn->backend_conn);
			close (conn->backend_sock);
		}

		conn->flags |= RSPAMD_BACKEND_CLOSED;
	}
}

static gboolean
proxy_backend_parse_results (struct rspamd_proxy_session *session,
		struct rspamd_proxy_backend_connection *conn,
		lua_State *L, gint parser_ref,
		const gchar *in, gsize inlen)
{
	struct ucl_parser *parser;
	GString *tb = NULL;
	gint err_idx;

	if (inlen == 0 || in == NULL) {
		return FALSE;
	}

	if (parser_ref != -1) {
		/* Call parser function */
		lua_pushcfunction (L, &rspamd_lua_traceback);
		err_idx = lua_gettop (L);

		lua_rawgeti (L, LUA_REGISTRYINDEX, parser_ref);
		/* XXX: copies all data */
		lua_pushlstring (L, in, inlen);

		if (lua_pcall (L, 1, 1, err_idx) != 0) {
			tb = lua_touserdata (L, -1);
			msg_err_session (
					"cannot run lua parser script: %s",
					tb->str);
			g_string_free (tb, TRUE);
			lua_settop (L, 0);

			return FALSE;
		}

		conn->results = ucl_object_lua_import (L, -1);
		lua_settop (L, 0);
	}
	else {
		parser = ucl_parser_new (0);

		if (!ucl_parser_add_chunk (parser, in, inlen)) {
			msg_err_session ("cannot parse input: %s", ucl_parser_get_error (
					parser));
			ucl_parser_free (parser);

			return FALSE;
		}

		conn->results = ucl_parser_get_object (parser);
		ucl_parser_free (parser);
	}

	return TRUE;
}

static void
proxy_call_cmp_script (struct rspamd_proxy_session *session, gint cbref)
{
	GString *tb = NULL;
	gint err_idx;
	guint i;
	struct rspamd_proxy_backend_connection *conn;
	lua_State *L;

	L = session->ctx->lua_state;
	lua_pushcfunction (L, &rspamd_lua_traceback);
	err_idx = lua_gettop (L);

	lua_rawgeti (L, LUA_REGISTRYINDEX, cbref);

	lua_createtable (L, 0, session->mirror_conns->len + 1);
	/* Now push master results */
	if (session->master_conn && session->master_conn->results) {
		lua_pushstring (L, "master");
		ucl_object_push_lua (L, session->master_conn->results, true);
		lua_settable (L, -3);
	}
	else {
		lua_pushstring (L, "master");
		lua_pushstring (L, "no results");
		lua_settable (L, -3);
	}

	for (i = 0; i < session->mirror_conns->len; i ++) {
		conn = g_ptr_array_index (session->mirror_conns, i);

		if (conn->results) {
			lua_pushstring (L, conn->name);
			ucl_object_push_lua (L, conn->results, true);
			lua_settable (L, -3);
		}
		else {
			lua_pushstring (L, conn->name);
			lua_pushstring (L, conn->err ? conn->err : "unknown error");
			lua_settable (L, -3);
		}
	}

	if (lua_pcall (L, 1, 0, err_idx) != 0) {
		tb = lua_touserdata (L, -1);
		msg_err_session (
				"cannot run lua compare script: %s",
				tb->str);
		g_string_free (tb, TRUE);
	}

	lua_settop (L, 0);
}

static void
proxy_session_dtor (struct rspamd_proxy_session *session)
{
	guint i;
	gint cbref;
	struct rspamd_proxy_backend_connection *conn;

	if (session->master_conn && session->master_conn->results) {
		for (i = 0; i < session->ctx->cmp_refs->len; i++) {
			cbref = g_array_index (session->ctx->cmp_refs, gint, i);
			proxy_call_cmp_script (session, cbref);
		}
	}

	if (session->master_conn) {
		proxy_backend_close_connection (session->master_conn);
	}

	if (session->client_milter_conn) {
		rspamd_milter_session_unref (session->client_milter_conn);
	}
	else if (session->client_conn) {
		rspamd_http_connection_reset (session->client_conn);
		rspamd_http_connection_unref (session->client_conn);
	}

	if (session->map && session->map_len) {
		munmap (session->map, session->map_len);
	}

	for (i = 0; i < session->mirror_conns->len; i ++) {
		conn = g_ptr_array_index (session->mirror_conns, i);

		if (!(conn->flags & RSPAMD_BACKEND_CLOSED)) {
			proxy_backend_close_connection (conn);
		}

		if (conn->results) {
			ucl_object_unref (conn->results);
		}
	}

	if (session->master_conn) {
		if (session->master_conn->results) {
			ucl_object_unref (session->master_conn->results);
		}

		if (session->master_conn->task) {
			rspamd_session_destroy (session->master_conn->task->s);
		}
	}

	g_ptr_array_free (session->mirror_conns, TRUE);
	rspamd_http_message_shmem_unref (session->shmem_ref);
	rspamd_http_message_unref (session->client_message);

	if (session->client_addr) {
		rspamd_inet_address_free (session->client_addr);
	}

	if (session->client_sock != -1) {
		close (session->client_sock);
	}

	if (session->ctx->sessions_cache) {
		rspamd_worker_session_cache_remove (session->ctx->sessions_cache,
				session);
	}

	if (session->pool) {
		rspamd_mempool_delete (session->pool);
	}

	g_slice_free1 (sizeof (*session), session);
}

static void
proxy_request_compress (struct rspamd_http_message *msg)
{
	guint flags;
	ZSTD_CCtx *zctx;
	rspamd_fstring_t *body;
	const gchar *in;
	gsize inlen;

	flags = rspamd_http_message_get_flags (msg);

	if (!rspamd_http_message_find_header (msg, "Compression")) {
		if ((flags & RSPAMD_HTTP_FLAG_SHMEM) ||
				!(flags & RSPAMD_HTTP_FLAG_HAS_BODY)) {
			/* Cannot compress shared or empty message */
			return;
		}

		in = rspamd_http_message_get_body (msg, &inlen);

		if (in == NULL || inlen == 0) {
			return;
		}

		body = rspamd_fstring_sized_new (ZSTD_compressBound (inlen));
		zctx = ZSTD_createCCtx ();
		body->len = ZSTD_compressCCtx (zctx, body->str, body->allocated,
				in, inlen, 1);

		if (ZSTD_isError (body->len)) {
			msg_err ("compression error");
			rspamd_fstring_free (body);
			ZSTD_freeCCtx (zctx);

			return;
		}

		ZSTD_freeCCtx (zctx);
		rspamd_http_message_set_body_from_fstring_steal (msg, body);
		rspamd_http_message_add_header (msg, "Compression", "zstd");
	}
}

static void
proxy_request_decompress (struct rspamd_http_message *msg)
{
	rspamd_fstring_t *body;
	const gchar *in;
	gsize inlen, outlen, r;
	ZSTD_DStream *zstream;
	ZSTD_inBuffer zin;
	ZSTD_outBuffer zout;

	if (rspamd_http_message_find_header (msg, "Compression")) {
		in = rspamd_http_message_get_body (msg, &inlen);

		if (in == NULL || inlen == 0) {
			return;
		}

		zstream = ZSTD_createDStream ();
		ZSTD_initDStream (zstream);

		zin.pos = 0;
		zin.src = in;
		zin.size = inlen;

		if ((outlen = ZSTD_getDecompressedSize (zin.src, zin.size)) == 0) {
			outlen = ZSTD_DStreamOutSize ();
		}

		body = rspamd_fstring_sized_new (outlen);
		zout.dst = body->str;
		zout.pos = 0;
		zout.size = outlen;

		while (zin.pos < zin.size) {
			r = ZSTD_decompressStream (zstream, &zout, &zin);

			if (ZSTD_isError (r)) {
				msg_err ("Decompression error: %s", ZSTD_getErrorName (r));
				ZSTD_freeDStream (zstream);
				rspamd_fstring_free (body);

				return;
			}

			if (zout.pos == zout.size) {
				/* We need to extend output buffer */
				zout.size = zout.size * 1.5 + 1.0;
				body = rspamd_fstring_grow (body, zout.size);
				zout.size = body->allocated;
				zout.dst = body->str;
			}
		}

		body->len = zout.pos;
		ZSTD_freeDStream (zstream);
		rspamd_http_message_set_body_from_fstring_steal (msg, body);
		rspamd_http_message_remove_header (msg, "Compression");
	}

	return;
}

static struct rspamd_proxy_session *
proxy_session_refresh (struct rspamd_proxy_session *session)
{
	struct rspamd_proxy_session *nsession;

	nsession = g_slice_alloc0 (sizeof (*nsession));
	nsession->client_milter_conn = session->client_milter_conn;
	session->client_milter_conn = NULL;
	rspamd_milter_update_userdata (nsession->client_milter_conn,
			nsession);
	nsession->client_addr = session->client_addr;
	session->client_addr = NULL;
	nsession->ctx = session->ctx;
	nsession->worker = session->worker;
	nsession->pool = rspamd_mempool_new (rspamd_mempool_suggest_size (), "proxy");
	nsession->client_sock = session->client_sock;
	session->client_sock = -1;
	nsession->mirror_conns = g_ptr_array_sized_new (nsession->ctx->mirrors->len);

	REF_INIT_RETAIN (nsession, proxy_session_dtor);

	if (nsession->ctx->sessions_cache) {
		rspamd_worker_session_cache_add (nsession->ctx->sessions_cache,
				nsession->pool->tag.uid, &nsession->ref.refcount, nsession);
	}

	return nsession;
}

static gboolean
proxy_check_file (struct rspamd_http_message *msg,
		struct rspamd_proxy_session *session)
{
	const rspamd_ftok_t *tok, *key_tok;
	rspamd_ftok_t srch;
	gchar *file_str;
	GHashTable *query_args;
	GHashTableIter it;
	gpointer k, v;
	struct http_parser_url u;
	rspamd_fstring_t *new_url;

	tok = rspamd_http_message_find_header (msg, "File");

	if (tok) {
		file_str = rspamd_mempool_ftokdup (session->pool, tok);
		session->map = rspamd_file_xmap (file_str, PROT_READ, &session->map_len,
				TRUE);

		if (session->map == NULL) {
			msg_err_session ("cannot map %s: %s", file_str, strerror (errno));

			return FALSE;
		}
		/* Remove header after processing */
		rspamd_http_message_remove_header (msg, "File");
		session->fname = file_str;
	}
	else {
		/* Need to parse query URL */
		if (http_parser_parse_url (msg->url->str, msg->url->len, 0, &u) != 0) {
			msg_err_session ("bad request url: %V", msg->url);

			return FALSE;
		}

		if (u.field_set & (1 << UF_QUERY)) {
			/* In case if we have a query, we need to store it somewhere */
			query_args = rspamd_http_message_parse_query (msg);
			srch.begin = "File";
			srch.len = strlen ("File");
			tok = g_hash_table_lookup (query_args, &srch);

			if (tok) {
				file_str = rspamd_mempool_ftokdup (session->pool, tok);
				session->map = rspamd_file_xmap (file_str, PROT_READ,
						&session->map_len, TRUE);

				if (session->map == NULL) {
					msg_err_session ("cannot map %s: %s", file_str, strerror (errno));
					g_hash_table_unref (query_args);

					return FALSE;
				}

				/* We need to create a new URL with file attribute removed */
				new_url = rspamd_fstring_new_init (msg->url->str,
						u.field_data[UF_QUERY].off);
				new_url = rspamd_fstring_append (new_url, "?", 1);

				g_hash_table_iter_init (&it, query_args);

				while (g_hash_table_iter_next (&it, &k, &v)) {
					key_tok = k;
					tok = v;

					if (!rspamd_ftok_icase_equal (key_tok, &srch)) {
						rspamd_printf_fstring (&new_url, "%T=%T&",
								key_tok, tok);
					}
				}

				/* Erase last character (might be either & or ?) */
				rspamd_fstring_erase (new_url, new_url->len - 1, 1);

				rspamd_fstring_free (msg->url);
				msg->url = new_url;
				session->fname = file_str;
			}

			g_hash_table_unref (query_args);
		}

	}

	return TRUE;
}

static void
proxy_backend_mirror_error_handler (struct rspamd_http_connection *conn, GError *err)
{
	struct rspamd_proxy_backend_connection *bk_conn = conn->ud;
	struct rspamd_proxy_session *session;

	session = bk_conn->s;
	msg_info_session ("abnormally closing connection from backend: %s:%s, "
			"error: %e",
			bk_conn->name,
			rspamd_inet_address_to_string (rspamd_upstream_addr (bk_conn->up)),
			err);

	if (err) {
		bk_conn->err = rspamd_mempool_strdup (session->pool, err->message);
	}

	rspamd_upstream_fail (bk_conn->up);

	proxy_backend_close_connection (bk_conn);
	REF_RELEASE (bk_conn->s);
}

static gint
proxy_backend_mirror_finish_handler (struct rspamd_http_connection *conn,
	struct rspamd_http_message *msg)
{
	struct rspamd_proxy_backend_connection *bk_conn = conn->ud;
	struct rspamd_proxy_session *session;

	session = bk_conn->s;

	proxy_request_decompress (msg);

	if (!proxy_backend_parse_results (session, bk_conn, session->ctx->lua_state,
			bk_conn->parser_from_ref, msg->body_buf.begin, msg->body_buf.len)) {
		msg_warn_session ("cannot parse results from the mirror backend %s:%s",
				bk_conn->name,
				rspamd_inet_address_to_string (rspamd_upstream_addr (bk_conn->up)));
		bk_conn->err = "cannot parse ucl";
	}

	msg_info_session ("finished mirror connection to %s", bk_conn->name);
	rspamd_upstream_ok (bk_conn->up);

	proxy_backend_close_connection (bk_conn);
	REF_RELEASE (bk_conn->s);

	return 0;
}

static void
proxy_open_mirror_connections (struct rspamd_proxy_session *session)
{
	gdouble coin;
	struct rspamd_http_mirror *m;
	guint i;
	struct rspamd_proxy_backend_connection *bk_conn;
	struct rspamd_http_message *msg;

	coin = rspamd_random_double ();

	for (i = 0; i < session->ctx->mirrors->len; i ++) {
		m = g_ptr_array_index (session->ctx->mirrors, i);

		if (m->prob < coin) {
			/* No luck */
			continue;
		}

		bk_conn = rspamd_mempool_alloc0 (session->pool,
				sizeof (*bk_conn));
		bk_conn->s = session;
		bk_conn->name = m->name;
		bk_conn->io_tv = &m->io_tv;

		bk_conn->up = rspamd_upstream_get (m->u,
				RSPAMD_UPSTREAM_ROUND_ROBIN, NULL, 0);
		bk_conn->parser_from_ref = m->parser_from_ref;
		bk_conn->parser_to_ref = m->parser_to_ref;

		if (bk_conn->up == NULL) {
			msg_err_session ("cannot select upstream for %s", m->name);
			continue;
		}

		bk_conn->backend_sock = rspamd_inet_address_connect (
				rspamd_upstream_addr (bk_conn->up),
				SOCK_STREAM, TRUE);

		if (bk_conn->backend_sock == -1) {
			msg_err_session ("cannot connect upstream for %s", m->name);
			rspamd_upstream_fail (bk_conn->up);
			continue;
		}

		msg = rspamd_http_connection_copy_msg (session->client_message);

		if (msg == NULL) {
			msg_err_session ("cannot copy message to send to a mirror %s: %s",
					m->name, strerror (errno));
			continue;
		}

		msg->method = HTTP_GET;

		if (msg->url->len == 0) {
			msg->url = rspamd_fstring_append (msg->url, "/check", strlen ("/check"));
		}

		if (m->settings_id != NULL) {
			rspamd_http_message_remove_header (msg, "Settings-ID");
			rspamd_http_message_add_header (msg, "Settings-ID", m->settings_id);
		}

		bk_conn->backend_conn = rspamd_http_connection_new (NULL,
				proxy_backend_mirror_error_handler,
				proxy_backend_mirror_finish_handler,
				RSPAMD_HTTP_CLIENT_SIMPLE,
				RSPAMD_HTTP_CLIENT,
				session->ctx->keys_cache,
				NULL);

		if (m->key) {
			rspamd_http_connection_set_key (bk_conn->backend_conn,
					session->ctx->local_key);
			msg->peer_key = rspamd_pubkey_ref (m->key);
		}

		if (m->local ||
				rspamd_inet_address_is_local (
						rspamd_upstream_addr (bk_conn->up), FALSE)) {

			if (session->fname) {
				rspamd_http_message_add_header (msg, "File", session->fname);
			}

			rspamd_http_connection_write_message_shared (bk_conn->backend_conn,
					msg, NULL, NULL, bk_conn,
					bk_conn->backend_sock,
					bk_conn->io_tv, session->ctx->ev_base);
		}
		else {
			if (session->fname) {
				rspamd_http_message_set_body (msg, session->map, session->map_len);
			}

			if (m->compress) {
				proxy_request_compress (msg);

				if (session->client_milter_conn) {
					rspamd_http_message_add_header (msg, "Content-Type",
							"application/octet-stream");
				}
			}
			else {
				if (session->client_milter_conn) {
					rspamd_http_message_add_header (msg, "Content-Type",
							"text/plain");
				}
			}

			rspamd_http_connection_write_message (bk_conn->backend_conn,
					msg, NULL, NULL, bk_conn,
					bk_conn->backend_sock,
					bk_conn->io_tv, session->ctx->ev_base);
		}

		g_ptr_array_add (session->mirror_conns, bk_conn);
		REF_RETAIN (session);
		msg_info_session ("send request to %s", m->name);
	}
}

static void
proxy_client_write_error (struct rspamd_proxy_session *session, gint code,
		const gchar *status)
{
	struct rspamd_http_message *reply;

	if (session->client_milter_conn) {
		rspamd_milter_send_action (session->client_milter_conn,
				RSPAMD_MILTER_TEMPFAIL);
		REF_RELEASE (session);
	}
	else {
		reply = rspamd_http_new_message (HTTP_RESPONSE);
		reply->code = code;
		reply->status = rspamd_fstring_new_init (status, strlen (status));
		rspamd_http_connection_write_message (session->client_conn,
				reply, NULL, NULL, session, session->client_sock,
				&session->ctx->io_tv, session->ctx->ev_base);
	}
}

static void
proxy_backend_master_error_handler (struct rspamd_http_connection *conn, GError *err)
{
	struct rspamd_proxy_backend_connection *bk_conn = conn->ud;
	struct rspamd_proxy_session *session;

	session = bk_conn->s;
	msg_info_session ("abnormally closing connection from backend: %s, error: %s,"
			" retries left: %d",
		rspamd_inet_address_to_string (rspamd_upstream_addr (session->master_conn->up)),
		err->message,
		session->ctx->max_retries - session->retries);
	session->retries ++;
	rspamd_upstream_fail (bk_conn->up);
	proxy_backend_close_connection (session->master_conn);

	if (session->ctx->max_retries &&
			session->retries > session->ctx->max_retries) {
		msg_err_session ("cannot connect to upstream, maximum retries "
				"has been reached: %d", session->retries);
		/* Terminate session immediately */
		proxy_client_write_error (session, err->code, err->message);
	}
	else {
		if (!proxy_send_master_message (session)) {
			proxy_client_write_error (session, err->code, err->message);
		}
		else {
			msg_info_session ("retry connection to: %s"
					" retries left: %d",
					rspamd_inet_address_to_string (
							rspamd_upstream_addr (session->master_conn->up)),
					session->ctx->max_retries - session->retries);
		}
	}
}

static gint
proxy_backend_master_finish_handler (struct rspamd_http_connection *conn,
	struct rspamd_http_message *msg)
{
	struct rspamd_proxy_backend_connection *bk_conn = conn->ud;
	struct rspamd_proxy_session *session, *nsession;
	rspamd_fstring_t *reply;

	session = bk_conn->s;
	rspamd_http_connection_steal_msg (session->master_conn->backend_conn);
	proxy_request_decompress (msg);

	rspamd_http_message_remove_header (msg, "Content-Length");
	rspamd_http_message_remove_header (msg, "Key");
	rspamd_http_connection_reset (session->master_conn->backend_conn);

	if (!proxy_backend_parse_results (session, bk_conn, session->ctx->lua_state,
			bk_conn->parser_from_ref, msg->body_buf.begin, msg->body_buf.len)) {
		msg_warn_session ("cannot parse results from the master backend");
	}


	if (session->legacy_support > LEGACY_SUPPORT_NO) {
		/* We need to reformat ucl to fit with legacy spamc protocol */
		if (bk_conn->results) {
			reply = rspamd_fstring_new ();

			if (session->legacy_support == LEGACY_SUPPORT_SPAMC) {
				rspamd_ucl_tospamc_output (bk_conn->results, &reply);
				msg->flags |= RSPAMD_HTTP_FLAG_SPAMC;
			}
			else {
				rspamd_ucl_torspamc_output (bk_conn->results, &reply);
			}

			rspamd_http_message_set_body_from_fstring_steal (msg, reply);
			msg->method = HTTP_SYMBOLS;
		}
		else {
			msg_warn_session ("cannot parse results from the master backend, "
					"return them as is");
		}
	}

	rspamd_upstream_ok (bk_conn->up);

	if (session->client_milter_conn) {
		nsession = proxy_session_refresh (session);
		rspamd_milter_send_task_results (nsession->client_milter_conn,
				session->master_conn->results);
		REF_RELEASE (session);
		rspamd_http_message_free (msg);
	}
	else {
		rspamd_http_connection_write_message (session->client_conn,
				msg, NULL, NULL, session, session->client_sock,
				bk_conn->io_tv, session->ctx->ev_base);
	}

	return 0;
}

static void
rspamd_proxy_scan_self_reply (struct rspamd_task *task)
{
	struct rspamd_http_message *msg;
	struct rspamd_proxy_session *session = task->fin_arg, *nsession;
	ucl_object_t *rep = NULL;
	const char *ctype = "application/json";

	msg = rspamd_http_new_message (HTTP_RESPONSE);
	msg->date = time (NULL);
	msg->code = 200;

	switch (task->cmd) {
	case CMD_REPORT_IFSPAM:
	case CMD_REPORT:
	case CMD_CHECK:
	case CMD_SYMBOLS:
	case CMD_PROCESS:
	case CMD_SKIP:
	case CMD_CHECK_V2:
		rspamd_protocol_http_reply (msg, task, &rep);
		rspamd_protocol_write_log_pipe (task);
		break;
	case CMD_PING:
		rspamd_http_message_set_body (msg, "pong" CRLF, 6);
		ctype = "text/plain";
		break;
	case CMD_OTHER:
		msg_err_task ("BROKEN");
		break;
	}

	session->master_conn->flags |= RSPAMD_BACKEND_CLOSED;

	if (rep) {
		session->master_conn->results = ucl_object_ref (rep);
	}

	if (session->client_milter_conn) {
		nsession = proxy_session_refresh (session);
		rspamd_milter_send_task_results (nsession->client_milter_conn,
				session->master_conn->results);
		rspamd_http_message_free (msg);
		REF_RELEASE (session);
	}
	else {
		rspamd_http_connection_reset (session->client_conn);
		rspamd_http_connection_write_message (session->client_conn,
				msg,
				NULL,
				ctype,
				session,
				session->client_sock,
				NULL,
				session->ctx->ev_base);
	}
}

static gboolean
rspamd_proxy_task_fin (void *ud)
{
	struct rspamd_task *task = ud;

	msg_debug_task ("finish task");

	if (RSPAMD_TASK_IS_PROCESSED (task)) {
		rspamd_proxy_scan_self_reply (task);
		return TRUE;
	}

	if (!rspamd_task_process (task, RSPAMD_TASK_PROCESS_ALL)) {
		rspamd_proxy_scan_self_reply (task);
		return TRUE;
	}

	if (RSPAMD_TASK_IS_PROCESSED (task)) {
		rspamd_proxy_scan_self_reply (task);
		return TRUE;
	}

	/* One more iteration */
	return FALSE;
}

static gboolean
rspamd_proxy_self_scan (struct rspamd_proxy_session *session)
{
	struct rspamd_task *task;
	struct rspamd_http_message *msg;
	const gchar *data;
	gsize len;

	msg = session->client_message;
	task = rspamd_task_new (session->worker, session->ctx->cfg,
			session->pool);
	task->flags |= RSPAMD_TASK_FLAG_MIME;
	task->sock = -1;

	if (session->client_milter_conn) {
		task->client_addr = rspamd_inet_address_copy (
				session->client_milter_conn->addr);
	}
	else {
		task->client_addr = rspamd_inet_address_copy (session->client_addr);
	}

	task->fin_arg = session;
	task->resolver = session->ctx->resolver;
	/* TODO: allow to disable autolearn in protocol */
	task->flags |= RSPAMD_TASK_FLAG_LEARN_AUTO;
	task->ev_base = session->ctx->ev_base;
	task->s = rspamd_session_create (task->task_pool, rspamd_proxy_task_fin,
			NULL, (event_finalizer_t )rspamd_task_free, task);
	data = rspamd_http_message_get_body (msg, &len);

	/* Process message */
	if (!rspamd_protocol_handle_request (task, msg)) {
		msg_err_task ("cannot handle request: %e", task->err);
		task->flags |= RSPAMD_TASK_FLAG_SKIP;
	}
	else {
		if (task->cmd == CMD_PING) {
			task->flags |= RSPAMD_TASK_FLAG_SKIP;
		}
		else {
			if (!rspamd_task_load_message (task, msg, data, len)) {
				msg_err_task ("cannot load message: %e", task->err);
				task->flags |= RSPAMD_TASK_FLAG_SKIP;
			}
		}
	}

	/* Set global timeout for the task */
	if (session->ctx->default_upstream->timeout > 0.0) {
		struct timeval task_tv;

		event_set (&task->timeout_ev, -1, EV_TIMEOUT, rspamd_task_timeout,
				task);
		event_base_set (session->ctx->ev_base, &task->timeout_ev);
		double_to_tv (session->ctx->default_upstream->timeout, &task_tv);
		event_add (&task->timeout_ev, &task_tv);
	}

	session->master_conn->task = task;
	rspamd_task_process (task, RSPAMD_TASK_PROCESS_ALL);

	rspamd_session_pending (task->s);

	return TRUE;
}

static gboolean
proxy_send_master_message (struct rspamd_proxy_session *session)
{
	struct rspamd_http_message *msg;
	struct rspamd_http_upstream *backend = NULL;
	const rspamd_ftok_t *host;
	gchar hostbuf[512];

	host = rspamd_http_message_find_header (session->client_message, "Host");

	if (host == NULL) {
		backend = session->ctx->default_upstream;
	}
	else {
		rspamd_strlcpy (hostbuf, host->begin, MIN(host->len + 1, sizeof (hostbuf)));
		backend = g_hash_table_lookup (session->ctx->upstreams, hostbuf);

		if (backend == NULL) {
			backend = session->ctx->default_upstream;
		}
	}

	if (backend == NULL) {
		/* No backend */
		msg_err_session ("cannot find upstream for %s", host ? hostbuf : "default");
		goto err;
	}
	else {
		if (backend->self_scan) {
			return rspamd_proxy_self_scan (session);
		}
retry:
		if (session->ctx->max_retries &&
				session->retries > session->ctx->max_retries) {
			msg_err_session ("cannot connect to upstream, maximum retries "
					"has been reached: %d", session->retries);
			goto err;
		}

		session->master_conn->up = rspamd_upstream_get (backend->u,
				RSPAMD_UPSTREAM_ROUND_ROBIN, NULL, 0);
		session->master_conn->io_tv = &backend->io_tv;

		if (session->master_conn->up == NULL) {
			msg_err_session ("cannot select upstream for %s",
					host ? hostbuf : "default");
			goto err;
		}

		session->master_conn->backend_sock = rspamd_inet_address_connect (
				rspamd_upstream_addr (session->master_conn->up),
				SOCK_STREAM, TRUE);

		if (session->master_conn->backend_sock == -1) {
			msg_err_session ("cannot connect upstream: %s(%s)",
					host ? hostbuf : "default",
							rspamd_inet_address_to_string (rspamd_upstream_addr (
									session->master_conn->up)));
			rspamd_upstream_fail (session->master_conn->up);
			session->retries ++;
			goto retry;
		}

		session->master_conn->backend_conn = rspamd_http_connection_new (
				NULL,
				proxy_backend_master_error_handler,
				proxy_backend_master_finish_handler,
				RSPAMD_HTTP_CLIENT_SIMPLE,
				RSPAMD_HTTP_CLIENT,
				session->ctx->keys_cache,
				NULL);
		session->master_conn->flags &= ~RSPAMD_BACKEND_CLOSED;
		session->master_conn->parser_from_ref = backend->parser_from_ref;
		session->master_conn->parser_to_ref = backend->parser_to_ref;

		msg = rspamd_http_connection_copy_msg (session->client_message);

		if (backend->key) {
			msg->peer_key = rspamd_pubkey_ref (backend->key);
			rspamd_http_connection_set_key (session->master_conn->backend_conn,
					session->ctx->local_key);
		}

		if (backend->local ||
				rspamd_inet_address_is_local (
						rspamd_upstream_addr (session->master_conn->up), FALSE)) {

			if (session->fname) {
				rspamd_http_message_add_header (msg, "File", session->fname);
			}

			rspamd_http_connection_write_message_shared (
					session->master_conn->backend_conn,
					msg, NULL, NULL, session->master_conn,
					session->master_conn->backend_sock,
					session->master_conn->io_tv, session->ctx->ev_base);
		}
		else {
			if (session->fname) {
				rspamd_http_message_set_body (msg,
						session->map, session->map_len);
			}

			if (backend->compress) {
				proxy_request_compress (msg);
				if (session->client_milter_conn) {
					rspamd_http_message_add_header (msg, "Content-Type",
							"application/octet-stream");
				}
			}
			else {
				if (session->client_milter_conn) {
					rspamd_http_message_add_header (msg, "Content-Type",
							"text/plain");
				}
			}

			rspamd_http_connection_write_message (
					session->master_conn->backend_conn,
					msg, NULL, NULL, session->master_conn,
					session->master_conn->backend_sock,
					session->master_conn->io_tv, session->ctx->ev_base);
		}
	}

	return TRUE;

err:
	if (session->client_milter_conn) {
		rspamd_milter_send_action (session->client_milter_conn,
				RSPAMD_MILTER_TEMPFAIL);
		REF_RELEASE (session);
	}
	else {
		rspamd_http_connection_steal_msg (session->client_conn);
		rspamd_http_connection_reset (session->client_conn);
		proxy_client_write_error (session, 404, "Backend not found");
	}

	return FALSE;
}

static void
proxy_client_error_handler (struct rspamd_http_connection *conn, GError *err)
{
	struct rspamd_proxy_session *session = conn->ud;

	msg_info_session ("abnormally closing connection from: %s, error: %s",
		rspamd_inet_address_to_string (session->client_addr), err->message);
	/* Terminate session immediately */
	proxy_backend_close_connection (session->master_conn);
	REF_RELEASE (session);
}

static gint
proxy_client_finish_handler (struct rspamd_http_connection *conn,
	struct rspamd_http_message *msg)
{
	struct rspamd_proxy_session *session = conn->ud;

	if (!session->master_conn) {
		session->master_conn = rspamd_mempool_alloc0 (session->pool,
				sizeof (*session->master_conn));
		session->master_conn->s = session;
		session->master_conn->name = "master";

		/* Reset spamc legacy */
		if (msg->method >= HTTP_SYMBOLS) {
			msg->method = HTTP_GET;

			if (msg->flags & RSPAMD_HTTP_FLAG_SPAMC) {
				session->legacy_support = LEGACY_SUPPORT_SPAMC;
			}
			else {
				session->legacy_support = LEGACY_SUPPORT_SPAMC;
			}

			msg_info_session ("enabling legacy rspamc mode for session");
		}

		if (msg->url->len == 0) {
			msg->url = rspamd_fstring_append (msg->url, "/check", strlen ("/check"));
		}

		if (!proxy_check_file (msg, session)) {
			goto err;
		}

		session->client_message = rspamd_http_connection_steal_msg (
				session->client_conn);
		session->shmem_ref = rspamd_http_message_shmem_ref (session->client_message);
		rspamd_http_message_remove_header (msg, "Content-Length");
		rspamd_http_message_remove_header (msg, "Key");

		proxy_open_mirror_connections (session);
		rspamd_http_connection_reset (session->client_conn);

		proxy_send_master_message (session);
	}
	else {
		msg_info_session ("finished master connection");
		proxy_backend_close_connection (session->master_conn);
		REF_RELEASE (session);
	}

	return 0;

err:
	rspamd_http_connection_steal_msg (session->client_conn);
	rspamd_http_message_remove_header (msg, "Content-Length");
	rspamd_http_message_remove_header (msg, "Key");
	rspamd_http_connection_reset (session->client_conn);
	proxy_client_write_error (session, 404, "Backend not found");

	return 0;
}

static void
proxy_milter_finish_handler (gint fd,
		struct rspamd_milter_session *rms,
		void *ud)
{
	struct rspamd_proxy_session *session = ud;
	struct rspamd_http_message *msg;

	session->client_milter_conn = rms;

	if (rms->message == NULL || rms->message->len == 0) {
		msg_info_session ("finished milter connection");
		proxy_backend_close_connection (session->master_conn);
		REF_RELEASE (session);
	}
	else {
		if (!session->master_conn) {
			session->master_conn = rspamd_mempool_alloc0 (session->pool,
					sizeof (*session->master_conn));
		}

		msg = rspamd_milter_to_http (rms);
		session->master_conn->s = session;
		session->master_conn->name = "master";
		session->client_message = msg;

		proxy_open_mirror_connections (session);
		proxy_send_master_message (session);
	}
}

static void
proxy_milter_error_handler (gint fd,
		struct rspamd_milter_session *rms,
		void *ud, GError *err)
{
	struct rspamd_proxy_session *session = ud;

	msg_info_session ("abnormally closing milter connection from: %s, "
			"error: %s", rspamd_inet_address_to_string (session->client_addr),
			err->message);
	/* Terminate session immediately */
	proxy_backend_close_connection (session->master_conn);
	REF_RELEASE (session);
}

static void
proxy_accept_socket (gint fd, short what, void *arg)
{
	struct rspamd_worker *worker = (struct rspamd_worker *) arg;
	struct rspamd_proxy_ctx *ctx;
	rspamd_inet_addr_t *addr;
	struct rspamd_proxy_session *session;
	gint nfd;

	ctx = worker->ctx;

	if ((nfd =
		rspamd_accept_from_socket (fd, &addr, worker->accept_events)) == -1) {
		msg_warn ("accept failed: %s", strerror (errno));
		return;
	}
	/* Check for EAGAIN */
	if (nfd == 0) {
		return;
	}

	session = g_slice_alloc0 (sizeof (*session));
	REF_INIT_RETAIN (session, proxy_session_dtor);
	session->client_sock = nfd;
	session->client_addr = addr;
	session->mirror_conns = g_ptr_array_sized_new (ctx->mirrors->len);

	session->pool = rspamd_mempool_new (rspamd_mempool_suggest_size (),
			"proxy");
	session->ctx = ctx;
	session->worker = worker;

	if (ctx->sessions_cache) {
		rspamd_worker_session_cache_add (ctx->sessions_cache,
				session->pool->tag.uid, &session->ref.refcount, session);
	}

	if (!ctx->milter) {
		session->client_conn = rspamd_http_connection_new (NULL,
				proxy_client_error_handler,
				proxy_client_finish_handler,
				0,
				RSPAMD_HTTP_SERVER,
				ctx->keys_cache,
				NULL);

		if (ctx->key) {
			rspamd_http_connection_set_key (session->client_conn, ctx->key);
		}

		msg_info_session ("accepted http connection from %s port %d",
				rspamd_inet_address_to_string (addr),
				rspamd_inet_address_get_port (addr));

		rspamd_http_connection_read_message_shared (session->client_conn,
				session,
				nfd,
				&ctx->io_tv,
				ctx->ev_base);
	}
	else {
		msg_info_session ("accepted milter connection from %s port %d",
				rspamd_inet_address_to_string (addr),
				rspamd_inet_address_get_port (addr));

		rspamd_milter_handle_socket (nfd, NULL,
				session->pool,
				ctx->ev_base,
				proxy_milter_finish_handler,
				proxy_milter_error_handler,
				session);
	}
}

static void
proxy_rotate_key (gint fd, short what, void *arg)
{
	struct timeval rot_tv;
	struct rspamd_proxy_ctx *ctx = arg;
	gpointer kp;

	double_to_tv (ctx->rotate_tm, &rot_tv);
	rot_tv.tv_sec += ottery_rand_range (rot_tv.tv_sec);
	event_del (&ctx->rotate_ev);
	event_add (&ctx->rotate_ev, &rot_tv);

	kp = ctx->local_key;
	ctx->local_key = rspamd_keypair_new (RSPAMD_KEYPAIR_KEX,
			RSPAMD_CRYPTOBOX_MODE_25519);
	rspamd_keypair_unref (kp);
}

void
start_rspamd_proxy (struct rspamd_worker *worker) {
	struct rspamd_proxy_ctx *ctx = worker->ctx;
	struct timeval rot_tv;

	ctx->cfg = worker->srv->cfg;
	ctx->ev_base = rspamd_prepare_worker (worker, "rspamd_proxy",
			proxy_accept_socket);

	ctx->resolver = dns_resolver_init (worker->srv->logger,
			ctx->ev_base,
			worker->srv->cfg);
	double_to_tv (ctx->timeout, &ctx->io_tv);
	rspamd_map_watch (worker->srv->cfg, ctx->ev_base, ctx->resolver, 0);

	rspamd_upstreams_library_config (worker->srv->cfg, ctx->cfg->ups_ctx,
			ctx->ev_base, ctx->resolver->r);

	/* XXX: stupid default */
	ctx->keys_cache = rspamd_keypair_cache_new (256);
	ctx->local_key = rspamd_keypair_new (RSPAMD_KEYPAIR_KEX,
			RSPAMD_CRYPTOBOX_MODE_25519);

	double_to_tv (ctx->rotate_tm, &rot_tv);
	rot_tv.tv_sec += ottery_rand_range (rot_tv.tv_sec);
	event_set (&ctx->rotate_ev, -1, EV_TIMEOUT, proxy_rotate_key, ctx);
	event_base_set (ctx->ev_base, &ctx->rotate_ev);
	event_add (&ctx->rotate_ev, &rot_tv);

	if (ctx->has_self_scan) {
		/* Additional initialisation needed */
		rspamd_worker_init_scanner (worker, ctx->ev_base, ctx->resolver);
	}

	if (worker->srv->cfg->enable_sessions_cache) {
		ctx->sessions_cache = rspamd_worker_session_cache_new (worker,
				ctx->ev_base);
	}

	rspamd_milter_init_library (ctx->spam_header, ctx->sessions_cache,
			ctx->discard_on_reject);
	rspamd_lua_run_postloads (ctx->cfg->lua_state, ctx->cfg, ctx->ev_base,
			worker);

	event_base_loop (ctx->ev_base, 0);
	rspamd_worker_block_signals ();

	rspamd_log_close (worker->srv->logger);

	if (ctx->has_self_scan) {
		rspamd_stat_close ();
	}

	rspamd_keypair_cache_destroy (ctx->keys_cache);
	REF_RELEASE (ctx->cfg);

	exit (EXIT_SUCCESS);
}