-
-
Notifications
You must be signed in to change notification settings - Fork 478
Expand file tree
/
Copy pathrspamd_proxy.c
More file actions
3556 lines (3010 loc) · 99.9 KB
/
Copy pathrspamd_proxy.c
File metadata and controls
3556 lines (3010 loc) · 99.9 KB
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
/*
* 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 "config.h"
#include "libutil/util.h"
#include "libserver/maps/map.h"
#include "libutil/upstream.h"
#include "libserver/http/http_connection.h"
#include "libserver/http/http_private.h"
#include "libserver/protocol.h"
#include "libserver/protocol_internal.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 "libserver/ssl_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 "libserver/milter_internal.h"
#include "libmime/lang_detection.h"
#include "libmime/content_type.h"
#include "libserver/multipart_form.h"
#include <math.h>
#include <string.h>
#ifdef HAVE_NETINET_TCP_H
#include <netinet/tcp.h> /* for TCP_NODELAY */
#endif
#ifdef SYS_ZSTD
#include "zstd.h"
#else
#include "contrib/zstd/zstd.h"
#endif
/* 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, \
RSPAMD_LOG_FUNC, \
__VA_ARGS__)
#define msg_warn_session(...) rspamd_default_log_function(G_LOG_LEVEL_WARNING, \
session->pool->tag.tagname, session->pool->tag.uid, \
RSPAMD_LOG_FUNC, \
__VA_ARGS__)
#define msg_info_session(...) rspamd_default_log_function(G_LOG_LEVEL_INFO, \
session->pool->tag.tagname, session->pool->tag.uid, \
RSPAMD_LOG_FUNC, \
__VA_ARGS__)
#define msg_debug_session(...) rspamd_conditional_debug_fast(NULL, session->client_addr, \
rspamd_proxy_log_id, "proxy", session->pool->tag.uid, \
RSPAMD_LOG_FUNC, \
__VA_ARGS__)
INIT_LOG_MODULE(proxy)
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_SCANNER,
RSPAMD_WORKER_SOCKET_TCP, /* TCP socket */
RSPAMD_WORKER_VER};
enum rspamd_proxy_log_tag_type {
RSPAMD_PROXY_LOG_TAG_SESSION = 0, /* Use session mempool tag (default) */
RSPAMD_PROXY_LOG_TAG_QUEUE_ID, /* Use Queue-ID from client message */
RSPAMD_PROXY_LOG_TAG_NONE, /* Skip log tag passing */
};
struct rspamd_http_upstream {
char *name;
char *settings_id;
struct upstream_list *u;
struct rspamd_cryptobox_pubkey *key;
double timeout;
int parser_from_ref;
int parser_to_ref;
gboolean local;
gboolean self_scan;
gboolean compress;
gboolean ssl;
gboolean keepalive; /* Whether to use keepalive for this upstream */
enum rspamd_proxy_log_tag_type log_tag_type;
ucl_object_t *extra_headers;
};
struct rspamd_http_mirror {
char *name;
char *settings_id;
struct upstream_list *u;
struct rspamd_cryptobox_pubkey *key;
double prob;
double timeout;
int parser_from_ref;
int parser_to_ref;
gboolean local;
gboolean compress;
gboolean ssl;
gboolean keepalive; /* Whether to use keepalive for this mirror */
gboolean follow_master; /* Tie mirror lifetime to master upstream */
enum rspamd_proxy_log_tag_type log_tag_type;
ucl_object_t *extra_headers;
};
static const uint64_t rspamd_rspamd_proxy_magic = 0xcdeb4fd1fc351980ULL;
struct rspamd_proxy_ctx {
uint64_t magic;
/* Events base */
struct ev_loop *event_loop;
/* DNS resolver */
struct rspamd_dns_resolver *resolver;
/* Config */
struct rspamd_config *cfg;
/* END OF COMMON PART */
double timeout;
/* Encryption key for clients */
struct rspamd_cryptobox_keypair *key;
/* HTTP context */
struct rspamd_http_context *http_ctx;
/* Upstreams to use */
GHashTable *upstreams;
/* Mirrors to send traffic to */
GPtrArray *mirrors;
/* Default upstream */
struct rspamd_http_upstream *default_upstream;
lua_State *lua_state;
/* Array of callback functions called on end of scan to compare results */
GArray *cmp_refs;
/* Maximum count for retries */
unsigned int max_retries;
gboolean encrypted_only;
/* 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;
/* Quarantine messages instead of rejecting them */
gboolean quarantine_on_reject;
/* Milter spam header */
char *spam_header;
/* CA name that can be used for client certificates */
char *client_ca_name;
/* Milter messages */
char *reject_message;
char *quarantine_message;
char *tempfail_message;
/* Sessions cache */
void *sessions_cache;
struct rspamd_milter_context milter_ctx;
/* Language detector */
struct rspamd_lang_detector *lang_det;
double task_timeout;
/* Default log tag type for worker */
enum rspamd_proxy_log_tag_type log_tag_type;
struct rspamd_main *srv;
/* SSL cert */
char *ssl_cert;
/* SSL private key */
char *ssl_key;
/* Server SSL context */
gpointer server_ssl_ctx;
};
enum rspamd_backend_flags {
RSPAMD_BACKEND_REPLIED = 1 << 0,
RSPAMD_BACKEND_CLOSED = 1 << 1,
RSPAMD_BACKEND_PARSED = 1 << 2,
RSPAMD_BACKEND_FOLLOW_MASTER = 1 << 3,
};
struct rspamd_proxy_session;
struct rspamd_proxy_backend_connection {
const char *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 char *err;
struct rspamd_proxy_session *s;
int backend_sock;
ev_tstamp timeout;
enum rspamd_backend_flags flags;
int parser_from_ref;
int parser_to_ref;
struct rspamd_task *task;
gsize reserved_tokens; /* Tokens reserved for this request (token bucket) */
const char *body_data; /* Extracted body from multipart response */
gsize body_len;
};
enum rspamd_proxy_legacy_support {
LEGACY_SUPPORT_NO = 0,
LEGACY_SUPPORT_RSPAMC,
LEGACY_SUPPORT_SPAMC
};
enum rspamd_proxy_session_flags {
RSPAMD_PROXY_SESSION_FLAG_USE_KEEPALIVE = 1 << 0,
RSPAMD_PROXY_SESSION_FLAG_CLIENT_SUPPORTS_COMPRESSION = 1 << 1,
};
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;
struct rspamd_http_upstream *backend;
gpointer map;
char *fname;
gpointer shmem_ref;
struct rspamd_proxy_backend_connection *master_conn;
struct rspamd_http_message *client_message;
GPtrArray *mirror_conns;
gsize map_len;
int client_sock;
enum rspamd_proxy_legacy_support legacy_support;
int retries;
ref_entry_t ref;
enum rspamd_proxy_session_flags flags;
/* ESMTP arguments from milter session */
GHashTable *mail_esmtp_args;
GPtrArray *rcpt_esmtp_args;
};
static gboolean proxy_send_master_message(struct rspamd_proxy_session *session);
static void
proxy_add_client_ip_header(struct rspamd_http_message *msg,
struct rspamd_proxy_session *session)
{
const rspamd_ftok_t *existing_ip_hdr = NULL;
/* Check if the client message already has an IP header (from another proxy in the chain) */
if (session->client_message) {
existing_ip_hdr = rspamd_http_message_find_header(session->client_message, IP_ADDR_HEADER);
}
/* Add/overwrite IP header with the actual client IP */
rspamd_http_message_remove_header(msg, IP_ADDR_HEADER);
if (session->client_milter_conn && session->client_milter_conn->addr) {
/* For milter connections, use the address from the CONNECT command */
if (rspamd_inet_address_get_af(session->client_milter_conn->addr) != AF_UNIX) {
rspamd_http_message_add_header(msg, IP_ADDR_HEADER,
rspamd_inet_address_to_string_pretty(session->client_milter_conn->addr));
}
else {
rspamd_http_message_add_header(msg, IP_ADDR_HEADER,
rspamd_inet_address_to_string(session->client_milter_conn->addr));
}
}
else if (existing_ip_hdr) {
/* Preserve IP header from upstream proxy in the chain */
rspamd_http_message_add_header_len(msg, IP_ADDR_HEADER,
existing_ip_hdr->begin, existing_ip_hdr->len);
}
else if (session->client_addr) {
/* For direct HTTP connections, use the client address */
if (rspamd_inet_address_get_af(session->client_addr) != AF_UNIX) {
rspamd_http_message_add_header(msg, IP_ADDR_HEADER,
rspamd_inet_address_to_string_pretty(session->client_addr));
}
else {
rspamd_http_message_add_header(msg, IP_ADDR_HEADER,
rspamd_inet_address_to_string(session->client_addr));
}
}
}
static GQuark
rspamd_proxy_quark(void)
{
return g_quark_from_static_string("rspamd-proxy");
}
static enum rspamd_proxy_log_tag_type
rspamd_proxy_parse_log_tag_type(const char *str)
{
if (str == NULL) {
return RSPAMD_PROXY_LOG_TAG_SESSION;
}
if (g_ascii_strcasecmp(str, "session") == 0 ||
g_ascii_strcasecmp(str, "session_tag") == 0) {
return RSPAMD_PROXY_LOG_TAG_SESSION;
}
else if (g_ascii_strcasecmp(str, "queue_id") == 0 ||
g_ascii_strcasecmp(str, "queue-id") == 0) {
return RSPAMD_PROXY_LOG_TAG_QUEUE_ID;
}
else if (g_ascii_strcasecmp(str, "none") == 0 ||
g_ascii_strcasecmp(str, "skip") == 0) {
return RSPAMD_PROXY_LOG_TAG_NONE;
}
/* Default to session tag for unknown values */
return RSPAMD_PROXY_LOG_TAG_SESSION;
}
static void
rspamd_proxy_add_log_tag_header(struct rspamd_http_message *msg,
struct rspamd_proxy_session *session,
enum rspamd_proxy_log_tag_type log_tag_type)
{
const rspamd_ftok_t *queue_id_hdr;
switch (log_tag_type) {
case RSPAMD_PROXY_LOG_TAG_SESSION:
/* Use session mempool tag (current behavior) */
rspamd_http_message_add_header_len(msg, LOG_TAG_HEADER, session->pool->tag.uid,
strnlen(session->pool->tag.uid, sizeof(session->pool->tag.uid)));
break;
case RSPAMD_PROXY_LOG_TAG_QUEUE_ID:
/* Try to extract Queue-ID from client message */
if (session->client_message) {
queue_id_hdr = rspamd_http_message_find_header(session->client_message, QUEUE_ID_HEADER);
if (queue_id_hdr) {
rspamd_http_message_add_header_len(msg, LOG_TAG_HEADER,
queue_id_hdr->begin, queue_id_hdr->len);
}
/* If no Queue-ID found, fall back to session tag */
else {
rspamd_http_message_add_header_len(msg, LOG_TAG_HEADER, session->pool->tag.uid,
strnlen(session->pool->tag.uid, sizeof(session->pool->tag.uid)));
}
}
else {
/* No client message, fall back to session tag */
rspamd_http_message_add_header_len(msg, LOG_TAG_HEADER, session->pool->tag.uid,
strnlen(session->pool->tag.uid, sizeof(session->pool->tag.uid)));
}
break;
case RSPAMD_PROXY_LOG_TAG_NONE:
/* Skip adding log tag header */
break;
default:
/* Fall back to session tag for unknown types */
rspamd_http_message_add_header_len(msg, LOG_TAG_HEADER, session->pool->tag.uid,
strnlen(session->pool->tag.uid, sizeof(session->pool->tag.uid)));
break;
}
}
static gboolean
rspamd_proxy_parse_lua_parser(lua_State *L, const ucl_object_t *obj,
int *ref_from, int *ref_to, GError **err)
{
const char *lua_script;
gsize slen;
int err_idx, ref_idx;
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) {
g_set_error(err,
rspamd_proxy_quark(),
EINVAL,
"cannot init lua parser script: %s",
lua_tostring(L, -1));
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) {
if (ucl_object_type(obj) != UCL_NULL) {
msg_info_pool_check("upstream %s is disabled by setting it to NULL",
ucl_object_key(obj));
return TRUE;
}
g_set_error(err, rspamd_proxy_quark(), 100,
"upstream option must be an object");
return FALSE;
}
if (!rspamd_config_is_enabled_from_ucl(pool, obj)) {
/* Upstream is valid but disabled */
msg_info_pool_check("upstream %s is disabled",
ucl_object_lookup(obj, "name") ? ucl_object_tostring(ucl_object_lookup(obj, "name")) : ucl_object_key(obj));
return TRUE;
}
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;
up->log_tag_type = ctx->log_tag_type; /* Inherit from worker default */
elt = ucl_object_lookup(obj, "key");
if (elt != NULL) {
up->key = rspamd_pubkey_from_base32(ucl_object_tostring(elt), 0,
RSPAMD_KEYPAIR_KEX);
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, "ssl");
if (elt && ucl_object_toboolean(elt)) {
up->ssl = TRUE;
}
elt = ucl_object_lookup_any(obj, "keepalive", "keep_alive", NULL);
if (elt && ucl_object_toboolean(elt)) {
up->keepalive = 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);
}
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));
}
elt = ucl_object_lookup(obj, "extra_headers");
if (elt && ucl_object_type(elt) == UCL_OBJECT) {
up->extra_headers = ucl_object_ref(elt);
rspamd_mempool_add_destructor(pool,
(rspamd_mempool_destruct_t) ucl_object_unref,
up->extra_headers);
}
elt = ucl_object_lookup(obj, "extra_headers");
if (elt && ucl_object_type(elt) == UCL_OBJECT) {
up->extra_headers = ucl_object_ref(elt);
rspamd_mempool_add_destructor(pool,
(rspamd_mempool_destruct_t) ucl_object_unref,
up->extra_headers);
}
elt = ucl_object_lookup_any(obj, "log_tag", "log_tag_type", NULL);
if (elt && ucl_object_type(elt) == UCL_STRING) {
up->log_tag_type = rspamd_proxy_parse_log_tag_type(ucl_object_tostring(elt));
}
/* Parse token_bucket configuration for weighted load balancing */
elt = ucl_object_lookup(obj, "token_bucket");
if (elt != NULL && ucl_object_type(elt) == UCL_OBJECT && up->u != NULL) {
gsize max_tokens = 10000, scale = 1024, min_tokens = 1, base_cost = 10;
const ucl_object_t *tb_elt;
if ((tb_elt = ucl_object_lookup(elt, "max_tokens")) != NULL) {
max_tokens = ucl_object_toint(tb_elt);
if (max_tokens == 0) {
msg_warn_pool("token_bucket.max_tokens must be > 0, using default 10000");
max_tokens = 10000;
}
}
if ((tb_elt = ucl_object_lookup(elt, "scale")) != NULL) {
scale = ucl_object_toint(tb_elt);
if (scale == 0) {
msg_warn_pool("token_bucket.scale cannot be 0 (division by zero), using default 1024");
scale = 1024;
}
}
if ((tb_elt = ucl_object_lookup(elt, "min_tokens")) != NULL) {
min_tokens = ucl_object_toint(tb_elt);
}
if ((tb_elt = ucl_object_lookup(elt, "base_cost")) != NULL) {
base_cost = ucl_object_toint(tb_elt);
}
/* Validate relationships */
if (min_tokens > max_tokens) {
msg_warn_pool("token_bucket.min_tokens (%zu) > max_tokens (%zu), clamping",
min_tokens, max_tokens);
min_tokens = max_tokens;
}
if (base_cost >= max_tokens) {
msg_warn_pool("token_bucket.base_cost (%zu) >= max_tokens (%zu), reducing to max/2",
base_cost, max_tokens);
base_cost = max_tokens / 2;
}
/* Enable token bucket rotation and configure parameters */
rspamd_upstreams_set_rotation(up->u, RSPAMD_UPSTREAM_TOKEN_BUCKET);
rspamd_upstreams_set_token_bucket(up->u, max_tokens, scale, min_tokens, base_cost);
msg_info_pool_check("upstream %s: token_bucket enabled (max=%zu, scale=%zu, min=%zu, base=%zu)",
up->name, max_tokens, scale, min_tokens, base_cost);
}
/*
* 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);
}
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) {
if (ucl_object_type(obj) != UCL_NULL) {
msg_info_pool_check("mirror %s is disabled by setting it to NULL",
ucl_object_key(obj));
return TRUE;
}
g_set_error(err, rspamd_proxy_quark(), 100,
"mirror option must be an object");
return FALSE;
}
if (!rspamd_config_is_enabled_from_ucl(pool, obj)) {
/* Upstream is valid but disabled */
msg_info_pool_check("mirror %s is disabled",
ucl_object_lookup(obj, "name") ? ucl_object_tostring(ucl_object_lookup(obj, "name")) : ucl_object_key(obj));
return TRUE;
}
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;
up->log_tag_type = ctx->log_tag_type; /* Inherit from worker default */
elt = ucl_object_lookup(obj, "key");
if (elt != NULL) {
up->key = rspamd_pubkey_from_base32(ucl_object_tostring(elt), 0,
RSPAMD_KEYPAIR_KEX);
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, "ssl");
if (elt && ucl_object_toboolean(elt)) {
up->ssl = TRUE;
}
elt = ucl_object_lookup_any(obj, "keepalive", "keep_alive", NULL);
if (elt && ucl_object_toboolean(elt)) {
up->keepalive = TRUE;
}
elt = ucl_object_lookup(obj, "timeout");
if (elt) {
ucl_object_todouble_safe(elt, &up->timeout);
}
elt = ucl_object_lookup(obj, "follow_master");
if (elt && ucl_object_toboolean(elt)) {
up->follow_master = TRUE;
}
/*
* 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));
}
elt = ucl_object_lookup_any(obj, "log_tag", "log_tag_type", NULL);
if (elt && ucl_object_type(elt) == UCL_STRING) {
up->log_tag_type = rspamd_proxy_parse_log_tag_type(ucl_object_tostring(elt));
}
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 char *lua_script;
gsize slen;
int err_idx, ref_idx;
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) {
g_set_error(err,
rspamd_proxy_quark(),
EINVAL,
"cannot init lua parser script: %s",
lua_tostring(L, -1));
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: