File: res_send.c

package info (click to toggle)
libdnsres 0.1a-4
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k, lenny, squeeze
  • size: 1,696 kB
  • ctags: 789
  • sloc: sh: 8,139; ansic: 6,864; makefile: 80
file content (1190 lines) | stat: -rw-r--r-- 32,007 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
/*
 * Copyright 2005 Niels Provos <provos@citi.umich.edu>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Niels Provos.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
 */

/*	$OpenBSD: res_send.c,v 1.15 2003/06/02 20:18:36 millert Exp $	*/

/*
 * ++Copyright++ 1985, 1989, 1993
 * -
 * Copyright (c) 1985, 1989, 1993
 *    The Regents of the University of California.  All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name of the University 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 REGENTS 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 REGENTS 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.
 * -
 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
 * 
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies, and that
 * the name of Digital Equipment Corporation not be used in advertising or
 * publicity pertaining to distribution of the document or software without
 * specific, written prior permission.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
 * SOFTWARE.
 * -
 * --Copyright--
 */

	/* change this to "0"
	 * if you talk to a lot
	 * of multi-homed SunOS
	 * ("broken") name servers.
	 */
#define	CHECK_SRVR_ADDR	1	/* XXX - should be in options.h */

/*
 * Send query to name server and wait for reply.
 */

#include <sys/types.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <arpa/inet.h>

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <event.h>

#include "dnsres.h"
#include "resolv.h"
#include "dnsres-internal.h"

#ifndef FD_SET
/* XXX - should be in portability.h */
#define	NFDBITS		32
#define	FD_SETSIZE	32
#define	FD_SET(n, p)	((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
#define	FD_CLR(n, p)	((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
#define	FD_ISSET(n, p)	((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
#define FD_ZERO(p)	bzero((char *)(p), sizeof(*(p)))
#endif

#ifndef DEBUG
#   define Dprint(cond, args) /*empty*/
#   define DprintQ(cond, args, query, size) /*empty*/
#   define Aerror(file, string, error, address) /*empty*/
#   define Perror(file, string, error) /*empty*/
#else
#   define Dprint(cond, args) if (cond) {fprintf args;} else {}
#   define DprintQ(cond, args, query, size) if (cond) {\
			fprintf args;\
			__fp_nquery(query, size, stdout);\
		} else {}
static char abuf[NI_MAXHOST];
static char pbuf[NI_MAXSERV];
static void Aerror(FILE *, char *, int, struct sockaddr *);
static void Perror(FILE *, char *, int);

    static void
    Aerror(file, string, error, address)
	FILE *file;
	char *string;
	int error;
	struct sockaddr *address;
    {
	struct dnsres *_resp = NULL;
	int save = errno;
	socklen_t salen;

	if (address->sa_family == AF_INET6)
		salen = sizeof(struct sockaddr_in6);
	else if (address->sa_family == AF_INET)
		salen = sizeof(struct sockaddr_in);
	else
		salen = 0;	/*unknown, die on connect*/

	if (_resp->options & RES_DEBUG) {
		if (getnameinfo(address, salen, abuf, sizeof(abuf),
		    pbuf, sizeof(pbuf),
		    NI_NUMERICHOST|NI_NUMERICSERV|NI_WITHSCOPEID) != 0) {
			strlcpy(abuf, "?", sizeof(abuf));
			strlcpy(pbuf, "?", sizeof(pbuf));
		}
		fprintf(file, "res_send: %s ([%s].%s): %s\n",
			string, abuf, pbuf, strerror(error));
	}
	errno = save;
    }
    static void
    Perror(file, string, error)
	FILE *file;
	char *string;
	int error;
    {
	struct dnsres *_resp = NULL;
	int save = errno;

	if (_resp->options & RES_DEBUG) {
		fprintf(file, "res_send: %s: %s\n",
			string, strerror(error));
	}
	errno = save;
    }
#endif

static res_send_qhook Qhook = NULL;
static res_send_rhook Rhook = NULL;

void
res_send_setqhook(res_send_qhook hook)
{

	Qhook = hook;
}

void
res_send_setrhook(res_send_rhook hook)
{

	Rhook = hook;
}

static struct sockaddr * get_nsaddr(struct dnsres *, size_t n);

/*
 * pick appropriate nsaddr_list for use.  see res_init() for initialization.
 */
