avoid freeing uninit ptr on error path
[oweals/gnunet.git] / src / dns / dnsparser.c
1 /*
2       This file is part of GNUnet
3       Copyright (C) 2010-2014 GNUnet e.V.
4
5       GNUnet is free software; you can redistribute it and/or modify
6       it under the terms of the GNU General Public License as published
7       by the Free Software Foundation; either version 3, or (at your
8       option) any later version.
9
10       GNUnet is distributed in the hope that it will be useful, but
11       WITHOUT ANY WARRANTY; without even the implied warranty of
12       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13       General Public License for more details.
14
15       You should have received a copy of the GNU General Public License
16       along with GNUnet; see the file COPYING.  If not, write to the
17       Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18       Boston, MA 02110-1301, USA.
19  */
20
21 /**
22  * @file dns/dnsparser.c
23  * @brief helper library to parse DNS packets.
24  * @author Philipp Toelke
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include <idna.h>
29 #if WINDOWS
30 #include <idn-free.h>
31 #endif
32 #include "gnunet_util_lib.h"
33 #include "gnunet_dnsparser_lib.h"
34 #include "gnunet_tun_lib.h"
35
36
37 /**
38  * Check if a label in UTF-8 format can be coded into valid IDNA.
39  * This can fail if the ASCII-conversion becomes longer than 63 characters.
40  *
41  * @param label label to check (UTF-8 string)
42  * @return #GNUNET_OK if the label can be converted to IDNA,
43  *         #GNUNET_SYSERR if the label is not valid for DNS names
44  */
45 int
46 GNUNET_DNSPARSER_check_label (const char *label)
47 {
48   char *output;
49   size_t slen;
50
51   if (NULL != strchr (label, '.'))
52     return GNUNET_SYSERR; /* not a label! Did you mean GNUNET_DNSPARSER_check_name? */
53   if (IDNA_SUCCESS !=
54       idna_to_ascii_8z (label, &output, IDNA_ALLOW_UNASSIGNED))
55     return GNUNET_SYSERR;
56   slen = strlen (output);
57 #if WINDOWS
58   idn_free (output);
59 #else
60   free (output);
61 #endif
62   return (slen > 63) ? GNUNET_SYSERR : GNUNET_OK;
63 }
64
65
66 /**
67  * Check if a label in UTF-8 format can be coded into valid IDNA.
68  * This can fail if the ASCII-conversion becomes longer than 253 characters.
69  *
70  * @param name name to check (UTF-8 string)
71  * @return #GNUNET_OK if the label can be converted to IDNA,
72  *         #GNUNET_SYSERR if the label is not valid for DNS names
73  */
74 int
75 GNUNET_DNSPARSER_check_name (const char *name)
76 {
77   char *ldup;
78   char *output;
79   size_t slen;
80   char *tok;
81
82   ldup = GNUNET_strdup (name);
83   for (tok = strtok (ldup, "."); NULL != tok; tok = strtok (NULL, "."))
84     if (GNUNET_OK !=
85         GNUNET_DNSPARSER_check_label (tok))
86     {
87       GNUNET_free (ldup);
88       return GNUNET_SYSERR;
89     }
90   GNUNET_free (ldup);
91   if (IDNA_SUCCESS !=
92       idna_to_ascii_8z (name, &output, IDNA_ALLOW_UNASSIGNED))
93     return GNUNET_SYSERR;
94   slen = strlen (output);
95 #if WINDOWS
96   idn_free (output);
97 #else
98   free (output);
99 #endif
100   return (slen > 253) ? GNUNET_SYSERR : GNUNET_OK;
101 }
102
103
104 /**
105  * Free SOA information record.
106  *
107  * @param soa record to free
108  */
109 void
110 GNUNET_DNSPARSER_free_soa (struct GNUNET_DNSPARSER_SoaRecord *soa)
111 {
112   if (NULL == soa)
113     return;
114   GNUNET_free_non_null (soa->mname);
115   GNUNET_free_non_null (soa->rname);
116   GNUNET_free (soa);
117 }
118
119
120 /**
121  * Free CERT information record.
122  *
123  * @param cert record to free
124  */
125 void
126 GNUNET_DNSPARSER_free_cert (struct GNUNET_DNSPARSER_CertRecord *cert)
127 {
128   if (NULL == cert)
129     return;
130   GNUNET_free_non_null (cert->certificate_data);
131   GNUNET_free (cert);
132 }
133
134
135 /**
136  * Free SRV information record.
137  *
138  * @param srv record to free
139  */
140 void
141 GNUNET_DNSPARSER_free_srv (struct GNUNET_DNSPARSER_SrvRecord *srv)
142 {
143   if (NULL == srv)
144     return;
145   GNUNET_free_non_null (srv->target);
146   GNUNET_free (srv);
147 }
148
149
150 /**
151  * Free MX information record.
152  *
153  * @param mx record to free
154  */
155 void
156 GNUNET_DNSPARSER_free_mx (struct GNUNET_DNSPARSER_MxRecord *mx)
157 {
158   if (NULL == mx)
159     return;
160   GNUNET_free_non_null (mx->mxhost);
161   GNUNET_free (mx);
162 }
163
164
165 /**
166  * Free the given DNS record.
167  *
168  * @param r record to free
169  */
170 void
171 GNUNET_DNSPARSER_free_record (struct GNUNET_DNSPARSER_Record *r)
172 {
173   GNUNET_free_non_null (r->name);
174   switch (r->type)
175   {
176   case GNUNET_DNSPARSER_TYPE_MX:
177     GNUNET_DNSPARSER_free_mx (r->data.mx);
178     break;
179   case GNUNET_DNSPARSER_TYPE_SOA:
180     GNUNET_DNSPARSER_free_soa (r->data.soa);
181     break;
182   case GNUNET_DNSPARSER_TYPE_SRV:
183     GNUNET_DNSPARSER_free_srv (r->data.srv);
184     break;
185   case GNUNET_DNSPARSER_TYPE_CERT:
186     GNUNET_DNSPARSER_free_cert (r->data.cert);
187     break;
188   case GNUNET_DNSPARSER_TYPE_NS:
189   case GNUNET_DNSPARSER_TYPE_CNAME:
190   case GNUNET_DNSPARSER_TYPE_PTR:
191     GNUNET_free_non_null (r->data.hostname);
192     break;
193   default:
194     GNUNET_free_non_null (r->data.raw.data);
195     break;
196   }
197 }
198
199
200 /**
201  * Parse name inside of a DNS query or record.
202  *
203  * @param udp_payload entire UDP payload
204  * @param udp_payload_length length of @a udp_payload
205  * @param off pointer to the offset of the name to parse in the udp_payload (to be
206  *                    incremented by the size of the name)
207  * @param depth current depth of our recursion (to prevent stack overflow)
208  * @return name as 0-terminated C string on success, NULL if the payload is malformed
209  */
210 static char *
211 parse_name (const char *udp_payload,
212             size_t udp_payload_length,
213             size_t *off,
214             unsigned int depth)
215 {
216   const uint8_t *input = (const uint8_t *) udp_payload;
217   char *ret;
218   char *tmp;
219   char *xstr;
220   uint8_t len;
221   size_t xoff;
222   char *utf8;
223   Idna_rc rc;
224
225   ret = GNUNET_strdup ("");
226   while (1)
227   {
228     if (*off >= udp_payload_length)
229     {
230       GNUNET_break_op (0);
231       goto error;
232     }
233     len = input[*off];
234     if (0 == len)
235     {
236       (*off)++;
237       break;
238     }
239     if (len < 64)
240     {
241       if (*off + 1 + len > udp_payload_length)
242       {
243         GNUNET_break_op (0);
244         goto error;
245       }
246       GNUNET_asprintf (&tmp,
247                        "%.*s",
248                        (int) len,
249                        &udp_payload[*off + 1]);
250       if (IDNA_SUCCESS !=
251           (rc = idna_to_unicode_8z8z (tmp, &utf8, IDNA_ALLOW_UNASSIGNED)))
252       {
253         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
254                     _("Failed to convert DNS IDNA name `%s' to UTF-8: %s\n"),
255                     tmp,
256                     idna_strerror (rc));
257         GNUNET_free (tmp);
258         GNUNET_asprintf (&tmp,
259                          "%s%.*s.",
260                          ret,
261                          (int) len,
262                          &udp_payload[*off + 1]);
263       }
264       else
265       {
266         GNUNET_free (tmp);
267         GNUNET_asprintf (&tmp,
268                          "%s%s.",
269                          ret,
270                          utf8);
271 #if WINDOWS
272         idn_free (utf8);
273 #else
274         free (utf8);
275 #endif
276       }
277       GNUNET_free (ret);
278       ret = tmp;
279       *off += 1 + len;
280     }
281     else if ((64 | 128) == (len & (64 | 128)) )
282     {
283       if (depth > 32)
284       {
285         GNUNET_break_op (0);
286         goto error; /* hard bound on stack to prevent "infinite" recursion, disallow! */
287       }
288       /* pointer to string */
289       if (*off + 1 > udp_payload_length)
290       {
291         GNUNET_break_op (0);
292         goto error;
293       }
294       xoff = ((len - (64 | 128)) << 8) + input[*off+1];
295       xstr = parse_name (udp_payload,
296                          udp_payload_length,
297                          &xoff,
298                          depth + 1);
299       if (NULL == xstr)
300       {
301         GNUNET_break_op (0);
302         goto error;
303       }
304       GNUNET_asprintf (&tmp,
305                        "%s%s.",
306                        ret,
307                        xstr);
308       GNUNET_free (ret);
309       GNUNET_free (xstr);
310       ret = tmp;
311       if (strlen (ret) > udp_payload_length)
312       {
313         GNUNET_break_op (0);
314         goto error; /* we are looping (building an infinite string) */
315       }
316       *off += 2;
317       /* pointers always terminate names */
318       break;
319     }
320     else
321     {
322       /* neither pointer nor inline string, not supported... */
323       GNUNET_break_op (0);
324       goto error;
325     }
326   }
327   if (0 < strlen(ret))
328     ret[strlen(ret)-1] = '\0'; /* eat tailing '.' */
329   return ret;
330  error:
331   GNUNET_break_op (0);
332   GNUNET_free (ret);
333   return NULL;
334 }
335
336
337 /**
338  * Parse name inside of a DNS query or record.
339  *
340  * @param udp_payload entire UDP payload
341  * @param udp_payload_length length of @a udp_payload
342  * @param off pointer to the offset of the name to parse in the udp_payload (to be
343  *                    incremented by the size of the name)
344  * @return name as 0-terminated C string on success, NULL if the payload is malformed
345  */
346 char *
347 GNUNET_DNSPARSER_parse_name (const char *udp_payload,
348                              size_t udp_payload_length,
349                              size_t *off)
350 {
351   return parse_name (udp_payload, udp_payload_length, off, 0);
352 }
353
354
355 /**
356  * Parse a DNS query entry.
357  *
358  * @param udp_payload entire UDP payload
359  * @param udp_payload_length length of @a udp_payload
360  * @param off pointer to the offset of the query to parse in the udp_payload (to be
361  *                    incremented by the size of the query)
362  * @param q where to write the query information
363  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the query is malformed
364  */
365 int
366 GNUNET_DNSPARSER_parse_query (const char *udp_payload,
367                               size_t udp_payload_length,
368                               size_t *off,
369                               struct GNUNET_DNSPARSER_Query *q)
370 {
371   char *name;
372   struct GNUNET_TUN_DnsQueryLine ql;
373
374   name = GNUNET_DNSPARSER_parse_name (udp_payload,
375                                       udp_payload_length,
376                                       off);
377   if (NULL == name)
378   {
379     GNUNET_break_op (0);
380     return GNUNET_SYSERR;
381   }
382   q->name = name;
383   if (*off + sizeof (struct GNUNET_TUN_DnsQueryLine) > udp_payload_length)
384   {
385     GNUNET_break_op (0);
386     return GNUNET_SYSERR;
387   }
388   GNUNET_memcpy (&ql, &udp_payload[*off], sizeof (ql));
389   *off += sizeof (ql);
390   q->type = ntohs (ql.type);
391   q->dns_traffic_class = ntohs (ql.dns_traffic_class);
392   return GNUNET_OK;
393 }
394
395
396 /**
397  * Parse a DNS SOA record.
398  *
399  * @param udp_payload reference to UDP packet
400  * @param udp_payload_length length of @a udp_payload
401  * @param off pointer to the offset of the query to parse in the SOA record (to be
402  *                    incremented by the size of the record), unchanged on error
403  * @return the parsed SOA record, NULL on error
404  */
405 struct GNUNET_DNSPARSER_SoaRecord *
406 GNUNET_DNSPARSER_parse_soa (const char *udp_payload,
407                             size_t udp_payload_length,
408                             size_t *off)
409 {
410   struct GNUNET_DNSPARSER_SoaRecord *soa;
411   struct GNUNET_TUN_DnsSoaRecord soa_bin;
412   size_t old_off;
413
414   old_off = *off;
415   soa = GNUNET_new (struct GNUNET_DNSPARSER_SoaRecord);
416   soa->mname = GNUNET_DNSPARSER_parse_name (udp_payload,
417                                             udp_payload_length,
418                                             off);
419   soa->rname = GNUNET_DNSPARSER_parse_name (udp_payload,
420                                             udp_payload_length,
421                                             off);
422   if ( (NULL == soa->mname) ||
423        (NULL == soa->rname) ||
424        (*off + sizeof (struct GNUNET_TUN_DnsSoaRecord) > udp_payload_length) )
425   {
426     GNUNET_break_op (0);
427     GNUNET_DNSPARSER_free_soa (soa);
428     *off = old_off;
429     return NULL;
430   }
431   GNUNET_memcpy (&soa_bin,
432           &udp_payload[*off],
433           sizeof (struct GNUNET_TUN_DnsSoaRecord));
434   soa->serial = ntohl (soa_bin.serial);
435   soa->refresh = ntohl (soa_bin.refresh);
436   soa->retry = ntohl (soa_bin.retry);
437   soa->expire = ntohl (soa_bin.expire);
438   soa->minimum_ttl = ntohl (soa_bin.minimum);
439   (*off) += sizeof (struct GNUNET_TUN_DnsSoaRecord);
440   return soa;
441 }
442
443
444 /**
445  * Parse a DNS MX record.
446  *
447  * @param udp_payload reference to UDP packet
448  * @param udp_payload_length length of @a udp_payload
449  * @param off pointer to the offset of the query to parse in the MX record (to be
450  *                    incremented by the size of the record), unchanged on error
451  * @return the parsed MX record, NULL on error
452  */
453 struct GNUNET_DNSPARSER_MxRecord *
454 GNUNET_DNSPARSER_parse_mx (const char *udp_payload,
455                            size_t udp_payload_length,
456                            size_t *off)
457 {
458   struct GNUNET_DNSPARSER_MxRecord *mx;
459   uint16_t mxpref;
460   size_t old_off;
461
462   old_off = *off;
463   if (*off + sizeof (uint16_t) > udp_payload_length)
464   {
465     GNUNET_break_op (0);
466     return NULL;
467   }
468   GNUNET_memcpy (&mxpref, &udp_payload[*off], sizeof (uint16_t));
469   (*off) += sizeof (uint16_t);
470   mx = GNUNET_new (struct GNUNET_DNSPARSER_MxRecord);
471   mx->preference = ntohs (mxpref);
472   mx->mxhost = GNUNET_DNSPARSER_parse_name (udp_payload,
473                                             udp_payload_length,
474                                             off);
475   if (NULL == mx->mxhost)
476   {
477     GNUNET_break_op (0);
478     GNUNET_DNSPARSER_free_mx (mx);
479     *off = old_off;
480     return NULL;
481   }
482   return mx;
483 }
484
485
486 /**
487  * Parse a DNS SRV record.
488  *
489  * @param udp_payload reference to UDP packet
490  * @param udp_payload_length length of @a udp_payload
491  * @param off pointer to the offset of the query to parse in the SRV record (to be
492  *                    incremented by the size of the record), unchanged on error
493  * @return the parsed SRV record, NULL on error
494  */
495 struct GNUNET_DNSPARSER_SrvRecord *
496 GNUNET_DNSPARSER_parse_srv (const char *udp_payload,
497                             size_t udp_payload_length,
498                             size_t *off)
499 {
500   struct GNUNET_DNSPARSER_SrvRecord *srv;
501   struct GNUNET_TUN_DnsSrvRecord srv_bin;
502   size_t old_off;
503
504   old_off = *off;
505   if (*off + sizeof (struct GNUNET_TUN_DnsSrvRecord) > udp_payload_length)
506     return NULL;
507   GNUNET_memcpy (&srv_bin,
508           &udp_payload[*off],
509           sizeof (struct GNUNET_TUN_DnsSrvRecord));
510   (*off) += sizeof (struct GNUNET_TUN_DnsSrvRecord);
511   srv = GNUNET_new (struct GNUNET_DNSPARSER_SrvRecord);
512   srv->priority = ntohs (srv_bin.prio);
513   srv->weight = ntohs (srv_bin.weight);
514   srv->port = ntohs (srv_bin.port);
515   srv->target = GNUNET_DNSPARSER_parse_name (udp_payload,
516                                              udp_payload_length,
517                                              off);
518   if (NULL == srv->target)
519   {
520     GNUNET_DNSPARSER_free_srv (srv);
521     *off = old_off;
522     return NULL;
523   }
524   return srv;
525 }
526
527
528 /**
529  * Parse a DNS CERT record.
530  *
531  * @param udp_payload reference to UDP packet
532  * @param udp_payload_length length of @a udp_payload
533  * @param off pointer to the offset of the query to parse in the CERT record (to be
534  *                    incremented by the size of the record), unchanged on error
535  * @return the parsed CERT record, NULL on error
536  */
537 struct GNUNET_DNSPARSER_CertRecord *
538 GNUNET_DNSPARSER_parse_cert (const char *udp_payload,
539                              size_t udp_payload_length,
540                              size_t *off)
541 {
542   struct GNUNET_DNSPARSER_CertRecord *cert;
543   struct GNUNET_TUN_DnsCertRecord dcert;
544
545   if (*off + sizeof (struct GNUNET_TUN_DnsCertRecord) >= udp_payload_length)
546   {
547     GNUNET_break_op (0);
548     return NULL;
549   }
550   GNUNET_memcpy (&dcert, &udp_payload[*off], sizeof (struct GNUNET_TUN_DnsCertRecord));
551   (*off) += sizeof (struct GNUNET_TUN_DnsCertRecord);
552   cert = GNUNET_new (struct GNUNET_DNSPARSER_CertRecord);
553   cert->cert_type = ntohs (dcert.cert_type);
554   cert->cert_tag = ntohs (dcert.cert_tag);
555   cert->algorithm = dcert.algorithm;
556   cert->certificate_size = udp_payload_length - (*off);
557   cert->certificate_data = GNUNET_malloc (cert->certificate_size);
558   GNUNET_memcpy (cert->certificate_data,
559           &udp_payload[*off],
560           cert->certificate_size);
561   (*off) += cert->certificate_size;
562   return cert;
563 }
564
565
566 /**
567  * Parse a DNS record entry.
568  *
569  * @param udp_payload entire UDP payload
570  * @param udp_payload_length length of @a udp_payload
571  * @param off pointer to the offset of the record to parse in the udp_payload (to be
572  *                    incremented by the size of the record)
573  * @param r where to write the record information
574  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the record is malformed
575  */
576 int
577 GNUNET_DNSPARSER_parse_record (const char *udp_payload,
578                                size_t udp_payload_length,
579                                size_t *off,
580                                struct GNUNET_DNSPARSER_Record *r)
581 {
582   char *name;
583   struct GNUNET_TUN_DnsRecordLine rl;
584   size_t old_off;
585   uint16_t data_len;
586
587   name = GNUNET_DNSPARSER_parse_name (udp_payload,
588                                       udp_payload_length,
589                                       off);
590   if (NULL == name)
591   {
592     GNUNET_break_op (0);
593     return GNUNET_SYSERR;
594   }
595   r->name = name;
596   if (*off + sizeof (struct GNUNET_TUN_DnsRecordLine) > udp_payload_length)
597   {
598     GNUNET_break_op (0);
599     return GNUNET_SYSERR;
600   }
601   GNUNET_memcpy (&rl, &udp_payload[*off], sizeof (rl));
602   (*off) += sizeof (rl);
603   r->type = ntohs (rl.type);
604   r->dns_traffic_class = ntohs (rl.dns_traffic_class);
605   r->expiration_time = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
606                                                                                         ntohl (rl.ttl)));
607   data_len = ntohs (rl.data_len);
608   if (*off + data_len > udp_payload_length)
609   {
610     GNUNET_break_op (0);
611     return GNUNET_SYSERR;
612   }
613   old_off = *off;
614   switch (r->type)
615   {
616   case GNUNET_DNSPARSER_TYPE_NS:
617   case GNUNET_DNSPARSER_TYPE_CNAME:
618   case GNUNET_DNSPARSER_TYPE_PTR:
619     r->data.hostname = GNUNET_DNSPARSER_parse_name (udp_payload,
620                                                     udp_payload_length,
621                                                     off);
622     if ( (NULL == r->data.hostname) ||
623          (old_off + data_len != *off) )
624       return GNUNET_SYSERR;
625     return GNUNET_OK;
626   case GNUNET_DNSPARSER_TYPE_SOA:
627     r->data.soa = GNUNET_DNSPARSER_parse_soa (udp_payload,
628                                               udp_payload_length,
629                                               off);
630     if ( (NULL == r->data.soa) ||
631          (old_off + data_len != *off) )
632     {
633       GNUNET_break_op (0);
634       return GNUNET_SYSERR;
635     }
636     return GNUNET_OK;
637   case GNUNET_DNSPARSER_TYPE_MX:
638     r->data.mx = GNUNET_DNSPARSER_parse_mx (udp_payload,
639                                             udp_payload_length,
640                                             off);
641     if ( (NULL == r->data.mx) ||
642          (old_off + data_len != *off) )
643     {
644       GNUNET_break_op (0);
645       return GNUNET_SYSERR;
646     }
647     return GNUNET_OK;
648   case GNUNET_DNSPARSER_TYPE_SRV:
649     r->data.srv = GNUNET_DNSPARSER_parse_srv (udp_payload,
650                                               udp_payload_length,
651                                               off);
652     if ( (NULL == r->data.srv) ||
653          (old_off + data_len != *off) )
654     {
655       GNUNET_break_op (0);
656       return GNUNET_SYSERR;
657     }
658     return GNUNET_OK;
659   default:
660     r->data.raw.data = GNUNET_malloc (data_len);
661     r->data.raw.data_len = data_len;
662     GNUNET_memcpy (r->data.raw.data, &udp_payload[*off], data_len);
663     break;
664   }
665   (*off) += data_len;
666   return GNUNET_OK;
667 }
668
669
670 /**
671  * Parse a UDP payload of a DNS packet in to a nice struct for further
672  * processing and manipulation.
673  *
674  * @param udp_payload wire-format of the DNS packet
675  * @param udp_payload_length number of bytes in @a udp_payload
676  * @return NULL on error, otherwise the parsed packet
677  */
678 struct GNUNET_DNSPARSER_Packet *
679 GNUNET_DNSPARSER_parse (const char *udp_payload,
680                         size_t udp_payload_length)
681 {
682   struct GNUNET_DNSPARSER_Packet *p;
683   const struct GNUNET_TUN_DnsHeader *dns;
684   size_t off;
685   unsigned int n;
686   unsigned int i;
687
688   if (udp_payload_length < sizeof (struct GNUNET_TUN_DnsHeader))
689     return NULL;
690   dns = (const struct GNUNET_TUN_DnsHeader *) udp_payload;
691   off = sizeof (struct GNUNET_TUN_DnsHeader);
692   p = GNUNET_new (struct GNUNET_DNSPARSER_Packet);
693   p->flags = dns->flags;
694   p->id = dns->id;
695   n = ntohs (dns->query_count);
696   if (n > 0)
697   {
698     p->queries = GNUNET_malloc (n * sizeof (struct GNUNET_DNSPARSER_Query));
699     p->num_queries = n;
700     for (i=0;i<n;i++)
701       if (GNUNET_OK !=
702           GNUNET_DNSPARSER_parse_query (udp_payload,
703                                         udp_payload_length,
704                                         &off,
705                                         &p->queries[i]))
706         goto error;
707   }
708   n = ntohs (dns->answer_rcount);
709   if (n > 0)
710   {
711     p->answers = GNUNET_malloc (n * sizeof (struct GNUNET_DNSPARSER_Record));
712     p->num_answers = n;
713     for (i=0;i<n;i++)
714       if (GNUNET_OK !=
715           GNUNET_DNSPARSER_parse_record (udp_payload,
716                                          udp_payload_length,
717                                          &off,
718                                          &p->answers[i]))
719         goto error;
720   }
721   n = ntohs (dns->authority_rcount);
722   if (n > 0)
723   {
724     p->authority_records = GNUNET_malloc (n * sizeof (struct GNUNET_DNSPARSER_Record));
725     p->num_authority_records = n;
726     for (i=0;i<n;i++)
727       if (GNUNET_OK !=
728           GNUNET_DNSPARSER_parse_record (udp_payload,
729                                          udp_payload_length,
730                                          &off,
731                                          &p->authority_records[i]))
732         goto error;
733   }
734   n = ntohs (dns->additional_rcount);
735   if (n > 0)
736   {
737     p->additional_records = GNUNET_malloc (n * sizeof (struct GNUNET_DNSPARSER_Record));
738     p->num_additional_records = n;
739     for (i=0;i<n;i++)
740       if (GNUNET_OK !=
741           GNUNET_DNSPARSER_parse_record (udp_payload,
742                                          udp_payload_length,
743                                          &off,
744                                          &p->additional_records[i]))
745         goto error;
746   }
747   return p;
748  error:
749   GNUNET_break_op (0);
750   GNUNET_DNSPARSER_free_packet (p);
751   return NULL;
752 }
753
754
755 /**
756  * Free memory taken by a packet.
757  *
758  * @param p packet to free
759  */
760 void
761 GNUNET_DNSPARSER_free_packet (struct GNUNET_DNSPARSER_Packet *p)
762 {
763   unsigned int i;
764
765   for (i=0;i<p->num_queries;i++)
766     GNUNET_free_non_null (p->queries[i].name);
767   GNUNET_free_non_null (p->queries);
768   for (i=0;i<p->num_answers;i++)
769     GNUNET_DNSPARSER_free_record (&p->answers[i]);
770   GNUNET_free_non_null (p->answers);
771   for (i=0;i<p->num_authority_records;i++)
772     GNUNET_DNSPARSER_free_record (&p->authority_records[i]);
773   GNUNET_free_non_null (p->authority_records);
774   for (i=0;i<p->num_additional_records;i++)
775     GNUNET_DNSPARSER_free_record (&p->additional_records[i]);
776   GNUNET_free_non_null (p->additional_records);
777   GNUNET_free (p);
778 }
779
780
781 /* ********************** DNS packet assembly code **************** */
782
783
784 /**
785  * Add a DNS name to the UDP packet at the given location, converting
786  * the name to IDNA notation as necessary.
787  *
788  * @param dst where to write the name (UDP packet)
789  * @param dst_len number of bytes in @a dst
790  * @param off pointer to offset where to write the name (increment by bytes used)
791  *            must not be changed if there is an error
792  * @param name name to write
793  * @return #GNUNET_SYSERR if @a name is invalid
794  *         #GNUNET_NO if @a name did not fit
795  *         #GNUNET_OK if @a name was added to @a dst
796  */
797 int
798 GNUNET_DNSPARSER_builder_add_name (char *dst,
799                                    size_t dst_len,
800                                    size_t *off,
801                                    const char *name)
802 {
803   const char *dot;
804   const char *idna_name;
805   char *idna_start;
806   size_t start;
807   size_t pos;
808   size_t len;
809   Idna_rc rc;
810
811   if (NULL == name)
812     return GNUNET_SYSERR;
813
814   if (IDNA_SUCCESS !=
815       (rc = idna_to_ascii_8z (name, &idna_start, IDNA_ALLOW_UNASSIGNED)))
816   {
817     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
818                 _("Failed to convert UTF-8 name `%s' to DNS IDNA format: %s\n"),
819                 name,
820                 idna_strerror (rc));
821     return GNUNET_NO;
822   }
823   idna_name = idna_start;
824   start = *off;
825   if (start + strlen (idna_name) + 2 > dst_len)
826     goto fail;
827   pos = start;
828   do
829   {
830     dot = strchr (idna_name, '.');
831     if (NULL == dot)
832       len = strlen (idna_name);
833     else
834       len = dot - idna_name;
835     if ( (len >= 64) || (0 == len) )
836     {
837       GNUNET_break (0);
838       goto fail; /* segment too long or empty */
839     }
840     dst[pos++] = (char) (uint8_t) len;
841     GNUNET_memcpy (&dst[pos], idna_name, len);
842     pos += len;
843     idna_name += len + 1; /* also skip dot */
844   }
845   while (NULL != dot);
846   dst[pos++] = '\0'; /* terminator */
847   *off = pos;
848 #if WINDOWS
849   idn_free (idna_start);
850 #else
851   free (idna_start);
852 #endif
853   return GNUNET_OK;
854  fail:
855 #if WINDOWS
856   idn_free (idna_start);
857 #else
858   free (idna_start);
859 #endif
860   return GNUNET_NO;
861 }
862
863
864 /**
865  * Add a DNS query to the UDP packet at the given location.
866  *
867  * @param dst where to write the query
868  * @param dst_len number of bytes in @a dst
869  * @param off pointer to offset where to write the query (increment by bytes used)
870  *            must not be changed if there is an error
871  * @param query query to write
872  * @return #GNUNET_SYSERR if @a query is invalid
873  *         #GNUNET_NO if @a query did not fit
874  *         #GNUNET_OK if @a query was added to @a dst
875  */
876 int
877 GNUNET_DNSPARSER_builder_add_query (char *dst,
878                                     size_t dst_len,
879                                     size_t *off,
880                                     const struct GNUNET_DNSPARSER_Query *query)
881 {
882   int ret;
883   struct GNUNET_TUN_DnsQueryLine ql;
884
885   ret = GNUNET_DNSPARSER_builder_add_name (dst, dst_len - sizeof (struct GNUNET_TUN_DnsQueryLine), off, query->name);
886   if (ret != GNUNET_OK)
887     return ret;
888   ql.type = htons (query->type);
889   ql.dns_traffic_class = htons (query->dns_traffic_class);
890   GNUNET_memcpy (&dst[*off], &ql, sizeof (ql));
891   (*off) += sizeof (ql);
892   return GNUNET_OK;
893 }
894
895
896 /**
897  * Add an MX record to the UDP packet at the given location.
898  *
899  * @param dst where to write the mx record
900  * @param dst_len number of bytes in @a dst
901  * @param off pointer to offset where to write the mx information (increment by bytes used);
902  *            can also change if there was an error
903  * @param mx mx information to write
904  * @return #GNUNET_SYSERR if @a mx is invalid
905  *         #GNUNET_NO if @a mx did not fit
906  *         #GNUNET_OK if @a mx was added to @a dst
907  */
908 int
909 GNUNET_DNSPARSER_builder_add_mx (char *dst,
910                                  size_t dst_len,
911                                  size_t *off,
912                                  const struct GNUNET_DNSPARSER_MxRecord *mx)
913 {
914   uint16_t mxpref;
915
916   if (*off + sizeof (uint16_t) > dst_len)
917     return GNUNET_NO;
918   mxpref = htons (mx->preference);
919   GNUNET_memcpy (&dst[*off], &mxpref, sizeof (mxpref));
920   (*off) += sizeof (mxpref);
921   return GNUNET_DNSPARSER_builder_add_name (dst, dst_len, off, mx->mxhost);
922 }
923
924
925 /**
926  * Add a CERT record to the UDP packet at the given location.
927  *
928  * @param dst where to write the CERT record
929  * @param dst_len number of bytes in @a dst
930  * @param off pointer to offset where to write the CERT information (increment by bytes used);
931  *            can also change if there was an error
932  * @param cert CERT information to write
933  * @return #GNUNET_SYSERR if @a cert is invalid
934  *         #GNUNET_NO if @a cert did not fit
935  *         #GNUNET_OK if @a cert was added to @a dst
936  */
937 int
938 GNUNET_DNSPARSER_builder_add_cert (char *dst,
939                                    size_t dst_len,
940                                    size_t *off,
941                                    const struct GNUNET_DNSPARSER_CertRecord *cert)
942 {
943   struct GNUNET_TUN_DnsCertRecord dcert;
944
945   if ( (cert->cert_type > UINT16_MAX) ||
946        (cert->cert_tag > UINT16_MAX) ||
947        (cert->algorithm > UINT8_MAX) )
948   {
949     GNUNET_break (0);
950     return GNUNET_SYSERR;
951   }
952   if (*off + sizeof (struct GNUNET_TUN_DnsCertRecord) + cert->certificate_size > dst_len)
953     return GNUNET_NO;
954   dcert.cert_type = htons ((uint16_t) cert->cert_type);
955   dcert.cert_tag = htons ((uint16_t) cert->cert_tag);
956   dcert.algorithm = (uint8_t) cert->algorithm;
957   GNUNET_memcpy (&dst[*off], &dcert, sizeof (dcert));
958   (*off) += sizeof (dcert);
959   GNUNET_memcpy (&dst[*off], cert->certificate_data, cert->certificate_size);
960   (*off) += cert->certificate_size;
961   return GNUNET_OK;
962 }
963
964
965 /**
966  * Add an SOA record to the UDP packet at the given location.
967  *
968  * @param dst where to write the SOA record
969  * @param dst_len number of bytes in @a dst
970  * @param off pointer to offset where to write the SOA information (increment by bytes used)
971  *            can also change if there was an error
972  * @param soa SOA information to write
973  * @return #GNUNET_SYSERR if @a soa is invalid
974  *         #GNUNET_NO if @a soa did not fit
975  *         #GNUNET_OK if @a soa was added to @a dst
976  */
977 int
978 GNUNET_DNSPARSER_builder_add_soa (char *dst,
979                                   size_t dst_len,
980                                   size_t *off,
981                                   const struct GNUNET_DNSPARSER_SoaRecord *soa)
982 {
983   struct GNUNET_TUN_DnsSoaRecord sd;
984   int ret;
985
986   if ( (GNUNET_OK != (ret = GNUNET_DNSPARSER_builder_add_name (dst,
987                                                                dst_len,
988                                                                off,
989                                                                soa->mname))) ||
990        (GNUNET_OK != (ret = GNUNET_DNSPARSER_builder_add_name (dst,
991                                                                dst_len,
992                                                                off,
993                                                                soa->rname)) ) )
994     return ret;
995   if (*off + sizeof (struct GNUNET_TUN_DnsSoaRecord) > dst_len)
996     return GNUNET_NO;
997   sd.serial = htonl (soa->serial);
998   sd.refresh = htonl (soa->refresh);
999   sd.retry = htonl (soa->retry);
1000   sd.expire = htonl (soa->expire);
1001   sd.minimum = htonl (soa->minimum_ttl);
1002   GNUNET_memcpy (&dst[*off], &sd, sizeof (sd));
1003   (*off) += sizeof (sd);
1004   return GNUNET_OK;
1005 }
1006
1007
1008 /**
1009  * Add an SRV record to the UDP packet at the given location.
1010  *
1011  * @param dst where to write the SRV record
1012  * @param dst_len number of bytes in @a dst
1013  * @param off pointer to offset where to write the SRV information (increment by bytes used)
1014  *            can also change if there was an error
1015  * @param srv SRV information to write
1016  * @return #GNUNET_SYSERR if @a srv is invalid
1017  *         #GNUNET_NO if @a srv did not fit
1018  *         #GNUNET_OK if @a srv was added to @a dst
1019  */
1020 int
1021 GNUNET_DNSPARSER_builder_add_srv (char *dst,
1022                                   size_t dst_len,
1023                                   size_t *off,
1024                                   const struct GNUNET_DNSPARSER_SrvRecord *srv)
1025 {
1026   struct GNUNET_TUN_DnsSrvRecord sd;
1027   int ret;
1028
1029   if (*off + sizeof (struct GNUNET_TUN_DnsSrvRecord) > dst_len)
1030     return GNUNET_NO;
1031   sd.prio = htons (srv->priority);
1032   sd.weight = htons (srv->weight);
1033   sd.port = htons (srv->port);
1034   GNUNET_memcpy (&dst[*off], &sd, sizeof (sd));
1035   (*off) += sizeof (sd);
1036   if (GNUNET_OK != (ret = GNUNET_DNSPARSER_builder_add_name (dst,
1037                                     dst_len,
1038                                     off,
1039                                     srv->target)))
1040     return ret;
1041   return GNUNET_OK;
1042 }
1043
1044
1045 /**
1046  * Add a DNS record to the UDP packet at the given location.
1047  *
1048  * @param dst where to write the query
1049  * @param dst_len number of bytes in @a dst
1050  * @param off pointer to offset where to write the query (increment by bytes used)
1051  *            must not be changed if there is an error
1052  * @param record record to write
1053  * @return #GNUNET_SYSERR if @a record is invalid
1054  *         #GNUNET_NO if @a record did not fit
1055  *         #GNUNET_OK if @a record was added to @a dst
1056  */
1057 static int
1058 add_record (char *dst,
1059             size_t dst_len,
1060             size_t *off,
1061             const struct GNUNET_DNSPARSER_Record *record)
1062 {
1063   int ret;
1064   size_t start;
1065   size_t pos;
1066   struct GNUNET_TUN_DnsRecordLine rl;
1067
1068   start = *off;
1069   ret = GNUNET_DNSPARSER_builder_add_name (dst,
1070                                            dst_len - sizeof (struct GNUNET_TUN_DnsRecordLine),
1071                                            off,
1072                                            record->name);
1073   if (GNUNET_OK != ret)
1074     return ret;
1075   /* '*off' is now the position where we will need to write the record line */
1076
1077   pos = *off + sizeof (struct GNUNET_TUN_DnsRecordLine);
1078   switch (record->type)
1079   {
1080   case GNUNET_DNSPARSER_TYPE_MX:
1081     ret = GNUNET_DNSPARSER_builder_add_mx (dst, dst_len, &pos, record->data.mx);
1082     break;
1083   case GNUNET_DNSPARSER_TYPE_CERT:
1084     ret = GNUNET_DNSPARSER_builder_add_cert (dst, dst_len, &pos, record->data.cert);
1085     break;
1086   case GNUNET_DNSPARSER_TYPE_SOA:
1087     ret = GNUNET_DNSPARSER_builder_add_soa (dst, dst_len, &pos, record->data.soa);
1088     break;
1089   case GNUNET_DNSPARSER_TYPE_NS:
1090   case GNUNET_DNSPARSER_TYPE_CNAME:
1091   case GNUNET_DNSPARSER_TYPE_PTR:
1092     ret = GNUNET_DNSPARSER_builder_add_name (dst, dst_len, &pos, record->data.hostname);
1093     break;
1094   case GNUNET_DNSPARSER_TYPE_SRV:
1095     ret = GNUNET_DNSPARSER_builder_add_srv (dst, dst_len, &pos, record->data.srv);
1096     break;
1097   default:
1098     if (pos + record->data.raw.data_len > dst_len)
1099     {
1100       ret = GNUNET_NO;
1101       break;
1102     }
1103     GNUNET_memcpy (&dst[pos], record->data.raw.data, record->data.raw.data_len);
1104     pos += record->data.raw.data_len;
1105     ret = GNUNET_OK;
1106     break;
1107   }
1108   if (GNUNET_OK != ret)
1109   {
1110     *off = start;
1111     return GNUNET_NO;
1112   }
1113
1114   if (pos - (*off + sizeof (struct GNUNET_TUN_DnsRecordLine)) > UINT16_MAX)
1115   {
1116     /* record data too long */
1117     *off = start;
1118     return GNUNET_NO;
1119   }
1120   rl.type = htons (record->type);
1121   rl.dns_traffic_class = htons (record->dns_traffic_class);
1122   rl.ttl = htonl (GNUNET_TIME_absolute_get_remaining (record->expiration_time).rel_value_us / 1000LL / 1000LL); /* in seconds */
1123   rl.data_len = htons ((uint16_t) (pos - (*off + sizeof (struct GNUNET_TUN_DnsRecordLine))));
1124   GNUNET_memcpy (&dst[*off], &rl, sizeof (struct GNUNET_TUN_DnsRecordLine));
1125   *off = pos;
1126   return GNUNET_OK;
1127 }
1128
1129
1130 /**
1131  * Given a DNS packet @a p, generate the corresponding UDP payload.
1132  * Note that we do not attempt to pack the strings with pointers
1133  * as this would complicate the code and this is about being
1134  * simple and secure, not fast, fancy and broken like bind.
1135  *
1136  * @param p packet to pack
1137  * @param max maximum allowed size for the resulting UDP payload
1138  * @param buf set to a buffer with the packed message
1139  * @param buf_length set to the length of @a buf
1140  * @return #GNUNET_SYSERR if @a p is invalid
1141  *         #GNUNET_NO if @a p was truncated (but there is still a result in @a buf)
1142  *         #GNUNET_OK if @a p was packed completely into @a buf
1143  */
1144 int
1145 GNUNET_DNSPARSER_pack (const struct GNUNET_DNSPARSER_Packet *p,
1146                        uint16_t max,
1147                        char **buf,
1148                        size_t *buf_length)
1149 {
1150   struct GNUNET_TUN_DnsHeader dns;
1151   size_t off;
1152   char tmp[max];
1153   unsigned int i;
1154   int ret;
1155   int trc;
1156
1157   if ( (p->num_queries > UINT16_MAX) ||
1158        (p->num_answers > UINT16_MAX) ||
1159        (p->num_authority_records > UINT16_MAX) ||
1160        (p->num_additional_records > UINT16_MAX) )
1161     return GNUNET_SYSERR;
1162   dns.id = p->id;
1163   dns.flags = p->flags;
1164   dns.query_count = htons (p->num_queries);
1165   dns.answer_rcount = htons (p->num_answers);
1166   dns.authority_rcount = htons (p->num_authority_records);
1167   dns.additional_rcount = htons (p->num_additional_records);
1168
1169   off = sizeof (struct GNUNET_TUN_DnsHeader);
1170   trc = GNUNET_NO;
1171   for (i=0;i<p->num_queries;i++)
1172   {
1173     ret = GNUNET_DNSPARSER_builder_add_query (tmp,
1174                                               sizeof (tmp),
1175                                               &off,
1176                                               &p->queries[i]);
1177     if (GNUNET_SYSERR == ret)
1178       return GNUNET_SYSERR;
1179     if (GNUNET_NO == ret)
1180     {
1181       dns.query_count = htons ((uint16_t) (i-1));
1182       trc = GNUNET_YES;
1183       break;
1184     }
1185   }
1186   for (i=0;i<p->num_answers;i++)
1187   {
1188     ret = add_record (tmp,
1189                       sizeof (tmp),
1190                       &off,
1191                       &p->answers[i]);
1192     if (GNUNET_SYSERR == ret)
1193       return GNUNET_SYSERR;
1194     if (GNUNET_NO == ret)
1195     {
1196       dns.answer_rcount = htons ((uint16_t) (i-1));
1197       trc = GNUNET_YES;
1198       break;
1199     }
1200   }
1201   for (i=0;i<p->num_authority_records;i++)
1202   {
1203     ret = add_record (tmp,
1204                       sizeof (tmp),
1205                       &off,
1206                       &p->authority_records[i]);
1207     if (GNUNET_SYSERR == ret)
1208       return GNUNET_SYSERR;
1209     if (GNUNET_NO == ret)
1210     {
1211       dns.authority_rcount = htons ((uint16_t) (i-1));
1212       trc = GNUNET_YES;
1213       break;
1214     }
1215   }
1216   for (i=0;i<p->num_additional_records;i++)
1217   {
1218     ret = add_record (tmp,
1219                       sizeof (tmp),
1220                       &off,
1221                       &p->additional_records[i]);
1222     if (GNUNET_SYSERR == ret)
1223       return GNUNET_SYSERR;
1224     if (GNUNET_NO == ret)
1225     {
1226       dns.additional_rcount = htons (i-1);
1227       trc = GNUNET_YES;
1228       break;
1229     }
1230   }
1231
1232   if (GNUNET_YES == trc)
1233     dns.flags.message_truncated = 1;
1234   GNUNET_memcpy (tmp,
1235                  &dns,
1236                  sizeof (struct GNUNET_TUN_DnsHeader));
1237
1238   *buf = GNUNET_malloc (off);
1239   *buf_length = off;
1240   GNUNET_memcpy (*buf,
1241                  tmp,
1242                  off);
1243   if (GNUNET_YES == trc)
1244     return GNUNET_NO;
1245   return GNUNET_OK;
1246 }
1247
1248
1249 /**
1250  * Convert a block of binary data to HEX.
1251  *
1252  * @param data binary data to convert
1253  * @param data_size number of bytes in @a data
1254  * @return HEX string (lower case)
1255  */
1256 char *
1257 GNUNET_DNSPARSER_bin_to_hex (const void *data,
1258                              size_t data_size)
1259 {
1260   char *ret;
1261   size_t off;
1262   const uint8_t *idata;
1263
1264   idata = data;
1265   ret = GNUNET_malloc (data_size * 2 + 1);
1266   for (off = 0; off < data_size; off++)
1267     sprintf (&ret[off * 2],
1268              "%02x",
1269              idata[off]);
1270   return ret;
1271 }
1272
1273
1274 /**
1275  * Convert a HEX string to block of binary data.
1276  *
1277  * @param hex HEX string to convert (may contain mixed case)
1278  * @param data where to write result, must be
1279  *             at least `strlen(hex)/2` bytes long
1280  * @return number of bytes written to data
1281  */
1282 size_t
1283 GNUNET_DNSPARSER_hex_to_bin (const char *hex,
1284                              void *data)
1285 {
1286   size_t data_size;
1287   size_t off;
1288   uint8_t *idata;
1289   unsigned int h;
1290   char in[3];
1291
1292   data_size = strlen (hex) / 2;
1293   idata = data;
1294   in[2] = '\0';
1295   for (off = 0; off < data_size; off++)
1296   {
1297     in[0] = tolower ((unsigned char) hex[off * 2]);
1298     in[1] = tolower ((unsigned char) hex[off * 2 + 1]);
1299     if (1 != sscanf (in, "%x", &h))
1300       return off;
1301     idata[off] = (uint8_t) h;
1302   }
1303   return off;
1304 }
1305
1306
1307 /* end of dnsparser.c */