c11ec25d6c438b57dcfec4b646fea168e82569b2
[oweals/gnunet.git] / src / dns / dnsparser.c
1 /*
2       This file is part of GNUnet
3       (C) 2010, 2011, 2012 Christian Grothoff (and other contributing authors)
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 2, 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., 59 Temple Place - Suite 330,
18       Boston, MA 02111-1307, 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 "gnunet_util_lib.h"
29 #include "gnunet_dnsparser_lib.h"
30
31
32 GNUNET_NETWORK_STRUCT_BEGIN
33
34 /* FIXME: replace this one with the one from tcpip_tun.h!? */
35 /**
36  * Head of a any DNS message.
37  */
38 struct GNUNET_TUN_DnsHeader
39 {
40   /**
41    * Request/response ID. (NBO)
42    */
43   uint16_t id GNUNET_PACKED;
44
45   /**
46    * Flags for the operation.
47    */
48   struct GNUNET_DNSPARSER_Flags flags; 
49
50   /**
51    * number of questions (NBO)
52    */
53   uint16_t query_count GNUNET_PACKED;
54
55   /**
56    * number of answers (NBO)
57    */
58   uint16_t answer_rcount GNUNET_PACKED;
59
60   /**
61    * number of authority-records (NBO)
62    */
63   uint16_t authority_rcount GNUNET_PACKED;
64
65   /**
66    * number of additional records (NBO)
67    */
68   uint16_t additional_rcount GNUNET_PACKED;
69 };
70
71
72 /**
73  * DNS query prefix.
74  */
75 struct query_line
76 {
77   /**
78    * Desired type (GNUNET_DNSPARSER_TYPE_XXX). (NBO)
79    */
80   uint16_t type GNUNET_PACKED;
81
82   /**
83    * Desired class (usually GNUNET_DNSPARSER_CLASS_INTERNET). (NBO)
84    */
85   uint16_t class GNUNET_PACKED;
86 };
87
88
89 /**
90  * General DNS record prefix.
91  */
92 struct record_line
93 {
94   /**
95    * Record type (GNUNET_DNSPARSER_TYPE_XXX). (NBO)
96    */
97   uint16_t type GNUNET_PACKED;
98
99   /**
100    * Record class (usually GNUNET_DNSPARSER_CLASS_INTERNET). (NBO)
101    */
102   uint16_t class GNUNET_PACKED;
103
104   /**
105    * Expiration for the record (in seconds). (NBO)
106    */
107   uint32_t ttl GNUNET_PACKED;
108
109   /**
110    * Number of bytes of data that follow. (NBO)
111    */
112   uint16_t data_len GNUNET_PACKED;
113 };
114
115
116 /**
117  * Payload of DNS SOA record (header).
118  */
119 struct soa_data
120 {
121   /**
122    * The version number of the original copy of the zone.   (NBO)
123    */
124   uint32_t serial GNUNET_PACKED;
125   
126   /**
127    * Time interval before the zone should be refreshed. (NBO)
128    */
129   uint32_t refresh GNUNET_PACKED;
130   
131   /**
132    * Time interval that should elapse before a failed refresh should
133    * be retried. (NBO)
134    */
135   uint32_t retry GNUNET_PACKED;
136  
137   /**
138    * Time value that specifies the upper limit on the time interval
139    * that can elapse before the zone is no longer authoritative. (NBO)
140    */
141   uint32_t expire GNUNET_PACKED;
142
143   /**
144    * The bit minimum TTL field that should be exported with any RR
145    * from this zone. (NBO)
146    */
147   uint32_t minimum GNUNET_PACKED;
148 };
149
150
151 /**
152  * Payload of DNS SRV record (header).
153  */
154 struct srv_data
155 {
156
157   /**
158    * Preference for this entry (lower value is higher preference).  Clients
159    * will contact hosts from the lowest-priority group first and fall back
160    * to higher priorities if the low-priority entries are unavailable. (NBO)
161    */
162   uint16_t prio GNUNET_PACKED;
163
164   /**
165    * Relative weight for records with the same priority.  Clients will use
166    * the hosts of the same (lowest) priority with a probability proportional
167    * to the weight given. (NBO)
168    */
169   uint16_t weight GNUNET_PACKED;
170
171   /**
172    * TCP or UDP port of the service. (NBO)
173    */
174   uint16_t port GNUNET_PACKED;
175
176   /* followed by 'target' name */
177 };
178
179 GNUNET_NETWORK_STRUCT_END
180
181
182 /**
183  * Parse name inside of a DNS query or record.
184  *
185  * @param udp_payload entire UDP payload
186  * @param udp_payload_length length of udp_payload
187  * @param off pointer to the offset of the name to parse in the udp_payload (to be
188  *                    incremented by the size of the name)
189  * @param depth current depth of our recursion (to prevent stack overflow)
190  * @return name as 0-terminated C string on success, NULL if the payload is malformed
191  */
192 static char *
193 parse_name (const char *udp_payload,
194             size_t udp_payload_length,
195             size_t *off,
196             unsigned int depth)
197 {
198   const uint8_t *input = (const uint8_t *) udp_payload;
199   char *ret;
200   char *tmp;
201   char *xstr;
202   uint8_t len;
203   size_t xoff;
204   
205   ret = GNUNET_strdup ("");
206   while (1)
207   {
208     if (*off >= udp_payload_length)
209       goto error;
210     len = input[*off];
211     if (0 == len)
212     {
213       (*off)++;
214       break;
215     }
216     if (len < 64)
217     {
218       if (*off + 1 + len > udp_payload_length)
219         goto error;
220       GNUNET_asprintf (&tmp,
221                        "%s%.*s.",
222                        ret,
223                        (int) len,
224                        &udp_payload[*off + 1]);
225       GNUNET_free (ret);
226       ret = tmp;
227       *off += 1 + len;
228     }
229     else if ((64 | 128) == (len & (64 | 128)) )
230     {
231       if (depth > 32)
232         goto error; /* hard bound on stack to prevent "infinite" recursion, disallow! */
233       /* pointer to string */
234       if (*off + 1 > udp_payload_length)
235         goto error;
236       xoff = ((len - (64 | 128)) << 8) + input[*off+1];
237       xstr = parse_name (udp_payload,
238                          udp_payload_length,
239                          &xoff,
240                          depth + 1);
241       if (NULL == xstr)
242         goto error;
243       GNUNET_asprintf (&tmp,
244                        "%s%s.",
245                        ret,
246                        xstr);
247       GNUNET_free (ret);
248       GNUNET_free (xstr);
249       ret = tmp;
250       if (strlen (ret) > udp_payload_length)
251         goto error; /* we are looping (building an infinite string) */
252       *off += 2;
253       /* pointers always terminate names */
254       break;
255     } 
256     else
257     {
258       /* neither pointer nor inline string, not supported... */
259       goto error;
260     }
261   }
262   if (0 < strlen(ret))
263     ret[strlen(ret)-1] = '\0'; /* eat tailing '.' */
264   return ret;
265  error:  
266   GNUNET_free (ret);
267   return NULL;
268 }
269
270
271 /**
272  * Parse a DNS query entry.
273  *
274  * @param udp_payload entire UDP payload
275  * @param udp_payload_length length of udp_payload
276  * @param off pointer to the offset of the query to parse in the udp_payload (to be
277  *                    incremented by the size of the query)
278  * @param q where to write the query information
279  * @return GNUNET_OK on success, GNUNET_SYSERR if the query is malformed
280  */
281 static int
282 parse_query (const char *udp_payload,
283              size_t udp_payload_length,
284              size_t *off,
285              struct GNUNET_DNSPARSER_Query *q)
286 {
287   char *name;
288   struct query_line ql;
289
290   name = parse_name (udp_payload, 
291                      udp_payload_length,
292                      off, 0);
293   if (NULL == name)
294     return GNUNET_SYSERR;
295   q->name = name;
296   if (*off + sizeof (struct query_line) > udp_payload_length)
297     return GNUNET_SYSERR;
298   memcpy (&ql, &udp_payload[*off], sizeof (ql));
299   *off += sizeof (ql);
300   q->type = ntohs (ql.type);
301   q->class = ntohs (ql.class);
302   return GNUNET_OK;
303 }
304
305
306 /**
307  * Parse a DNS record entry.
308  *
309  * @param udp_payload entire UDP payload
310  * @param udp_payload_length length of udp_payload
311  * @param off pointer to the offset of the record to parse in the udp_payload (to be
312  *                    incremented by the size of the record)
313  * @param r where to write the record information
314  * @return GNUNET_OK on success, GNUNET_SYSERR if the record is malformed
315  */
316 static int
317 parse_record (const char *udp_payload,
318               size_t udp_payload_length,
319               size_t *off,
320               struct GNUNET_DNSPARSER_Record *r)
321 {
322   char *name;
323   struct record_line rl;
324   size_t old_off;
325   struct soa_data soa;
326   uint16_t mxpref;
327   uint16_t data_len;
328
329   name = parse_name (udp_payload, 
330                      udp_payload_length,
331                      off, 0);
332   if (NULL == name)
333     return GNUNET_SYSERR;
334   r->name = name;
335   if (*off + sizeof (struct record_line) > udp_payload_length)
336     return GNUNET_SYSERR;
337   memcpy (&rl, &udp_payload[*off], sizeof (rl));
338   (*off) += sizeof (rl);
339   r->type = ntohs (rl.type);
340   r->class = ntohs (rl.class);
341   r->expiration_time = GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
342                                                                                         ntohl (rl.ttl)));
343   data_len = ntohs (rl.data_len);
344   if (*off + data_len > udp_payload_length)
345     return GNUNET_SYSERR;
346   switch (r->type)
347   {
348   case GNUNET_DNSPARSER_TYPE_NS:
349   case GNUNET_DNSPARSER_TYPE_CNAME:
350   case GNUNET_DNSPARSER_TYPE_PTR:
351     old_off = *off;
352     r->data.hostname = parse_name (udp_payload,
353                                    udp_payload_length,
354                                    off, 0);    
355     if ( (NULL == r->data.hostname) ||
356          (old_off + data_len != *off) )
357       return GNUNET_SYSERR;
358     return GNUNET_OK;
359   case GNUNET_DNSPARSER_TYPE_SOA:
360     old_off = *off;
361     r->data.soa = GNUNET_malloc (sizeof (struct GNUNET_DNSPARSER_SoaRecord));
362     r->data.soa->mname = parse_name (udp_payload,
363                                      udp_payload_length,
364                                      off, 0);
365     r->data.soa->rname = parse_name (udp_payload,
366                                      udp_payload_length,
367                                      off, 0);
368     if ( (NULL == r->data.soa->mname) ||
369          (NULL == r->data.soa->rname) ||
370          (*off + sizeof (struct soa_data) > udp_payload_length) )
371       return GNUNET_SYSERR;
372     memcpy (&soa, &udp_payload[*off], sizeof (struct soa_data));
373     r->data.soa->serial = ntohl (soa.serial);
374     r->data.soa->refresh = ntohl (soa.refresh);
375     r->data.soa->retry = ntohl (soa.retry);
376     r->data.soa->expire = ntohl (soa.expire);
377     r->data.soa->minimum_ttl = ntohl (soa.minimum);
378     (*off) += sizeof (struct soa_data);
379     if (old_off + data_len != *off) 
380       return GNUNET_SYSERR;
381     return GNUNET_OK;
382   case GNUNET_DNSPARSER_TYPE_MX:
383     old_off = *off;
384     if (*off + sizeof (uint16_t) > udp_payload_length)
385       return GNUNET_SYSERR;
386     memcpy (&mxpref, &udp_payload[*off], sizeof (uint16_t));    
387     (*off) += sizeof (uint16_t);
388     r->data.mx = GNUNET_malloc (sizeof (struct GNUNET_DNSPARSER_MxRecord));
389     r->data.mx->preference = ntohs (mxpref);
390     r->data.mx->mxhost = parse_name (udp_payload,
391                                      udp_payload_length,
392                                      off, 0);
393     if (old_off + data_len != *off) 
394       return GNUNET_SYSERR;
395     return GNUNET_OK;
396   default:
397     r->data.raw.data = GNUNET_malloc (data_len);
398     r->data.raw.data_len = data_len;
399     memcpy (r->data.raw.data, &udp_payload[*off], data_len);
400     break;
401   }
402   (*off) += data_len;
403   return GNUNET_OK;  
404 }
405
406
407 /**
408  * Parse a UDP payload of a DNS packet in to a nice struct for further
409  * processing and manipulation.
410  *
411  * @param udp_payload wire-format of the DNS packet
412  * @param udp_payload_length number of bytes in udp_payload 
413  * @return NULL on error, otherwise the parsed packet
414  */
415 struct GNUNET_DNSPARSER_Packet *
416 GNUNET_DNSPARSER_parse (const char *udp_payload,
417                         size_t udp_payload_length)
418 {
419   struct GNUNET_DNSPARSER_Packet *p;
420   const struct GNUNET_TUN_DnsHeader *dns;
421   size_t off;
422   unsigned int n;  
423   unsigned int i;
424
425   if (udp_payload_length < sizeof (struct GNUNET_TUN_DnsHeader))
426     return NULL;
427   dns = (const struct GNUNET_TUN_DnsHeader *) udp_payload;
428   off = sizeof (struct GNUNET_TUN_DnsHeader);
429   p = GNUNET_malloc (sizeof (struct GNUNET_DNSPARSER_Packet));
430   p->flags = dns->flags;
431   p->id = dns->id;
432   n = ntohs (dns->query_count);
433   if (n > 0)
434   {
435     p->queries = GNUNET_malloc (n * sizeof (struct GNUNET_DNSPARSER_Query));
436     p->num_queries = n;
437     for (i=0;i<n;i++)
438       if (GNUNET_OK !=
439           parse_query (udp_payload,
440                        udp_payload_length,
441                        &off,
442                        &p->queries[i]))
443         goto error;
444   }
445   n = ntohs (dns->answer_rcount);
446   if (n > 0)
447   {
448     p->answers = GNUNET_malloc (n * sizeof (struct GNUNET_DNSPARSER_Record));
449     p->num_answers = n;
450     for (i=0;i<n;i++)
451       if (GNUNET_OK !=
452           parse_record (udp_payload,
453                         udp_payload_length,
454                         &off,
455                         &p->answers[i]))
456         goto error;
457   }
458   n = ntohs (dns->authority_rcount);
459   if (n > 0)
460   {
461     p->authority_records = GNUNET_malloc (n * sizeof (struct GNUNET_DNSPARSER_Record));
462     p->num_authority_records = n;
463     for (i=0;i<n;i++)
464       if (GNUNET_OK !=
465           parse_record (udp_payload,
466                         udp_payload_length,
467                         &off,
468                         &p->authority_records[i]))
469         goto error;  
470   }
471   n = ntohs (dns->additional_rcount);
472   if (n > 0)
473   {
474     p->additional_records = GNUNET_malloc (n * sizeof (struct GNUNET_DNSPARSER_Record));
475     p->num_additional_records = n;
476     for (i=0;i<n;i++)
477       if (GNUNET_OK !=
478           parse_record (udp_payload,
479                         udp_payload_length,
480                         &off,
481                         &p->additional_records[i]))
482         goto error;   
483   }
484   return p;
485  error:
486   GNUNET_DNSPARSER_free_packet (p);
487   return NULL;
488 }
489
490
491 /**
492  * Free SOA information record.
493  *
494  * @param soa record to free
495  */
496 static void
497 free_soa (struct GNUNET_DNSPARSER_SoaRecord *soa)
498 {
499   if (NULL == soa)
500     return;
501   GNUNET_free_non_null (soa->mname);
502   GNUNET_free_non_null (soa->rname);
503   GNUNET_free (soa);      
504 }
505
506
507 /**
508  * Free MX information record.
509  *
510  * @param mx record to free
511  */
512 static void
513 free_mx (struct GNUNET_DNSPARSER_MxRecord *mx)
514 {
515   if (NULL == mx)
516     return;
517   GNUNET_free_non_null (mx->mxhost);
518   GNUNET_free (mx);      
519 }
520
521
522 static void
523 free_record (struct GNUNET_DNSPARSER_Record *r)
524 {
525   GNUNET_free_non_null (r->name);
526   switch (r->type)
527   {
528   case GNUNET_DNSPARSER_TYPE_MX:
529     free_mx (r->data.mx);
530     break;
531   case GNUNET_DNSPARSER_TYPE_SOA:
532     free_soa (r->data.soa);
533     break;
534   case GNUNET_DNSPARSER_TYPE_NS:
535   case GNUNET_DNSPARSER_TYPE_CNAME:
536   case GNUNET_DNSPARSER_TYPE_PTR:
537     GNUNET_free_non_null (r->data.hostname);
538     break;
539   default:
540     GNUNET_free_non_null (r->data.raw.data);
541     break;
542   }
543 }
544
545
546 /**
547  * Free memory taken by a packet.
548  *
549  * @param p packet to free
550  */
551 void
552 GNUNET_DNSPARSER_free_packet (struct GNUNET_DNSPARSER_Packet *p)
553 {
554   unsigned int i;
555
556   for (i=0;i<p->num_queries;i++)
557     GNUNET_free_non_null (p->queries[i].name);
558   GNUNET_free_non_null (p->queries);
559   for (i=0;i<p->num_answers;i++)
560     free_record (&p->answers[i]);
561   GNUNET_free_non_null (p->answers);
562   for (i=0;i<p->num_authority_records;i++)
563     free_record (&p->authority_records[i]);
564   GNUNET_free_non_null (p->authority_records);
565   for (i=0;i<p->num_additional_records;i++)
566     free_record (&p->additional_records[i]);
567   GNUNET_free_non_null (p->additional_records);
568   GNUNET_free (p);
569 }
570
571
572 /* ********************** DNS packet assembly code **************** */
573
574
575 /**
576  * Add a DNS name to the UDP packet at the given location.
577  *
578  * @param dst where to write the name
579  * @param dst_len number of bytes in dst
580  * @param off pointer to offset where to write the name (increment by bytes used)
581  *            must not be changed if there is an error
582  * @param name name to write
583  * @return GNUNET_SYSERR if 'name' is invalid
584  *         GNUNET_NO if 'name' did not fit
585  *         GNUNET_OK if 'name' was added to 'dst'
586  */
587 static int
588 add_name (char *dst,
589           size_t dst_len,
590           size_t *off,
591           const char *name)
592 {
593   const char *dot;
594   size_t start;
595   size_t pos;
596   size_t len;
597
598   if (NULL == name)
599     return GNUNET_SYSERR;
600   start = *off;
601   if (start + strlen (name) + 2 > dst_len)
602     return GNUNET_NO;
603   pos = start;
604   do
605   {
606     dot = strchr (name, '.');
607     if (NULL == dot)
608       len = strlen (name);
609     else
610       len = dot - name;
611     if ( (len >= 64) || (len == 0) )
612       return GNUNET_NO; /* segment too long or empty */
613     dst[pos++] = (char) (uint8_t) len;
614     memcpy (&dst[pos], name, len);
615     pos += len;
616     name += len + 1; /* also skip dot */
617   }
618   while (NULL != dot);
619   dst[pos++] = '\0'; /* terminator */
620   *off = pos;
621   return GNUNET_OK;
622 }
623
624
625 /**
626  * Add a DNS query to the UDP packet at the given location.
627  *
628  * @param dst where to write the query
629  * @param dst_len number of bytes in dst
630  * @param off pointer to offset where to write the query (increment by bytes used)
631  *            must not be changed if there is an error
632  * @param query query to write
633  * @return GNUNET_SYSERR if 'query' is invalid
634  *         GNUNET_NO if 'query' did not fit
635  *         GNUNET_OK if 'query' was added to 'dst'
636  */
637 static int
638 add_query (char *dst,
639            size_t dst_len,
640            size_t *off,
641            const struct GNUNET_DNSPARSER_Query *query)
642 {
643   int ret;
644   struct query_line ql;
645
646   ret = add_name (dst, dst_len - sizeof (struct query_line), off, query->name);
647   if (ret != GNUNET_OK)
648     return ret;
649   ql.type = htons (query->type);
650   ql.class = htons (query->class);
651   memcpy (&dst[*off], &ql, sizeof (ql));
652   (*off) += sizeof (ql);
653   return GNUNET_OK;
654 }
655
656
657 /**
658  * Add an MX record to the UDP packet at the given location.
659  *
660  * @param dst where to write the mx record
661  * @param dst_len number of bytes in dst
662  * @param off pointer to offset where to write the mx information (increment by bytes used);
663  *            can also change if there was an error
664  * @param mx mx information to write
665  * @return GNUNET_SYSERR if 'mx' is invalid
666  *         GNUNET_NO if 'mx' did not fit
667  *         GNUNET_OK if 'mx' was added to 'dst'
668  */
669 static int
670 add_mx (char *dst,
671         size_t dst_len,
672         size_t *off,
673         const struct GNUNET_DNSPARSER_MxRecord *mx)
674 {
675   uint16_t mxpref;
676
677   if (*off + sizeof (uint16_t) > dst_len)
678     return GNUNET_NO;
679   mxpref = htons (mx->preference);
680   memcpy (&dst[*off], &mxpref, sizeof (mxpref));
681   (*off) += sizeof (mxpref);
682   return add_name (dst, dst_len, off, mx->mxhost);
683 }
684
685
686 /**
687  * Add an SOA record to the UDP packet at the given location.
688  *
689  * @param dst where to write the SOA record
690  * @param dst_len number of bytes in dst
691  * @param off pointer to offset where to write the SOA information (increment by bytes used)
692  *            can also change if there was an error
693  * @param soa SOA information to write
694  * @return GNUNET_SYSERR if 'soa' is invalid
695  *         GNUNET_NO if 'soa' did not fit
696  *         GNUNET_OK if 'soa' was added to 'dst'
697  */
698 static int
699 add_soa (char *dst,
700          size_t dst_len,
701          size_t *off,
702          const struct GNUNET_DNSPARSER_SoaRecord *soa)
703 {
704   struct soa_data sd;
705   int ret;
706
707   if ( (GNUNET_OK != (ret = add_name (dst,
708                                       dst_len,
709                                       off,
710                                       soa->mname))) ||
711        (GNUNET_OK != (ret = add_name (dst,
712                                       dst_len,
713                                       off,
714                                       soa->rname)) ) )
715     return ret;
716   if (*off + sizeof (struct soa_data) > dst_len)
717     return GNUNET_NO;
718   sd.serial = htonl (soa->serial);
719   sd.refresh = htonl (soa->refresh);
720   sd.retry = htonl (soa->retry);
721   sd.expire = htonl (soa->expire);
722   sd.minimum = htonl (soa->minimum_ttl);
723   memcpy (&dst[*off], &sd, sizeof (sd));
724   (*off) += sizeof (sd);
725   return GNUNET_OK;
726 }
727
728
729 /**
730  * Add a DNS record to the UDP packet at the given location.
731  *
732  * @param dst where to write the query
733  * @param dst_len number of bytes in dst
734  * @param off pointer to offset where to write the query (increment by bytes used)
735  *            must not be changed if there is an error
736  * @param record record to write
737  * @return GNUNET_SYSERR if 'record' is invalid
738  *         GNUNET_NO if 'record' did not fit
739  *         GNUNET_OK if 'record' was added to 'dst'
740  */
741 static int
742 add_record (char *dst,
743             size_t dst_len,
744             size_t *off,
745             const struct GNUNET_DNSPARSER_Record *record)
746 {
747   int ret;
748   size_t start;
749   size_t pos;
750   struct record_line rl;
751
752   start = *off;
753   ret = add_name (dst, dst_len - sizeof (struct record_line), off, record->name);
754   if (ret != GNUNET_OK)
755     return ret;
756   /* '*off' is now the position where we will need to write the record line */
757
758   pos = *off + sizeof (struct record_line);
759   switch (record->type)
760   { 
761   case GNUNET_DNSPARSER_TYPE_MX:
762     ret = add_mx (dst, dst_len, &pos, record->data.mx);    
763     break;
764   case GNUNET_DNSPARSER_TYPE_SOA:
765     ret = add_soa (dst, dst_len, &pos, record->data.soa);
766     break;
767   case GNUNET_DNSPARSER_TYPE_NS:
768   case GNUNET_DNSPARSER_TYPE_CNAME:
769   case GNUNET_DNSPARSER_TYPE_PTR:
770     ret = add_name (dst, dst_len, &pos, record->data.hostname);
771     break;
772   default:
773     if (pos + record->data.raw.data_len > dst_len)
774     {
775       ret = GNUNET_NO;
776       break;
777     }
778     memcpy (&dst[pos], record->data.raw.data, record->data.raw.data_len);
779     pos += record->data.raw.data_len;
780     ret = GNUNET_OK;
781     break;
782   }
783   if (ret != GNUNET_OK)
784   {
785     *off = start;
786     return GNUNET_NO;
787   }
788
789   if (pos - (*off + sizeof (struct record_line)) > UINT16_MAX)
790   {
791     /* record data too long */
792     *off = start;
793     return GNUNET_NO;
794   }
795   rl.type = htons (record->type);
796   rl.class = htons (record->class);
797   rl.ttl = htonl (GNUNET_TIME_absolute_get_remaining (record->expiration_time).rel_value / 1000); /* in seconds */
798   rl.data_len = htons ((uint16_t) (pos - (*off + sizeof (struct record_line))));
799   memcpy (&dst[*off], &rl, sizeof (struct record_line));
800   *off = pos;
801   return GNUNET_OK;  
802 }
803
804
805 /**
806  * Given a DNS packet, generate the corresponding UDP payload.
807  * Note that we do not attempt to pack the strings with pointers
808  * as this would complicate the code and this is about being 
809  * simple and secure, not fast, fancy and broken like bind.
810  *
811  * @param p packet to pack
812  * @param max maximum allowed size for the resulting UDP payload
813  * @param buf set to a buffer with the packed message
814  * @param buf_length set to the length of buf
815  * @return GNUNET_SYSERR if 'p' is invalid
816  *         GNUNET_NO if 'p' was truncated (but there is still a result in 'buf')
817  *         GNUNET_OK if 'p' was packed completely into '*buf'
818  */
819 int
820 GNUNET_DNSPARSER_pack (const struct GNUNET_DNSPARSER_Packet *p,
821                        uint16_t max,
822                        char **buf,
823                        size_t *buf_length)
824 {  
825   struct GNUNET_TUN_DnsHeader dns;
826   size_t off;
827   char tmp[max];
828   unsigned int i;
829   int ret;
830   int trc;
831   
832   if ( (p->num_queries > UINT16_MAX) ||
833        (p->num_answers > UINT16_MAX) ||
834        (p->num_authority_records > UINT16_MAX) ||
835        (p->num_additional_records > UINT16_MAX) )
836     return GNUNET_SYSERR;
837   dns.id = p->id;
838   dns.flags = p->flags;
839   dns.query_count = htons (p->num_queries);
840   dns.answer_rcount = htons (p->num_answers);
841   dns.authority_rcount = htons (p->num_authority_records);
842   dns.additional_rcount = htons (p->num_additional_records);
843
844   off = sizeof (struct GNUNET_TUN_DnsHeader);
845   trc = GNUNET_NO;
846   for (i=0;i<p->num_queries;i++)
847   {
848     ret = add_query (tmp, sizeof (tmp), &off, &p->queries[i]);  
849     if (GNUNET_SYSERR == ret)
850       return GNUNET_SYSERR;
851     if (GNUNET_NO == ret)
852     {
853       dns.query_count = htons ((uint16_t) (i-1));
854       trc = GNUNET_YES;      
855       break;
856     }
857   }
858   for (i=0;i<p->num_answers;i++)
859   {
860     ret = add_record (tmp, sizeof (tmp), &off, &p->answers[i]);  
861     if (GNUNET_SYSERR == ret)
862       return GNUNET_SYSERR;
863     if (GNUNET_NO == ret)
864     {
865       dns.answer_rcount = htons ((uint16_t) (i-1));
866       trc = GNUNET_YES;      
867       break;
868     }
869   }
870   for (i=0;i<p->num_authority_records;i++)
871   {
872     ret = add_record (tmp, sizeof (tmp), &off, &p->authority_records[i]);  
873     if (GNUNET_SYSERR == ret)
874       return GNUNET_SYSERR;
875     if (GNUNET_NO == ret)
876     {
877       dns.authority_rcount = htons ((uint16_t) (i-1));
878       trc = GNUNET_YES;      
879       break;
880     }
881   }
882   for (i=0;i<p->num_additional_records;i++)
883   {
884     ret = add_record (tmp, sizeof (tmp), &off, &p->additional_records[i]);  
885     if (GNUNET_SYSERR == ret)
886       return GNUNET_SYSERR;
887     if (GNUNET_NO == ret)
888     {
889       dns.additional_rcount = htons (i-1);
890       trc = GNUNET_YES;      
891       break;
892     }
893   }
894
895   if (GNUNET_YES == trc)
896     dns.flags.message_truncated = 1;    
897   memcpy (tmp, &dns, sizeof (struct GNUNET_TUN_DnsHeader));
898
899   *buf = GNUNET_malloc (off);
900   *buf_length = off;
901   memcpy (*buf, tmp, off);
902   if (GNUNET_YES == trc)
903     return GNUNET_NO;
904   return GNUNET_OK;
905 }
906
907 /* end of dnsparser.c */