static struct sockaddr *
get_nsaddr(struct dnsres *_resp, size_t n)
{
	struct dnsres_ext *_res_extp = &_resp->ext;
	if (!_resp->nsaddr_list[n].sin_family) {
		/*
		 * - _res_extp->nsaddr_list[n] holds an address that is larger
		 *   than struct sockaddr, and
		 * - user code did not update _resp->nsaddr_list[n].
		 */
		return (struct sockaddr *)&_res_extp->nsaddr_list[n];
	} else {
		/*
		 * - user code updated _res.nsaddr_list[n], or
		 * - _resp->nsaddr_list[n] has the same content as
		 *   _res_extp->nsaddr_list[n].
		 */
		return (struct sockaddr *)&_resp->nsaddr_list[n];
	}
}

/* int
 * res_isourserver(ina)
 *	looks up "ina" in _resp->ns_addr_list[]
 * returns:
 *	0  : not found
 *	>0 : found
 * author:
 *	paul vixie, 29may94
 */
int
res_isourserver(struct dnsres *_resp, const struct sockaddr_in *inp)
{
	const struct sockaddr_in6 *in6p = (const struct sockaddr_in6 *)inp;
	const struct sockaddr_in6 *srv6;
	const struct sockaddr_in *srv;
	int ns, ret;

	ret = 0;
	switch (inp->sin_family) {
	case AF_INET6:
		for (ns = 0; ns < _resp->nscount; ns++) {
			srv6 = (struct sockaddr_in6 *)get_nsaddr(_resp, ns);
			if (srv6->sin6_family == in6p->sin6_family &&
			    srv6->sin6_port == in6p->sin6_port &&
			    srv6->sin6_scope_id == in6p->sin6_scope_id &&
			    (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
			     IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr,
			         &in6p->sin6_addr))) {
				ret++;
				break;
			}
		}
		break;
	case AF_INET:
		for (ns = 0; ns < _resp->nscount; ns++) {
			srv = (struct sockaddr_in *)get_nsaddr(_resp, ns);
			if (srv->sin_family == inp->sin_family &&
			    srv->sin_port == inp->sin_port &&
			    (srv->sin_addr.s_addr == INADDR_ANY ||
			     srv->sin_addr.s_addr == inp->sin_addr.s_addr)) {
				ret++;
				break;
			}
		}
		break;
	}
	return (ret);
}

/* int
 * res_nameinquery(name, type, class, buf, eom)
 *	look for (name,type,class) in the query section of packet (buf,eom)
 * returns:
 *	-1 : format error
 *	0  : not found
 *	>0 : found
 * author:
 *	paul vixie, 29may94
 */
int
res_nameinquery(name, type, class, buf, eom)
	const char *name;
	register int type, class;
	const u_char *buf, *eom;
{
	register const u_char *cp = buf + DNSRES_HFIXEDSZ;
	int qdcount = ntohs(((DNSRES_HEADER*)buf)->qdcount);

	while (qdcount-- > 0) {
		char tname[DNSRES_MAXDNAME+1];
		register int n, ttype, tclass;

		n = dn_expand(buf, eom, cp, tname, sizeof tname);
		if (n < 0)
			return (-1);
		cp += n;
		ttype = getshort(cp); cp += DNSRES_INT16SZ;
		tclass = getshort(cp); cp += DNSRES_INT16SZ;
		if (ttype == type &&
		    tclass == class &&
		    strcasecmp(tname, name) == 0)
			return (1);
	}
	return (0);
}

/* int
 * res_queriesmatch(buf1, eom1, buf2, eom2)
 *	is there a 1:1 mapping of (name,type,class)
 *	in (buf1,eom1) and (buf2,eom2)?
 * returns:
 *	-1 : format error
 *	0  : not a 1:1 mapping
 *	>0 : is a 1:1 mapping
 * author:
 *	paul vixie, 29may94
 */
int
res_queriesmatch(buf1, eom1, buf2, eom2)
	const u_char *buf1, *eom1;
	const u_char *buf2, *eom2;
{
	register const u_char *cp = buf1 + DNSRES_HFIXEDSZ;
	int qdcount = ntohs(((DNSRES_HEADER*)buf1)->qdcount);

	if (qdcount != ntohs(((DNSRES_HEADER*)buf2)->qdcount))
		return (0);
	while (qdcount-- > 0) {
		char tname[DNSRES_MAXDNAME+1];
		register int n, ttype, tclass;

		n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
		if (n < 0)
			return (-1);
		cp += n;
		ttype = getshort(cp);	cp += DNSRES_INT16SZ;
		tclass = getshort(cp); cp += DNSRES_INT16SZ;
		if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
			return (0);
	}
	return (1);
}

