1 //*****************************************************************************
2 //
3 //! \file dns.c
4 //! \brief DNS APIs Implement file.
5 //! \details Send DNS query & Receive DNS reponse.  \n
6 //!          It depends on stdlib.h & string.h in ansi-c library
7 //! \version 1.1.0
8 //! \date 2013/11/18
9 //! \par  Revision history
10 //!       <2013/10/21> 1st Release
11 //!       <2013/12/20> V1.1.0
12 //!         1. Remove secondary DNS server in DNS_run
13 //!            If 1st DNS_run failed, call DNS_run with 2nd DNS again
14 //!         2. DNS_timerHandler -> DNS_time_handler
15 //!         3. Remove the unused define
16 //!         4. Integrated dns.h dns.c & dns_parse.h dns_parse.c into dns.h & dns.c
17 //!       <2013/12/20> V1.1.0
18 //!
19 //! \author Eric Jung & MidnightCow
20 //! \copyright
21 //!
22 //! Copyright (c)  2013, WIZnet Co., LTD.
23 //! All rights reserved.
24 //!
25 //! Redistribution and use in source and binary forms, with or without
26 //! modification, are permitted provided that the following conditions
27 //! are met:
28 //!
29 //!     * Redistributions of source code must retain the above copyright
30 //! notice, this list of conditions and the following disclaimer.
31 //!     * Redistributions in binary form must reproduce the above copyright
32 //! notice, this list of conditions and the following disclaimer in the
33 //! documentation and/or other materials provided with the distribution.
34 //!     * Neither the name of the <ORGANIZATION> nor the names of its
35 //! contributors may be used to endorse or promote products derived
36 //! from this software without specific prior written permission.
37 //!
38 //! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
39 //! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40 //! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
41 //! ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
42 //! LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
43 //! CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
44 //! SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
45 //! INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
46 //! CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
47 //! ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
48 //! THE POSSIBILITY OF SUCH DAMAGE.
49 //
50 //*****************************************************************************
51 
52 #include <string.h>
53 #include <stdlib.h>
54 
55 //#include "Ethernet/socket.h"
56 //#include "Internet/DNS/dns.h"
57 #include "../../ethernet/socket.h"
58 #include "dns.h"
59 
60 #ifdef _DNS_DEBUG_
61    #include <stdio.h>
62 #endif
63 
64 #define	INITRTT		2000L	/* Initial smoothed response time */
65 #define	MAXCNAME	   (MAX_DOMAIN_NAME + (MAX_DOMAIN_NAME>>1))	   /* Maximum amount of cname recursion */
66 
67 #define	TYPE_A		1	   /* Host address */
68 #define	TYPE_NS		2	   /* Name server */
69 #define	TYPE_MD		3	   /* Mail destination (obsolete) */
70 #define	TYPE_MF		4	   /* Mail forwarder (obsolete) */
71 #define	TYPE_CNAME	5	   /* Canonical name */
72 #define	TYPE_SOA	   6	   /* Start of Authority */
73 #define	TYPE_MB		7	   /* Mailbox name (experimental) */
74 #define	TYPE_MG		8	   /* Mail group member (experimental) */
75 #define	TYPE_MR		9	   /* Mail rename name (experimental) */
76 #define	TYPE_NULL	10	   /* Null (experimental) */
77 #define	TYPE_WKS	   11	   /* Well-known sockets */
78 #define	TYPE_PTR	   12	   /* Pointer record */
79 #define	TYPE_HINFO	13	   /* Host information */
80 #define	TYPE_MINFO	14	   /* Mailbox information (experimental)*/
81 #define	TYPE_MX		15	   /* Mail exchanger */
82 #define	TYPE_TXT	   16	   /* Text strings */
83 #define	TYPE_ANY	   255	/* Matches any type */
84 
85 #define	CLASS_IN	   1	   /* The ARPA Internet */
86 
87 /* Round trip timing parameters */
88 #define	AGAIN	      8     /* Average RTT gain = 1/8 */
89 #define	LAGAIN      3     /* Log2(AGAIN) */
90 #define	DGAIN       4     /* Mean deviation gain = 1/4 */
91 #define	LDGAIN      2     /* log2(DGAIN) */
92 
93 /* Header for all domain messages */
94 struct dhdr
95 {
96 	uint16_t id;   /* Identification */
97 	uint8_t	qr;      /* Query/Response */
98 #define	QUERY    0
99 #define	RESPONSE 1
100 	uint8_t	opcode;
101 #define	IQUERY   1
102 	uint8_t	aa;      /* Authoratative answer */
103 	uint8_t	tc;      /* Truncation */
104 	uint8_t	rd;      /* Recursion desired */
105 	uint8_t	ra;      /* Recursion available */
106 	uint8_t	rcode;   /* Response code */
107 #define	NO_ERROR       0
108 #define	FORMAT_ERROR   1
109 #define	SERVER_FAIL    2
110 #define	NAME_ERROR     3
111 #define	NOT_IMPL       4
112 #define	REFUSED        5
113 	uint16_t qdcount;	/* Question count */
114 	uint16_t ancount;	/* Answer count */
115 	uint16_t nscount;	/* Authority (name server) count */
116 	uint16_t arcount;	/* Additional record count */
117 };
118 
119 
120 uint8_t* pDNSMSG;       // DNS message buffer
121 uint8_t  DNS_SOCKET;    // SOCKET number for DNS
122 uint16_t DNS_MSGID;     // DNS message ID
123 
124 extern uint32_t HAL_GetTick(void);
125 uint32_t hal_sys_tick;
126 
127 /* converts uint16_t from network buffer to a host byte order integer. */
get16(uint8_t * s)128 uint16_t get16(uint8_t * s)
129 {
130 	uint16_t i;
131 	i = *s++ << 8;
132 	i = i + *s;
133 	return i;
134 }
135 
136 /* copies uint16_t to the network buffer with network byte order. */
put16(uint8_t * s,uint16_t i)137 uint8_t * put16(uint8_t * s, uint16_t i)
138 {
139 	*s++ = i >> 8;
140 	*s++ = i;
141 	return s;
142 }
143 
144 
145 /*
146  *              CONVERT A DOMAIN NAME TO THE HUMAN-READABLE FORM
147  *
148  * Description : This function converts a compressed domain name to the human-readable form
149  * Arguments   : msg        - is a pointer to the reply message
150  *               compressed - is a pointer to the domain name in reply message.
151  *               buf        - is a pointer to the buffer for the human-readable form name.
152  *               len        - is the MAX. size of buffer.
153  * Returns     : the length of compressed message
154  */
parse_name(uint8_t * msg,uint8_t * compressed,char * buf,int16_t len)155 int parse_name(uint8_t * msg, uint8_t * compressed, char * buf, int16_t len)
156 {
157 	uint16_t slen;		/* Length of current segment */
158 	uint8_t * cp;
159 	int clen = 0;		/* Total length of compressed name */
160 	int indirect = 0;	/* Set if indirection encountered */
161 	int nseg = 0;		/* Total number of segments in name */
162 
163 	cp = compressed;
164 
165 	for (;;)
166 	{
167 		slen = *cp++;	/* Length of this segment */
168 
169 		if (!indirect) clen++;
170 
171 		if ((slen & 0xc0) == 0xc0)
172 		{
173 			if (!indirect)
174 				clen++;
175 			indirect = 1;
176 			/* Follow indirection */
177 			cp = &msg[((slen & 0x3f)<<8) + *cp];
178 			slen = *cp++;
179 		}
180 
181 		if (slen == 0)	/* zero length == all done */
182 			break;
183 
184 		len -= slen + 1;
185 
186 		if (len < 0) return -1;
187 
188 		if (!indirect) clen += slen;
189 
190 		while (slen-- != 0) *buf++ = (char)*cp++;
191 		*buf++ = '.';
192 		nseg++;
193 	}
194 
195 	if (nseg == 0)
196 	{
197 		/* Root name; represent as single dot */
198 		*buf++ = '.';
199 		len--;
200 	}
201 
202 	*buf++ = '\0';
203 	len--;
204 
205 	return clen;	/* Length of compressed message */
206 }
207 
208 /*
209  *              PARSE QUESTION SECTION
210  *
211  * Description : This function parses the question record of the reply message.
212  * Arguments   : msg - is a pointer to the reply message
213  *               cp  - is a pointer to the question record.
214  * Returns     : a pointer the to next record.
215  */
dns_question(uint8_t * msg,uint8_t * cp)216 uint8_t * dns_question(uint8_t * msg, uint8_t * cp)
217 {
218 	int len;
219 	char name[MAXCNAME];
220 
221 	len = parse_name(msg, cp, name, MAXCNAME);
222 
223 
224 	if (len == -1) return 0;
225 
226 	cp += len;
227 	cp += 2;		/* type */
228 	cp += 2;		/* class */
229 
230 	return cp;
231 }
232 
233 
234 /*
235  *              PARSE ANSER SECTION
236  *
237  * Description : This function parses the answer record of the reply message.
238  * Arguments   : msg - is a pointer to the reply message
239  *               cp  - is a pointer to the answer record.
240  * Returns     : a pointer the to next record.
241  */
dns_answer(uint8_t * msg,uint8_t * cp,uint8_t * ip_from_dns)242 uint8_t * dns_answer(uint8_t * msg, uint8_t * cp, uint8_t * ip_from_dns)
243 {
244 	int len, type;
245 	char name[MAXCNAME];
246 
247 	len = parse_name(msg, cp, name, MAXCNAME);
248 
249 	if (len == -1) return 0;
250 
251 	cp += len;
252 	type = get16(cp);
253 	cp += 2;		/* type */
254 	cp += 2;		/* class */
255 	cp += 4;		/* ttl */
256 	cp += 2;		/* len */
257 
258 
259 	switch (type)
260 	{
261 	case TYPE_A:
262 		/* Just read the address directly into the structure */
263 		ip_from_dns[0] = *cp++;
264 		ip_from_dns[1] = *cp++;
265 		ip_from_dns[2] = *cp++;
266 		ip_from_dns[3] = *cp++;
267 		break;
268 	case TYPE_CNAME:
269 	case TYPE_MB:
270 	case TYPE_MG:
271 	case TYPE_MR:
272 	case TYPE_NS:
273 	case TYPE_PTR:
274 		/* These types all consist of a single domain name */
275 		/* convert it to ASCII format */
276 		len = parse_name(msg, cp, name, MAXCNAME);
277 		if (len == -1) return 0;
278 
279 		cp += len;
280 		break;
281 	case TYPE_HINFO:
282 		len = *cp++;
283 		cp += len;
284 
285 		len = *cp++;
286 		cp += len;
287 		break;
288 	case TYPE_MX:
289 		cp += 2;
290 		/* Get domain name of exchanger */
291 		len = parse_name(msg, cp, name, MAXCNAME);
292 		if (len == -1) return 0;
293 
294 		cp += len;
295 		break;
296 	case TYPE_SOA:
297 		/* Get domain name of name server */
298 		len = parse_name(msg, cp, name, MAXCNAME);
299 		if (len == -1) return 0;
300 
301 		cp += len;
302 
303 		/* Get domain name of responsible person */
304 		len = parse_name(msg, cp, name, MAXCNAME);
305 		if (len == -1) return 0;
306 
307 		cp += len;
308 
309 		cp += 4;
310 		cp += 4;
311 		cp += 4;
312 		cp += 4;
313 		cp += 4;
314 		break;
315 	case TYPE_TXT:
316 		/* Just stash */
317 		break;
318 	default:
319 		/* Ignore */
320 		break;
321 	}
322 
323 	return cp;
324 }
325 
326 /*
327  *              PARSE THE DNS REPLY
328  *
329  * Description : This function parses the reply message from DNS server.
330  * Arguments   : dhdr - is a pointer to the header for DNS message
331  *               buf  - is a pointer to the reply message.
332  *               len  - is the size of reply message.
333  * Returns     : -1 - Domain name length is too big
334  *                0 - Fail (Timeout or parse error)
335  *                1 - Success,
336  */
parseDNSMSG(struct dhdr * pdhdr,uint8_t * pbuf,uint8_t * ip_from_dns)337 int8_t parseDNSMSG(struct dhdr * pdhdr, uint8_t * pbuf, uint8_t * ip_from_dns)
338 {
339 	uint16_t tmp;
340 	uint16_t i;
341 	uint8_t * msg;
342 	uint8_t * cp;
343 
344 	msg = pbuf;
345 	memset(pdhdr, 0, sizeof(*pdhdr));
346 
347 	pdhdr->id = get16(&msg[0]);
348 	tmp = get16(&msg[2]);
349 	if (tmp & 0x8000) pdhdr->qr = 1;
350 
351 	pdhdr->opcode = (tmp >> 11) & 0xf;
352 
353 	if (tmp & 0x0400) pdhdr->aa = 1;
354 	if (tmp & 0x0200) pdhdr->tc = 1;
355 	if (tmp & 0x0100) pdhdr->rd = 1;
356 	if (tmp & 0x0080) pdhdr->ra = 1;
357 
358 	pdhdr->rcode = tmp & 0xf;
359 	pdhdr->qdcount = get16(&msg[4]);
360 	pdhdr->ancount = get16(&msg[6]);
361 	pdhdr->nscount = get16(&msg[8]);
362 	pdhdr->arcount = get16(&msg[10]);
363 
364 
365 	/* Now parse the variable length sections */
366 	cp = &msg[12];
367 
368 	/* Question section */
369 	for (i = 0; i < pdhdr->qdcount; i++)
370 	{
371 		cp = dns_question(msg, cp);
372 		if(!cp)
373 		{
374 #ifdef _DNS_DEBUG_
375 			printf("MAX_DOMAIN_NAME is too small, it should be redefined in dns.h\r\n");
376 #endif
377 			return -1;
378 		}
379 	}
380 
381 	/* Answer section */
382 	for (i = 0; i < pdhdr->ancount; i++)
383 	{
384 		cp = dns_answer(msg, cp, ip_from_dns);
385 		if(!cp)
386 		{
387 #ifdef _DNS_DEBUG_
388 			printf("MAX_DOMAIN_NAME is too small, it should be redefined in dns.h\r\n");
389 #endif
390 			return -1;
391 		}
392 
393 	}
394 
395 	/* Name server (authority) section */
396 	for (i = 0; i < pdhdr->nscount; i++)
397 	{
398 		;
399 	}
400 
401 	/* Additional section */
402 	for (i = 0; i < pdhdr->arcount; i++)
403 	{
404 		;
405 	}
406 
407 	if(pdhdr->rcode == 0) return 1;		// No error
408 	else return 0;
409 }
410 
411 
412 /*
413  *              MAKE DNS QUERY MESSAGE
414  *
415  * Description : This function makes DNS query message.
416  * Arguments   : op   - Recursion desired
417  *               name - is a pointer to the domain name.
418  *               buf  - is a pointer to the buffer for DNS message.
419  *               len  - is the MAX. size of buffer.
420  * Returns     : the pointer to the DNS message.
421  */
dns_makequery(uint16_t op,char * name,uint8_t * buf,uint16_t len)422 int16_t dns_makequery(uint16_t op, char * name, uint8_t * buf, uint16_t len)
423 {
424 	uint8_t *cp;
425 	char *cp1;
426 	char sname[MAXCNAME];
427 	char *dname;
428 	uint16_t p;
429 	uint16_t dlen;
430 
431 	cp = buf;
432 
433 	DNS_MSGID++;
434 	cp = put16(cp, DNS_MSGID);
435 	p = (op << 11) | 0x0100;			/* Recursion desired */
436 	cp = put16(cp, p);
437 	cp = put16(cp, 1);
438 	cp = put16(cp, 0);
439 	cp = put16(cp, 0);
440 	cp = put16(cp, 0);
441 
442 	strcpy(sname, name);
443 	dname = sname;
444 	dlen = strlen(dname);
445 	for (;;)
446 	{
447 		/* Look for next dot */
448 		cp1 = strchr(dname, '.');
449 
450 		if (cp1 != NULL) len = cp1 - dname;	/* More to come */
451 		else len = dlen;			/* Last component */
452 
453 		*cp++ = len;				/* Write length of component */
454 		if (len == 0) break;
455 
456 		/* Copy component up to (but not including) dot */
457 		memcpy(cp, dname, len);
458 		cp += len;
459 		if (cp1 == NULL)
460 		{
461 			*cp++ = 0;			/* Last one; write null and finish */
462 			break;
463 		}
464 		dname += len+1;
465 		dlen -= len+1;
466 	}
467 
468 	cp = put16(cp, 0x0001);				/* type */
469 	cp = put16(cp, 0x0001);				/* class */
470 
471 	return ((int16_t)((uint32_t)(cp) - (uint32_t)(buf)));
472 }
473 
474 /*
475  *              CHECK DNS TIMEOUT
476  *
477  * Description : This function check the DNS timeout
478  * Arguments   : None.
479  * Returns     : -1 - timeout occurred, 0 - timer over, but no timeout, 1 - no timer over, no timeout occur
480  * Note        : timeout : retry count and timer both over.
481  */
482 
check_DNS_timeout(void)483 int8_t check_DNS_timeout(void)
484 {
485 	static uint8_t retry_count;
486 
487     uint32_t tick = HAL_GetTick();
488 	if(tick - hal_sys_tick >= DNS_WAIT_TIME * 1000)
489 	{
490 		hal_sys_tick = tick;
491 		if(retry_count >= MAX_DNS_RETRY) {
492 			retry_count = 0;
493 			return -1; // timeout occurred
494 		}
495 		retry_count++;
496 		return 0; // timer over, but no timeout
497 	}
498 
499 	return 1; // no timer over, no timeout occur
500 }
501 
502 
503 
504 /* DNS CLIENT INIT */
DNS_init(uint8_t s,uint8_t * buf)505 void DNS_init(uint8_t s, uint8_t * buf)
506 {
507 	DNS_SOCKET = s; // SOCK_DNS
508 	pDNSMSG = buf; // User's shared buffer
509 	DNS_MSGID = DNS_MSG_ID;
510 }
511 
512 /* DNS CLIENT RUN */
DNS_run(uint8_t * dns_ip,uint8_t * name,uint8_t * ip_from_dns)513 int8_t DNS_run(uint8_t * dns_ip, uint8_t * name, uint8_t * ip_from_dns)
514 {
515 	int8_t ret;
516 	struct dhdr dhp;
517 	uint8_t ip[4];
518 	uint16_t len, port;
519 	int8_t ret_check_timeout;
520 
521         hal_sys_tick = HAL_GetTick();
522 
523    // Socket open
524    WIZCHIP_EXPORT(socket)(DNS_SOCKET, Sn_MR_UDP, 0, 0);
525 
526 #ifdef _DNS_DEBUG_
527 	printf("> DNS Query to DNS Server : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]);
528 #endif
529 
530 	len = dns_makequery(0, (char *)name, pDNSMSG, MAX_DNS_BUF_SIZE);
531 	WIZCHIP_EXPORT(sendto)(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN);
532 
533 	while (1)
534 	{
535 		if ((len = getSn_RX_RSR(DNS_SOCKET)) > 0)
536 		{
537 			if (len > MAX_DNS_BUF_SIZE) len = MAX_DNS_BUF_SIZE;
538 			len = WIZCHIP_EXPORT(recvfrom)(DNS_SOCKET, pDNSMSG, len, ip, &port);
539       #ifdef _DNS_DEBUG_
540 	      printf("> Receive DNS message from %d.%d.%d.%d(%d). len = %d\r\n", ip[0], ip[1], ip[2], ip[3],port,len);
541       #endif
542          ret = parseDNSMSG(&dhp, pDNSMSG, ip_from_dns);
543 			break;
544 		}
545 		// Check Timeout
546 		ret_check_timeout = check_DNS_timeout();
547 		if (ret_check_timeout < 0) {
548 
549 #ifdef _DNS_DEBUG_
550 			printf("> DNS Server is not responding : %d.%d.%d.%d\r\n", dns_ip[0], dns_ip[1], dns_ip[2], dns_ip[3]);
551 #endif
552 			return 0; // timeout occurred
553 		}
554 		else if (ret_check_timeout == 0) {
555 
556 #ifdef _DNS_DEBUG_
557 			printf("> DNS Timeout\r\n");
558 #endif
559 			WIZCHIP_EXPORT(sendto)(DNS_SOCKET, pDNSMSG, len, dns_ip, IPPORT_DOMAIN);
560 		}
561 	}
562 	WIZCHIP_EXPORT(close)(DNS_SOCKET);
563 	// Return value
564 	// 0 > :  failed / 1 - success
565 	return ret;
566 }
567