forked from c-ares/c-ares
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ares_init.c
2529 lines (2228 loc) · 71.1 KB
/
ares_init.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
/* Copyright 1998 by the Massachusetts Institute of Technology.
* Copyright (C) 2007-2013 by Daniel Stenberg
*
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the
* software without specific, written prior permission.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is"
* without express or implied warranty.
*/
#include "ares_setup.h"
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_ARPA_NAMESER_H
# include <arpa/nameser.h>
#else
# include "nameser.h"
#endif
#ifdef HAVE_ARPA_NAMESER_COMPAT_H
# include <arpa/nameser_compat.h>
#endif
#if defined(ANDROID) || defined(__ANDROID__)
#include <sys/system_properties.h>
/* From the Bionic sources */
#define DNS_PROP_NAME_PREFIX "net.dns"
#define MAX_DNS_PROPERTIES 8
#endif
#if defined(CARES_USE_LIBRESOLV)
#include <resolv.h>
#endif
#include "ares.h"
#include "ares_inet_net_pton.h"
#include "ares_library_init.h"
#include "ares_nowarn.h"
#include "ares_platform.h"
#include "ares_private.h"
#ifdef WATT32
#undef WIN32 /* Redefined in MingW/MSVC headers */
#endif
static int init_by_options(ares_channel channel,
const struct ares_options *options,
int optmask);
static int init_by_environment(ares_channel channel);
static int init_by_resolv_conf(ares_channel channel);
static int init_by_defaults(ares_channel channel);
#ifndef WATT32
static int config_nameserver(struct server_state **servers, int *nservers,
char *str);
#endif
static int set_search(ares_channel channel, const char *str);
static int set_options(ares_channel channel, const char *str);
static const char *try_option(const char *p, const char *q, const char *opt);
static int init_id_key(rc4_key* key,int key_data_len);
static int config_sortlist(struct apattern **sortlist, int *nsort,
const char *str);
static int sortlist_alloc(struct apattern **sortlist, int *nsort,
struct apattern *pat);
static int ip_addr(const char *s, ares_ssize_t len, struct in_addr *addr);
static void natural_mask(struct apattern *pat);
#if !defined(WIN32) && !defined(WATT32) && \
!defined(ANDROID) && !defined(__ANDROID__) && !defined(CARES_USE_LIBRESOLV)
static int config_domain(ares_channel channel, char *str);
static int config_lookup(ares_channel channel, const char *str,
const char *bindch, const char *altbindch,
const char *filech);
static char *try_config(char *s, const char *opt, char scc);
#endif
#define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
x->nservers > -1 && \
x->ndomains > -1 && \
x->ndots > -1 && x->timeout > -1 && \
x->tries > -1)
int ares_init(ares_channel *channelptr)
{
return ares_init_options(channelptr, NULL, 0);
}
int ares_init_options(ares_channel *channelptr, struct ares_options *options,
int optmask)
{
ares_channel channel;
int i;
int status = ARES_SUCCESS;
struct timeval now;
#ifdef CURLDEBUG
const char *env = getenv("CARES_MEMDEBUG");
if (env)
curl_memdebug(env);
env = getenv("CARES_MEMLIMIT");
if (env) {
char *endptr;
long num = strtol(env, &endptr, 10);
if((endptr != env) && (endptr == env + strlen(env)) && (num > 0))
curl_memlimit(num);
}
#endif
if (ares_library_initialized() != ARES_SUCCESS)
return ARES_ENOTINITIALIZED; /* LCOV_EXCL_LINE: n/a on non-WinSock */
channel = ares_malloc(sizeof(struct ares_channeldata));
if (!channel) {
*channelptr = NULL;
return ARES_ENOMEM;
}
now = ares__tvnow();
/* Set everything to distinguished values so we know they haven't
* been set yet.
*/
channel->flags = -1;
channel->timeout = -1;
channel->tries = -1;
channel->ndots = -1;
channel->rotate = -1;
channel->udp_port = -1;
channel->tcp_port = -1;
channel->ednspsz = -1;
channel->socket_send_buffer_size = -1;
channel->socket_receive_buffer_size = -1;
channel->nservers = -1;
channel->ndomains = -1;
channel->nsort = -1;
channel->tcp_connection_generation = 0;
channel->lookups = NULL;
channel->domains = NULL;
channel->sortlist = NULL;
channel->servers = NULL;
channel->sock_state_cb = NULL;
channel->sock_state_cb_data = NULL;
channel->sock_create_cb = NULL;
channel->sock_create_cb_data = NULL;
channel->sock_config_cb = NULL;
channel->sock_config_cb_data = NULL;
channel->sock_funcs = NULL;
channel->sock_func_cb_data = NULL;
channel->last_server = 0;
channel->last_timeout_processed = (time_t)now.tv_sec;
memset(&channel->local_dev_name, 0, sizeof(channel->local_dev_name));
channel->local_ip4 = 0;
memset(&channel->local_ip6, 0, sizeof(channel->local_ip6));
/* Initialize our lists of queries */
ares__init_list_head(&(channel->all_queries));
for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
{
ares__init_list_head(&(channel->queries_by_qid[i]));
}
for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
{
ares__init_list_head(&(channel->queries_by_timeout[i]));
}
/* Initialize configuration by each of the four sources, from highest
* precedence to lowest.
*/
status = init_by_options(channel, options, optmask);
if (status != ARES_SUCCESS) {
DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
ares_strerror(status)));
/* If we fail to apply user-specified options, fail the whole init process */
goto done;
}
status = init_by_environment(channel);
if (status != ARES_SUCCESS)
DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
ares_strerror(status)));
if (status == ARES_SUCCESS) {
status = init_by_resolv_conf(channel);
if (status != ARES_SUCCESS)
DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
ares_strerror(status)));
}
/*
* No matter what failed or succeeded, seed defaults to provide
* useful behavior for things that we missed.
*/
status = init_by_defaults(channel);
if (status != ARES_SUCCESS)
DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
ares_strerror(status)));
/* Generate random key */
if (status == ARES_SUCCESS) {
status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
if (status == ARES_SUCCESS)
channel->next_id = ares__generate_new_id(&channel->id_key);
else
DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
ares_strerror(status)));
}
done:
if (status != ARES_SUCCESS)
{
/* Something failed; clean up memory we may have allocated. */
if (channel->servers)
ares_free(channel->servers);
if (channel->domains)
{
for (i = 0; i < channel->ndomains; i++)
ares_free(channel->domains[i]);
ares_free(channel->domains);
}
if (channel->sortlist)
ares_free(channel->sortlist);
if(channel->lookups)
ares_free(channel->lookups);
ares_free(channel);
return status;
}
/* Trim to one server if ARES_FLAG_PRIMARY is set. */
if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
channel->nservers = 1;
ares__init_servers_state(channel);
*channelptr = channel;
return ARES_SUCCESS;
}
/* ares_dup() duplicates a channel handle with all its options and returns a
new channel handle */
int ares_dup(ares_channel *dest, ares_channel src)
{
struct ares_options opts;
struct ares_addr_port_node *servers;
int non_v4_default_port = 0;
int i, rc;
int optmask;
*dest = NULL; /* in case of failure return NULL explicitly */
/* First get the options supported by the old ares_save_options() function,
which is most of them */
rc = ares_save_options(src, &opts, &optmask);
if(rc)
{
ares_destroy_options(&opts);
return rc;
}
/* Then create the new channel with those options */
rc = ares_init_options(dest, &opts, optmask);
/* destroy the options copy to not leak any memory */
ares_destroy_options(&opts);
if(rc)
return rc;
/* Now clone the options that ares_save_options() doesn't support. */
(*dest)->sock_create_cb = src->sock_create_cb;
(*dest)->sock_create_cb_data = src->sock_create_cb_data;
(*dest)->sock_config_cb = src->sock_config_cb;
(*dest)->sock_config_cb_data = src->sock_config_cb_data;
(*dest)->sock_funcs = src->sock_funcs;
(*dest)->sock_func_cb_data = src->sock_func_cb_data;
strncpy((*dest)->local_dev_name, src->local_dev_name,
sizeof(src->local_dev_name));
(*dest)->local_ip4 = src->local_ip4;
memcpy((*dest)->local_ip6, src->local_ip6, sizeof(src->local_ip6));
/* Full name server cloning required if there is a non-IPv4, or non-default port, nameserver */
for (i = 0; i < src->nservers; i++)
{
if ((src->servers[i].addr.family != AF_INET) ||
(src->servers[i].addr.udp_port != 0) ||
(src->servers[i].addr.tcp_port != 0)) {
non_v4_default_port++;
break;
}
}
if (non_v4_default_port) {
rc = ares_get_servers_ports(src, &servers);
if (rc != ARES_SUCCESS) {
ares_destroy(*dest);
*dest = NULL;
return rc;
}
rc = ares_set_servers_ports(*dest, servers);
ares_free_data(servers);
if (rc != ARES_SUCCESS) {
ares_destroy(*dest);
*dest = NULL;
return rc;
}
}
return ARES_SUCCESS; /* everything went fine */
}
/* Save options from initialized channel */
int ares_save_options(ares_channel channel, struct ares_options *options,
int *optmask)
{
int i, j;
int ipv4_nservers = 0;
/* Zero everything out */
memset(options, 0, sizeof(struct ares_options));
if (!ARES_CONFIG_CHECK(channel))
return ARES_ENODATA;
/* Traditionally the optmask wasn't saved in the channel struct so it was
recreated here. ROTATE is the first option that has no struct field of
its own in the public config struct */
(*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS);
(*optmask) |= (channel->rotate ? ARES_OPT_ROTATE : ARES_OPT_NOROTATE);
/* Copy easy stuff */
options->flags = channel->flags;
/* We return full millisecond resolution but that's only because we don't
set the ARES_OPT_TIMEOUT anymore, only the new ARES_OPT_TIMEOUTMS */
options->timeout = channel->timeout;
options->tries = channel->tries;
options->ndots = channel->ndots;
options->udp_port = ntohs(aresx_sitous(channel->udp_port));
options->tcp_port = ntohs(aresx_sitous(channel->tcp_port));
options->sock_state_cb = channel->sock_state_cb;
options->sock_state_cb_data = channel->sock_state_cb_data;
/* Copy IPv4 servers that use the default port */
if (channel->nservers) {
for (i = 0; i < channel->nservers; i++)
{
if ((channel->servers[i].addr.family == AF_INET) &&
(channel->servers[i].addr.udp_port == 0) &&
(channel->servers[i].addr.tcp_port == 0))
ipv4_nservers++;
}
if (ipv4_nservers) {
options->servers = ares_malloc(ipv4_nservers * sizeof(struct in_addr));
if (!options->servers)
return ARES_ENOMEM;
for (i = j = 0; i < channel->nservers; i++)
{
if ((channel->servers[i].addr.family == AF_INET) &&
(channel->servers[i].addr.udp_port == 0) &&
(channel->servers[i].addr.tcp_port == 0))
memcpy(&options->servers[j++],
&channel->servers[i].addr.addrV4,
sizeof(channel->servers[i].addr.addrV4));
}
}
}
options->nservers = ipv4_nservers;
/* copy domains */
if (channel->ndomains) {
options->domains = ares_malloc(channel->ndomains * sizeof(char *));
if (!options->domains)
return ARES_ENOMEM;
for (i = 0; i < channel->ndomains; i++)
{
options->ndomains = i;
options->domains[i] = ares_strdup(channel->domains[i]);
if (!options->domains[i])
return ARES_ENOMEM;
}
}
options->ndomains = channel->ndomains;
/* copy lookups */
if (channel->lookups) {
options->lookups = ares_strdup(channel->lookups);
if (!options->lookups && channel->lookups)
return ARES_ENOMEM;
}
/* copy sortlist */
if (channel->nsort) {
options->sortlist = ares_malloc(channel->nsort * sizeof(struct apattern));
if (!options->sortlist)
return ARES_ENOMEM;
for (i = 0; i < channel->nsort; i++)
options->sortlist[i] = channel->sortlist[i];
}
options->nsort = channel->nsort;
return ARES_SUCCESS;
}
static int init_by_options(ares_channel channel,
const struct ares_options *options,
int optmask)
{
int i;
/* Easy stuff. */
if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
channel->flags = options->flags;
if ((optmask & ARES_OPT_TIMEOUTMS) && channel->timeout == -1)
channel->timeout = options->timeout;
else if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
channel->timeout = options->timeout * 1000;
if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
channel->tries = options->tries;
if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
channel->ndots = options->ndots;
if ((optmask & ARES_OPT_ROTATE) && channel->rotate == -1)
channel->rotate = 1;
if ((optmask & ARES_OPT_NOROTATE) && channel->rotate == -1)
channel->rotate = 0;
if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
channel->udp_port = htons(options->udp_port);
if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
channel->tcp_port = htons(options->tcp_port);
if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
{
channel->sock_state_cb = options->sock_state_cb;
channel->sock_state_cb_data = options->sock_state_cb_data;
}
if ((optmask & ARES_OPT_SOCK_SNDBUF)
&& channel->socket_send_buffer_size == -1)
channel->socket_send_buffer_size = options->socket_send_buffer_size;
if ((optmask & ARES_OPT_SOCK_RCVBUF)
&& channel->socket_receive_buffer_size == -1)
channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
if ((optmask & ARES_OPT_EDNSPSZ) && channel->ednspsz == -1)
channel->ednspsz = options->ednspsz;
/* Copy the IPv4 servers, if given. */
if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
{
/* Avoid zero size allocations at any cost */
if (options->nservers > 0)
{
channel->servers =
ares_malloc(options->nservers * sizeof(struct server_state));
if (!channel->servers)
return ARES_ENOMEM;
for (i = 0; i < options->nservers; i++)
{
channel->servers[i].addr.family = AF_INET;
channel->servers[i].addr.udp_port = 0;
channel->servers[i].addr.tcp_port = 0;
memcpy(&channel->servers[i].addr.addrV4,
&options->servers[i],
sizeof(channel->servers[i].addr.addrV4));
}
}
channel->nservers = options->nservers;
}
/* Copy the domains, if given. Keep channel->ndomains consistent so
* we can clean up in case of error.
*/
if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
{
/* Avoid zero size allocations at any cost */
if (options->ndomains > 0)
{
channel->domains = ares_malloc(options->ndomains * sizeof(char *));
if (!channel->domains)
return ARES_ENOMEM;
for (i = 0; i < options->ndomains; i++)
{
channel->ndomains = i;
channel->domains[i] = ares_strdup(options->domains[i]);
if (!channel->domains[i])
return ARES_ENOMEM;
}
}
channel->ndomains = options->ndomains;
}
/* Set lookups, if given. */
if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
{
channel->lookups = ares_strdup(options->lookups);
if (!channel->lookups)
return ARES_ENOMEM;
}
/* copy sortlist */
if ((optmask & ARES_OPT_SORTLIST) && (channel->nsort == -1)) {
if (options->nsort > 0) {
channel->sortlist = ares_malloc(options->nsort * sizeof(struct apattern));
if (!channel->sortlist)
return ARES_ENOMEM;
for (i = 0; i < options->nsort; i++)
channel->sortlist[i] = options->sortlist[i];
}
channel->nsort = options->nsort;
}
channel->optmask = optmask;
return ARES_SUCCESS;
}
static int init_by_environment(ares_channel channel)
{
const char *localdomain, *res_options;
int status;
localdomain = getenv("LOCALDOMAIN");
if (localdomain && channel->ndomains == -1)
{
status = set_search(channel, localdomain);
if (status != ARES_SUCCESS)
return status;
}
res_options = getenv("RES_OPTIONS");
if (res_options)
{
status = set_options(channel, res_options);
if (status != ARES_SUCCESS)
return status; /* LCOV_EXCL_LINE: set_options() never fails */
}
return ARES_SUCCESS;
}
#ifdef WIN32
/*
* get_REG_SZ()
*
* Given a 'hKey' handle to an open registry key and a 'leafKeyName' pointer
* to the name of the registry leaf key to be queried, fetch it's string
* value and return a pointer in *outptr to a newly allocated memory area
* holding it as a null-terminated string.
*
* Returns 0 and nullifies *outptr upon inability to return a string value.
*
* Returns 1 and sets *outptr when returning a dynamically allocated string.
*
* Supported on Windows NT 3.5 and newer.
*/
static int get_REG_SZ(HKEY hKey, const char *leafKeyName, char **outptr)
{
DWORD size = 0;
int res;
*outptr = NULL;
/* Find out size of string stored in registry */
res = RegQueryValueEx(hKey, leafKeyName, 0, NULL, NULL, &size);
if ((res != ERROR_SUCCESS && res != ERROR_MORE_DATA) || !size)
return 0;
/* Allocate buffer of indicated size plus one given that string
might have been stored without null termination */
*outptr = ares_malloc(size+1);
if (!*outptr)
return 0;
/* Get the value for real */
res = RegQueryValueEx(hKey, leafKeyName, 0, NULL,
(unsigned char *)*outptr, &size);
if ((res != ERROR_SUCCESS) || (size == 1))
{
ares_free(*outptr);
*outptr = NULL;
return 0;
}
/* Null terminate buffer allways */
*(*outptr + size) = '\0';
return 1;
}
/*
* get_REG_SZ_9X()
*
* Functionally identical to get_REG_SZ()
*
* Supported on Windows 95, 98 and ME.
*/
static int get_REG_SZ_9X(HKEY hKey, const char *leafKeyName, char **outptr)
{
DWORD dataType = 0;
DWORD size = 0;
int res;
*outptr = NULL;
/* Find out size of string stored in registry */
res = RegQueryValueEx(hKey, leafKeyName, 0, &dataType, NULL, &size);
if ((res != ERROR_SUCCESS && res != ERROR_MORE_DATA) || !size)
return 0;
/* Allocate buffer of indicated size plus one given that string
might have been stored without null termination */
*outptr = ares_malloc(size+1);
if (!*outptr)
return 0;
/* Get the value for real */
res = RegQueryValueEx(hKey, leafKeyName, 0, &dataType,
(unsigned char *)*outptr, &size);
if ((res != ERROR_SUCCESS) || (size == 1))
{
ares_free(*outptr);
*outptr = NULL;
return 0;
}
/* Null terminate buffer allways */
*(*outptr + size) = '\0';
return 1;
}
/*
* get_enum_REG_SZ()
*
* Given a 'hKeyParent' handle to an open registry key and a 'leafKeyName'
* pointer to the name of the registry leaf key to be queried, parent key
* is enumerated searching in child keys for given leaf key name and its
* associated string value. When located, this returns a pointer in *outptr
* to a newly allocated memory area holding it as a null-terminated string.
*
* Returns 0 and nullifies *outptr upon inability to return a string value.
*
* Returns 1 and sets *outptr when returning a dynamically allocated string.
*
* Supported on Windows NT 3.5 and newer.
*/
static int get_enum_REG_SZ(HKEY hKeyParent, const char *leafKeyName,
char **outptr)
{
char enumKeyName[256];
DWORD enumKeyNameBuffSize;
DWORD enumKeyIdx = 0;
HKEY hKeyEnum;
int gotString;
int res;
*outptr = NULL;
for(;;)
{
enumKeyNameBuffSize = sizeof(enumKeyName);
res = RegEnumKeyEx(hKeyParent, enumKeyIdx++, enumKeyName,
&enumKeyNameBuffSize, 0, NULL, NULL, NULL);
if (res != ERROR_SUCCESS)
break;
res = RegOpenKeyEx(hKeyParent, enumKeyName, 0, KEY_QUERY_VALUE,
&hKeyEnum);
if (res != ERROR_SUCCESS)
continue;
gotString = get_REG_SZ(hKeyEnum, leafKeyName, outptr);
RegCloseKey(hKeyEnum);
if (gotString)
break;
}
if (!*outptr)
return 0;
return 1;
}
/*
* get_DNS_Registry_9X()
*
* Functionally identical to get_DNS_Registry()
*
* Implementation supports Windows 95, 98 and ME.
*/
static int get_DNS_Registry_9X(char **outptr)
{
HKEY hKey_VxD_MStcp;
int gotString;
int res;
*outptr = NULL;
res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X, 0, KEY_READ,
&hKey_VxD_MStcp);
if (res != ERROR_SUCCESS)
return 0;
gotString = get_REG_SZ_9X(hKey_VxD_MStcp, NAMESERVER, outptr);
RegCloseKey(hKey_VxD_MStcp);
if (!gotString || !*outptr)
return 0;
return 1;
}
/*
* get_DNS_Registry_NT()
*
* Functionally identical to get_DNS_Registry()
*
* Refs: Microsoft Knowledge Base articles KB120642 and KB314053.
*
* Implementation supports Windows NT 3.5 and newer.
*/
static int get_DNS_Registry_NT(char **outptr)
{
HKEY hKey_Interfaces = NULL;
HKEY hKey_Tcpip_Parameters;
int gotString;
int res;
*outptr = NULL;
res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, KEY_READ,
&hKey_Tcpip_Parameters);
if (res != ERROR_SUCCESS)
return 0;
/*
** Global DNS settings override adapter specific parameters when both
** are set. Additionally static DNS settings override DHCP-configured
** parameters when both are set.
*/
/* Global DNS static parameters */
gotString = get_REG_SZ(hKey_Tcpip_Parameters, NAMESERVER, outptr);
if (gotString)
goto done;
/* Global DNS DHCP-configured parameters */
gotString = get_REG_SZ(hKey_Tcpip_Parameters, DHCPNAMESERVER, outptr);
if (gotString)
goto done;
/* Try adapter specific parameters */
res = RegOpenKeyEx(hKey_Tcpip_Parameters, "Interfaces", 0,
KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS,
&hKey_Interfaces);
if (res != ERROR_SUCCESS)
{
hKey_Interfaces = NULL;
goto done;
}
/* Adapter specific DNS static parameters */
gotString = get_enum_REG_SZ(hKey_Interfaces, NAMESERVER, outptr);
if (gotString)
goto done;
/* Adapter specific DNS DHCP-configured parameters */
gotString = get_enum_REG_SZ(hKey_Interfaces, DHCPNAMESERVER, outptr);
done:
if (hKey_Interfaces)
RegCloseKey(hKey_Interfaces);
RegCloseKey(hKey_Tcpip_Parameters);
if (!gotString || !*outptr)
return 0;
return 1;
}
/*
* get_DNS_Registry()
*
* Locates DNS info in the registry. When located, this returns a pointer
* in *outptr to a newly allocated memory area holding a null-terminated
* string with a space or comma seperated list of DNS IP addresses.
*
* Returns 0 and nullifies *outptr upon inability to return DNSes string.
*
* Returns 1 and sets *outptr when returning a dynamically allocated string.
*/
static int get_DNS_Registry(char **outptr)
{
win_platform platform;
int gotString = 0;
*outptr = NULL;
platform = ares__getplatform();
if (platform == WIN_NT)
gotString = get_DNS_Registry_NT(outptr);
else if (platform == WIN_9X)
gotString = get_DNS_Registry_9X(outptr);
if (!gotString)
return 0;
return 1;
}
static void commanjoin(char** dst, const char* const src, const size_t len)
{
char *newbuf;
size_t newsize;
/* 1 for terminating 0 and 2 for , and terminating 0 */
newsize = len + (*dst ? (strlen(*dst) + 2) : 1);
newbuf = ares_realloc(*dst, newsize);
if (!newbuf)
return;
if (*dst == NULL)
*newbuf = '\0';
*dst = newbuf;
if (strlen(*dst) != 0)
strcat(*dst, ",");
strncat(*dst, src, len);
}
/*
* commajoin()
*
* RTF code.
*/
static void commajoin(char **dst, const char *src)
{
commanjoin(dst, src, strlen(src));
}
/*
* get_DNS_NetworkParams()
*
* Locates DNS info using GetNetworkParams() function from the Internet
* Protocol Helper (IP Helper) API. When located, this returns a pointer
* in *outptr to a newly allocated memory area holding a null-terminated
* string with a space or comma seperated list of DNS IP addresses.
*
* Returns 0 and nullifies *outptr upon inability to return DNSes string.
*
* Returns 1 and sets *outptr when returning a dynamically allocated string.
*
* Implementation supports Windows 98 and newer.
*
* Note: Ancient PSDK required in order to build a W98 target.
*/
static int get_DNS_NetworkParams(char **outptr)
{
FIXED_INFO *fi, *newfi;
struct ares_addr namesrvr;
char *txtaddr;
IP_ADDR_STRING *ipAddr;
int res;
DWORD size = sizeof (*fi);
*outptr = NULL;
/* Verify run-time availability of GetNetworkParams() */
if (ares_fpGetNetworkParams == ZERO_NULL)
return 0;
fi = ares_malloc(size);
if (!fi)
return 0;
res = (*ares_fpGetNetworkParams) (fi, &size);
if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
goto done;
newfi = ares_realloc(fi, size);
if (!newfi)
goto done;
fi = newfi;
res = (*ares_fpGetNetworkParams) (fi, &size);
if (res != ERROR_SUCCESS)
goto done;
for (ipAddr = &fi->DnsServerList; ipAddr; ipAddr = ipAddr->Next)
{
txtaddr = &ipAddr->IpAddress.String[0];
/* Validate converting textual address to binary format. */
if (ares_inet_pton(AF_INET, txtaddr, &namesrvr.addrV4) == 1)
{
if ((namesrvr.addrV4.S_un.S_addr == INADDR_ANY) ||
(namesrvr.addrV4.S_un.S_addr == INADDR_NONE))
continue;
}
else if (ares_inet_pton(AF_INET6, txtaddr, &namesrvr.addrV6) == 1)
{
if (memcmp(&namesrvr.addrV6, &ares_in6addr_any,
sizeof(namesrvr.addrV6)) == 0)
continue;
}
else
continue;
commajoin(outptr, txtaddr);
if (!*outptr)
break;
}
done:
if (fi)
ares_free(fi);
if (!*outptr)
return 0;
return 1;
}
static BOOL ares_IsWindowsVistaOrGreater(void)
{
OSVERSIONINFO vinfo;
memset(&vinfo, 0, sizeof(vinfo));
vinfo.dwOSVersionInfoSize = sizeof(vinfo);
if (!GetVersionEx(&vinfo) || vinfo.dwMajorVersion < 6)
return FALSE;
return TRUE;
}
/* A structure to hold the string form of IPv4 and IPv6 addresses so we can
* sort them by a metric.
*/
typedef struct
{
/* The metric we sort them by. */
ULONG metric;
/* Original index of the item, used as a secondary sort parameter to make
* qsort() stable if the metrics are equal */
size_t orig_idx;
/* Room enough for the string form of any IPv4 or IPv6 address that
* ares_inet_ntop() will create. Based on the existing c-ares practice.
*/
char text[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")];
} Address;
/* Sort Address values \a left and \a right by metric, returning the usual
* indicators for qsort().
*/
static int compareAddresses(const void *arg1,
const void *arg2)
{
const Address * const left = arg1;
const Address * const right = arg2;
/* Lower metric the more preferred */
if(left->metric < right->metric) return -1;
if(left->metric > right->metric) return 1;
/* If metrics are equal, lower original index more preferred */
if(left->orig_idx < right->orig_idx) return -1;
if(left->orig_idx > right->orig_idx) return 1;
return 0;
}
/* There can be multiple routes to "the Internet". And there can be different
* DNS servers associated with each of the interfaces that offer those routes.
* We have to assume that any DNS server can serve any request. But, some DNS
* servers may only respond if requested over their associated interface. But
* we also want to use "the preferred route to the Internet" whenever possible
* (and not use DNS servers on a non-preferred route even by forcing request
* to go out on the associated non-preferred interface). i.e. We want to use
* the DNS servers associated with the same interface that we would use to
* make a general request to anything else.