/* Parameters that control the behavior of res_send_loop_cb */

enum {
	RS_LOOP_BREAK  = -1,
	RS_LOOP_CONT   = 0,
	RS_LOOP_REPEAT = 1
};

/* Non-blocking */
int
QhookDispatch(void (*cb)(int, struct res_search_state *),
    struct res_search_state *state)
{
	struct sockaddr *nsap = get_nsaddr(state->_resp, state->ns);
	int done = 0, loops = 0;

	do {
		const struct dnsres_target *q = state->target;
		res_sendhookact act;

		act = (*Qhook)((struct sockaddr_in **)&nsap,
		    &state->send_buf, &state->send_buflen,
		    q->answer, q->anslen,
		    &state->resplen);
		switch (act) {
		case res_goahead:
			done = 1;
			break;
		case res_nextns:
			res_close(&state->ds);
			(*cb)(RS_LOOP_CONT, state);
			return (-1);
		case res_done:
			state->ret = state->resplen;
			(*cb)(RS_LOOP_BREAK, state);
			return (-1);
		case res_modified:
			/* give the hook another try */
			if (++loops < 42) /*doug adams*/
				break;
			/*FALLTHROUGH*/
		case res_error:
			/*FALLTHROUGH*/
		default:
			state->ret = -1;
			(*cb)(RS_LOOP_BREAK, state);
			return (-1);
		}
	} while (!done);

	return (0);
}

int
RhookDispatch(void (*cb)(int, struct res_search_state *),
    struct res_search_state *state)
{
	struct sockaddr *nsap = get_nsaddr(state->_resp, state->ns);
	int done = 0, loops = 0;

	do {
		const struct dnsres_target *q = state->target;
		res_sendhookact act;

		act = (*Rhook)((struct sockaddr_in *)nsap,
		    state->send_buf, state->send_buflen,
		    q->answer, q->anslen,
		    &state->resplen);
		switch (act) {
		case res_goahead:
		case res_done:
			done = 1;
			break;
		case res_nextns:
			res_close(&state->ds);
			(*cb)(RS_LOOP_CONT, state);
			return (-1);
		case res_modified:
			/* give the hook another try */
			if (++loops < 42) /*doug adams*/
				break;
			/*FALLTHROUGH*/
		case res_error:
			/*FALLTHROUGH*/
		default:
			state->ret = -1;
			(*cb)(RS_LOOP_BREAK, state);
			return (-1);
		}
	} while (!done);

	return (0);
}

int
res_make_socket(struct dnsres_socket *ds, int af, int type)
{
	if (ds->vc >= 0)
		res_close(ds);
	ds->af = af;
	ds->s = socket(ds->af, type, 0);
	if (ds->s == -1)
		return (-1);

	/* Make the socket non-blocking */
        if (fcntl(ds->s, F_SETFL, O_NONBLOCK) == -1)
                Perror(stderr, "fcntl(O_NONBLOCK)", errno);

        if (fcntl(ds->s, F_SETFD, 1) == -1)
                Perror(stderr, "fcntl(F_SETFD)", errno);

#ifdef IPV6_MINMTU
	if (type == SOCK_DGRAM && af == AF_INET6) {
		const int yes = 1;
		(void)setsockopt(s, IPPROTO_IPV6, IPV6_USE_MIN_MTU,
		    &yes, sizeof(yes));
	}
#endif
	ds->connected = 0;

	return (0);
}

void res_send_loop(struct res_search_state *state);
void res_send_loop_cb(int ok, struct res_search_state *state);
void res_send_loop_bottom(struct res_search_state *state);

void res_send_iterator_bottom(struct res_search_state *state);

void res_send_vcircuit(struct res_search_state *state,
    struct sockaddr *nsap, socklen_t salen);
void res_send_dgram(struct res_search_state *state,
    struct sockaddr *nsap, socklen_t salen);

