forked from haproxy/haproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.c
7193 lines (6196 loc) · 215 KB
/
server.c
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
/*
* Server management functions.
*
* Copyright 2000-2012 Willy Tarreau <w@1wt.eu>
* Copyright 2007-2008 Krzysztof Piotr Oledzki <ole@ans.pl>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <sys/types.h>
#include <netinet/tcp.h>
#include <ctype.h>
#include <errno.h>
#include <import/ebmbtree.h>
#include <haproxy/api.h>
#include <haproxy/applet-t.h>
#include <haproxy/backend.h>
#include <haproxy/cfgparse.h>
#include <haproxy/check.h>
#include <haproxy/cli.h>
#include <haproxy/connection.h>
#include <haproxy/dict-t.h>
#include <haproxy/errors.h>
#include <haproxy/global.h>
#include <haproxy/guid.h>
#include <haproxy/log.h>
#include <haproxy/mailers.h>
#include <haproxy/namespace.h>
#include <haproxy/port_range.h>
#include <haproxy/protocol.h>
#include <haproxy/proxy.h>
#include <haproxy/queue.h>
#include <haproxy/resolvers.h>
#include <haproxy/sample.h>
#include <haproxy/sc_strm.h>
#include <haproxy/server.h>
#include <haproxy/stats.h>
#include <haproxy/stconn.h>
#include <haproxy/stream.h>
#include <haproxy/task.h>
#include <haproxy/tcpcheck.h>
#include <haproxy/time.h>
#include <haproxy/tools.h>
#include <haproxy/xxhash.h>
#include <haproxy/event_hdl.h>
static void srv_update_status(struct server *s, int type, int cause);
static int srv_apply_lastaddr(struct server *srv, int *err_code);
static void srv_cleanup_connections(struct server *srv);
/* extra keywords used as value for other arguments. They are used as
* suggestions for mistyped words.
*/
static const char *extra_kw_list[] = {
"ipv4", "ipv6", "legacy", "octet-count",
"fail-check", "sudden-death", "mark-down",
NULL /* must be last */
};
/* List head of all known server keywords */
struct srv_kw_list srv_keywords = {
.list = LIST_HEAD_INIT(srv_keywords.list)
};
__decl_thread(HA_SPINLOCK_T idle_conn_srv_lock);
struct eb_root idle_conn_srv = EB_ROOT;
struct task *idle_conn_task __read_mostly = NULL;
struct list servers_list = LIST_HEAD_INIT(servers_list);
static struct task *server_atomic_sync_task = NULL;
static event_hdl_async_equeue server_atomic_sync_queue;
/* SERVER DELETE(n)->ADD global tracker:
* This is meant to provide srv->rid (revision id) value.
* Revision id allows to differentiate between a previously existing
* deleted server and a new server reusing deleted server name/id.
*
* start value is 0 (even value)
* LSB is used to specify that one or multiple srv delete in a row
* were performed.
* When adding a new server, increment by 1 if current
* value is odd (odd = LSB set),
* because adding a new server after one or
* multiple deletions means we could potentially be reusing old names:
* Increase the revision id to prevent mixups between old and new names.
*
* srv->rid is calculated from cnt even values only.
* sizeof(srv_id_reuse_cnt) must be twice sizeof(srv->rid)
*
* Wraparound is expected and should not cause issues
* (with current design we allow up to 4 billion unique revisions)
*
* Counter is only used under thread_isolate (cli_add/cli_del),
* no need for atomic ops.
*/
static uint64_t srv_id_reuse_cnt = 0;
/* The server names dictionary */
struct dict server_key_dict = {
.name = "server keys",
.values = EB_ROOT_UNIQUE,
};
static const char *srv_adm_st_chg_cause_str[] = {
[SRV_ADM_STCHGC_NONE] = "",
[SRV_ADM_STCHGC_DNS_NOENT] = "entry removed from SRV record",
[SRV_ADM_STCHGC_DNS_NOIP] = "No IP for server ",
[SRV_ADM_STCHGC_DNS_NX] = "DNS NX status",
[SRV_ADM_STCHGC_DNS_TIMEOUT] = "DNS timeout status",
[SRV_ADM_STCHGC_DNS_REFUSED] = "DNS refused status",
[SRV_ADM_STCHGC_DNS_UNSPEC] = "unspecified DNS error",
[SRV_ADM_STCHGC_STATS_DISABLE] = "'disable' on stats page",
[SRV_ADM_STCHGC_STATS_STOP] = "'stop' on stats page"
};
const char *srv_adm_st_chg_cause(enum srv_adm_st_chg_cause cause)
{
return srv_adm_st_chg_cause_str[cause];
}
static const char *srv_op_st_chg_cause_str[] = {
[SRV_OP_STCHGC_NONE] = "",
[SRV_OP_STCHGC_HEALTH] = "",
[SRV_OP_STCHGC_AGENT] = "",
[SRV_OP_STCHGC_CLI] = "changed from CLI",
[SRV_OP_STCHGC_LUA] = "changed from Lua script",
[SRV_OP_STCHGC_STATS_WEB] = "changed from Web interface",
[SRV_OP_STCHGC_STATEFILE] = "changed from server-state after a reload"
};
const char *srv_op_st_chg_cause(enum srv_op_st_chg_cause cause)
{
return srv_op_st_chg_cause_str[cause];
}
int srv_downtime(const struct server *s)
{
if ((s->cur_state != SRV_ST_STOPPED) || s->counters.last_change >= ns_to_sec(now_ns)) // ignore negative time
return s->down_time;
return ns_to_sec(now_ns) - s->counters.last_change + s->down_time;
}
int srv_getinter(const struct check *check)
{
const struct server *s = check->server;
if ((check->state & (CHK_ST_CONFIGURED|CHK_ST_FASTINTER)) == CHK_ST_CONFIGURED &&
(check->health == check->rise + check->fall - 1))
return check->inter;
if ((s->next_state == SRV_ST_STOPPED) && check->health == 0)
return (check->downinter)?(check->downinter):(check->inter);
return (check->fastinter)?(check->fastinter):(check->inter);
}
/* Update server's addr:svc_port tuple in INET context
*
* Must be called under thread isolation to ensure consistent readings across
* all threads (addr:svc_port might be read without srv lock being held).
*/
static void _srv_set_inetaddr_port(struct server *srv,
const struct sockaddr_storage *addr,
unsigned int svc_port, uint8_t mapped_port)
{
ipcpy(addr, &srv->addr);
srv->svc_port = svc_port;
if (mapped_port)
srv->flags |= SRV_F_MAPPORTS;
else
srv->flags &= ~SRV_F_MAPPORTS;
if (srv->proxy->lbprm.update_server_eweight) {
/* some balancers (chash in particular) may use the addr in their routing decisions */
srv->proxy->lbprm.update_server_eweight(srv);
}
if (srv->log_target && srv->log_target->type == LOG_TARGET_DGRAM) {
/* server is used as a log target, manually update log target addr for DGRAM */
ipcpy(addr, srv->log_target->addr);
set_host_port(srv->log_target->addr, svc_port);
}
}
/* same as _srv_set_inetaddr_port() but only updates the addr part
*/
static void _srv_set_inetaddr(struct server *srv,
const struct sockaddr_storage *addr)
{
_srv_set_inetaddr_port(srv, addr, srv->svc_port, !!(srv->flags & SRV_F_MAPPORTS));
}
/*
* Function executed by server_atomic_sync_task to perform atomic updates on
* compatible server struct members that are not guarded by any lock since
* they are not supposed to change often and are subject to being used in
* sensitive codepaths
*
* Some updates may require thread isolation: we start without isolation
* but as soon as we encounter an event that requires isolation, we do so.
* Once the event is processed, we keep the isolation until we've processed
* the whole batch of events and leave isolation once we're done, as it would
* be very costly to try to acquire isolation multiple times in a row.
* The task will limit itself to a number of events per run to prevent
* thread contention (see: "tune.events.max-events-at-once").
*
* TODO: if we find out that enforcing isolation is too costly, we may
* consider adding thread_isolate_try_full(timeout) or equivalent to the
* thread API so that we can do our best not to block harmless threads
* for too long if one or multiple threads are still heavily busy. This
* would mean that the task would be capable of rescheduling itself to
* start again on the current event if it failed to acquire thread
* isolation. This would also imply that the event_hdl API allows us
* to check an event without popping it from the queue first (remove the
* event once it is successfully processed).
*/
static void srv_set_addr_desc(struct server *s, int reattach);
static struct task *server_atomic_sync(struct task *task, void *context, unsigned int state)
{
unsigned int remain = event_hdl_tune.max_events_at_once; // to limit max number of events per batch
struct event_hdl_async_event *event;
/* check for new server events that we care about */
while ((event = event_hdl_async_equeue_pop(&server_atomic_sync_queue))) {
if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_END)) {
/* ending event: no more events to come */
event_hdl_async_free_event(event);
task_destroy(task);
task = NULL;
break;
}
if (!remain) {
/* STOP: we've already spent all our budget here, and
* considering we possibly are under isolation, we cannot
* keep blocking other threads any longer.
*
* Reschedule the task to finish where we left off if
* there are remaining events in the queue.
*/
if (!event_hdl_async_equeue_isempty(&server_atomic_sync_queue))
task_wakeup(task, TASK_WOKEN_OTHER);
break;
}
remain--;
/* new event to process */
if (event_hdl_sub_type_equal(event->type, EVENT_HDL_SUB_SERVER_INETADDR)) {
struct sockaddr_storage new_addr;
struct event_hdl_cb_data_server_inetaddr *data = event->data;
struct proxy *px;
struct server *srv;
/* server ip:port changed, we must atomically update data members
* to prevent invalid reads by other threads.
*/
/* check if related server still exists */
px = proxy_find_by_id(data->server.safe.proxy_uuid, PR_CAP_BE, 0);
if (!px)
continue;
srv = server_find_by_id_unique(px, data->server.safe.puid, data->server.safe.rid);
if (!srv)
continue;
/* prepare new addr based on event cb data */
memset(&new_addr, 0, sizeof(new_addr));
new_addr.ss_family = data->safe.next.family;
switch (new_addr.ss_family) {
case AF_INET:
((struct sockaddr_in *)&new_addr)->sin_addr.s_addr =
data->safe.next.addr.v4.s_addr;
break;
case AF_INET6:
memcpy(&((struct sockaddr_in6 *)&new_addr)->sin6_addr,
&data->safe.next.addr.v6,
sizeof(struct in6_addr));
break;
case AF_UNSPEC:
/* addr reset, nothing to do */
break;
default:
/* should not happen */
break;
}
/*
* this requires thread isolation, which is safe since we're the only
* task working for the current subscription and we don't hold locks
* or resources that other threads may depend on to complete a running
* cycle. Note that we do this way because we assume that this event is
* rather rare.
*/
if (!thread_isolated())
thread_isolate_full();
/* apply new addr:port combination */
_srv_set_inetaddr_port(srv, &new_addr,
data->safe.next.port.svc, data->safe.next.port.map);
/* propagate the changes, force connection cleanup */
if (new_addr.ss_family != AF_UNSPEC &&
(srv->next_admin & SRV_ADMF_RMAINT)) {
/* server was previously put under DNS maintenance due
* to DNS error, but addr resolves again, so we must
* put it out of maintenance
*/
srv_clr_admin_flag(srv, SRV_ADMF_RMAINT);
/* thanks to valid DNS resolution? */
if (data->safe.updater.dns) {
chunk_reset(&trash);
chunk_printf(&trash, "Server %s/%s administratively READY thanks to valid DNS answer", srv->proxy->id, srv->id);
ha_warning("%s.\n", trash.area);
send_log(srv->proxy, LOG_NOTICE, "%s.\n", trash.area);
}
}
srv_cleanup_connections(srv);
srv_set_dyncookie(srv);
srv_set_addr_desc(srv, 1);
}
event_hdl_async_free_event(event);
}
/* some events possibly required thread_isolation:
* now that we are done, we must leave thread isolation before
* returning
*/
if (thread_isolated())
thread_release();
return task;
}
/* Try to start the atomic server sync task.
*
* Returns ERR_NONE on success and a combination of ERR_CODE on failure
*/
static int server_atomic_sync_start()
{
struct event_hdl_sub_type subscriptions = EVENT_HDL_SUB_NONE;
if (server_atomic_sync_task)
return ERR_NONE; // nothing to do
server_atomic_sync_task = task_new_anywhere();
if (!server_atomic_sync_task)
goto fail;
server_atomic_sync_task->process = server_atomic_sync;
event_hdl_async_equeue_init(&server_atomic_sync_queue);
/* task created, now subscribe to relevant server events in the global list */
subscriptions = event_hdl_sub_type_add(subscriptions, EVENT_HDL_SUB_SERVER_INETADDR);
if (!event_hdl_subscribe(NULL, subscriptions,
EVENT_HDL_ASYNC_TASK(&server_atomic_sync_queue,
server_atomic_sync_task,
NULL,
NULL)))
goto fail;
return ERR_NONE;
fail:
task_destroy(server_atomic_sync_task);
server_atomic_sync_task = NULL;
return ERR_ALERT | ERR_FATAL;
}
REGISTER_POST_CHECK(server_atomic_sync_start);
/* fill common server event data members struct
* must be called with server lock or under thread isolate
*/
static inline void _srv_event_hdl_prepare(struct event_hdl_cb_data_server *cb_data,
struct server *srv, uint8_t thread_isolate)
{
/* safe data assignments */
cb_data->safe.puid = srv->puid;
cb_data->safe.rid = srv->rid;
cb_data->safe.flags = srv->flags;
snprintf(cb_data->safe.name, sizeof(cb_data->safe.name), "%s", srv->id);
cb_data->safe.proxy_name[0] = '\0';
cb_data->safe.proxy_uuid = -1; /* default value */
if (srv->proxy) {
cb_data->safe.proxy_uuid = srv->proxy->uuid;
snprintf(cb_data->safe.proxy_name, sizeof(cb_data->safe.proxy_name), "%s", srv->proxy->id);
}
/* unsafe data assignments */
cb_data->unsafe.ptr = srv;
cb_data->unsafe.thread_isolate = thread_isolate;
cb_data->unsafe.srv_lock = !thread_isolate;
}
/* take an event-check snapshot from a live check */
void _srv_event_hdl_prepare_checkres(struct event_hdl_cb_data_server_checkres *checkres,
struct check *check)
{
checkres->agent = !!(check->state & CHK_ST_AGENT);
checkres->result = check->result;
checkres->duration = check->duration;
checkres->reason.status = check->status;
checkres->reason.code = check->code;
checkres->health.cur = check->health;
checkres->health.rise = check->rise;
checkres->health.fall = check->fall;
}
/* Prepare SERVER_STATE event
*
* This special event will contain extra hints related to the state change
*
* Must be called with server lock held
*/
void _srv_event_hdl_prepare_state(struct event_hdl_cb_data_server_state *cb_data,
struct server *srv, int type, int cause,
enum srv_state prev_state, int requeued)
{
/* state event provides additional info about the server state change */
cb_data->safe.type = type;
cb_data->safe.new_state = srv->cur_state;
cb_data->safe.old_state = prev_state;
cb_data->safe.requeued = requeued;
if (type) {
/* administrative */
cb_data->safe.adm_st_chg.cause = cause;
}
else {
/* operational */
cb_data->safe.op_st_chg.cause = cause;
if (cause == SRV_OP_STCHGC_HEALTH || cause == SRV_OP_STCHGC_AGENT) {
struct check *check = (cause == SRV_OP_STCHGC_HEALTH) ? &srv->check : &srv->agent;
/* provide additional check-related state change result */
_srv_event_hdl_prepare_checkres(&cb_data->safe.op_st_chg.check, check);
}
}
}
/* Prepare SERVER_INETADDR event, prev data is learned from the current
* server settings.
*
* This special event will contain extra hints related to the addr change
*
* Must be called with the server lock held.
*/
static void _srv_event_hdl_prepare_inetaddr(struct event_hdl_cb_data_server_inetaddr *cb_data,
struct server *srv,
const struct server_inetaddr *next_inetaddr,
struct server_inetaddr_updater updater)
{
struct server_inetaddr prev_inetaddr;
server_get_inetaddr(srv, &prev_inetaddr);
/* only INET families are supported */
BUG_ON((next_inetaddr->family != AF_UNSPEC &&
next_inetaddr->family != AF_INET && next_inetaddr->family != AF_INET6));
/* prev */
cb_data->safe.prev = prev_inetaddr;
/* next */
cb_data->safe.next = *next_inetaddr;
/* updater */
cb_data->safe.updater = updater;
}
/* server event publishing helper: publish in both global and
* server dedicated subscription list.
*/
#define _srv_event_hdl_publish(e, d, s) \
({ \
/* publish in server dedicated sub list */ \
event_hdl_publish(&s->e_subs, e, EVENT_HDL_CB_DATA(&d));\
/* publish in global subscription list */ \
event_hdl_publish(NULL, e, EVENT_HDL_CB_DATA(&d)); \
})
/* General server event publishing:
* Use this to publish EVENT_HDL_SUB_SERVER family type event
* from srv facility.
*
* server ptr must be valid.
* Must be called with srv lock or under thread_isolate.
*/
static void srv_event_hdl_publish(struct event_hdl_sub_type event,
struct server *srv, uint8_t thread_isolate)
{
struct event_hdl_cb_data_server cb_data;
/* prepare event data */
_srv_event_hdl_prepare(&cb_data, srv, thread_isolate);
_srv_event_hdl_publish(event, cb_data, srv);
}
/* Publish SERVER_CHECK event
*
* This special event will contain extra hints related to the check itself
*
* Must be called with server lock held
*/
void srv_event_hdl_publish_check(struct server *srv, struct check *check)
{
struct event_hdl_cb_data_server_check cb_data;
/* check event provides additional info about the server check */
_srv_event_hdl_prepare_checkres(&cb_data.safe.res, check);
cb_data.unsafe.ptr = check;
/* prepare event data (common server data) */
_srv_event_hdl_prepare((struct event_hdl_cb_data_server *)&cb_data, srv, 0);
_srv_event_hdl_publish(EVENT_HDL_SUB_SERVER_CHECK, cb_data, srv);
}
/*
* Check that we did not get a hash collision.
* Unlikely, but it can happen. The server's proxy must be at least
* read-locked.
*/
static inline void srv_check_for_dup_dyncookie(struct server *s)
{
struct proxy *p = s->proxy;
struct server *tmpserv;
for (tmpserv = p->srv; tmpserv != NULL;
tmpserv = tmpserv->next) {
if (tmpserv == s)
continue;
if (tmpserv->next_admin & SRV_ADMF_FMAINT)
continue;
if (tmpserv->cookie &&
strcmp(tmpserv->cookie, s->cookie) == 0) {
ha_warning("We generated two equal cookies for two different servers.\n"
"Please change the secret key for '%s'.\n",
s->proxy->id);
}
}
}
/*
* Must be called with the server lock held, and will read-lock the proxy.
*/
void srv_set_dyncookie(struct server *s)
{
struct proxy *p = s->proxy;
char *tmpbuf;
unsigned long long hash_value;
size_t key_len;
size_t buffer_len;
int addr_len;
int port;
HA_RWLOCK_RDLOCK(PROXY_LOCK, &p->lock);
if ((s->flags & SRV_F_COOKIESET) ||
!(s->proxy->ck_opts & PR_CK_DYNAMIC) ||
s->proxy->dyncookie_key == NULL)
goto out;
key_len = strlen(p->dyncookie_key);
if (s->addr.ss_family != AF_INET &&
s->addr.ss_family != AF_INET6)
goto out;
/*
* Buffer to calculate the cookie value.
* The buffer contains the secret key + the server IP address
* + the TCP port.
*/
addr_len = (s->addr.ss_family == AF_INET) ? 4 : 16;
/*
* The TCP port should use only 2 bytes, but is stored in
* an unsigned int in struct server, so let's use 4, to be
* on the safe side.
*/
buffer_len = key_len + addr_len + 4;
tmpbuf = trash.area;
memcpy(tmpbuf, p->dyncookie_key, key_len);
memcpy(&(tmpbuf[key_len]),
s->addr.ss_family == AF_INET ?
(void *)&((struct sockaddr_in *)&s->addr)->sin_addr.s_addr :
(void *)&(((struct sockaddr_in6 *)&s->addr)->sin6_addr.s6_addr),
addr_len);
/*
* Make sure it's the same across all the load balancers,
* no matter their endianness.
*/
port = htonl(s->svc_port);
memcpy(&tmpbuf[key_len + addr_len], &port, 4);
hash_value = XXH64(tmpbuf, buffer_len, 0);
memprintf(&s->cookie, "%016llx", hash_value);
if (!s->cookie)
goto out;
s->cklen = 16;
/* Don't bother checking if the dyncookie is duplicated if
* the server is marked as "disabled", maybe it doesn't have
* its real IP yet, but just a place holder.
*/
if (!(s->next_admin & SRV_ADMF_FMAINT))
srv_check_for_dup_dyncookie(s);
out:
HA_RWLOCK_RDUNLOCK(PROXY_LOCK, &p->lock);
}
/* Returns true if it's possible to reuse an idle connection from server <srv>
* for a websocket stream. This is the case if server is configured to use the
* same protocol for both HTTP and websocket streams. This depends on the value
* of "proto", "alpn" and "ws" keywords.
*/
int srv_check_reuse_ws(struct server *srv)
{
if (srv->mux_proto || srv->use_ssl != 1 || !srv->ssl_ctx.alpn_str) {
/* explicit srv.mux_proto or no ALPN : srv.mux_proto is used
* for mux selection.
*/
const struct ist srv_mux = srv->mux_proto ?
srv->mux_proto->token : IST_NULL;
switch (srv->ws) {
/* "auto" means use the same protocol : reuse is possible. */
case SRV_WS_AUTO:
return 1;
/* "h2" means use h2 for websocket : reuse is possible if
* server mux is h2.
*/
case SRV_WS_H2:
if (srv->mux_proto && isteq(srv_mux, ist("h2")))
return 1;
break;
/* "h1" means use h1 for websocket : reuse is possible if
* server mux is h1.
*/
case SRV_WS_H1:
if (!srv->mux_proto || isteq(srv_mux, ist("h1")))
return 1;
break;
}
}
else {
/* ALPN selection.
* Based on the assumption that only "h2" and "http/1.1" token
* are used on server ALPN.
*/
const struct ist alpn = ist2(srv->ssl_ctx.alpn_str,
srv->ssl_ctx.alpn_len);
switch (srv->ws) {
case SRV_WS_AUTO:
/* for auto mode, consider reuse as possible if the
* server uses a single protocol ALPN
*/
if (!istchr(alpn, ','))
return 1;
break;
case SRV_WS_H2:
return isteq(alpn, ist("\x02h2"));
case SRV_WS_H1:
return isteq(alpn, ist("\x08http/1.1"));
}
}
return 0;
}
/* Return the proto to used for a websocket stream on <srv> without ALPN. NULL
* is a valid value indicating to use the fallback mux.
*/
const struct mux_ops *srv_get_ws_proto(struct server *srv)
{
const struct mux_proto_list *mux = NULL;
switch (srv->ws) {
case SRV_WS_AUTO:
mux = srv->mux_proto;
break;
case SRV_WS_H1:
mux = get_mux_proto(ist("h1"));
break;
case SRV_WS_H2:
mux = get_mux_proto(ist("h2"));
break;
}
return mux ? mux->mux : NULL;
}
/*
* Must be called with the server lock held. The server is first removed from
* the proxy tree if it was already attached. If <reattach> is true, the server
* will then be attached in the proxy tree. The proxy lock is held to
* manipulate the tree.
*/
static void srv_set_addr_desc(struct server *s, int reattach)
{
struct proxy *p = s->proxy;
char *key;
key = sa2str(&s->addr, s->svc_port, s->flags & SRV_F_MAPPORTS);
if (s->addr_node.key) {
if (key && strcmp(key, s->addr_node.key) == 0) {
free(key);
return;
}
HA_RWLOCK_WRLOCK(PROXY_LOCK, &p->lock);
ebpt_delete(&s->addr_node);
HA_RWLOCK_WRUNLOCK(PROXY_LOCK, &p->lock);
free(s->addr_node.key);
}
s->addr_node.key = key;
if (reattach) {
if (s->addr_node.key) {
HA_RWLOCK_WRLOCK(PROXY_LOCK, &p->lock);
ebis_insert(&p->used_server_addr, &s->addr_node);
HA_RWLOCK_WRUNLOCK(PROXY_LOCK, &p->lock);
}
}
}
/*
* Registers the server keyword list <kwl> as a list of valid keywords for next
* parsing sessions.
*/
void srv_register_keywords(struct srv_kw_list *kwl)
{
LIST_APPEND(&srv_keywords.list, &kwl->list);
}
/* Return a pointer to the server keyword <kw>, or NULL if not found. If the
* keyword is found with a NULL ->parse() function, then an attempt is made to
* find one with a valid ->parse() function. This way it is possible to declare
* platform-dependant, known keywords as NULL, then only declare them as valid
* if some options are met. Note that if the requested keyword contains an
* opening parenthesis, everything from this point is ignored.
*/
struct srv_kw *srv_find_kw(const char *kw)
{
int index;
const char *kwend;
struct srv_kw_list *kwl;
struct srv_kw *ret = NULL;
kwend = strchr(kw, '(');
if (!kwend)
kwend = kw + strlen(kw);
list_for_each_entry(kwl, &srv_keywords.list, list) {
for (index = 0; kwl->kw[index].kw != NULL; index++) {
if ((strncmp(kwl->kw[index].kw, kw, kwend - kw) == 0) &&
kwl->kw[index].kw[kwend-kw] == 0) {
if (kwl->kw[index].parse)
return &kwl->kw[index]; /* found it !*/
else
ret = &kwl->kw[index]; /* may be OK */
}
}
}
return ret;
}
/* Dumps all registered "server" keywords to the <out> string pointer. The
* unsupported keywords are only dumped if their supported form was not
* found.
*/
void srv_dump_kws(char **out)
{
struct srv_kw_list *kwl;
int index;
if (!out)
return;
*out = NULL;
list_for_each_entry(kwl, &srv_keywords.list, list) {
for (index = 0; kwl->kw[index].kw != NULL; index++) {
if (kwl->kw[index].parse ||
srv_find_kw(kwl->kw[index].kw) == &kwl->kw[index]) {
memprintf(out, "%s[%4s] %s%s%s%s\n", *out ? *out : "",
kwl->scope,
kwl->kw[index].kw,
kwl->kw[index].skip ? " <arg>" : "",
kwl->kw[index].default_ok ? " [dflt_ok]" : "",
kwl->kw[index].parse ? "" : " (not supported)");
}
}
}
}
/* Try to find in srv_keyword the word that looks closest to <word> by counting
* transitions between letters, digits and other characters. Will return the
* best matching word if found, otherwise NULL. An optional array of extra
* words to compare may be passed in <extra>, but it must then be terminated
* by a NULL entry. If unused it may be NULL.
*/
static const char *srv_find_best_kw(const char *word)
{
uint8_t word_sig[1024];
uint8_t list_sig[1024];
const struct srv_kw_list *kwl;
const char *best_ptr = NULL;
int dist, best_dist = INT_MAX;
const char **extra;
int index;
make_word_fingerprint(word_sig, word);
list_for_each_entry(kwl, &srv_keywords.list, list) {
for (index = 0; kwl->kw[index].kw != NULL; index++) {
make_word_fingerprint(list_sig, kwl->kw[index].kw);
dist = word_fingerprint_distance(word_sig, list_sig);
if (dist < best_dist) {
best_dist = dist;
best_ptr = kwl->kw[index].kw;
}
}
}
for (extra = extra_kw_list; *extra; extra++) {
make_word_fingerprint(list_sig, *extra);
dist = word_fingerprint_distance(word_sig, list_sig);
if (dist < best_dist) {
best_dist = dist;
best_ptr = *extra;
}
}
if (best_dist > 2 * strlen(word) || (best_ptr && best_dist > 2 * strlen(best_ptr)))
best_ptr = NULL;
return best_ptr;
}
/* Parse the "backup" server keyword */
static int srv_parse_backup(char **args, int *cur_arg,
struct proxy *curproxy, struct server *newsrv, char **err)
{
newsrv->flags |= SRV_F_BACKUP;
return 0;
}
/* Parse the "cookie" server keyword */
static int srv_parse_cookie(char **args, int *cur_arg,
struct proxy *curproxy, struct server *newsrv, char **err)
{
char *arg;
arg = args[*cur_arg + 1];
if (!*arg) {
memprintf(err, "'%s' expects <value> as argument.\n", args[*cur_arg]);
return ERR_ALERT | ERR_FATAL;
}
free(newsrv->cookie);
newsrv->cookie = strdup(arg);
newsrv->cklen = strlen(arg);
newsrv->flags |= SRV_F_COOKIESET;
return 0;
}
/* Parse the "disabled" server keyword */
static int srv_parse_disabled(char **args, int *cur_arg,
struct proxy *curproxy, struct server *newsrv, char **err)
{
newsrv->next_admin |= SRV_ADMF_CMAINT | SRV_ADMF_FMAINT;
newsrv->next_state = SRV_ST_STOPPED;
newsrv->check.state |= CHK_ST_PAUSED;
newsrv->check.health = 0;
return 0;
}
/* Parse the "enabled" server keyword */
static int srv_parse_enabled(char **args, int *cur_arg,
struct proxy *curproxy, struct server *newsrv, char **err)
{
newsrv->next_admin &= ~SRV_ADMF_CMAINT & ~SRV_ADMF_FMAINT;
newsrv->next_state = SRV_ST_RUNNING;
newsrv->check.state &= ~CHK_ST_PAUSED;
newsrv->check.health = newsrv->check.rise;
return 0;
}
/* Parse the "error-limit" server keyword */
static int srv_parse_error_limit(char **args, int *cur_arg,
struct proxy *curproxy, struct server *newsrv, char **err)
{
if (!*args[*cur_arg + 1]) {
memprintf(err, "'%s' expects an integer argument.",
args[*cur_arg]);
return ERR_ALERT | ERR_FATAL;
}
newsrv->consecutive_errors_limit = atoi(args[*cur_arg + 1]);
if (newsrv->consecutive_errors_limit <= 0) {
memprintf(err, "%s has to be > 0.",
args[*cur_arg]);
return ERR_ALERT | ERR_FATAL;
}
return 0;
}
/* Parse the "guid" keyword */
static int srv_parse_guid(char **args, int *cur_arg,
struct proxy *curproxy, struct server *newsrv, char **err)
{
const char *guid;
char *guid_err = NULL;
if (!*args[*cur_arg + 1]) {
memprintf(err, "'%s' : expects an argument", args[*cur_arg]);
return ERR_ALERT | ERR_FATAL;
}
guid = args[*cur_arg + 1];
if (guid_insert(&newsrv->obj_type, guid, &guid_err)) {
memprintf(err, "'%s': %s", args[*cur_arg], guid_err);
ha_free(&guid_err);
return ERR_ALERT | ERR_FATAL;
}
return 0;
}
/* Parse the "ws" keyword */
static int srv_parse_ws(char **args, int *cur_arg,
struct proxy *curproxy, struct server *newsrv, char **err)
{
if (!args[*cur_arg + 1]) {
memprintf(err, "'%s' expects 'auto', 'h1' or 'h2' value", args[*cur_arg]);
return ERR_ALERT | ERR_FATAL;
}
if (strcmp(args[*cur_arg + 1], "h1") == 0) {
newsrv->ws = SRV_WS_H1;
}
else if (strcmp(args[*cur_arg + 1], "h2") == 0) {
newsrv->ws = SRV_WS_H2;
}
else if (strcmp(args[*cur_arg + 1], "auto") == 0) {
newsrv->ws = SRV_WS_AUTO;
}
else {
memprintf(err, "'%s' has to be 'auto', 'h1' or 'h2'", args[*cur_arg]);
return ERR_ALERT | ERR_FATAL;
}
return 0;
}
/* Parse the "hash-key" server keyword */
static int srv_parse_hash_key(char **args, int *cur_arg,
struct proxy *curproxy, struct server *newsrv, char **err)
{
if (!args[*cur_arg + 1]) {
memprintf(err, "'%s expects 'id', 'addr', or 'addr-port' value", args[*cur_arg]);
return ERR_ALERT | ERR_FATAL;
}
if (strcmp(args[*cur_arg + 1], "id") == 0) {
newsrv->hash_key = SRV_HASH_KEY_ID;
}
else if (strcmp(args[*cur_arg + 1], "addr") == 0) {
newsrv->hash_key = SRV_HASH_KEY_ADDR;
}
else if (strcmp(args[*cur_arg + 1], "addr-port") == 0) {
newsrv->hash_key = SRV_HASH_KEY_ADDR_PORT;
}
else {
memprintf(err, "'%s' has to be 'id', 'addr', or 'addr-port'", args[*cur_arg]);
return ERR_ALERT | ERR_FATAL;
}
return 0;
}
/* Parse the "init-addr" server keyword */
static int srv_parse_init_addr(char **args, int *cur_arg,
struct proxy *curproxy, struct server *newsrv, char **err)
{