forked from haproxy/haproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolvers.c
3513 lines (3017 loc) · 102 KB
/
resolvers.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
/*
* Name server resolution
*
* Copyright 2014 Baptiste Assmann <bedis9@gmail.com>
*
* 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 <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <import/ebistree.h>
#include <haproxy/action.h>
#include <haproxy/api.h>
#include <haproxy/cfgparse.h>
#include <haproxy/channel.h>
#include <haproxy/check.h>
#include <haproxy/cli.h>
#include <haproxy/dns.h>
#include <haproxy/errors.h>
#include <haproxy/fd.h>
#include <haproxy/http_rules.h>
#include <haproxy/log.h>
#include <haproxy/net_helper.h>
#include <haproxy/protocol.h>
#include <haproxy/proxy.h>
#include <haproxy/resolvers.h>
#include <haproxy/ring.h>
#include <haproxy/sample.h>
#include <haproxy/server.h>
#include <haproxy/stats.h>
#include <haproxy/stream_interface.h>
#include <haproxy/task.h>
#include <haproxy/tcp_rules.h>
#include <haproxy/ticks.h>
#include <haproxy/time.h>
#include <haproxy/tools.h>
#include <haproxy/vars.h>
struct list sec_resolvers = LIST_HEAD_INIT(sec_resolvers);
struct list resolv_srvrq_list = LIST_HEAD_INIT(resolv_srvrq_list);
static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
struct resolvers *curr_resolvers = NULL;
DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
static unsigned int resolution_uuid = 1;
unsigned int resolv_failed_resolutions = 0;
enum {
DNS_STAT_ID,
DNS_STAT_PID,
DNS_STAT_SENT,
DNS_STAT_SND_ERROR,
DNS_STAT_VALID,
DNS_STAT_UPDATE,
DNS_STAT_CNAME,
DNS_STAT_CNAME_ERROR,
DNS_STAT_ANY_ERR,
DNS_STAT_NX,
DNS_STAT_TIMEOUT,
DNS_STAT_REFUSED,
DNS_STAT_OTHER,
DNS_STAT_INVALID,
DNS_STAT_TOO_BIG,
DNS_STAT_TRUNCATED,
DNS_STAT_OUTDATED,
DNS_STAT_END,
};
static struct name_desc dns_stats[] = {
[DNS_STAT_ID] = { .name = "id", .desc = "ID" },
[DNS_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
[DNS_STAT_SENT] = { .name = "sent", .desc = "Sent" },
[DNS_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
[DNS_STAT_VALID] = { .name = "valid", .desc = "Valid" },
[DNS_STAT_UPDATE] = { .name = "update", .desc = "Update" },
[DNS_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
[DNS_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
[DNS_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
[DNS_STAT_NX] = { .name = "nx", .desc = "NX" },
[DNS_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
[DNS_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
[DNS_STAT_OTHER] = { .name = "other", .desc = "Other" },
[DNS_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
[DNS_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
[DNS_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
[DNS_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
};
static struct dns_counters dns_counters;
static void dns_fill_stats(void *d, struct field *stats)
{
struct dns_counters *counters = d;
stats[DNS_STAT_ID] = mkf_str(FO_CONFIG, counters->id);
stats[DNS_STAT_PID] = mkf_str(FO_CONFIG, counters->pid);
stats[DNS_STAT_SENT] = mkf_u64(FN_GAUGE, counters->sent);
stats[DNS_STAT_SND_ERROR] = mkf_u64(FN_GAUGE, counters->snd_error);
stats[DNS_STAT_VALID] = mkf_u64(FN_GAUGE, counters->valid);
stats[DNS_STAT_UPDATE] = mkf_u64(FN_GAUGE, counters->update);
stats[DNS_STAT_CNAME] = mkf_u64(FN_GAUGE, counters->cname);
stats[DNS_STAT_CNAME_ERROR] = mkf_u64(FN_GAUGE, counters->cname_error);
stats[DNS_STAT_ANY_ERR] = mkf_u64(FN_GAUGE, counters->any_err);
stats[DNS_STAT_NX] = mkf_u64(FN_GAUGE, counters->nx);
stats[DNS_STAT_TIMEOUT] = mkf_u64(FN_GAUGE, counters->timeout);
stats[DNS_STAT_REFUSED] = mkf_u64(FN_GAUGE, counters->refused);
stats[DNS_STAT_OTHER] = mkf_u64(FN_GAUGE, counters->other);
stats[DNS_STAT_INVALID] = mkf_u64(FN_GAUGE, counters->invalid);
stats[DNS_STAT_TOO_BIG] = mkf_u64(FN_GAUGE, counters->too_big);
stats[DNS_STAT_TRUNCATED] = mkf_u64(FN_GAUGE, counters->truncated);
stats[DNS_STAT_OUTDATED] = mkf_u64(FN_GAUGE, counters->outdated);
}
static struct stats_module dns_stats_module = {
.name = "dns",
.domain_flags = STATS_DOMAIN_DNS << STATS_DOMAIN,
.fill_stats = dns_fill_stats,
.stats = dns_stats,
.stats_count = DNS_STAT_END,
.counters = &dns_counters,
.counters_size = sizeof(dns_counters),
.clearable = 0,
};
INITCALL1(STG_REGISTER, stats_register_module, &dns_stats_module);
/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
* no match is found.
*/
struct resolvers *find_resolvers_by_id(const char *id)
{
struct resolvers *res;
list_for_each_entry(res, &sec_resolvers, list) {
if (strcmp(res->id, id) == 0)
return res;
}
return NULL;
}
/* Compare hostnames in a case-insensitive way .
* Returns 0 if they are the same, non-zero otherwise
*/
static __inline int resolv_hostname_cmp(const char *name1, const char *name2, int len)
{
int i;
for (i = 0; i < len; i++)
if (tolower((unsigned char)name1[i]) != tolower((unsigned char)name2[i]))
return -1;
return 0;
}
/* Returns a pointer on the SRV request matching the name <name> for the proxy
* <px>. NULL is returned if no match is found.
*/
struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
{
struct resolv_srvrq *srvrq;
list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
return srvrq;
}
return NULL;
}
/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
* NULL if an error occurred. */
struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
{
struct proxy *px = srv->proxy;
struct resolv_srvrq *srvrq = NULL;
int fqdn_len, hostname_dn_len;
fqdn_len = strlen(fqdn);
hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len + 1, trash.area,
trash.size);
if (hostname_dn_len == -1) {
ha_alert("%s '%s', server '%s': failed to parse FQDN '%s'\n",
proxy_type_str(px), px->id, srv->id, fqdn);
goto err;
}
if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
ha_alert("%s '%s', server '%s': out of memory\n",
proxy_type_str(px), px->id, srv->id);
goto err;
}
srvrq->obj_type = OBJ_TYPE_SRVRQ;
srvrq->proxy = px;
srvrq->name = strdup(fqdn);
srvrq->hostname_dn = strdup(trash.area);
srvrq->hostname_dn_len = hostname_dn_len;
if (!srvrq->name || !srvrq->hostname_dn) {
ha_alert("%s '%s', server '%s': out of memory\n",
proxy_type_str(px), px->id, srv->id);
goto err;
}
LIST_INIT(&srvrq->attached_servers);
srvrq->named_servers = EB_ROOT;
LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
return srvrq;
err:
if (srvrq) {
free(srvrq->name);
free(srvrq->hostname_dn);
free(srvrq);
}
return NULL;
}
/* finds and return the SRV answer item associated to a requester (whose type is 'server').
*
* returns NULL in case of error or not found.
*/
struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
{
struct resolv_resolution *res;
struct resolv_answer_item *item;
struct server *srv;
if (!requester)
return NULL;
if ((srv = objt_server(requester->owner)) == NULL)
return NULL;
/* check if the server is managed by a SRV record */
if (srv->srvrq == NULL)
return NULL;
res = srv->srvrq->requester->resolution;
/* search an ANSWER record whose target points to the server's hostname and whose port is
* the same as server's svc_port */
list_for_each_entry(item, &res->response.answer_list, list) {
if (resolv_hostname_cmp(srv->hostname_dn, item->target, srv->hostname_dn_len) == 0 &&
(srv->svc_port == item->port))
return item;
}
return NULL;
}
/* 2 bytes random generator to generate DNS query ID */
static inline uint16_t resolv_rnd16(void)
{
if (!resolv_query_id_seed)
resolv_query_id_seed = now_ms;
resolv_query_id_seed ^= resolv_query_id_seed << 13;
resolv_query_id_seed ^= resolv_query_id_seed >> 7;
resolv_query_id_seed ^= resolv_query_id_seed << 17;
return resolv_query_id_seed;
}
static inline int resolv_resolution_timeout(struct resolv_resolution *res)
{
return res->resolvers->timeout.resolve;
}
/* Updates a resolvers' task timeout for next wake up and queue it */
static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
{
struct resolv_resolution *res;
int next;
next = tick_add(now_ms, resolvers->timeout.resolve);
if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
next = MIN(next, tick_add(res->last_query, resolvers->timeout.retry));
}
list_for_each_entry(res, &resolvers->resolutions.wait, list)
next = MIN(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
resolvers->t->expire = next;
task_queue(resolvers->t);
}
/* Forges a DNS query. It needs the following information from the caller:
* - <query_id> : the DNS query id corresponding to this query
* - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
* - <hostname_dn> : hostname in domain name format
* - <hostname_dn_len> : length of <hostname_dn>
*
* To store the query, the caller must pass a buffer <buf> and its size
* <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
* too short.
*/
static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
{
struct dns_header dns_hdr;
struct dns_question qinfo;
struct dns_additional_record edns;
char *p = buf;
if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
return -1;
memset(buf, 0, bufsize);
/* Set dns query headers */
dns_hdr.id = (unsigned short) htons(query_id);
dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
dns_hdr.qdcount = htons(1); /* 1 question */
dns_hdr.ancount = 0;
dns_hdr.nscount = 0;
dns_hdr.arcount = htons(1);
memcpy(p, &dns_hdr, sizeof(dns_hdr));
p += sizeof(dns_hdr);
/* Set up query hostname */
memcpy(p, hostname_dn, hostname_dn_len);
p += hostname_dn_len;
*p++ = 0;
/* Set up query info (type and class) */
qinfo.qtype = htons(query_type);
qinfo.qclass = htons(DNS_RCLASS_IN);
memcpy(p, &qinfo, sizeof(qinfo));
p += sizeof(qinfo);
/* Set the DNS extension */
edns.name = 0;
edns.type = htons(DNS_RTYPE_OPT);
edns.udp_payload_size = htons(accepted_payload_size);
edns.extension = 0;
edns.data_length = 0;
memcpy(p, &edns, sizeof(edns));
p += sizeof(edns);
return (p - buf);
}
/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
* success, -1 otherwise.
*/
static int resolv_send_query(struct resolv_resolution *resolution)
{
struct resolvers *resolvers = resolution->resolvers;
struct dns_nameserver *ns;
int len;
/* Update resolution */
resolution->nb_queries = 0;
resolution->nb_responses = 0;
resolution->last_query = now_ms;
len = resolv_build_query(resolution->query_id, resolution->query_type,
resolvers->accepted_payload_size,
resolution->hostname_dn, resolution->hostname_dn_len,
trash.area, trash.size);
list_for_each_entry(ns, &resolvers->nameservers, list) {
if (len < 0) {
ns->counters->snd_error++;
continue;
}
if (dns_send_nameserver(ns, trash.area, len) < 0)
ns->counters->snd_error++;
else
resolution->nb_queries++;
}
/* Push the resolution at the end of the active list */
LIST_DELETE(&resolution->list);
LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
return 0;
}
/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
* skipped and -1 if an error occurred.
*/
static int
resolv_run_resolution(struct resolv_resolution *resolution)
{
struct resolvers *resolvers = resolution->resolvers;
int query_id, i;
/* Avoid sending requests for resolutions that don't yet have an
* hostname, ie resolutions linked to servers that do not yet have an
* fqdn */
if (!resolution->hostname_dn)
return 0;
/* Check if a resolution has already been started for this server return
* directly to avoid resolution pill up. */
if (resolution->step != RSLV_STEP_NONE)
return 0;
/* Generates a new query id. We try at most 100 times to find a free
* query id */
for (i = 0; i < 100; ++i) {
query_id = resolv_rnd16();
if (!eb32_lookup(&resolvers->query_ids, query_id))
break;
query_id = -1;
}
if (query_id == -1) {
send_log(NULL, LOG_NOTICE,
"could not generate a query id for %s, in resolvers %s.\n",
resolution->hostname_dn, resolvers->id);
return -1;
}
/* Update resolution parameters */
resolution->query_id = query_id;
resolution->qid.key = query_id;
resolution->step = RSLV_STEP_RUNNING;
resolution->query_type = resolution->prefered_query_type;
resolution->try = resolvers->resolve_retries;
eb32_insert(&resolvers->query_ids, &resolution->qid);
/* Send the DNS query */
resolution->try -= 1;
resolv_send_query(resolution);
return 1;
}
/* Performs a name resolution for the requester <req> */
void resolv_trigger_resolution(struct resolv_requester *req)
{
struct resolvers *resolvers;
struct resolv_resolution *res;
int exp;
if (!req || !req->resolution)
return;
res = req->resolution;
resolvers = res->resolvers;
/* The resolution must not be triggered yet. Use the cached response, if
* valid */
exp = tick_add(res->last_resolution, resolvers->hold.valid);
if (resolvers->t && (res->status != RSLV_STATUS_VALID ||
!tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms)))
task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
}
/* Resets some resolution parameters to initial values and also delete the query
* ID from the resolver's tree.
*/
static void resolv_reset_resolution(struct resolv_resolution *resolution)
{
/* update resolution status */
resolution->step = RSLV_STEP_NONE;
resolution->try = 0;
resolution->last_resolution = now_ms;
resolution->nb_queries = 0;
resolution->nb_responses = 0;
resolution->query_type = resolution->prefered_query_type;
/* clean up query id */
eb32_delete(&resolution->qid);
resolution->query_id = 0;
resolution->qid.key = 0;
}
/* Returns the query id contained in a DNS response */
static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
{
return resp[0] * 256 + resp[1];
}
/* Analyses, re-builds and copies the name <name> from the DNS response packet
* <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
* for compressed data. The result is copied into <dest>, ensuring we don't
* overflow using <dest_len> Returns the number of bytes the caller can move
* forward. If 0 it means an error occurred while parsing the name. <offset> is
* the number of bytes the caller could move forward.
*/
int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
unsigned char *name, char *destination, int dest_len,
int *offset, unsigned int depth)
{
int nb_bytes = 0, n = 0;
int label_len;
unsigned char *reader = name;
char *dest = destination;
while (1) {
if (reader >= bufend)
goto err;
/* Name compression is in use */
if ((*reader & 0xc0) == 0xc0) {
if (reader + 1 >= bufend)
goto err;
/* Must point BEFORE current position */
if ((buffer + reader[1]) > reader)
goto err;
if (depth++ > 100)
goto err;
n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
dest, dest_len - nb_bytes, offset, depth);
if (n == 0)
goto err;
dest += n;
nb_bytes += n;
goto out;
}
label_len = *reader;
if (label_len == 0)
goto out;
/* Check if:
* - we won't read outside the buffer
* - there is enough place in the destination
*/
if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
goto err;
/* +1 to take label len + label string */
label_len++;
memcpy(dest, reader, label_len);
dest += label_len;
nb_bytes += label_len;
reader += label_len;
}
out:
/* offset computation:
* parse from <name> until finding either NULL or a pointer "c0xx"
*/
reader = name;
*offset = 0;
while (reader < bufend) {
if ((reader[0] & 0xc0) == 0xc0) {
*offset += 2;
break;
}
else if (*reader == 0) {
*offset += 1;
break;
}
*offset += 1;
++reader;
}
return nb_bytes;
err:
return 0;
}
/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
* happens when an SRV item is purged or when the server status is considered as
* obsolete.
*
* Must be called with the DNS lock held.
*/
static void resolv_srvrq_cleanup_srv(struct server *srv)
{
resolv_unlink_resolution(srv->resolv_requester, 0);
HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
srvrq_update_srv_status(srv, 1);
ha_free(&srv->hostname);
ha_free(&srv->hostname_dn);
srv->hostname_dn_len = 0;
memset(&srv->addr, 0, sizeof(srv->addr));
srv->svc_port = 0;
srv->flags |= SRV_F_NO_RESOLUTION;
ebpt_delete(&srv->host_dn);
ha_free(&srv->host_dn.key);
HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
LIST_DELETE(&srv->srv_rec_item);
LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
srv->srvrq_check->expire = TICK_ETERNITY;
}
/* Takes care to cleanup a server resolution when it is outdated. This only
* happens for a server relying on a SRV record.
*/
static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
{
struct server *srv = context;
if (!tick_is_expired(t->expire, now_ms))
goto end;
HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
resolv_srvrq_cleanup_srv(srv);
HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
end:
return t;
}
/* Checks for any obsolete record, also identify any SRV request, and try to
* find a corresponding server.
*/
static void resolv_check_response(struct resolv_resolution *res)
{
struct resolvers *resolvers = res->resolvers;
struct resolv_requester *req;
struct resolv_answer_item *item, *itemback;
struct server *srv, *srvback;
struct resolv_srvrq *srvrq;
list_for_each_entry_safe(item, itemback, &res->response.answer_list, list) {
struct resolv_answer_item *ar_item = item->ar_item;
/* clean up obsolete Additional record */
if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
/* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
* item is also obsolete.
*/
pool_free(resolv_answer_item_pool, ar_item);
item->ar_item = NULL;
}
/* Remove obsolete items */
if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
/* Remove any associated server */
list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
LIST_DEL_INIT(&srv->ip_rec_item);
}
}
else if (item->type == DNS_RTYPE_SRV) {
/* Remove any associated server */
list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
resolv_srvrq_cleanup_srv(srv);
}
LIST_DELETE(&item->list);
if (item->ar_item) {
pool_free(resolv_answer_item_pool, item->ar_item);
item->ar_item = NULL;
}
pool_free(resolv_answer_item_pool, item);
continue;
}
if (item->type != DNS_RTYPE_SRV)
continue;
/* Now process SRV records */
list_for_each_entry(req, &res->requesters, list) {
struct ebpt_node *node;
char target[DNS_MAX_NAME_SIZE+1];
int i;
if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
continue;
/* Check if a server already uses that record */
srv = NULL;
list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
if (srv->srvrq == srvrq) {
HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
goto srv_found;
}
}
/* If not empty we try to match a server
* in server state file tree with the same hostname
*/
if (!eb_is_empty(&srvrq->named_servers)) {
srv = NULL;
/* convert the key to lookup in lower case */
for (i = 0 ; item->target[i] ; i++)
target[i] = tolower(item->target[i]);
target[i] = 0;
node = ebis_lookup(&srvrq->named_servers, target);
if (node) {
srv = ebpt_entry(node, struct server, host_dn);
HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
/* an entry was found with the same hostname
* let check this node if the port matches
* and try next node if the hostname
* is still the same
*/
while (1) {
if (srv->svc_port == item->port) {
/* server found, we remove it from tree */
ebpt_delete(node);
ha_free(&srv->host_dn.key);
goto srv_found;
}
HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
node = ebpt_next(node);
if (!node)
break;
srv = ebpt_entry(node, struct server, host_dn);
HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
if ((item->data_len != srv->hostname_dn_len)
|| resolv_hostname_cmp(srv->hostname_dn, item->target, item->data_len)) {
HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
break;
}
}
}
}
/* Pick the first server listed in srvrq (those ones don't
* have hostname and are free to use)
*/
srv = NULL;
list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
LIST_DEL_INIT(&srv->srv_rec_item);
HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
goto srv_found;
}
srv = NULL;
srv_found:
/* And update this server, if found (srv is locked here) */
if (srv) {
/* re-enable DNS resolution for this server by default */
srv->flags &= ~SRV_F_NO_RESOLUTION;
srv->srvrq_check->expire = TICK_ETERNITY;
/* Check if an Additional Record is associated to this SRV record.
* Perform some sanity checks too to ensure the record can be used.
* If all fine, we simply pick up the IP address found and associate
* it to the server. And DNS resolution is disabled for this server.
*/
if ((item->ar_item != NULL) &&
(item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
{
switch (item->ar_item->type) {
case DNS_RTYPE_A:
srv_update_addr(srv, &(((struct sockaddr_in*)&item->ar_item->address)->sin_addr), AF_INET, "DNS additional record");
break;
case DNS_RTYPE_AAAA:
srv_update_addr(srv, &(((struct sockaddr_in6*)&item->ar_item->address)->sin6_addr), AF_INET6, "DNS additional record");
break;
}
srv->flags |= SRV_F_NO_RESOLUTION;
/* Unlink A/AAAA resolution for this server if there is an AR item.
* It is usless to perform an extra resolution
*/
resolv_unlink_resolution(srv->resolv_requester, 0);
}
if (!srv->hostname_dn) {
const char *msg = NULL;
char hostname[DNS_MAX_NAME_SIZE];
if (resolv_dn_label_to_str(item->target, item->data_len+1,
hostname, DNS_MAX_NAME_SIZE) == -1) {
HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
continue;
}
msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
if (msg)
send_log(srv->proxy, LOG_NOTICE, "%s", msg);
}
if (!LIST_INLIST(&srv->srv_rec_item))
LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
/* If there is no AR item responsible of the FQDN resolution,
* trigger a dedicated DNS resolution
*/
if (!srv->resolv_requester || !srv->resolv_requester->resolution)
resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
}
/* Update the server status */
srvrq_update_srv_status(srv, (srv->addr.ss_family != AF_INET && srv->addr.ss_family != AF_INET6));
srv->svc_port = item->port;
srv->flags &= ~SRV_F_MAPPORTS;
if (!srv->resolv_opts.ignore_weight) {
char weight[9];
int ha_weight;
/* DNS weight range if from 0 to 65535
* HAProxy weight is from 0 to 256
* The rule below ensures that weight 0 is well respected
* while allowing a "mapping" from DNS weight into HAProxy's one.
*/
ha_weight = (item->weight + 255) / 256;
snprintf(weight, sizeof(weight), "%d", ha_weight);
server_parse_weight_change_request(srv, weight);
}
HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
}
}
}
}
/* Validates that the buffer DNS response provided in <resp> and finishing
* before <bufend> is valid from a DNS protocol point of view.
*
* The result is stored in <resolution>' response, buf_response,
* response_query_records and response_answer_records members.
*
* This function returns one of the RSLV_RESP_* code to indicate the type of
* error found.
*/
static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
struct resolv_resolution *resolution, int max_answer_records)
{
unsigned char *reader;
char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
int len, flags, offset;
int query_record_id;
int nb_saved_records;
struct resolv_query_item *query;
struct resolv_answer_item *answer_record, *tmp_record;
struct resolv_response *r_res;
int i, found = 0;
int cause = RSLV_RESP_ERROR;
reader = resp;
len = 0;
previous_dname = NULL;
query = NULL;
answer_record = NULL;
/* Initialization of response buffer and structure */
r_res = &resolution->response;
/* query id */
if (reader + 2 >= bufend)
goto invalid_resp;
r_res->header.id = reader[0] * 256 + reader[1];
reader += 2;
/* Flags and rcode are stored over 2 bytes
* First byte contains:
* - response flag (1 bit)
* - opcode (4 bits)
* - authoritative (1 bit)
* - truncated (1 bit)
* - recursion desired (1 bit)
*/
if (reader + 2 >= bufend)
goto invalid_resp;
flags = reader[0] * 256 + reader[1];
if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
cause = RSLV_RESP_NX_DOMAIN;
goto return_error;
}
else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
cause = RSLV_RESP_REFUSED;
goto return_error;
}
else {
cause = RSLV_RESP_ERROR;
goto return_error;
}
}
/* Move forward 2 bytes for flags */
reader += 2;
/* 2 bytes for question count */
if (reader + 2 >= bufend)
goto invalid_resp;
r_res->header.qdcount = reader[0] * 256 + reader[1];
/* (for now) we send one query only, so we expect only one in the
* response too */
if (r_res->header.qdcount != 1) {
cause = RSLV_RESP_QUERY_COUNT_ERROR;
goto return_error;
}
if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
goto invalid_resp;
reader += 2;
/* 2 bytes for answer count */
if (reader + 2 >= bufend)
goto invalid_resp;
r_res->header.ancount = reader[0] * 256 + reader[1];
if (r_res->header.ancount == 0) {
cause = RSLV_RESP_ANCOUNT_ZERO;
goto return_error;
}
/* Check if too many records are announced */
if (r_res->header.ancount > max_answer_records)
goto invalid_resp;
reader += 2;
/* 2 bytes authority count */
if (reader + 2 >= bufend)
goto invalid_resp;
r_res->header.nscount = reader[0] * 256 + reader[1];
reader += 2;
/* 2 bytes additional count */
if (reader + 2 >= bufend)
goto invalid_resp;
r_res->header.arcount = reader[0] * 256 + reader[1];
reader += 2;
/* Parsing dns queries */
LIST_INIT(&r_res->query_list);
for (query_record_id = 0; query_record_id < r_res->header.qdcount; query_record_id++) {
/* Use next pre-allocated resolv_query_item after ensuring there is
* still one available.
* It's then added to our packet query list. */
if (query_record_id > DNS_MAX_QUERY_RECORDS)
goto invalid_resp;
query = &resolution->response_query_records[query_record_id];
LIST_APPEND(&r_res->query_list, &query->list);
/* Name is a NULL terminated string in our case, since we have
* one query per response and the first one can't be compressed
* (using the 0x0c format) */
offset = 0;
len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
if (len == 0)
goto invalid_resp;
reader += offset;
previous_dname = query->name;
/* move forward 2 bytes for question type */
if (reader + 2 >= bufend)
goto invalid_resp;
query->type = reader[0] * 256 + reader[1];
reader += 2;
/* move forward 2 bytes for question class */
if (reader + 2 >= bufend)
goto invalid_resp;
query->class = reader[0] * 256 + reader[1];
reader += 2;
}
/* TRUNCATED flag must be checked after we could read the query type
* because a TRUNCATED SRV query type response can still be exploited */
if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
cause = RSLV_RESP_TRUNCATED;
goto return_error;
}
/* now parsing response records */
nb_saved_records = 0;
for (i = 0; i < r_res->header.ancount; i++) {
if (reader >= bufend)
goto invalid_resp;
answer_record = pool_alloc(resolv_answer_item_pool);
if (answer_record == NULL)
goto invalid_resp;
/* initialization */
answer_record->ar_item = NULL;
answer_record->last_seen = TICK_ETERNITY;
LIST_INIT(&answer_record->attached_servers);
offset = 0;
len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);