void
res_send_iterator(struct res_search_state *state)
{
	struct dnsres *_resp = state->_resp;
	struct sockaddr *nsap = get_nsaddr(_resp, state->ns);
	socklen_t salen;

	if (nsap->sa_family == AF_INET6)
		salen = sizeof(struct sockaddr_in6);
	else if (nsap->sa_family == AF_INET)
		salen = sizeof(struct sockaddr_in);
	else
		salen = 0;	/*unknown, die on connect*/

	if (state->badns & (1 << state->ns)) {
		res_close(&state->ds);
		res_send_loop_cb(RS_LOOP_CONT, state);
		return;
	}

	if (Qhook) {
		if (QhookDispatch(res_send_loop_cb, state) == -1)
			return;
	}

	Dprint((_resp->options & RES_DEBUG) &&
	    getnameinfo(nsap, salen, abuf, sizeof(abuf),
		NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID) == 0,
	    (stdout, ";; Querying server (# %d) address = %s\n",
		ns + 1, abuf));

	if (state->v_circuit)
		res_send_vcircuit(state, nsap, salen);
	else
		res_send_dgram(state, nsap, salen);
}

void res_send_vcircuit_writev(int fd, short what, void *arg);
void res_send_vcircuit_connectcb(int fd, short what, void *arg);
void res_send_vcircuit_readcb(int fd, short what, void *arg);
void res_send_vcircuit_read2ndcb(int fd, short what, void *arg);

void
res_send_vcircuit(struct res_search_state *state,
    struct sockaddr *nsap, socklen_t salen)
{
	struct dnsres *_resp = state->_resp;
	struct dnsres_socket *ds = &state->ds;

	/*
	 * Use virtual circuit; at most one attempt per server.
	 */
	state->try = _resp->retry;
	if ((ds->s < 0) ||
	    (ds->vc == 0) || 
	    (ds->af != nsap->sa_family)) {
		if (res_make_socket(ds, nsap->sa_family, SOCK_STREAM) == -1) {
			state->terrno = errno;
			Perror(stderr, "socket(vc)", errno);
			state->badns |= (1 << state->ns);
			res_close(&state->ds);
			res_send_loop_cb(RS_LOOP_CONT, state);
			return;
		}
		errno = 0;
		if (connect(ds->s, nsap, salen) < 0) {
			res_send_vcircuit_connectcb(ds->s, EV_WRITE, state);
			return;
		}

		if (event_initialized(&ds->ev))
			event_del(&ds->ev);
		event_set(&ds->ev, ds->s, EV_WRITE,
		    res_send_vcircuit_connectcb, state);
		event_add(&ds->ev, NULL);
		return;
	}

	/* We might be able to get rid of the del */
	if (event_initialized(&ds->ev))
		event_del(&ds->ev);
	event_set(&ds->ev, ds->s, EV_WRITE,
	    res_send_vcircuit_writev, state);
	event_add(&ds->ev, NULL);
}

void
res_send_vcircuit_connectcb(int fd, short what, void *arg)
{
	struct res_search_state *state = arg;
	struct dnsres_socket *ds = &state->ds;
	int error;
	socklen_t errsz = sizeof(error);

	/* Check if the connection completed */
	if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &errsz) == -1) {
		Perror(stderr, "getsockopt", errno);
		/* Just make up an error number */
		error = ECONNREFUSED;
	}

	if (error) {
		state->terrno = errno;
		Aerror(stderr, "connect/vc",
		    errno, nsap);
		state->badns |= (1 << state->ns);
		res_close(&state->ds);
		res_send_loop_cb(RS_LOOP_CONT, state);
		return;
	}

	ds->vc = 1;

	/* Setup the next event. Yeah */
	event_set(&ds->ev, ds->s, EV_WRITE,
	    res_send_vcircuit_writev, state);
	event_add(&ds->ev, NULL);
}

void
res_send_vcircuit_writev(int fd, short what, void *arg)
{
	struct res_search_state *state = arg;
	struct dnsres *_resp = state->_resp;
	struct dnsres_socket *ds = &state->ds;
	struct iovec iov[2];
	struct timeval timeout;
	u_short len;

	/*
	 * Send length & message
	 */
	putshort((u_short)state->send_buflen, (u_char*)&len);
	iov[0].iov_base = (caddr_t)&len;
	iov[0].iov_len = DNSRES_INT16SZ;
	iov[1].iov_base = (caddr_t)state->send_buf;
	iov[1].iov_len = state->send_buflen;
	if (writev(ds->s, iov, 2) != (DNSRES_INT16SZ + state->send_buflen)) {
		state->terrno = errno;
		Perror(stderr, "write failed", errno);
		state->badns |= (1 << state->ns);
		res_close(&state->ds);
		res_send_loop_cb(RS_LOOP_CONT, state);
		return;
	}
	
	/* Setup the next event. Yeah */
	event_set(&ds->ev, ds->s, EV_READ,
	    res_send_vcircuit_readcb, state);
	timerclear(&timeout);
	timeout.tv_sec = _resp->retrans;
	event_add(&ds->ev, &timeout);
}

