-
Notifications
You must be signed in to change notification settings - Fork 29.6k
/
cares_wrap.cc
1985 lines (1631 loc) Β· 60.6 KB
/
cares_wrap.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "cares_wrap.h"
#include "ada.h"
#include "async_wrap-inl.h"
#include "base64-inl.h"
#include "base_object-inl.h"
#include "env-inl.h"
#include "memory_tracker-inl.h"
#include "node.h"
#include "node_errors.h"
#include "node_external_reference.h"
#include "req_wrap-inl.h"
#include "util-inl.h"
#include "uv.h"
#include "v8.h"
#include <cerrno>
#include <cstring>
#include <memory>
#include <vector>
#include <unordered_set>
#ifndef T_CAA
# define T_CAA 257 /* Certification Authority Authorization */
#endif
// OpenBSD does not define these
#ifndef AI_ALL
# define AI_ALL 0
#endif
#ifndef AI_V4MAPPED
# define AI_V4MAPPED 0
#endif
namespace node {
namespace cares_wrap {
using v8::Array;
using v8::Context;
using v8::EscapableHandleScope;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Int32;
using v8::Integer;
using v8::Isolate;
using v8::Just;
using v8::Local;
using v8::Maybe;
using v8::Nothing;
using v8::Null;
using v8::Object;
using v8::String;
using v8::Value;
namespace {
Mutex ares_library_mutex;
inline uint16_t cares_get_16bit(const unsigned char* p) {
return static_cast<uint32_t>(p[0] << 8U) | (static_cast<uint32_t>(p[1]));
}
void ares_poll_cb(uv_poll_t* watcher, int status, int events) {
NodeAresTask* task = ContainerOf(&NodeAresTask::poll_watcher, watcher);
ChannelWrap* channel = task->channel;
/* Reset the idle timer */
uv_timer_again(channel->timer_handle());
if (status < 0) {
/* An error happened. Just pretend that the socket is both readable and */
/* writable. */
ares_process_fd(channel->cares_channel(), task->sock, task->sock);
return;
}
/* Process DNS responses */
ares_process_fd(channel->cares_channel(),
events & UV_READABLE ? task->sock : ARES_SOCKET_BAD,
events & UV_WRITABLE ? task->sock : ARES_SOCKET_BAD);
}
void ares_poll_close_cb(uv_poll_t* watcher) {
std::unique_ptr<NodeAresTask> free_me(
ContainerOf(&NodeAresTask::poll_watcher, watcher));
}
/* Callback from ares when socket operation is started */
void ares_sockstate_cb(void* data, ares_socket_t sock, int read, int write) {
ChannelWrap* channel = static_cast<ChannelWrap*>(data);
NodeAresTask* task;
NodeAresTask lookup_task;
lookup_task.sock = sock;
auto it = channel->task_list()->find(&lookup_task);
task = (it == channel->task_list()->end()) ? nullptr : *it;
if (read || write) {
if (!task) {
/* New socket */
channel->StartTimer();
task = NodeAresTask::Create(channel, sock);
if (task == nullptr) {
/* This should never happen unless we're out of memory or something */
/* is seriously wrong. The socket won't be polled, but the query will */
/* eventually time out. */
return;
}
channel->task_list()->insert(task);
}
/* This should never fail. If it fails anyway, the query will eventually */
/* time out. */
uv_poll_start(&task->poll_watcher,
(read ? UV_READABLE : 0) | (write ? UV_WRITABLE : 0),
ares_poll_cb);
} else {
/* read == 0 and write == 0 this is c-ares's way of notifying us that */
/* the socket is now closed. We must free the data associated with */
/* socket. */
CHECK(task &&
"When an ares socket is closed we should have a handle for it");
channel->task_list()->erase(it);
channel->env()->CloseHandle(&task->poll_watcher, ares_poll_close_cb);
if (channel->task_list()->empty()) {
channel->CloseTimer();
}
}
}
Local<Array> HostentToNames(Environment* env, struct hostent* host) {
EscapableHandleScope scope(env->isolate());
std::vector<Local<Value>> names;
for (uint32_t i = 0; host->h_aliases[i] != nullptr; ++i)
names.emplace_back(OneByteString(env->isolate(), host->h_aliases[i]));
Local<Array> ret = Array::New(env->isolate(), names.data(), names.size());
return scope.Escape(ret);
}
Local<Array> HostentToNames(Environment* env,
struct hostent* host,
Local<Array> names) {
size_t offset = names->Length();
for (uint32_t i = 0; host->h_aliases[i] != nullptr; ++i) {
names->Set(
env->context(),
i + offset,
OneByteString(env->isolate(), host->h_aliases[i])).Check();
}
return names;
}
template <typename T>
Local<Array> AddrTTLToArray(
Environment* env,
const T* addrttls,
size_t naddrttls) {
MaybeStackBuffer<Local<Value>, 8> ttls(naddrttls);
for (size_t i = 0; i < naddrttls; i++)
ttls[i] = Integer::NewFromUnsigned(env->isolate(), addrttls[i].ttl);
return Array::New(env->isolate(), ttls.out(), naddrttls);
}
int ParseGeneralReply(
Environment* env,
const unsigned char* buf,
int len,
int* type,
Local<Array> ret,
void* addrttls = nullptr,
int* naddrttls = nullptr) {
HandleScope handle_scope(env->isolate());
hostent* host;
int status;
switch (*type) {
case ns_t_a:
case ns_t_cname:
case ns_t_cname_or_a:
status = ares_parse_a_reply(buf,
len,
&host,
static_cast<ares_addrttl*>(addrttls),
naddrttls);
break;
case ns_t_aaaa:
status = ares_parse_aaaa_reply(buf,
len,
&host,
static_cast<ares_addr6ttl*>(addrttls),
naddrttls);
break;
case ns_t_ns:
status = ares_parse_ns_reply(buf, len, &host);
break;
case ns_t_ptr:
status = ares_parse_ptr_reply(buf, len, nullptr, 0, AF_INET, &host);
break;
default:
UNREACHABLE("Bad NS type");
}
if (status != ARES_SUCCESS)
return status;
CHECK_NOT_NULL(host);
HostEntPointer ptr(host);
/* If it's `CNAME`, return the CNAME value;
* And if it's `CNAME_OR_A` and it has value in `h_name` and `h_aliases[0]`,
* we consider it's a CNAME record, otherwise we consider it's an A record. */
if ((*type == ns_t_cname_or_a && ptr->h_name && ptr->h_aliases[0]) ||
*type == ns_t_cname) {
// A cname lookup always returns a single record but we follow the
// common API here.
*type = ns_t_cname;
ret->Set(env->context(),
ret->Length(),
OneByteString(env->isolate(), ptr->h_name)).Check();
return ARES_SUCCESS;
}
if (*type == ns_t_cname_or_a)
*type = ns_t_a;
if (*type == ns_t_ns) {
HostentToNames(env, ptr.get(), ret);
} else if (*type == ns_t_ptr) {
uint32_t offset = ret->Length();
for (uint32_t i = 0; ptr->h_aliases[i] != nullptr; i++) {
auto alias = OneByteString(env->isolate(), ptr->h_aliases[i]);
ret->Set(env->context(), i + offset, alias).Check();
}
} else {
uint32_t offset = ret->Length();
char ip[INET6_ADDRSTRLEN];
for (uint32_t i = 0; ptr->h_addr_list[i] != nullptr; ++i) {
uv_inet_ntop(ptr->h_addrtype, ptr->h_addr_list[i], ip, sizeof(ip));
auto address = OneByteString(env->isolate(), ip);
ret->Set(env->context(), i + offset, address).Check();
}
}
return ARES_SUCCESS;
}
int ParseMxReply(
Environment* env,
const unsigned char* buf,
int len,
Local<Array> ret,
bool need_type = false) {
HandleScope handle_scope(env->isolate());
struct ares_mx_reply* mx_start;
int status = ares_parse_mx_reply(buf, len, &mx_start);
if (status != ARES_SUCCESS)
return status;
uint32_t offset = ret->Length();
ares_mx_reply* current = mx_start;
for (uint32_t i = 0; current != nullptr; ++i, current = current->next) {
Local<Object> mx_record = Object::New(env->isolate());
mx_record->Set(env->context(),
env->exchange_string(),
OneByteString(env->isolate(), current->host)).Check();
mx_record->Set(env->context(),
env->priority_string(),
Integer::New(env->isolate(), current->priority)).Check();
if (need_type)
mx_record->Set(env->context(),
env->type_string(),
env->dns_mx_string()).Check();
ret->Set(env->context(), i + offset, mx_record).Check();
}
ares_free_data(mx_start);
return ARES_SUCCESS;
}
int ParseCaaReply(
Environment* env,
const unsigned char* buf,
int len,
Local<Array> ret,
bool need_type = false) {
HandleScope handle_scope(env->isolate());
struct ares_caa_reply* caa_start;
int status = ares_parse_caa_reply(buf, len, &caa_start);
if (status != ARES_SUCCESS)
return status;
uint32_t offset = ret->Length();
ares_caa_reply* current = caa_start;
for (uint32_t i = 0; current != nullptr; ++i, current = current->next) {
Local<Object> caa_record = Object::New(env->isolate());
caa_record->Set(env->context(),
env->dns_critical_string(),
Integer::New(env->isolate(), current->critical)).Check();
caa_record->Set(env->context(),
OneByteString(env->isolate(), current->property),
OneByteString(env->isolate(), current->value)).Check();
if (need_type)
caa_record->Set(env->context(),
env->type_string(),
env->dns_caa_string()).Check();
ret->Set(env->context(), i + offset, caa_record).Check();
}
ares_free_data(caa_start);
return ARES_SUCCESS;
}
int ParseTxtReply(
Environment* env,
const unsigned char* buf,
int len,
Local<Array> ret,
bool need_type = false) {
HandleScope handle_scope(env->isolate());
struct ares_txt_ext* txt_out;
int status = ares_parse_txt_reply_ext(buf, len, &txt_out);
if (status != ARES_SUCCESS)
return status;
Local<Array> txt_chunk;
struct ares_txt_ext* current = txt_out;
uint32_t i = 0, j;
uint32_t offset = ret->Length();
for (j = 0; current != nullptr; current = current->next) {
Local<String> txt =
OneByteString(env->isolate(), current->txt, current->length);
// New record found - write out the current chunk
if (current->record_start) {
if (!txt_chunk.IsEmpty()) {
if (need_type) {
Local<Object> elem = Object::New(env->isolate());
elem->Set(env->context(), env->entries_string(), txt_chunk).Check();
elem->Set(env->context(),
env->type_string(),
env->dns_txt_string()).Check();
ret->Set(env->context(), offset + i++, elem).Check();
} else {
ret->Set(env->context(), offset + i++, txt_chunk).Check();
}
}
txt_chunk = Array::New(env->isolate());
j = 0;
}
txt_chunk->Set(env->context(), j++, txt).Check();
}
// Push last chunk if it isn't empty
if (!txt_chunk.IsEmpty()) {
if (need_type) {
Local<Object> elem = Object::New(env->isolate());
elem->Set(env->context(), env->entries_string(), txt_chunk).Check();
elem->Set(env->context(),
env->type_string(),
env->dns_txt_string()).Check();
ret->Set(env->context(), offset + i, elem).Check();
} else {
ret->Set(env->context(), offset + i, txt_chunk).Check();
}
}
ares_free_data(txt_out);
return ARES_SUCCESS;
}
int ParseSrvReply(
Environment* env,
const unsigned char* buf,
int len,
Local<Array> ret,
bool need_type = false) {
HandleScope handle_scope(env->isolate());
struct ares_srv_reply* srv_start;
int status = ares_parse_srv_reply(buf, len, &srv_start);
if (status != ARES_SUCCESS)
return status;
ares_srv_reply* current = srv_start;
int offset = ret->Length();
for (uint32_t i = 0; current != nullptr; ++i, current = current->next) {
Local<Object> srv_record = Object::New(env->isolate());
srv_record->Set(env->context(),
env->name_string(),
OneByteString(env->isolate(), current->host)).Check();
srv_record->Set(env->context(),
env->port_string(),
Integer::New(env->isolate(), current->port)).Check();
srv_record->Set(env->context(),
env->priority_string(),
Integer::New(env->isolate(), current->priority)).Check();
srv_record->Set(env->context(),
env->weight_string(),
Integer::New(env->isolate(), current->weight)).Check();
if (need_type)
srv_record->Set(env->context(),
env->type_string(),
env->dns_srv_string()).Check();
ret->Set(env->context(), i + offset, srv_record).Check();
}
ares_free_data(srv_start);
return ARES_SUCCESS;
}
int ParseNaptrReply(
Environment* env,
const unsigned char* buf,
int len,
Local<Array> ret,
bool need_type = false) {
HandleScope handle_scope(env->isolate());
ares_naptr_reply* naptr_start;
int status = ares_parse_naptr_reply(buf, len, &naptr_start);
if (status != ARES_SUCCESS)
return status;
ares_naptr_reply* current = naptr_start;
int offset = ret->Length();
for (uint32_t i = 0; current != nullptr; ++i, current = current->next) {
Local<Object> naptr_record = Object::New(env->isolate());
naptr_record->Set(env->context(),
env->flags_string(),
OneByteString(env->isolate(), current->flags)).Check();
naptr_record->Set(env->context(),
env->service_string(),
OneByteString(env->isolate(),
current->service)).Check();
naptr_record->Set(env->context(),
env->regexp_string(),
OneByteString(env->isolate(),
current->regexp)).Check();
naptr_record->Set(env->context(),
env->replacement_string(),
OneByteString(env->isolate(),
current->replacement)).Check();
naptr_record->Set(env->context(),
env->order_string(),
Integer::New(env->isolate(), current->order)).Check();
naptr_record->Set(env->context(),
env->preference_string(),
Integer::New(env->isolate(),
current->preference)).Check();
if (need_type)
naptr_record->Set(env->context(),
env->type_string(),
env->dns_naptr_string()).Check();
ret->Set(env->context(), i + offset, naptr_record).Check();
}
ares_free_data(naptr_start);
return ARES_SUCCESS;
}
int ParseSoaReply(
Environment* env,
unsigned char* buf,
int len,
Local<Object>* ret) {
EscapableHandleScope handle_scope(env->isolate());
// Manage memory using standardard smart pointer std::unique_tr
struct AresDeleter {
void operator()(char* ptr) const noexcept { ares_free_string(ptr); }
};
using ares_unique_ptr = std::unique_ptr<char[], AresDeleter>;
// Can't use ares_parse_soa_reply() here which can only parse single record
const unsigned int ancount = cares_get_16bit(buf + 6);
unsigned char* ptr = buf + NS_HFIXEDSZ;
char* name_temp = nullptr;
long temp_len; // NOLINT(runtime/int)
int status = ares_expand_name(ptr, buf, len, &name_temp, &temp_len);
if (status != ARES_SUCCESS) {
// returns EBADRESP in case of invalid input
return status == ARES_EBADNAME ? ARES_EBADRESP : status;
}
const ares_unique_ptr name(name_temp);
if (ptr + temp_len + NS_QFIXEDSZ > buf + len) {
return ARES_EBADRESP;
}
ptr += temp_len + NS_QFIXEDSZ;
for (unsigned int i = 0; i < ancount; i++) {
char* rr_name_temp = nullptr;
long rr_temp_len; // NOLINT(runtime/int)
int status2 = ares_expand_name(ptr, buf, len, &rr_name_temp, &rr_temp_len);
if (status2 != ARES_SUCCESS)
return status2 == ARES_EBADNAME ? ARES_EBADRESP : status2;
const ares_unique_ptr rr_name(rr_name_temp);
ptr += rr_temp_len;
if (ptr + NS_RRFIXEDSZ > buf + len) {
return ARES_EBADRESP;
}
const int rr_type = cares_get_16bit(ptr);
const int rr_len = cares_get_16bit(ptr + 8);
ptr += NS_RRFIXEDSZ;
// only need SOA
if (rr_type == ns_t_soa) {
char* nsname_temp = nullptr;
long nsname_temp_len; // NOLINT(runtime/int)
int status3 = ares_expand_name(ptr, buf, len,
&nsname_temp,
&nsname_temp_len);
if (status3 != ARES_SUCCESS) {
return status3 == ARES_EBADNAME ? ARES_EBADRESP : status3;
}
const ares_unique_ptr nsname(nsname_temp);
ptr += nsname_temp_len;
char* hostmaster_temp = nullptr;
long hostmaster_temp_len; // NOLINT(runtime/int)
int status4 = ares_expand_name(ptr, buf, len,
&hostmaster_temp,
&hostmaster_temp_len);
if (status4 != ARES_SUCCESS) {
return status4 == ARES_EBADNAME ? ARES_EBADRESP : status4;
}
const ares_unique_ptr hostmaster(hostmaster_temp);
ptr += hostmaster_temp_len;
if (ptr + 5 * 4 > buf + len) {
return ARES_EBADRESP;
}
const unsigned int serial = ReadUint32BE(ptr + 0 * 4);
const unsigned int refresh = ReadUint32BE(ptr + 1 * 4);
const unsigned int retry = ReadUint32BE(ptr + 2 * 4);
const unsigned int expire = ReadUint32BE(ptr + 3 * 4);
const unsigned int minttl = ReadUint32BE(ptr + 4 * 4);
Local<Object> soa_record = Object::New(env->isolate());
soa_record->Set(env->context(),
env->nsname_string(),
OneByteString(env->isolate(), nsname.get())).Check();
soa_record->Set(env->context(),
env->hostmaster_string(),
OneByteString(env->isolate(),
hostmaster.get())).Check();
soa_record->Set(env->context(),
env->serial_string(),
Integer::NewFromUnsigned(env->isolate(), serial)).Check();
soa_record->Set(env->context(),
env->refresh_string(),
Integer::New(env->isolate(), refresh)).Check();
soa_record->Set(env->context(),
env->retry_string(),
Integer::New(env->isolate(), retry)).Check();
soa_record->Set(env->context(),
env->expire_string(),
Integer::New(env->isolate(), expire)).Check();
soa_record->Set(env->context(),
env->minttl_string(),
Integer::NewFromUnsigned(env->isolate(), minttl)).Check();
soa_record->Set(env->context(),
env->type_string(),
env->dns_soa_string()).Check();
*ret = handle_scope.Escape(soa_record);
break;
}
ptr += rr_len;
}
return ARES_SUCCESS;
}
} // anonymous namespace
ChannelWrap::ChannelWrap(
Environment* env,
Local<Object> object,
int timeout,
int tries)
: AsyncWrap(env, object, PROVIDER_DNSCHANNEL),
timeout_(timeout),
tries_(tries) {
MakeWeak();
Setup();
}
void ChannelWrap::MemoryInfo(MemoryTracker* tracker) const {
if (timer_handle_ != nullptr)
tracker->TrackField("timer_handle", *timer_handle_);
tracker->TrackField("task_list", task_list_, "NodeAresTask::List");
}
void ChannelWrap::New(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
CHECK_EQ(args.Length(), 2);
CHECK(args[0]->IsInt32());
CHECK(args[1]->IsInt32());
const int timeout = args[0].As<Int32>()->Value();
const int tries = args[1].As<Int32>()->Value();
Environment* env = Environment::GetCurrent(args);
new ChannelWrap(env, args.This(), timeout, tries);
}
GetAddrInfoReqWrap::GetAddrInfoReqWrap(
Environment* env,
Local<Object> req_wrap_obj,
bool verbatim)
: ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_GETADDRINFOREQWRAP),
verbatim_(verbatim) {}
GetNameInfoReqWrap::GetNameInfoReqWrap(
Environment* env,
Local<Object> req_wrap_obj)
: ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_GETNAMEINFOREQWRAP) {}
/* This is called once per second by loop->timer. It is used to constantly */
/* call back into c-ares for possibly processing timeouts. */
void ChannelWrap::AresTimeout(uv_timer_t* handle) {
ChannelWrap* channel = static_cast<ChannelWrap*>(handle->data);
CHECK_EQ(channel->timer_handle(), handle);
CHECK_EQ(false, channel->task_list()->empty());
ares_process_fd(channel->cares_channel(), ARES_SOCKET_BAD, ARES_SOCKET_BAD);
}
void NodeAresTask::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("channel", channel);
}
/* Allocates and returns a new NodeAresTask */
NodeAresTask* NodeAresTask::Create(ChannelWrap* channel, ares_socket_t sock) {
auto task = new NodeAresTask();
task->channel = channel;
task->sock = sock;
if (uv_poll_init_socket(channel->env()->event_loop(),
&task->poll_watcher, sock) < 0) {
/* This should never happen. */
delete task;
return nullptr;
}
return task;
}
void ChannelWrap::Setup() {
struct ares_options options;
memset(&options, 0, sizeof(options));
options.flags = ARES_FLAG_NOCHECKRESP;
options.sock_state_cb = ares_sockstate_cb;
options.sock_state_cb_data = this;
options.timeout = timeout_;
options.tries = tries_;
int r;
if (!library_inited_) {
Mutex::ScopedLock lock(ares_library_mutex);
// Multiple calls to ares_library_init() increase a reference counter,
// so this is a no-op except for the first call to it.
r = ares_library_init(ARES_LIB_INIT_ALL);
if (r != ARES_SUCCESS)
return env()->ThrowError(ToErrorCodeString(r));
}
/* We do the call to ares_init_option for caller. */
const int optmask =
ARES_OPT_FLAGS | ARES_OPT_TIMEOUTMS |
ARES_OPT_SOCK_STATE_CB | ARES_OPT_TRIES;
r = ares_init_options(&channel_, &options, optmask);
if (r != ARES_SUCCESS) {
Mutex::ScopedLock lock(ares_library_mutex);
ares_library_cleanup();
return env()->ThrowError(ToErrorCodeString(r));
}
library_inited_ = true;
}
void ChannelWrap::StartTimer() {
if (timer_handle_ == nullptr) {
timer_handle_ = new uv_timer_t();
timer_handle_->data = static_cast<void*>(this);
uv_timer_init(env()->event_loop(), timer_handle_);
} else if (uv_is_active(reinterpret_cast<uv_handle_t*>(timer_handle_))) {
return;
}
int timeout = timeout_;
if (timeout == 0) timeout = 1;
if (timeout < 0 || timeout > 1000) timeout = 1000;
uv_timer_start(timer_handle_, AresTimeout, timeout, timeout);
}
void ChannelWrap::CloseTimer() {
if (timer_handle_ == nullptr)
return;
env()->CloseHandle(timer_handle_, [](uv_timer_t* handle) { delete handle; });
timer_handle_ = nullptr;
}
ChannelWrap::~ChannelWrap() {
ares_destroy(channel_);
if (library_inited_) {
Mutex::ScopedLock lock(ares_library_mutex);
// This decreases the reference counter increased by ares_library_init().
ares_library_cleanup();
}
CloseTimer();
}
void ChannelWrap::ModifyActivityQueryCount(int count) {
active_query_count_ += count;
CHECK_GE(active_query_count_, 0);
}
/**
* This function is to check whether current servers are fallback servers
* when cares initialized.
*
* The fallback servers of cares is [ "127.0.0.1" ] with no user additional
* setting.
*/
void ChannelWrap::EnsureServers() {
/* if last query is OK or servers are set by user self, do not check */
if (query_last_ok_ || !is_servers_default_) {
return;
}
ares_addr_port_node* servers = nullptr;
ares_get_servers_ports(channel_, &servers);
/* if no server or multi-servers, ignore */
if (servers == nullptr) return;
if (servers->next != nullptr) {
ares_free_data(servers);
is_servers_default_ = false;
return;
}
/* if the only server is not 127.0.0.1, ignore */
if (servers[0].family != AF_INET ||
servers[0].addr.addr4.s_addr != htonl(INADDR_LOOPBACK) ||
servers[0].tcp_port != 0 ||
servers[0].udp_port != 0) {
ares_free_data(servers);
is_servers_default_ = false;
return;
}
ares_free_data(servers);
servers = nullptr;
/* destroy channel and reset channel */
ares_destroy(channel_);
CloseTimer();
Setup();
}
int AnyTraits::Send(QueryWrap<AnyTraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, ns_t_any);
return ARES_SUCCESS;
}
int ATraits::Send(QueryWrap<ATraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, ns_t_a);
return ARES_SUCCESS;
}
int AaaaTraits::Send(QueryWrap<AaaaTraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, ns_t_aaaa);
return ARES_SUCCESS;
}
int CaaTraits::Send(QueryWrap<CaaTraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, T_CAA);
return ARES_SUCCESS;
}
int CnameTraits::Send(QueryWrap<CnameTraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, ns_t_cname);
return ARES_SUCCESS;
}
int MxTraits::Send(QueryWrap<MxTraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, ns_t_mx);
return ARES_SUCCESS;
}
int NsTraits::Send(QueryWrap<NsTraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, ns_t_ns);
return ARES_SUCCESS;
}
int TxtTraits::Send(QueryWrap<TxtTraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, ns_t_txt);
return ARES_SUCCESS;
}
int SrvTraits::Send(QueryWrap<SrvTraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, ns_t_srv);
return ARES_SUCCESS;
}
int PtrTraits::Send(QueryWrap<PtrTraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, ns_t_ptr);
return ARES_SUCCESS;
}
int NaptrTraits::Send(QueryWrap<NaptrTraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, ns_t_naptr);
return ARES_SUCCESS;
}
int SoaTraits::Send(QueryWrap<SoaTraits>* wrap, const char* name) {
wrap->AresQuery(name, ns_c_in, ns_t_soa);
return ARES_SUCCESS;
}
int AnyTraits::Parse(
QueryAnyWrap* wrap,
const std::unique_ptr<ResponseData>& response) {
if (UNLIKELY(response->is_host))
return ARES_EBADRESP;
unsigned char* buf = response->buf.data;
int len = response->buf.size;
Environment* env = wrap->env();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Local<Array> ret = Array::New(env->isolate());
int type, status, old_count;
/* Parse A records or CNAME records */
ares_addrttl addrttls[256];
int naddrttls = arraysize(addrttls);
type = ns_t_cname_or_a;
status = ParseGeneralReply(env,
buf,
len,
&type,
ret,
addrttls,
&naddrttls);
uint32_t a_count = ret->Length();
if (status != ARES_SUCCESS && status != ARES_ENODATA)
return status;
if (type == ns_t_a) {
CHECK_EQ(static_cast<uint32_t>(naddrttls), a_count);
for (uint32_t i = 0; i < a_count; i++) {
Local<Object> obj = Object::New(env->isolate());
obj->Set(env->context(),
env->address_string(),
ret->Get(env->context(), i).ToLocalChecked()).Check();
obj->Set(env->context(),
env->ttl_string(),
Integer::NewFromUnsigned(
env->isolate(), addrttls[i].ttl)).Check();
obj->Set(env->context(),
env->type_string(),
env->dns_a_string()).Check();
ret->Set(env->context(), i, obj).Check();
}
} else {
for (uint32_t i = 0; i < a_count; i++) {
Local<Object> obj = Object::New(env->isolate());
obj->Set(env->context(),
env->value_string(),
ret->Get(env->context(), i).ToLocalChecked()).Check();
obj->Set(env->context(),
env->type_string(),
env->dns_cname_string()).Check();
ret->Set(env->context(), i, obj).Check();
}
}
/* Parse AAAA records */
ares_addr6ttl addr6ttls[256];
int naddr6ttls = arraysize(addr6ttls);
type = ns_t_aaaa;
status = ParseGeneralReply(env,
buf,
len,
&type,
ret,
addr6ttls,
&naddr6ttls);
uint32_t aaaa_count = ret->Length() - a_count;
if (status != ARES_SUCCESS && status != ARES_ENODATA)
return status;
CHECK_EQ(aaaa_count, static_cast<uint32_t>(naddr6ttls));
CHECK_EQ(ret->Length(), a_count + aaaa_count);
for (uint32_t i = a_count; i < ret->Length(); i++) {
Local<Object> obj = Object::New(env->isolate());
obj->Set(env->context(),
env->address_string(),
ret->Get(env->context(), i).ToLocalChecked()).Check();
obj->Set(env->context(),
env->ttl_string(),
Integer::NewFromUnsigned(
env->isolate(), addr6ttls[i - a_count].ttl)).Check();
obj->Set(env->context(),
env->type_string(),
env->dns_aaaa_string()).Check();
ret->Set(env->context(), i, obj).Check();
}
/* Parse MX records */
status = ParseMxReply(env, buf, len, ret, true);
if (status != ARES_SUCCESS && status != ARES_ENODATA)
return status;
/* Parse NS records */
type = ns_t_ns;
old_count = ret->Length();
status = ParseGeneralReply(env, buf, len, &type, ret);
if (status != ARES_SUCCESS && status != ARES_ENODATA)
return status;
for (uint32_t i = old_count; i < ret->Length(); i++) {
Local<Object> obj = Object::New(env->isolate());
obj->Set(env->context(),
env->value_string(),