4 * Low level DNS protocol routines
5 * AUTHOR: Duane Wessels
7 * SQUID Web Proxy Cache http://www.squid-cache.org/
8 * ----------------------------------------------------------
10 * Squid is the result of efforts by numerous individuals from
11 * the Internet community; see the CONTRIBUTORS file for full
12 * details. Many organizations have provided support for Squid's
13 * development; see the SPONSORS file for full details. Squid is
14 * Copyrighted (C) 2001 by the Regents of the University of
15 * California; see the COPYRIGHT file for full details. Squid
16 * incorporates software developed and/or copyrighted by other
17 * sources; see the CREDITS file for full details.
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
38 * UDP replies with TC set should be retried via TCP
60 #include <netinet/in.h>
63 #include <arpa/inet.h>
72 #define RFC1035_MAXLABELSZ 63
73 #define rfc1035_unpack_error 15
76 #define RFC1035_UNPACK_DEBUG fprintf(stderr, "unpack error at %s:%d\n", __FILE__,__LINE__)
78 #define RFC1035_UNPACK_DEBUG (void)0
86 * Packs a rfc1035_header structure into a buffer.
87 * Returns number of octets packed (should always be 12)
90 rfc1035HeaderPack(char *buf
, size_t sz
, rfc1035_message
* hdr
)
97 memcpy(buf
+ off
, &s
, sizeof(s
));
101 t
|= (hdr
->opcode
<< 11);
102 t
|= (hdr
->aa
<< 10);
108 memcpy(buf
+ off
, &s
, sizeof(s
));
110 s
= htons(hdr
->qdcount
);
111 memcpy(buf
+ off
, &s
, sizeof(s
));
113 s
= htons(hdr
->ancount
);
114 memcpy(buf
+ off
, &s
, sizeof(s
));
116 s
= htons(hdr
->nscount
);
117 memcpy(buf
+ off
, &s
, sizeof(s
));
119 s
= htons(hdr
->arcount
);
120 memcpy(buf
+ off
, &s
, sizeof(s
));
129 * Packs a label into a buffer. The format of
130 * a label is one octet specifying the number of character
131 * bytes to follow. Labels must be smaller than 64 octets.
132 * Returns number of octets packed.
135 rfc1035LabelPack(char *buf
, size_t sz
, const char *label
)
138 size_t len
= label
? strlen(label
) : 0;
140 assert(!strchr(label
, '.'));
141 if (len
> RFC1035_MAXLABELSZ
)
142 len
= RFC1035_MAXLABELSZ
;
143 assert(sz
>= len
+ 1);
144 *(buf
+ off
) = (char) len
;
146 memcpy(buf
+ off
, label
, len
);
154 * Packs a name into a buffer. Names are packed as a
155 * sequence of labels, terminated with NULL label.
156 * Note message compression is not supported here.
157 * Returns number of octets packed.
160 rfc1035NamePack(char *buf
, size_t sz
, const char *name
)
162 unsigned int off
= 0;
163 char *copy
= xstrdup(name
);
166 * NOTE: use of strtok here makes names like foo....com valid.
168 for (t
= strtok(copy
, "."); t
; t
= strtok(NULL
, "."))
169 off
+= rfc1035LabelPack(buf
+ off
, sz
- off
, t
);
171 off
+= rfc1035LabelPack(buf
+ off
, sz
- off
, NULL
);
177 * rfc1035QuestionPack()
179 * Packs a QUESTION section of a message.
180 * Returns number of octets packed.
183 rfc1035QuestionPack(char *buf
,
186 const unsigned short type
,
187 const unsigned short _class
)
189 unsigned int off
= 0;
191 off
+= rfc1035NamePack(buf
+ off
, sz
- off
, name
);
193 memcpy(buf
+ off
, &s
, sizeof(s
));
196 memcpy(buf
+ off
, &s
, sizeof(s
));
203 * rfc1035HeaderUnpack()
205 * Unpacks a RFC1035 message header buffer into the header fields
206 * of the rfc1035_message structure.
208 * Updates the buffer offset, which is the same as number of
209 * octects unpacked since the header starts at offset 0.
211 * Returns 0 (success) or 1 (error)
214 rfc1035HeaderUnpack(const char *buf
, size_t sz
, unsigned int *off
, rfc1035_message
* h
)
220 * The header is 12 octets. This is a bogus message if the size
225 memcpy(&s
, buf
+ (*off
), sizeof(s
));
228 memcpy(&s
, buf
+ (*off
), sizeof(s
));
231 h
->qr
= (t
>> 15) & 0x01;
232 h
->opcode
= (t
>> 11) & 0x0F;
233 h
->aa
= (t
>> 10) & 0x01;
234 h
->tc
= (t
>> 9) & 0x01;
235 h
->rd
= (t
>> 8) & 0x01;
236 h
->ra
= (t
>> 7) & 0x01;
238 * We might want to check that the reserved 'Z' bits (6-4) are
239 * all zero as per RFC 1035. If not the message should be
241 * NO! RFCs say ignore inbound reserved, they may be used in future.
242 * NEW messages need to be set 0, thats all.
245 memcpy(&s
, buf
+ (*off
), sizeof(s
));
247 h
->qdcount
= ntohs(s
);
248 memcpy(&s
, buf
+ (*off
), sizeof(s
));
250 h
->ancount
= ntohs(s
);
251 memcpy(&s
, buf
+ (*off
), sizeof(s
));
253 h
->nscount
= ntohs(s
);
254 memcpy(&s
, buf
+ (*off
), sizeof(s
));
256 h
->arcount
= ntohs(s
);
257 assert((*off
) == 12);
262 * rfc1035NameUnpack()
264 * Unpacks a Name in a message buffer into a char*.
265 * Note 'buf' points to the beginning of the whole message,
266 * 'off' points to the spot where the Name begins, and 'sz'
267 * is the size of the whole message. 'name' must be allocated
270 * Supports the RFC1035 message compression through recursion.
272 * Updates the new buffer offset.
274 * Returns 0 (success) or 1 (error)
277 rfc1035NameUnpack(const char *buf
, size_t sz
, unsigned int *off
, unsigned short *rdlength
, char *name
, size_t ns
, int rdepth
)
285 RFC1035_UNPACK_DEBUG
;
290 /* blasted compression */
293 if (rdepth
> 64) { /* infinite pointer loop */
294 RFC1035_UNPACK_DEBUG
;
297 memcpy(&s
, buf
+ (*off
), sizeof(s
));
302 RFC1035_UNPACK_DEBUG
;
306 /* Make sure the pointer is inside this message */
308 RFC1035_UNPACK_DEBUG
;
311 return rfc1035NameUnpack(buf
, sz
, &ptr
, rdlength
, name
+ no
, ns
- no
, rdepth
+ 1);
312 } else if (c
> RFC1035_MAXLABELSZ
) {
314 * "(The 10 and 01 combinations are reserved for future use.)"
316 RFC1035_UNPACK_DEBUG
;
323 if (len
> (ns
- no
- 1)) { /* label won't fit */
324 RFC1035_UNPACK_DEBUG
;
327 if ((*off
) + len
>= sz
) { /* message is too short */
328 RFC1035_UNPACK_DEBUG
;
331 memcpy(name
+ no
, buf
+ (*off
), len
);
334 *(name
+ (no
++)) = '.';
336 *rdlength
+= len
+ 1;
338 } while (c
> 0 && no
< ns
);
340 *(name
+ no
- 1) = '\0';
343 /* make sure we didn't allow someone to overflow the name buffer */
351 * Packs a RFC1035 Resource Record into a message buffer from 'RR'.
352 * The caller must allocate and free RR->rdata and RR->name!
354 * Updates the new message buffer.
356 * Returns the number of bytes added to the buffer or 0 for error.
359 rfc1035RRPack(char *buf
, const size_t sz
, const rfc1035_rr
* RR
)
365 off
= rfc1035NamePack(buf
, sz
, RR
->name
);
368 * Make sure the remaining message has enough octets for the
369 * rest of the RR fields.
371 if ((off
+ sizeof(s
)*3 + sizeof(i
) + RR
->rdlength
) > sz
) {
375 memcpy(buf
+ off
, &s
, sizeof(s
));
377 s
= htons(RR
->_class
);
378 memcpy(buf
+ off
, &s
, sizeof(s
));
381 memcpy(buf
+ off
, &i
, sizeof(i
));
383 s
= htons(RR
->rdlength
);
384 memcpy(buf
+ off
, &s
, sizeof(s
));
386 memcpy(buf
+ off
, &(RR
->rdata
), RR
->rdlength
);
395 * Unpacks a RFC1035 Resource Record into 'RR' from a message buffer.
396 * The caller must free RR->rdata!
398 * Updates the new message buffer offset.
400 * Returns 0 (success) or 1 (error)
403 rfc1035RRUnpack(const char *buf
, size_t sz
, unsigned int *off
, rfc1035_rr
* RR
)
407 unsigned short rdlength
;
408 unsigned int rdata_off
;
409 if (rfc1035NameUnpack(buf
, sz
, off
, NULL
, RR
->name
, RFC1035_MAXHOSTNAMESZ
, 0)) {
410 RFC1035_UNPACK_DEBUG
;
411 memset(RR
, '\0', sizeof(*RR
));
415 * Make sure the remaining message has enough octets for the
416 * rest of the RR fields.
418 if ((*off
) + 10 > sz
) {
419 RFC1035_UNPACK_DEBUG
;
420 memset(RR
, '\0', sizeof(*RR
));
423 memcpy(&s
, buf
+ (*off
), sizeof(s
));
426 memcpy(&s
, buf
+ (*off
), sizeof(s
));
428 RR
->_class
= ntohs(s
);
429 memcpy(&i
, buf
+ (*off
), sizeof(i
));
432 memcpy(&s
, buf
+ (*off
), sizeof(s
));
435 if ((*off
) + rdlength
> sz
) {
437 * We got a truncated packet. 'dnscache' truncates UDP
438 * replies at 512 octets, as per RFC 1035.
440 RFC1035_UNPACK_DEBUG
;
441 memset(RR
, '\0', sizeof(*RR
));
444 RR
->rdlength
= rdlength
;
447 case RFC1035_TYPE_CNAME
:
449 case RFC1035_TYPE_PTR
:
450 RR
->rdata
= (char*)xmalloc(RFC1035_MAXHOSTNAMESZ
);
452 RR
->rdlength
= 0; /* Filled in by rfc1035NameUnpack */
453 if (rfc1035NameUnpack(buf
, sz
, &rdata_off
, &RR
->rdlength
, RR
->rdata
, RFC1035_MAXHOSTNAMESZ
, 0)) {
454 RFC1035_UNPACK_DEBUG
;
457 if (rdata_off
> ((*off
) + rdlength
)) {
459 * This probably doesn't happen for valid packets, but
460 * I want to make sure that NameUnpack doesn't go beyond
463 RFC1035_UNPACK_DEBUG
;
465 memset(RR
, '\0', sizeof(*RR
));
471 RR
->rdata
= (char*)xmalloc(rdlength
);
472 memcpy(RR
->rdata
, buf
+ (*off
), rdlength
);
476 assert((*off
) <= sz
);
481 rfc1035ErrorMessage(int n
)
487 return "No error condition";
490 return "Format Error: The name server was "
491 "unable to interpret the query.";
494 return "Server Failure: The name server was "
495 "unable to process this query.";
498 return "Name Error: The domain name does "
502 return "Not Implemented: The name server does "
503 "not support the requested kind of query.";
506 return "Refused: The name server refuses to "
507 "perform the specified operation.";
509 case rfc1035_unpack_error
:
510 return "The DNS reply message is corrupt or could "
511 "not be safely parsed.";
514 return "Unknown Error";
520 rfc1035RRDestroy(rfc1035_rr
** rr
, int n
)
528 xfree((*rr
)[n
].rdata
);
535 * rfc1035QueryUnpack()
537 * Unpacks a RFC1035 Query Record into 'query' from a message buffer.
539 * Updates the new message buffer offset.
541 * Returns 0 (success) or 1 (error)
544 rfc1035QueryUnpack(const char *buf
, size_t sz
, unsigned int *off
, rfc1035_query
* query
)
547 if (rfc1035NameUnpack(buf
, sz
, off
, NULL
, query
->name
, RFC1035_MAXHOSTNAMESZ
, 0)) {
548 RFC1035_UNPACK_DEBUG
;
549 memset(query
, '\0', sizeof(*query
));
553 RFC1035_UNPACK_DEBUG
;
554 memset(query
, '\0', sizeof(*query
));
557 memcpy(&s
, buf
+ *off
, 2);
559 query
->qtype
= ntohs(s
);
560 memcpy(&s
, buf
+ *off
, 2);
562 query
->qclass
= ntohs(s
);
567 rfc1035MessageDestroy(rfc1035_message
** msg
)
572 xfree((*msg
)->query
);
574 rfc1035RRDestroy(&(*msg
)->answer
, (*msg
)->ancount
);
580 * rfc1035QueryCompare()
582 * Compares two rfc1035_query entries
584 * Returns 0 (equal) or !=0 (different)
587 rfc1035QueryCompare(const rfc1035_query
* a
, const rfc1035_query
* b
)
590 if (a
->qtype
!= b
->qtype
)
592 if (a
->qclass
!= b
->qclass
)
594 la
= strlen(a
->name
);
595 lb
= strlen(b
->name
);
597 /* Trim root label(s) */
598 while (la
> 0 && a
->name
[la
- 1] == '.')
600 while (lb
> 0 && b
->name
[lb
- 1] == '.')
606 return strncasecmp(a
->name
, b
->name
, la
);
610 * rfc1035MessageUnpack()
612 * Takes the contents of a DNS reply and fills in an array
613 * of resource record structures. The records array is allocated
614 * here, and should be freed by calling rfc1035RRDestroy().
616 * Returns number of records unpacked, zero if DNS reply indicates
617 * zero answers, or an error number < 0.
621 rfc1035MessageUnpack(const char *buf
,
623 rfc1035_message
** answer
)
625 unsigned int off
= 0;
628 rfc1035_message
*msg
= NULL
;
629 rfc1035_rr
*recs
= NULL
;
630 rfc1035_query
*querys
= NULL
;
631 msg
= (rfc1035_message
*)xcalloc(1, sizeof(*msg
));
632 if (rfc1035HeaderUnpack(buf
+ off
, sz
- off
, &off
, msg
)) {
633 RFC1035_UNPACK_DEBUG
;
635 return -rfc1035_unpack_error
;
637 i
= (unsigned int) msg
->qdcount
;
639 /* This can not be an answer to our queries.. */
640 RFC1035_UNPACK_DEBUG
;
642 return -rfc1035_unpack_error
;
644 querys
= msg
->query
= (rfc1035_query
*)xcalloc(i
, sizeof(*querys
));
645 for (j
= 0; j
< i
; j
++) {
646 if (rfc1035QueryUnpack(buf
, sz
, &off
, &querys
[j
])) {
647 RFC1035_UNPACK_DEBUG
;
648 rfc1035MessageDestroy(&msg
);
649 return -rfc1035_unpack_error
;
654 RFC1035_UNPACK_DEBUG
;
657 if (msg
->ancount
== 0)
659 i
= (unsigned int) msg
->ancount
;
660 recs
= msg
->answer
= (rfc1035_rr
*)xcalloc(i
, sizeof(*recs
));
661 for (j
= 0; j
< i
; j
++) {
662 if (off
>= sz
) { /* corrupt packet */
663 RFC1035_UNPACK_DEBUG
;
666 if (rfc1035RRUnpack(buf
, sz
, &off
, &recs
[j
])) { /* corrupt RR */
667 RFC1035_UNPACK_DEBUG
;
674 * we expected to unpack some answers (ancount != 0), but
675 * didn't actually get any.
677 rfc1035MessageDestroy(&msg
);
679 return -rfc1035_unpack_error
;
685 * rfc1035BuildAQuery()
687 * Builds a message buffer with a QUESTION to lookup A records
688 * for a hostname. Caller must allocate 'buf' which should
689 * probably be at least 512 octets. The 'szp' initially
690 * specifies the size of the buffer, on return it contains
691 * the size of the message (i.e. how much to write).
692 * Returns the size of the query
695 rfc1035BuildAQuery(const char *hostname
, char *buf
, size_t sz
, unsigned short qid
, rfc1035_query
* query
, ssize_t edns_sz
)
697 static rfc1035_message h
;
699 memset(&h
, '\0', sizeof(h
));
703 h
.opcode
= 0; /* QUERY */
704 h
.qdcount
= (unsigned int) 1;
705 h
.arcount
= (edns_sz
> 0 ? 1 : 0);
706 offset
+= rfc1035HeaderPack(buf
+ offset
, sz
- offset
, &h
);
707 offset
+= rfc1035QuestionPack(buf
+ offset
,
713 offset
+= rfc2671RROptPack(buf
+ offset
, sz
- offset
, edns_sz
);
715 query
->qtype
= RFC1035_TYPE_A
;
716 query
->qclass
= RFC1035_CLASS_IN
;
717 xstrncpy(query
->name
, hostname
, sizeof(query
->name
));
719 assert(offset
<= sz
);
724 * rfc1035BuildPTRQuery()
726 * Builds a message buffer with a QUESTION to lookup PTR records
727 * for an address. Caller must allocate 'buf' which should
728 * probably be at least 512 octets. The 'szp' initially
729 * specifies the size of the buffer, on return it contains
730 * the size of the message (i.e. how much to write).
731 * Returns the size of the query
734 rfc1035BuildPTRQuery(const struct in_addr addr
, char *buf
, size_t sz
, unsigned short qid
, rfc1035_query
* query
, ssize_t edns_sz
)
736 static rfc1035_message h
;
740 memset(&h
, '\0', sizeof(h
));
741 i
= (unsigned int) ntohl(addr
.s_addr
);
742 snprintf(rev
, 32, "%u.%u.%u.%u.in-addr.arpa.",
750 h
.opcode
= 0; /* QUERY */
751 h
.qdcount
= (unsigned int) 1;
752 h
.arcount
= (edns_sz
> 0 ? 1 : 0);
753 offset
+= rfc1035HeaderPack(buf
+ offset
, sz
- offset
, &h
);
754 offset
+= rfc1035QuestionPack(buf
+ offset
,
760 offset
+= rfc2671RROptPack(buf
+ offset
, sz
- offset
, edns_sz
);
762 query
->qtype
= RFC1035_TYPE_PTR
;
763 query
->qclass
= RFC1035_CLASS_IN
;
764 xstrncpy(query
->name
, rev
, sizeof(query
->name
));
766 assert(offset
<= sz
);
771 * We're going to retry a former query, but we
772 * just need a new ID for it. Lucky for us ID
773 * is the first field in the message buffer.
776 rfc1035SetQueryID(char *buf
, unsigned short qid
)
778 unsigned short s
= htons(qid
);
779 memcpy(buf
, &s
, sizeof(s
));
783 #include <sys/socket.h>
785 main(int argc
, char *argv
[])
787 char input
[SQUID_DNS_BUFSZ
];
788 char buf
[SQUID_DNS_BUFSZ
];
789 char rbuf
[SQUID_DNS_BUFSZ
];
790 size_t sz
= SQUID_DNS_BUFSZ
;
794 struct sockaddr_in S
;
796 fprintf(stderr
, "usage: %s ip port\n", argv
[0]);
799 setbuf(stdout
, NULL
);
800 setbuf(stderr
, NULL
);
801 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
806 memset(&S
, '\0', sizeof(S
));
807 S
.sin_family
= AF_INET
;
808 S
.sin_port
= htons(atoi(argv
[2]));
809 S
.sin_addr
.s_addr
= inet_addr(argv
[1]);
810 while (fgets(input
, RFC1035_DEFAULT_PACKET_SZ
, stdin
)) {
812 strtok(input
, "\r\n");
813 memset(buf
, '\0', RFC1035_DEFAULT_PACKET_SZ
);
814 sz
= RFC1035_DEFAULT_PACKET_SZ
;
815 if (inet_pton(AF_INET
, input
, &junk
)) {
816 sid
= rfc1035BuildPTRQuery(junk
, buf
, &sz
);
818 sid
= rfc1035BuildAQuery(input
, buf
, &sz
);
820 sendto(s
, buf
, sz
, 0, (struct sockaddr
*) &S
, sizeof(S
));
828 rl
= select(s
+ 1, &R
, NULL
, NULL
, &to
);
834 memset(rbuf
, '\0', RFC1035_DEFAULT_PACKET_SZ
);
835 rl
= recv(s
, rbuf
, RFC1035_DEFAULT_PACKET_SZ
, 0);
837 unsigned short rid
= 0;
840 rfc1035_rr
*answers
= NULL
;
841 n
= rfc1035AnswersUnpack(rbuf
,
846 printf("ERROR %d\n", -n
);
847 } else if (rid
!= sid
) {
848 printf("ERROR, ID mismatch (%#hx, %#hx)\n", sid
, rid
);
850 printf("%d answers\n", n
);
851 for (i
= 0; i
< n
; i
++) {
852 if (answers
[i
].type
== RFC1035_TYPE_A
) {
854 char ipa_str
[sizeof(a
)];
855 memcpy(&a
, answers
[i
].rdata
, 4);
856 printf("A\t%d\t%s\n", answers
[i
].ttl
, inet_ntop(AF_INET
,&a
,tmp
,sizeof(a
)));
857 } else if (answers
[i
].type
== RFC1035_TYPE_PTR
) {
859 strncpy(ptr
, answers
[i
].rdata
, answers
[i
].rdlength
);
860 printf("PTR\t%d\t%s\n", answers
[i
].ttl
, ptr
);
862 fprintf(stderr
, "can't print answer type %d\n",
863 (int) answers
[i
].type
);