void
res_send_vcircuit_readcb(int fd, short what, void *arg)
{
	struct res_search_state *state = arg;
	struct dnsres *_resp = state->_resp;
	struct dnsres_socket *ds = &state->ds;
	const struct dnsres_target *q = state->target;
	u_char *cp;
	u_short len;
	struct timeval timeout;
	int n;

	state->truncated = 0;

	/*
	 * Receive length & response
	 */
	cp = q->answer;
	len = DNSRES_INT16SZ;
	while ((n = read(ds->s, (char *)cp, (int)len)) > 0) {
		cp += n;
		if ((len -= n) <= 0)
			break;
	}
	if (n <= 0) {
		state->terrno = errno;
		Perror(stderr, "read failed", errno);
		res_close(&state->ds);
		/*
		 * A long running process might get its TCP connection
		 * reset if the remote server was restarted.  Requery
		 * the server instead of trying a new one.  When there
		 * is only one server, this means that a query might
		 * work instead of failing.  We only allow one reset
		 * per query to prevent looping.
		 */
		if (state->terrno == ECONNRESET && !state->connreset) {
			state->connreset = 1;
			res_close(&state->ds);
			res_send_loop_cb(RS_LOOP_REPEAT, state);
			return;
		}
		res_close(&state->ds);
		res_send_loop_cb(RS_LOOP_CONT, state);
		return;
	}
	state->resplen = getshort(q->answer);
	if (state->resplen > q->anslen) {
		Dprint(_resp->options & RES_DEBUG,
		    (stdout, ";; response truncated\n")
		    );
		state->truncated = 1;
		len = q->anslen;
	} else
		len = state->resplen;

	/* Setup state for next read */
	state->read_len = len;
	state->cp = q->answer;

	/* Setup the next event. Yeah */
	event_set(&ds->ev, ds->s, EV_READ,
	    res_send_vcircuit_read2ndcb, state);
	timerclear(&timeout);
	timeout.tv_sec = _resp->retrans;
	event_add(&ds->ev, &timeout);
}

void
res_send_vcircuit_read2ndcb(int fd, short what, void *arg)
{
	struct res_search_state *state = arg;
	struct dnsres *_resp = state->_resp;
	struct dnsres_socket *ds = &state->ds;
	const struct dnsres_target *q = state->target;
	DNSRES_HEADER *hp = (DNSRES_HEADER *) state->send_buf;
	DNSRES_HEADER *anhp = (DNSRES_HEADER *) q->answer;
	u_short len = state->read_len;
	u_char *cp;
	int n;

	cp = state->cp;
	n = read(ds->s, (char *)cp, (int)len);
	if (n > 0) {
		cp += n;
		len -= n;
		if (len > 0) {
			struct timeval timeout;

			state->read_len = len;
			state->cp = cp;

			/* Already setup to point to us, so add again */
			timerclear(&timeout);
			timeout.tv_sec = _resp->retrans;
			event_add(&ds->ev, &timeout);
			return;
		}
	}
	
	if (n <= 0) {
		state->terrno = errno;
		Perror(stderr, "read(vc)", errno);
		res_close(&state->ds);
		res_send_loop_cb(RS_LOOP_CONT, state);
		return;
	}
	if (state->truncated) {
		/*
		 * Flush rest of answer so connection stays in synch.
		 */
		anhp->tc = 1;
		len = state->resplen - q->anslen;
		while (len != 0) {
			char junk[DNSRES_PACKETSZ];

			n = (len > sizeof(junk)
			    ? sizeof(junk)
			    : len);
			if ((n = read(ds->s, junk, n)) > 0)
				len -= n;
			else
				break;
		}
	}
	/*
	 * The calling applicating has bailed out of a previous call
	 * and failed to arrange to have the circuit closed or the
	 * server has got itself confused. Anyway drop the packet and
	 * wait for the correct one.
	 *
	 * Well, that's how it used to be, we take a more conservative
	 * approach and close the socket and retry.
	 */
	if (hp->id != anhp->id) {
		DprintQ((_resp->options & RES_DEBUG) ||
		    (_resp->pfcode & RES_PRF_REPLY),
		    (stdout, ";; old answer (unexpected):\n"),
		    ans, (state->resplen>q->anslen)?q->anslen:state->resplen);
		res_close(&state->ds);
		res_send_loop_cb(RS_LOOP_REPEAT, state);
		return;
	}

	res_send_iterator_bottom(state);
}

