/
iterator.c
4512 lines (4305 loc) · 154 KB
/
iterator.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
/*
* iterator/iterator.c - iterative resolver DNS query response module
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file contains a module that performs recursive iterative DNS query
* processing.
*/
#include "config.h"
#include "iterator/iterator.h"
#include "iterator/iter_utils.h"
#include "iterator/iter_hints.h"
#include "iterator/iter_fwd.h"
#include "iterator/iter_donotq.h"
#include "iterator/iter_delegpt.h"
#include "iterator/iter_resptype.h"
#include "iterator/iter_scrub.h"
#include "iterator/iter_priv.h"
#include "validator/val_neg.h"
#include "services/cache/dns.h"
#include "services/cache/rrset.h"
#include "services/cache/infra.h"
#include "services/authzone.h"
#include "util/module.h"
#include "util/netevent.h"
#include "util/net_help.h"
#include "util/regional.h"
#include "util/data/dname.h"
#include "util/data/msgencode.h"
#include "util/fptr_wlist.h"
#include "util/config_file.h"
#include "util/random.h"
#include "sldns/rrdef.h"
#include "sldns/wire2str.h"
#include "sldns/str2wire.h"
#include "sldns/parseutil.h"
#include "sldns/sbuffer.h"
/* in msec */
int UNKNOWN_SERVER_NICENESS = 376;
/* in msec */
int USEFUL_SERVER_TOP_TIMEOUT = 120000;
/* Equals USEFUL_SERVER_TOP_TIMEOUT*4 */
int BLACKLIST_PENALTY = (120000*4);
static void target_count_increase_nx(struct iter_qstate* iq, int num);
int
iter_init(struct module_env* env, int id)
{
struct iter_env* iter_env = (struct iter_env*)calloc(1,
sizeof(struct iter_env));
if(!iter_env) {
log_err("malloc failure");
return 0;
}
env->modinfo[id] = (void*)iter_env;
lock_basic_init(&iter_env->queries_ratelimit_lock);
lock_protect(&iter_env->queries_ratelimit_lock,
&iter_env->num_queries_ratelimited,
sizeof(iter_env->num_queries_ratelimited));
if(!iter_apply_cfg(iter_env, env->cfg)) {
log_err("iterator: could not apply configuration settings.");
return 0;
}
return 1;
}
/** delete caps_whitelist element */
static void
caps_free(struct rbnode_type* n, void* ATTR_UNUSED(d))
{
if(n) {
free(((struct name_tree_node*)n)->name);
free(n);
}
}
void
iter_deinit(struct module_env* env, int id)
{
struct iter_env* iter_env;
if(!env || !env->modinfo[id])
return;
iter_env = (struct iter_env*)env->modinfo[id];
lock_basic_destroy(&iter_env->queries_ratelimit_lock);
free(iter_env->target_fetch_policy);
priv_delete(iter_env->priv);
donotq_delete(iter_env->donotq);
if(iter_env->caps_white) {
traverse_postorder(iter_env->caps_white, caps_free, NULL);
free(iter_env->caps_white);
}
free(iter_env);
env->modinfo[id] = NULL;
}
/** new query for iterator */
static int
iter_new(struct module_qstate* qstate, int id)
{
struct iter_qstate* iq = (struct iter_qstate*)regional_alloc(
qstate->region, sizeof(struct iter_qstate));
qstate->minfo[id] = iq;
if(!iq)
return 0;
memset(iq, 0, sizeof(*iq));
iq->state = INIT_REQUEST_STATE;
iq->final_state = FINISHED_STATE;
iq->an_prepend_list = NULL;
iq->an_prepend_last = NULL;
iq->ns_prepend_list = NULL;
iq->ns_prepend_last = NULL;
iq->dp = NULL;
iq->depth = 0;
iq->num_target_queries = 0;
iq->num_current_queries = 0;
iq->query_restart_count = 0;
iq->referral_count = 0;
iq->sent_count = 0;
iq->ratelimit_ok = 0;
iq->target_count = NULL;
iq->dp_target_count = 0;
iq->wait_priming_stub = 0;
iq->refetch_glue = 0;
iq->dnssec_expected = 0;
iq->dnssec_lame_query = 0;
iq->chase_flags = qstate->query_flags;
/* Start with the (current) qname. */
iq->qchase = qstate->qinfo;
outbound_list_init(&iq->outlist);
iq->minimise_count = 0;
iq->timeout_count = 0;
if (qstate->env->cfg->qname_minimisation)
iq->minimisation_state = INIT_MINIMISE_STATE;
else
iq->minimisation_state = DONOT_MINIMISE_STATE;
memset(&iq->qinfo_out, 0, sizeof(struct query_info));
return 1;
}
/**
* Transition to the next state. This can be used to advance a currently
* processing event. It cannot be used to reactivate a forEvent.
*
* @param iq: iterator query state
* @param nextstate The state to transition to.
* @return true. This is so this can be called as the return value for the
* actual process*State() methods. (Transitioning to the next state
* implies further processing).
*/
static int
next_state(struct iter_qstate* iq, enum iter_state nextstate)
{
/* If transitioning to a "response" state, make sure that there is a
* response */
if(iter_state_is_responsestate(nextstate)) {
if(iq->response == NULL) {
log_err("transitioning to response state sans "
"response.");
}
}
iq->state = nextstate;
return 1;
}
/**
* Transition an event to its final state. Final states always either return
* a result up the module chain, or reactivate a dependent event. Which
* final state to transition to is set in the module state for the event when
* it was created, and depends on the original purpose of the event.
*
* The response is stored in the qstate->buf buffer.
*
* @param iq: iterator query state
* @return false. This is so this method can be used as the return value for
* the processState methods. (Transitioning to the final state
*/
static int
final_state(struct iter_qstate* iq)
{
return next_state(iq, iq->final_state);
}
/**
* Callback routine to handle errors in parent query states
* @param qstate: query state that failed.
* @param id: module id.
* @param super: super state.
*/
static void
error_supers(struct module_qstate* qstate, int id, struct module_qstate* super)
{
struct iter_env* ie = (struct iter_env*)qstate->env->modinfo[id];
struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id];
if(qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) {
/* mark address as failed. */
struct delegpt_ns* dpns = NULL;
super_iq->num_target_queries--;
if(super_iq->dp)
dpns = delegpt_find_ns(super_iq->dp,
qstate->qinfo.qname, qstate->qinfo.qname_len);
if(!dpns) {
/* not interested */
/* this can happen, for eg. qname minimisation asked
* for an NXDOMAIN to be validated, and used qtype
* A for that, and the error of that, the name, is
* not listed in super_iq->dp */
verbose(VERB_ALGO, "subq error, but not interested");
log_query_info(VERB_ALGO, "superq", &super->qinfo);
return;
} else {
/* see if the failure did get (parent-lame) info */
if(!cache_fill_missing(super->env, super_iq->qchase.qclass,
super->region, super_iq->dp))
log_err("out of memory adding missing");
}
delegpt_mark_neg(dpns, qstate->qinfo.qtype);
if((dpns->got4 == 2 || (!ie->supports_ipv4 && !ie->use_nat64)) &&
(dpns->got6 == 2 || !ie->supports_ipv6)) {
dpns->resolved = 1; /* mark as failed */
target_count_increase_nx(super_iq, 1);
}
}
if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) {
/* prime failed to get delegation */
super_iq->dp = NULL;
}
/* evaluate targets again */
super_iq->state = QUERYTARGETS_STATE;
/* super becomes runnable, and will process this change */
}
/**
* Return an error to the client
* @param qstate: our query state
* @param id: module id
* @param rcode: error code (DNS errcode).
* @return: 0 for use by caller, to make notation easy, like:
* return error_response(..).
*/
static int
error_response(struct module_qstate* qstate, int id, int rcode)
{
verbose(VERB_QUERY, "return error response %s",
sldns_lookup_by_id(sldns_rcodes, rcode)?
sldns_lookup_by_id(sldns_rcodes, rcode)->name:"??");
qstate->return_rcode = rcode;
qstate->return_msg = NULL;
qstate->ext_state[id] = module_finished;
return 0;
}
/**
* Return an error to the client and cache the error code in the
* message cache (so per qname, qtype, qclass).
* @param qstate: our query state
* @param id: module id
* @param rcode: error code (DNS errcode).
* @return: 0 for use by caller, to make notation easy, like:
* return error_response(..).
*/
static int
error_response_cache(struct module_qstate* qstate, int id, int rcode)
{
struct reply_info err;
struct msgreply_entry* msg;
if(qstate->no_cache_store) {
return error_response(qstate, id, rcode);
}
if(qstate->prefetch_leeway > NORR_TTL) {
verbose(VERB_ALGO, "error response for prefetch in cache");
/* attempt to adjust the cache entry prefetch */
if(dns_cache_prefetch_adjust(qstate->env, &qstate->qinfo,
NORR_TTL, qstate->query_flags))
return error_response(qstate, id, rcode);
/* if that fails (not in cache), fall through to store err */
}
if((msg=msg_cache_lookup(qstate->env,
qstate->qinfo.qname, qstate->qinfo.qname_len,
qstate->qinfo.qtype, qstate->qinfo.qclass,
qstate->query_flags, 0,
qstate->env->cfg->serve_expired_ttl_reset)) != NULL) {
struct reply_info* rep = (struct reply_info*)msg->entry.data;
if(qstate->env->cfg->serve_expired &&
qstate->env->cfg->serve_expired_ttl_reset && rep &&
*qstate->env->now + qstate->env->cfg->serve_expired_ttl
> rep->serve_expired_ttl) {
verbose(VERB_ALGO, "reset serve-expired-ttl for "
"response in cache");
rep->serve_expired_ttl = *qstate->env->now +
qstate->env->cfg->serve_expired_ttl;
}
if(rep && (FLAGS_GET_RCODE(rep->flags) ==
LDNS_RCODE_NOERROR ||
FLAGS_GET_RCODE(rep->flags) ==
LDNS_RCODE_NXDOMAIN ||
FLAGS_GET_RCODE(rep->flags) ==
LDNS_RCODE_YXDOMAIN) &&
(qstate->env->cfg->serve_expired ||
*qstate->env->now <= rep->ttl)) {
/* we have a good entry, don't overwrite */
lock_rw_unlock(&msg->entry.lock);
return error_response(qstate, id, rcode);
}
lock_rw_unlock(&msg->entry.lock);
/* nothing interesting is cached (already error response or
* expired good record when we don't serve expired), so this
* servfail cache entry is useful (stops waste of time on this
* servfail NORR_TTL) */
}
/* store in cache */
memset(&err, 0, sizeof(err));
err.flags = (uint16_t)(BIT_QR | BIT_RA);
FLAGS_SET_RCODE(err.flags, rcode);
err.qdcount = 1;
err.ttl = NORR_TTL;
err.prefetch_ttl = PREFETCH_TTL_CALC(err.ttl);
err.serve_expired_ttl = NORR_TTL;
/* do not waste time trying to validate this servfail */
err.security = sec_status_indeterminate;
verbose(VERB_ALGO, "store error response in message cache");
iter_dns_store(qstate->env, &qstate->qinfo, &err, 0, 0, 0, NULL,
qstate->query_flags, qstate->qstarttime);
return error_response(qstate, id, rcode);
}
/** check if prepend item is duplicate item */
static int
prepend_is_duplicate(struct ub_packed_rrset_key** sets, size_t to,
struct ub_packed_rrset_key* dup)
{
size_t i;
for(i=0; i<to; i++) {
if(sets[i]->rk.type == dup->rk.type &&
sets[i]->rk.rrset_class == dup->rk.rrset_class &&
sets[i]->rk.dname_len == dup->rk.dname_len &&
query_dname_compare(sets[i]->rk.dname, dup->rk.dname)
== 0)
return 1;
}
return 0;
}
/** prepend the prepend list in the answer and authority section of dns_msg */
static int
iter_prepend(struct iter_qstate* iq, struct dns_msg* msg,
struct regional* region)
{
struct iter_prep_list* p;
struct ub_packed_rrset_key** sets;
size_t num_an = 0, num_ns = 0;;
for(p = iq->an_prepend_list; p; p = p->next)
num_an++;
for(p = iq->ns_prepend_list; p; p = p->next)
num_ns++;
if(num_an + num_ns == 0)
return 1;
verbose(VERB_ALGO, "prepending %d rrsets", (int)num_an + (int)num_ns);
if(num_an > RR_COUNT_MAX || num_ns > RR_COUNT_MAX ||
msg->rep->rrset_count > RR_COUNT_MAX) return 0; /* overflow */
sets = regional_alloc(region, (num_an+num_ns+msg->rep->rrset_count) *
sizeof(struct ub_packed_rrset_key*));
if(!sets)
return 0;
/* ANSWER section */
num_an = 0;
for(p = iq->an_prepend_list; p; p = p->next) {
sets[num_an++] = p->rrset;
if(ub_packed_rrset_ttl(p->rrset) < msg->rep->ttl)
msg->rep->ttl = ub_packed_rrset_ttl(p->rrset);
}
memcpy(sets+num_an, msg->rep->rrsets, msg->rep->an_numrrsets *
sizeof(struct ub_packed_rrset_key*));
/* AUTH section */
num_ns = 0;
for(p = iq->ns_prepend_list; p; p = p->next) {
if(prepend_is_duplicate(sets+msg->rep->an_numrrsets+num_an,
num_ns, p->rrset) || prepend_is_duplicate(
msg->rep->rrsets+msg->rep->an_numrrsets,
msg->rep->ns_numrrsets, p->rrset))
continue;
sets[msg->rep->an_numrrsets + num_an + num_ns++] = p->rrset;
if(ub_packed_rrset_ttl(p->rrset) < msg->rep->ttl)
msg->rep->ttl = ub_packed_rrset_ttl(p->rrset);
}
memcpy(sets + num_an + msg->rep->an_numrrsets + num_ns,
msg->rep->rrsets + msg->rep->an_numrrsets,
(msg->rep->ns_numrrsets + msg->rep->ar_numrrsets) *
sizeof(struct ub_packed_rrset_key*));
/* NXDOMAIN rcode can stay if we prepended DNAME/CNAMEs, because
* this is what recursors should give. */
msg->rep->rrset_count += num_an + num_ns;
msg->rep->an_numrrsets += num_an;
msg->rep->ns_numrrsets += num_ns;
msg->rep->rrsets = sets;
return 1;
}
/**
* Find rrset in ANSWER prepend list.
* to avoid duplicate DNAMEs when a DNAME is traversed twice.
* @param iq: iterator query state.
* @param rrset: rrset to add.
* @return false if not found
*/
static int
iter_find_rrset_in_prepend_answer(struct iter_qstate* iq,
struct ub_packed_rrset_key* rrset)
{
struct iter_prep_list* p = iq->an_prepend_list;
while(p) {
if(ub_rrset_compare(p->rrset, rrset) == 0 &&
rrsetdata_equal((struct packed_rrset_data*)p->rrset
->entry.data, (struct packed_rrset_data*)rrset
->entry.data))
return 1;
p = p->next;
}
return 0;
}
/**
* Add rrset to ANSWER prepend list
* @param qstate: query state.
* @param iq: iterator query state.
* @param rrset: rrset to add.
* @return false on failure (malloc).
*/
static int
iter_add_prepend_answer(struct module_qstate* qstate, struct iter_qstate* iq,
struct ub_packed_rrset_key* rrset)
{
struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
qstate->region, sizeof(struct iter_prep_list));
if(!p)
return 0;
p->rrset = rrset;
p->next = NULL;
/* add at end */
if(iq->an_prepend_last)
iq->an_prepend_last->next = p;
else iq->an_prepend_list = p;
iq->an_prepend_last = p;
return 1;
}
/**
* Add rrset to AUTHORITY prepend list
* @param qstate: query state.
* @param iq: iterator query state.
* @param rrset: rrset to add.
* @return false on failure (malloc).
*/
static int
iter_add_prepend_auth(struct module_qstate* qstate, struct iter_qstate* iq,
struct ub_packed_rrset_key* rrset)
{
struct iter_prep_list* p = (struct iter_prep_list*)regional_alloc(
qstate->region, sizeof(struct iter_prep_list));
if(!p)
return 0;
p->rrset = rrset;
p->next = NULL;
/* add at end */
if(iq->ns_prepend_last)
iq->ns_prepend_last->next = p;
else iq->ns_prepend_list = p;
iq->ns_prepend_last = p;
return 1;
}
/**
* Given a CNAME response (defined as a response containing a CNAME or DNAME
* that does not answer the request), process the response, modifying the
* state as necessary. This follows the CNAME/DNAME chain and returns the
* final query name.
*
* sets the new query name, after following the CNAME/DNAME chain.
* @param qstate: query state.
* @param iq: iterator query state.
* @param msg: the response.
* @param mname: returned target new query name.
* @param mname_len: length of mname.
* @return false on (malloc) error.
*/
static int
handle_cname_response(struct module_qstate* qstate, struct iter_qstate* iq,
struct dns_msg* msg, uint8_t** mname, size_t* mname_len)
{
size_t i;
/* Start with the (current) qname. */
*mname = iq->qchase.qname;
*mname_len = iq->qchase.qname_len;
/* Iterate over the ANSWER rrsets in order, looking for CNAMEs and
* DNAMES. */
for(i=0; i<msg->rep->an_numrrsets; i++) {
struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
/* If there is a (relevant) DNAME, add it to the list.
* We always expect there to be CNAME that was generated
* by this DNAME following, so we don't process the DNAME
* directly. */
if(ntohs(r->rk.type) == LDNS_RR_TYPE_DNAME &&
dname_strict_subdomain_c(*mname, r->rk.dname) &&
!iter_find_rrset_in_prepend_answer(iq, r)) {
if(!iter_add_prepend_answer(qstate, iq, r))
return 0;
continue;
}
if(ntohs(r->rk.type) == LDNS_RR_TYPE_CNAME &&
query_dname_compare(*mname, r->rk.dname) == 0 &&
!iter_find_rrset_in_prepend_answer(iq, r)) {
/* Add this relevant CNAME rrset to the prepend list.*/
if(!iter_add_prepend_answer(qstate, iq, r))
return 0;
get_cname_target(r, mname, mname_len);
}
/* Other rrsets in the section are ignored. */
}
/* add authority rrsets to authority prepend, for wildcarded CNAMEs */
for(i=msg->rep->an_numrrsets; i<msg->rep->an_numrrsets +
msg->rep->ns_numrrsets; i++) {
struct ub_packed_rrset_key* r = msg->rep->rrsets[i];
/* only add NSEC/NSEC3, as they may be needed for validation */
if(ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC ||
ntohs(r->rk.type) == LDNS_RR_TYPE_NSEC3) {
if(!iter_add_prepend_auth(qstate, iq, r))
return 0;
}
}
return 1;
}
/** fill fail address for later recovery */
static void
fill_fail_addr(struct iter_qstate* iq, struct sockaddr_storage* addr,
socklen_t addrlen)
{
if(addrlen == 0) {
iq->fail_addr_type = 0;
return;
}
if(((struct sockaddr_in*)addr)->sin_family == AF_INET) {
iq->fail_addr_type = 4;
memcpy(&iq->fail_addr.in,
&((struct sockaddr_in*)addr)->sin_addr,
sizeof(iq->fail_addr.in));
}
#ifdef AF_INET6
else if(((struct sockaddr_in*)addr)->sin_family == AF_INET6) {
iq->fail_addr_type = 6;
memcpy(&iq->fail_addr.in6,
&((struct sockaddr_in6*)addr)->sin6_addr,
sizeof(iq->fail_addr.in6));
}
#endif
else {
iq->fail_addr_type = 0;
}
}
/** print fail addr to string */
static void
print_fail_addr(struct iter_qstate* iq, char* buf, size_t len)
{
if(iq->fail_addr_type == 4) {
if(inet_ntop(AF_INET, &iq->fail_addr.in, buf,
(socklen_t)len) == 0)
(void)strlcpy(buf, "(inet_ntop error)", len);
}
#ifdef AF_INET6
else if(iq->fail_addr_type == 6) {
if(inet_ntop(AF_INET6, &iq->fail_addr.in6, buf,
(socklen_t)len) == 0)
(void)strlcpy(buf, "(inet_ntop error)", len);
}
#endif
else
(void)strlcpy(buf, "", len);
}
/** add response specific error information for log servfail */
static void
errinf_reply(struct module_qstate* qstate, struct iter_qstate* iq)
{
if(qstate->env->cfg->val_log_level < 2 && !qstate->env->cfg->log_servfail)
return;
if((qstate->reply && qstate->reply->remote_addrlen != 0) ||
(iq->fail_addr_type != 0)) {
char from[256], frm[512];
if(qstate->reply && qstate->reply->remote_addrlen != 0)
addr_to_str(&qstate->reply->remote_addr,
qstate->reply->remote_addrlen, from,
sizeof(from));
else
print_fail_addr(iq, from, sizeof(from));
snprintf(frm, sizeof(frm), "from %s", from);
errinf(qstate, frm);
}
if(iq->scrub_failures || iq->parse_failures) {
if(iq->scrub_failures)
errinf(qstate, "upstream response failed scrub");
if(iq->parse_failures)
errinf(qstate, "could not parse upstream response");
} else if(iq->response == NULL && iq->timeout_count != 0) {
errinf(qstate, "upstream server timeout");
} else if(iq->response == NULL) {
errinf(qstate, "no server to query");
if(iq->dp) {
if(iq->dp->target_list == NULL)
errinf(qstate, "no addresses for nameservers");
else errinf(qstate, "nameserver addresses not usable");
if(iq->dp->nslist == NULL)
errinf(qstate, "have no nameserver names");
if(iq->dp->bogus)
errinf(qstate, "NS record was dnssec bogus");
}
}
if(iq->response && iq->response->rep) {
if(FLAGS_GET_RCODE(iq->response->rep->flags) != 0) {
char rcode[256], rc[32];
(void)sldns_wire2str_rcode_buf(
FLAGS_GET_RCODE(iq->response->rep->flags),
rc, sizeof(rc));
snprintf(rcode, sizeof(rcode), "got %s", rc);
errinf(qstate, rcode);
} else {
/* rcode NOERROR */
if(iq->response->rep->an_numrrsets == 0) {
errinf(qstate, "nodata answer");
}
}
}
}
/** see if last resort is possible - does config allow queries to parent */
static int
can_have_last_resort(struct module_env* env, uint8_t* nm, size_t ATTR_UNUSED(nmlen),
uint16_t qclass, int* have_dp, struct delegpt** retdp,
struct regional* region)
{
struct delegpt* dp = NULL;
int nolock = 0;
/* do not process a last resort (the parent side) if a stub
* or forward is configured, because we do not want to go 'above'
* the configured servers */
if(!dname_is_root(nm) &&
(dp = hints_find(env->hints, nm, qclass, nolock)) &&
/* has_parent side is turned off for stub_first, where we
* are allowed to go to the parent */
dp->has_parent_side_NS) {
if(retdp) *retdp = delegpt_copy(dp, region);
lock_rw_unlock(&env->hints->lock);
if(have_dp) *have_dp = 1;
return 0;
}
if(dp) {
lock_rw_unlock(&env->hints->lock);
dp = NULL;
}
if((dp = forwards_find(env->fwds, nm, qclass, nolock)) &&
/* has_parent_side is turned off for forward_first, where
* we are allowed to go to the parent */
dp->has_parent_side_NS) {
if(retdp) *retdp = delegpt_copy(dp, region);
lock_rw_unlock(&env->fwds->lock);
if(have_dp) *have_dp = 1;
return 0;
}
/* lock_() calls are macros that could be nothing, surround in {} */
if(dp) { lock_rw_unlock(&env->fwds->lock); }
return 1;
}
/** see if target name is caps-for-id whitelisted */
static int
is_caps_whitelisted(struct iter_env* ie, struct iter_qstate* iq)
{
if(!ie->caps_white) return 0; /* no whitelist, or no capsforid */
return name_tree_lookup(ie->caps_white, iq->qchase.qname,
iq->qchase.qname_len, dname_count_labels(iq->qchase.qname),
iq->qchase.qclass) != NULL;
}
/**
* Create target count structure for this query. This is always explicitly
* created for the parent query.
*/
static void
target_count_create(struct iter_qstate* iq)
{
if(!iq->target_count) {
iq->target_count = (int*)calloc(TARGET_COUNT_MAX, sizeof(int));
/* if calloc fails we simply do not track this number */
if(iq->target_count) {
iq->target_count[TARGET_COUNT_REF] = 1;
iq->nxns_dp = (uint8_t**)calloc(1, sizeof(uint8_t*));
}
}
}
static void
target_count_increase(struct iter_qstate* iq, int num)
{
target_count_create(iq);
if(iq->target_count)
iq->target_count[TARGET_COUNT_QUERIES] += num;
iq->dp_target_count++;
}
static void
target_count_increase_nx(struct iter_qstate* iq, int num)
{
target_count_create(iq);
if(iq->target_count)
iq->target_count[TARGET_COUNT_NX] += num;
}
/**
* Generate a subrequest.
* Generate a local request event. Local events are tied to this module, and
* have a corresponding (first tier) event that is waiting for this event to
* resolve to continue.
*
* @param qname The query name for this request.
* @param qnamelen length of qname
* @param qtype The query type for this request.
* @param qclass The query class for this request.
* @param qstate The event that is generating this event.
* @param id: module id.
* @param iq: The iterator state that is generating this event.
* @param initial_state The initial response state (normally this
* is QUERY_RESP_STATE, unless it is known that the request won't
* need iterative processing
* @param finalstate The final state for the response to this request.
* @param subq_ret: if newly allocated, the subquerystate, or NULL if it does
* not need initialisation.
* @param v: if true, validation is done on the subquery.
* @param detached: true if this qstate should not attach to the subquery
* @return false on error (malloc).
*/
static int
generate_sub_request(uint8_t* qname, size_t qnamelen, uint16_t qtype,
uint16_t qclass, struct module_qstate* qstate, int id,
struct iter_qstate* iq, enum iter_state initial_state,
enum iter_state finalstate, struct module_qstate** subq_ret, int v,
int detached)
{
struct module_qstate* subq = NULL;
struct iter_qstate* subiq = NULL;
uint16_t qflags = 0; /* OPCODE QUERY, no flags */
struct query_info qinf;
int prime = (finalstate == PRIME_RESP_STATE)?1:0;
int valrec = 0;
qinf.qname = qname;
qinf.qname_len = qnamelen;
qinf.qtype = qtype;
qinf.qclass = qclass;
qinf.local_alias = NULL;
/* RD should be set only when sending the query back through the INIT
* state. */
if(initial_state == INIT_REQUEST_STATE)
qflags |= BIT_RD;
/* We set the CD flag so we can send this through the "head" of
* the resolution chain, which might have a validator. We are
* uninterested in validating things not on the direct resolution
* path. */
if(!v) {
qflags |= BIT_CD;
valrec = 1;
}
if(detached) {
struct mesh_state* sub = NULL;
fptr_ok(fptr_whitelist_modenv_add_sub(
qstate->env->add_sub));
if(!(*qstate->env->add_sub)(qstate, &qinf,
qflags, prime, valrec, &subq, &sub)){
return 0;
}
}
else {
/* attach subquery, lookup existing or make a new one */
fptr_ok(fptr_whitelist_modenv_attach_sub(
qstate->env->attach_sub));
if(!(*qstate->env->attach_sub)(qstate, &qinf, qflags, prime,
valrec, &subq)) {
return 0;
}
}
*subq_ret = subq;
if(subq) {
/* initialise the new subquery */
subq->curmod = id;
subq->ext_state[id] = module_state_initial;
subq->minfo[id] = regional_alloc(subq->region,
sizeof(struct iter_qstate));
if(!subq->minfo[id]) {
log_err("init subq: out of memory");
fptr_ok(fptr_whitelist_modenv_kill_sub(
qstate->env->kill_sub));
(*qstate->env->kill_sub)(subq);
return 0;
}
subiq = (struct iter_qstate*)subq->minfo[id];
memset(subiq, 0, sizeof(*subiq));
subiq->num_target_queries = 0;
target_count_create(iq);
subiq->target_count = iq->target_count;
if(iq->target_count) {
iq->target_count[TARGET_COUNT_REF] ++; /* extra reference */
subiq->nxns_dp = iq->nxns_dp;
}
subiq->dp_target_count = 0;
subiq->num_current_queries = 0;
subiq->depth = iq->depth+1;
outbound_list_init(&subiq->outlist);
subiq->state = initial_state;
subiq->final_state = finalstate;
subiq->qchase = subq->qinfo;
subiq->chase_flags = subq->query_flags;
subiq->refetch_glue = 0;
if(qstate->env->cfg->qname_minimisation)
subiq->minimisation_state = INIT_MINIMISE_STATE;
else
subiq->minimisation_state = DONOT_MINIMISE_STATE;
memset(&subiq->qinfo_out, 0, sizeof(struct query_info));
}
return 1;
}
/**
* Generate and send a root priming request.
* @param qstate: the qtstate that triggered the need to prime.
* @param iq: iterator query state.
* @param id: module id.
* @param qclass: the class to prime.
* @return 0 on failure
*/
static int
prime_root(struct module_qstate* qstate, struct iter_qstate* iq, int id,
uint16_t qclass)
{
struct delegpt* dp;
struct module_qstate* subq;
int nolock = 0;
verbose(VERB_DETAIL, "priming . %s NS",
sldns_lookup_by_id(sldns_rr_classes, (int)qclass)?
sldns_lookup_by_id(sldns_rr_classes, (int)qclass)->name:"??");
dp = hints_find_root(qstate->env->hints, qclass, nolock);
if(!dp) {
verbose(VERB_ALGO, "Cannot prime due to lack of hints");
return 0;
}
/* Priming requests start at the QUERYTARGETS state, skipping
* the normal INIT state logic (which would cause an infloop). */
if(!generate_sub_request((uint8_t*)"\000", 1, LDNS_RR_TYPE_NS,
qclass, qstate, id, iq, QUERYTARGETS_STATE, PRIME_RESP_STATE,
&subq, 0, 0)) {
lock_rw_unlock(&qstate->env->hints->lock);
verbose(VERB_ALGO, "could not prime root");
return 0;
}
if(subq) {
struct iter_qstate* subiq =
(struct iter_qstate*)subq->minfo[id];
/* Set the initial delegation point to the hint.
* copy dp, it is now part of the root prime query.
* dp was part of in the fixed hints structure. */
subiq->dp = delegpt_copy(dp, subq->region);
lock_rw_unlock(&qstate->env->hints->lock);
if(!subiq->dp) {
log_err("out of memory priming root, copydp");
fptr_ok(fptr_whitelist_modenv_kill_sub(
qstate->env->kill_sub));
(*qstate->env->kill_sub)(subq);
return 0;
}
/* there should not be any target queries. */
subiq->num_target_queries = 0;
subiq->dnssec_expected = iter_indicates_dnssec(
qstate->env, subiq->dp, NULL, subq->qinfo.qclass);
} else {
lock_rw_unlock(&qstate->env->hints->lock);
}
/* this module stops, our submodule starts, and does the query. */
qstate->ext_state[id] = module_wait_subquery;
return 1;
}
/**
* Generate and process a stub priming request. This method tests for the
* need to prime a stub zone, so it is safe to call for every request.
*
* @param qstate: the qtstate that triggered the need to prime.
* @param iq: iterator query state.
* @param id: module id.
* @param qname: request name.
* @param qclass: request class.
* @return true if a priming subrequest was made, false if not. The will only
* issue a priming request if it detects an unprimed stub.
* Uses value of 2 to signal during stub-prime in root-prime situation
* that a noprime-stub is available and resolution can continue.
*/
static int
prime_stub(struct module_qstate* qstate, struct iter_qstate* iq, int id,
uint8_t* qname, uint16_t qclass)
{
/* Lookup the stub hint. This will return null if the stub doesn't
* need to be re-primed. */
struct iter_hints_stub* stub;
struct delegpt* stub_dp;
struct module_qstate* subq;
int nolock = 0;
if(!qname) return 0;
stub = hints_lookup_stub(qstate->env->hints, qname, qclass, iq->dp,
nolock);
/* The stub (if there is one) does not need priming. */
if(!stub) return 0;
stub_dp = stub->dp;
/* if we have an auth_zone dp, and stub is equal, don't prime stub
* yet, unless we want to fallback and avoid the auth_zone */
if(!iq->auth_zone_avoid && iq->dp && iq->dp->auth_dp &&
query_dname_compare(iq->dp->name, stub_dp->name) == 0) {
lock_rw_unlock(&qstate->env->hints->lock);
return 0;
}
/* is it a noprime stub (always use) */
if(stub->noprime) {
int r = 0;
if(iq->dp == NULL) r = 2;
/* copy the dp out of the fixed hints structure, so that
* it can be changed when servicing this query */
iq->dp = delegpt_copy(stub_dp, qstate->region);
lock_rw_unlock(&qstate->env->hints->lock);
if(!iq->dp) {
log_err("out of memory priming stub");
errinf(qstate, "malloc failure, priming stub");
(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
return 1; /* return 1 to make module stop, with error */
}
log_nametypeclass(VERB_DETAIL, "use stub", iq->dp->name,
LDNS_RR_TYPE_NS, qclass);
return r;
}
/* Otherwise, we need to (re)prime the stub. */
log_nametypeclass(VERB_DETAIL, "priming stub", stub_dp->name,
LDNS_RR_TYPE_NS, qclass);
/* Stub priming events start at the QUERYTARGETS state to avoid the
* redundant INIT state processing. */