/*
 * Use datagrams.
 */

void res_send_dgram_wait_read(int fd, short what, void *arg);
void res_send_dgram_send(int fd, short what, void *arg);
void res_send_dgram_sendto(int fd, short what, void *arg);
void res_send_dgram_setup_wait(struct res_search_state *state);

void
res_send_dgram(struct res_search_state *state,
    struct sockaddr *nsap, socklen_t salen)
{
	struct dnsres *_resp = state->_resp;
	struct dnsres_socket *ds = &state->ds;

	if ((ds->s < 0) || ds->vc || (ds->af != nsap->sa_family)) {
		if (res_make_socket(ds, nsap->sa_family, SOCK_DGRAM) == -1) {
			state->terrno = errno;
			Perror(stderr, "socket(dg)", errno);
			state->badns |= (1 << state->ns);
			res_close(&state->ds);
			res_send_loop_cb(RS_LOOP_CONT, state);
			return;
		}
	}
	/*
	 * On a 4.3BSD+ machine (client and server, actually), sending
	 * to a nameserver datagram port with no nameserver will cause
	 * an ICMP port unreachable message to be returned.  If our
	 * datagram socket is "connected" to the server, we get an
	 * ECONNREFUSED error on the next socket operation, and select
	 * returns if the error message is received.  We can thus
	 * detect the absence of a nameserver without timing out.  If
	 * we have sent queries to at least two servers, however, we
	 * don't want to remain connected, as we wish to receive
	 * answers from the first server to respond.
	 */
	if (!(_resp->options & RES_INSECURE1) && (_resp->nscount == 1 || 
		(state->try == 0 && state->ns == 0))) {
		/*
		 * Connect only if we are sure we won't receive a
		 * response from another server.
		 */
		if (!ds->connected) {
			if (connect(ds->s, nsap, salen) < 0) {
				Aerror(stderr, "connect(dg)", errno, nsap);
				state->badns |= (1 << state->ns);
				res_close(&state->ds);
				res_send_loop_cb(RS_LOOP_CONT, state);
				return;
			}
			ds->connected = 1;
		}

		if (event_initialized(&ds->ev))
			event_del(&ds->ev);
		event_set(&ds->ev, ds->s, EV_WRITE,
		    res_send_dgram_send, state);
		event_add(&ds->ev, NULL);
	} else {
		/*
		 * Disconnect if we want to listen for responses from
		 * more than one server.
		 */
		if (ds->connected) {
			/* XXX: any errornous address */
			struct sockaddr_in no_addr;

			no_addr.sin_family = AF_INET;
			no_addr.sin_addr.s_addr = INADDR_ANY;
			no_addr.sin_port = 0;
			(void) connect(ds->s, (struct sockaddr *)
			    &no_addr, sizeof(no_addr));
#ifdef IPV6_MINMTU
			if (af == AF_INET6) {
				const int yes = 1;
				(void)setsockopt(s, IPPROTO_IPV6,
				    IPV6_USE_MIN_MTU, &yes,
				    sizeof(yes));
			}
#endif
			ds->connected = 0;
			errno = 0;
		}

		/* Tell it where to go */
		ds->nsap = nsap;
		ds->salen = salen;

		if (event_initialized(&ds->ev))
			event_del(&ds->ev);
		event_set(&ds->ev, ds->s, EV_WRITE,
		    res_send_dgram_sendto, state);
		event_add(&ds->ev, NULL);
	}
}

void
res_send_dgram_send(int fd, short what, void *arg)
{
	struct res_search_state *state = arg;

	if (send(fd, (char*)state->send_buf, state->send_buflen, 0)
	    != state->send_buflen) {
		Perror(stderr, "send", errno);
		state->badns |= (1 << state->ns);
		res_close(&state->ds);
		res_send_loop_cb(RS_LOOP_CONT, state);
		return;
	}

	res_send_dgram_setup_wait(state);
}

void
res_send_dgram_sendto(int fd, short what, void *arg)
{
	struct res_search_state *state = arg;
	struct dnsres_socket *ds = &state->ds;

	if (sendto(fd, (char*)state->send_buf, state->send_buflen, 0,
		ds->nsap, ds->salen) != state->send_buflen) {
		Aerror(stderr, "sendto", errno, nsap);
		state->badns |= (1 << state->ns);
		res_close(&state->ds);
		res_send_loop_cb(RS_LOOP_CONT, state);
		return;
	}

	res_send_dgram_setup_wait(state);
}

void
res_send_dgram_setup_wait(struct res_search_state *state)
{
	struct dnsres_socket *ds = &state->ds;
	struct dnsres *_resp = state->_resp;
	struct timeval timeout;

	/*
	 * Wait for reply
	 */
	event_set(&ds->ev, ds->s, EV_READ, res_send_dgram_wait_read, state);
	timeout.tv_sec = (_resp->retrans << state->try);
	if (state->try > 0)
		timeout.tv_sec /= _resp->nscount;
	if ((long) timeout.tv_sec <= 0)
		timeout.tv_sec = 1;
	timeout.tv_usec = 0;

	event_add(&ds->ev, &timeout);
}

void
res_send_dgram_wait_read(int fd, short what, void *arg)
{
	struct res_search_state *state = arg;
	struct dnsres *_resp = state->_resp;
	struct dnsres_socket *ds = &state->ds;
	const struct dnsres_target *q = state->target;
	DNSRES_HEADER *hp = (DNSRES_HEADER *) state->send_buf;
	DNSRES_HEADER *anhp = (DNSRES_HEADER *) q->answer;
	struct sockaddr_storage from;
	socklen_t fromlen;

	if (what == EV_TIMEOUT) {
		/*
		 * timeout
		 */
		Dprint(_resp->options & RES_DEBUG,
		    (stdout, ";; timeout\n"));
		state->gotsomewhere = 1;
		res_close(&state->ds);
		res_send_loop_cb(RS_LOOP_CONT, state);
		return;
	}
	errno = 0;
	fromlen = sizeof(from);
	state->resplen = recvfrom(ds->s,
	    (char*)q->answer, q->anslen, 0,
	    (struct sockaddr *)&from, &fromlen);
	if (state->resplen <= 0) {
		Perror(stderr, "recvfrom", errno);
		res_close(&state->ds);
		res_send_loop_cb(RS_LOOP_CONT, state);
		return;
	}
	state->gotsomewhere = 1;
	if (hp->id != anhp->id) {
		/*
		 * response from old query, ignore it.
		 * XXX - potential security hazard could
		 *	 be detected here.
		 */
		DprintQ((_resp->options & RES_DEBUG) ||
		    (_resp->pfcode & RES_PRF_REPLY),
		    (stdout, ";; old answer:\n"),
		    ans, (state->resplen>q->anslen)?q->anslen:state->resplen);
		res_send_dgram_setup_wait(state);
		return;
	}
#if CHECK_SRVR_ADDR
	if (!(_resp->options & RES_INSECURE1) &&
	    !res_isourserver(_resp, (struct sockaddr_in *)&from)) {
		/*
		 * response from wrong server? ignore it.
		 * XXX - potential security hazard could
		 *	 be detected here.
		 */
		DprintQ((_resp->options & RES_DEBUG) ||
		    (_resp->pfcode & RES_PRF_REPLY),
		    (stdout, ";; not our server:\n"),
		    ans, (state->resplen>q->anslen)?q->anslen:state->resplen);
		res_send_dgram_setup_wait(state);
		return;
	}
#endif
	if (!(_resp->options & RES_INSECURE2) &&
	    !res_queriesmatch(state->send_buf,
		state->send_buf + state->send_buflen,
		q->answer,
		q->answer + q->anslen)) {
		/*
		 * response contains wrong query? ignore it.
		 * XXX - potential security hazard could
		 *	 be detected here.
		 */
		DprintQ((_resp->options & RES_DEBUG) ||
		    (_resp->pfcode & RES_PRF_REPLY),
		    (stdout, ";; wrong query name:\n"),
		    ans, (state->resplen>q->anslen)?q->anslen:state->resplen);
		res_send_dgram_setup_wait(state);
		return;
	}
	if (anhp->rcode == DNSRES_SERVFAIL ||
	    anhp->rcode == DNSRES_NOTIMP ||
	    anhp->rcode == DNSRES_REFUSED) {
		DprintQ(_resp->options & RES_DEBUG,
		    (stdout, "server rejected query:\n"),
		    ans, (state->resplen>q->anslen)?q->anslen:state->resplen);
		state->badns |= (1 << state->ns);
		res_close(&state->ds);
		/* don't retry if called from dig */
		if (!_resp->pfcode) {
			res_send_loop_cb(RS_LOOP_CONT, state);
			return;
		}
	}
	if (!(_resp->options & RES_IGNTC) && anhp->tc) {
		/*
		 * get rest of answer;
		 * use TCP with same 		 */
		Dprint(_resp->options & RES_DEBUG,
		    (stdout, ";; truncated answer\n"));
		state->v_circuit = 1;
		res_close(&state->ds);
		res_send_loop_cb(RS_LOOP_REPEAT, state);
		return;
	}

	res_send_iterator_bottom(state);
}

void
res_send_iterator_bottom(struct res_search_state *state)
{
	struct dnsres *_resp = state->_resp;

	Dprint((_resp->options & RES_DEBUG) ||
	    ((_resp->pfcode & RES_PRF_REPLY) &&
		(_resp->pfcode & RES_PRF_HEAD1)),
	    (stdout, ";; got answer:\n"));
	DprintQ((_resp->options & RES_DEBUG) ||
	    (_resp->pfcode & RES_PRF_REPLY),
	    (stdout, "%s", ""),
	    ans, (state->resplen>q->anslen)?q->anslen:state->resplen);
	/*
	 * If using virtual circuits, we assume that the first server
	 * is preferred over the rest (i.e. it is on the local
	 * machine) and only keep that one open.
	 * If we have temporarily opened a virtual circuit,
	 * or if we haven't been asked to keep a socket open,
	 * close the socket.
	 */
	if ((state->v_circuit &&
		(!(_resp->options & RES_USEVC) || state->ns != 0)) ||
	    !(_resp->options & RES_STAYOPEN)) {
		res_close(&state->ds);
	}
	if (Rhook) {
		if (RhookDispatch(res_send_loop_cb, state) == -1)
			return;
	}

	state->ret = state->resplen;
	res_send_loop_cb(RS_LOOP_BREAK, state);
	return;
}

void
res_send(
	struct dnsres *_resp,
	const u_char *buf,
	int buflen,
	u_char *ans,
	int anslen,
	void (*cb)(int, struct res_search_state *),
	struct res_search_state *state
    )
{
	DprintQ((_resp->options & RES_DEBUG) || (_resp->pfcode & RES_PRF_QUERY),
		(stdout, ";; res_send()\n"), buf, buflen);

	/* Initialize our state */
	state->send_buf = buf;
	state->send_buflen = buflen;
	state->v_circuit = (_resp->options & RES_USEVC) || buflen > DNSRES_PACKETSZ;
	state->gotsomewhere = 0;
	state->terrno = ETIMEDOUT;
	state->send_cb = cb;
	state->connreset = 0;
	state->badns = 0;

	/*
	 * Send request, RETRY times, or until successful
	 */
	state->try = 0;
	state->ns = 0;

	res_send_loop(state);
}

void
res_send_loop(struct res_search_state *state)
{
	struct dnsres *_resp = state->_resp;

	if (state->ns == _resp->nscount) {
		state->ns = 0;
		state->try++;
		if (state->try == _resp->retry) {
			res_send_loop_bottom(state);
			return;
		}
	}

	/* This function will always call back to res_send_loop_cb */
	res_send_iterator(state);
}

void
res_send_loop_cb(int what, struct res_search_state *state)
{
	/* We terminate on failure */
	if ( what == RS_LOOP_BREAK ) {
		(*state->send_cb)(state->ret, state);
		return;
	}

	if ( what == RS_LOOP_CONT ) {
		/* Otherwise we try to complete the loop */
		state->ns++;
	}

	/* RS_LOOP_REPEAT is the remaining case */
	res_send_loop(state);
}

void
res_send_loop_bottom(struct res_search_state *state)
{
	res_close(&state->ds);
	if (!state->v_circuit) {
		if (!state->gotsomewhere)
			errno = ECONNREFUSED;	/* no nameservers found */
		else
			errno = ETIMEDOUT;	/* no answer obtained */
	} else
		errno = state->terrno;

	(*state->send_cb)(-1, state);
}

/*
 * This routine is for closing the socket if a virtual circuit is used and
 * the program wants to close it.  This provides support for endhostent()
 * which expects to close the socket.
 *
 * This routine is not expected to be user visible.
 */
void
res_close(struct dnsres_socket *ds)
{
	if (ds->s >= 0) {
		if (event_initialized(&ds->ev))
			event_del(&ds->ev);
		(void) close(ds->s);
		res_init_socket(ds);
	}
}