memory-leaks
[oweals/gnunet.git] / src / vpn / gnunet-service-dns.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 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 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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file vpn/gnunet-service-dns.c
23  * @author Philipp Toelke
24  */
25 #include "platform.h"
26 #include "gnunet_getopt_lib.h"
27 #include "gnunet_service_lib.h"
28 #include <gnunet_constants.h>
29 #include "gnunet_network_lib.h"
30 #include "gnunet_os_lib.h"
31 #include "gnunet-service-dns-p.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_applications.h"
34 #include "gnunet-vpn-packet.h"
35 #include "gnunet_container_lib.h"
36 #include "gnunet-dns-parser.h"
37 #include "gnunet_dht_service.h"
38 #include "gnunet_block_lib.h"
39 #include "block_dns.h"
40 #include "gnunet_crypto_lib.h"
41 #include "gnunet_mesh_service.h"
42 #include "gnunet_signatures.h"
43
44 struct GNUNET_MESH_Handle *mesh_handle;
45
46 /**
47  * The tunnel to send queries
48  */
49 static struct GNUNET_MESH_Tunnel* dns_tunnel;
50
51 /**
52  * The UDP-Socket through which DNS-Resolves will be sent if they are not to be
53  * sent through gnunet. The port of this socket will not be hijacked.
54  */
55 static struct GNUNET_NETWORK_Handle *dnsout;
56
57 /**
58  * The port bound to the socket dnsout
59  */
60 static unsigned short dnsoutport;
61
62 /**
63  * A handle to the DHT-Service
64  */
65 static struct GNUNET_DHT_Handle *dht;
66
67 /**
68  * The configuration to use
69  */
70 static const struct GNUNET_CONFIGURATION_Handle *cfg;
71
72 /**
73  * A list of DNS-Responses that have to be sent to the requesting client
74  */
75 static struct answer_packet_list *head;
76
77 /**
78  * The tail of the list of DNS-responses
79  */
80 static struct answer_packet_list *tail;
81
82 /**
83  * A structure containing a mapping from network-byte-ordered DNS-id (16 bit) to
84  * some information needed to handle this query
85  *
86  * It currently allocates at least
87  * (1 + machine-width + machine-width + 32 + 32 + 16 + machine-width + 8) * 65536 bit
88  * = 17 MiB on 64 bit.
89  * = 11 MiB on 32 bit.
90  */
91 static struct {
92     unsigned valid:1;
93     struct GNUNET_SERVER_Client* client;
94     struct GNUNET_MESH_Tunnel *tunnel;
95     uint32_t local_ip;
96     uint32_t remote_ip;
97     uint16_t local_port;
98     char* name;
99     uint8_t namelen;
100 } query_states[UINT16_MAX];
101
102 /**
103  * A struct used to give more than one value as
104  * closure to receive_dht
105  */
106 struct receive_dht_cls {
107     uint16_t id;
108     struct GNUNET_DHT_GetHandle* handle;
109 };
110
111 struct tunnel_notify_queue
112 {
113   struct tunnel_notify_queue* next;
114   struct tunnel_notify_queue* prev;
115   void* cls;
116   size_t len;
117   GNUNET_CONNECTION_TransmitReadyNotify cb;
118 };
119
120 /**
121  * Hijack all outgoing DNS-Traffic but for traffic leaving "our" port.
122  */
123 static void
124 hijack (void *cls __attribute__((unused)), const struct GNUNET_SCHEDULER_TaskContext *tc)
125 {
126   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
127     return;
128
129   if (0 == dnsoutport)
130     {
131       GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Delaying the hijacking, port is still %d!\n", dnsoutport);
132       GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, hijack, NULL);
133       return;
134     }
135
136   char port_s[6];
137   char *virt_dns;
138   struct GNUNET_OS_Process *proc;
139
140   if (GNUNET_SYSERR ==
141       GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "VIRTDNS",
142                                              &virt_dns))
143     {
144       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
145                   "No entry 'VIRTDNS' in configuration!\n");
146       exit (1);
147     }
148
149   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Hijacking, port is %d\n", dnsoutport);
150   snprintf (port_s, 6, "%d", dnsoutport);
151   if (NULL != (proc = GNUNET_OS_start_process (NULL,
152                                                NULL,
153                                                "gnunet-helper-hijack-dns",
154                                                "gnunet-hijack-dns",
155                                                port_s, virt_dns, NULL)))
156     GNUNET_OS_process_close (proc);
157   GNUNET_free (virt_dns);
158 }
159
160 /**
161  * Delete the hijacking-routes
162  */
163 static void
164 unhijack (unsigned short port)
165 {
166   char port_s[6];
167   char *virt_dns;
168   struct GNUNET_OS_Process *proc;
169
170   if (GNUNET_SYSERR ==
171       GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "VIRTDNS",
172                                              &virt_dns))
173     {
174       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
175                   "No entry 'VIRTDNS' in configuration!\n");
176       exit (1);
177     }
178
179   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "unHijacking, port is %d\n", port);
180   snprintf (port_s, 6, "%d", port);
181   if (NULL != (proc = GNUNET_OS_start_process (NULL,
182                                                NULL,
183                                                "gnunet-helper-hijack-dns",
184                                                "gnunet-hijack-dns",
185                                                "-d", port_s, virt_dns, NULL)))
186     GNUNET_OS_process_close (proc);
187   GNUNET_free (virt_dns);
188 }
189
190 /**
191  * Send the DNS-Response to the client. Gets called via the notify_transmit_ready-
192  * system.
193  */
194 static size_t
195 send_answer(void* cls, size_t size, void* buf) {
196     struct answer_packet_list* query = head;
197     size_t len = ntohs(query->pkt.hdr.size);
198
199     GNUNET_assert(len <= size);
200
201     memcpy(buf, &query->pkt.hdr, len);
202
203     GNUNET_CONTAINER_DLL_remove (head, tail, query);
204
205     GNUNET_free(query);
206
207     /* When more data is to be sent, reschedule */
208     if (head != NULL)
209       GNUNET_SERVER_notify_transmit_ready(cls,
210                                           ntohs(head->pkt.hdr.size),
211                                           GNUNET_TIME_UNIT_FOREVER_REL,
212                                           &send_answer,
213                                           cls);
214
215     return len;
216 }
217
218 struct tunnel_cls {
219     struct GNUNET_MESH_Tunnel *tunnel GNUNET_PACKED;
220     struct GNUNET_MessageHeader hdr;
221     struct dns_pkt dns;
222 };
223
224 struct tunnel_cls *remote_pending[UINT16_MAX];
225
226 static size_t
227 mesh_send_response (void *cls, size_t size, void *buf)
228 {
229   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
230   struct GNUNET_MessageHeader *hdr = buf;
231   uint32_t *sz = cls;
232   struct GNUNET_MESH_Tunnel **tunnel = (struct GNUNET_MESH_Tunnel**)(sz+1);
233   struct dns_pkt *dns = (struct dns_pkt *) (tunnel + 1);
234   hdr->type = htons (GNUNET_MESSAGE_TYPE_REMOTE_ANSWER_DNS);
235   hdr->size = htons (*sz + sizeof (struct GNUNET_MessageHeader));
236
237   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
238               "Sending response, size=%d, sz=%d, sz+hdr=%d\n", size, *sz,
239               *sz + sizeof (struct GNUNET_MessageHeader));
240
241   GNUNET_assert (size >= (*sz + sizeof (struct GNUNET_MessageHeader)));
242
243   memcpy (hdr + 1, dns, *sz);
244
245   if (NULL != GNUNET_MESH_tunnel_get_head(*tunnel))
246     {
247       struct tunnel_notify_queue* element = GNUNET_MESH_tunnel_get_head(*tunnel);
248       struct tunnel_notify_queue* head = GNUNET_MESH_tunnel_get_head(*tunnel);
249       struct tunnel_notify_queue* tail = GNUNET_MESH_tunnel_get_tail(*tunnel);
250
251       GNUNET_CONTAINER_DLL_remove(head, tail, element);
252
253       GNUNET_MESH_tunnel_set_head(*tunnel, head);
254       GNUNET_MESH_tunnel_set_tail(*tunnel, tail);
255       struct GNUNET_MESH_TransmitHandle* th = GNUNET_MESH_notify_transmit_ready (*tunnel,
256                                                                                  GNUNET_NO,
257                                                                                  42,
258                                                                                  GNUNET_TIME_relative_divide
259                                                                                  (GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
260                                                                                  (const struct GNUNET_PeerIdentity *)
261                                                                                  NULL, element->len,
262                                                                                  element->cb, element->cls);
263       /* save the handle */
264       GNUNET_MESH_tunnel_set_data(*tunnel, th);
265     }
266
267   GNUNET_free (cls);
268
269   return ntohs (hdr->size);
270 }
271
272 static size_t
273 mesh_send (void *cls, size_t size, void *buf)
274 {
275   struct tunnel_cls *cls_ = (struct tunnel_cls *) cls;
276   GNUNET_MESH_tunnel_set_data(cls_->tunnel, NULL);
277
278   GNUNET_assert(cls_->hdr.size <= size);
279
280   size = cls_->hdr.size;
281   cls_->hdr.size = htons(cls_->hdr.size);
282
283   memcpy(buf, &cls_->hdr, size);
284
285   if (NULL != GNUNET_MESH_tunnel_get_head(cls_->tunnel))
286     {
287       struct tunnel_notify_queue* element = GNUNET_MESH_tunnel_get_head(cls_->tunnel);
288       struct tunnel_notify_queue* head = GNUNET_MESH_tunnel_get_head(cls_->tunnel);
289       struct tunnel_notify_queue* tail = GNUNET_MESH_tunnel_get_tail(cls_->tunnel);
290
291       GNUNET_CONTAINER_DLL_remove(head, tail, element);
292
293       GNUNET_MESH_tunnel_set_head(cls_->tunnel, head);
294       GNUNET_MESH_tunnel_set_tail(cls_->tunnel, tail);
295       struct GNUNET_MESH_TransmitHandle* th = GNUNET_MESH_notify_transmit_ready (cls_->tunnel,
296                                                                                  GNUNET_NO,
297                                                                                  42,
298                                                                                  GNUNET_TIME_relative_divide
299                                                                                  (GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
300                                                                                  (const struct GNUNET_PeerIdentity *)
301                                                                                  NULL, element->len,
302                                                                                  element->cb, element->cls);
303       /* save the handle */
304       GNUNET_MESH_tunnel_set_data(cls_->tunnel, th);
305       GNUNET_free(element);
306     }
307
308   return size;
309 }
310
311
312 void
313 mesh_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
314               const struct GNUNET_TRANSPORT_ATS_Information *atsi
315               __attribute__ ((unused)))
316 {
317   if (NULL == peer)
318     return;
319   struct tunnel_cls *cls_ = (struct tunnel_cls *) cls;
320   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
321               "Connected to peer %s, sending query with id %d\n",
322               GNUNET_i2s (peer), ntohs (cls_->dns.s.id));
323
324   if (NULL == GNUNET_MESH_tunnel_get_data (cls_->tunnel))
325     {
326       struct GNUNET_MESH_TransmitHandle *th =
327         GNUNET_MESH_notify_transmit_ready (cls_->tunnel,
328                                            GNUNET_YES,
329                                            42,
330                                            GNUNET_TIME_UNIT_MINUTES,
331                                            NULL,
332                                            cls_->hdr.size,
333                                            mesh_send,
334                                            cls);
335
336       GNUNET_MESH_tunnel_set_data (cls_->tunnel, th);
337     }
338   else
339     {
340       struct tunnel_notify_queue* head = GNUNET_MESH_tunnel_get_head(cls_->tunnel);
341       struct tunnel_notify_queue* tail = GNUNET_MESH_tunnel_get_tail(cls_->tunnel);
342
343       struct tunnel_notify_queue* element = GNUNET_malloc(sizeof(struct tunnel_notify_queue));
344       element->cls = cls;
345       element->len = cls_->hdr.size;
346       element->cb = mesh_send;
347
348       GNUNET_CONTAINER_DLL_insert_tail(head, tail, element);
349       GNUNET_MESH_tunnel_set_head(cls_->tunnel, head);
350       GNUNET_MESH_tunnel_set_tail(cls_->tunnel, tail);
351     }
352 }
353
354
355 static void
356 send_mesh_query (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
357 {
358   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
359     return;
360
361   struct tunnel_cls *cls_ = (struct tunnel_cls*)cls;
362
363   if (NULL == dns_tunnel)
364     dns_tunnel = GNUNET_MESH_peer_request_connect_by_type(mesh_handle,
365                                                           GNUNET_TIME_UNIT_HOURS,
366                                                           GNUNET_APPLICATION_TYPE_INTERNET_RESOLVER,
367                                                           mesh_connect,
368                                                           NULL,
369                                                           cls_);
370   cls_->tunnel = dns_tunnel;
371   remote_pending[cls_->dns.s.id] = cls_;
372 }
373
374 static int
375 receive_mesh_query (void *cls __attribute__((unused)),
376                     struct GNUNET_MESH_Tunnel *tunnel,
377                     void **ctx __attribute__((unused)),
378                     const struct GNUNET_PeerIdentity *sender __attribute__((unused)),
379                     const struct GNUNET_MessageHeader *message,
380                     const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
381 {
382   struct dns_pkt *dns = (struct dns_pkt*)(message + 1);
383
384   struct sockaddr_in dest;
385   memset(&dest, 0, sizeof dest);
386   dest.sin_port = htons(53);
387   /* TODO: read from config */
388   inet_pton(AF_INET, "8.8.8.8", &dest.sin_addr);
389
390   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Querying for remote, id=%d\n", ntohs(dns->s.id));
391   query_states[dns->s.id].tunnel = tunnel;
392   query_states[dns->s.id].valid = GNUNET_YES;
393
394   GNUNET_NETWORK_socket_sendto(dnsout,
395                                dns,
396                                ntohs(message->size) - sizeof(struct GNUNET_MessageHeader),
397                                (struct sockaddr*) &dest,
398                                sizeof dest);
399
400   return GNUNET_SYSERR;
401 }
402
403 static int
404 receive_mesh_answer (void *cls __attribute__((unused)),
405                      struct GNUNET_MESH_Tunnel *tunnel,
406                      void **ctx __attribute__((unused)),
407                      const struct GNUNET_PeerIdentity *sender,
408                      const struct GNUNET_MessageHeader *message,
409                      const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
410 {
411   /* TODo: size check */
412   struct dns_pkt *dns = (struct dns_pkt *) (message + 1);
413
414   /* They sent us a packet we were not waiting for */
415   if (remote_pending[dns->s.id] == NULL
416       || remote_pending[dns->s.id]->tunnel != tunnel)
417     return GNUNET_OK;
418
419   GNUNET_free(remote_pending[dns->s.id]);
420   remote_pending[dns->s.id] = NULL;
421
422   if (query_states[dns->s.id].valid != GNUNET_YES)
423     return GNUNET_SYSERR;
424   query_states[dns->s.id].valid = GNUNET_NO;
425
426   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received answer from peer %s, dns-id %d\n", GNUNET_i2s(sender), ntohs(dns->s.id));
427
428   size_t len = sizeof (struct answer_packet) - 1 + sizeof (struct dns_static) + query_states[dns->s.id].namelen + sizeof (struct dns_query_line) + 2    /* To hold the pointer (as defined in RFC1035) to the name */
429     + sizeof (struct dns_record_line) - 1 + 16; /* To hold the IPv6-Address */
430
431   struct answer_packet_list *answer =
432     GNUNET_malloc (len + 2 * sizeof (struct answer_packet_list *));
433   memset (answer, 0, len + 2 * sizeof (struct answer_packet_list *));
434
435   answer->pkt.hdr.type = htons (GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS);
436   answer->pkt.hdr.size = htons (len);
437
438   struct dns_pkt_parsed* pdns = parse_dns_packet(dns);
439
440   if (ntohs(pdns->s.ancount) < 1)
441     {
442       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Answer only contains %d answers.\n", ntohs(pdns->s.ancount));
443       free_parsed_dns_packet(pdns);
444       return GNUNET_OK;
445     }
446
447   answer->pkt.addrsize = ntohs(pdns->answers[0]->data_len);
448   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "The first answer has the addrlen %d\n", answer->pkt.addrsize);
449   memcpy(answer->pkt.addr, pdns->answers[0]->data, ntohs(pdns->answers[0]->data_len));
450
451   answer->pkt.from = query_states[dns->s.id].remote_ip;
452
453   answer->pkt.to = query_states[dns->s.id].local_ip;
454   answer->pkt.dst_port = query_states[dns->s.id].local_port;
455
456   struct dns_pkt *dpkt = (struct dns_pkt *) answer->pkt.data;
457
458   dpkt->s.id = dns->s.id;
459   dpkt->s.aa = 1;
460   dpkt->s.qr = 1;
461   dpkt->s.ra = 1;
462   dpkt->s.qdcount = htons (1);
463   dpkt->s.ancount = htons (1);
464
465   memcpy (dpkt->data, query_states[dns->s.id].name,
466           query_states[dns->s.id].namelen);
467   GNUNET_free (query_states[dns->s.id].name);
468
469   struct dns_query_line *dque =
470     (struct dns_query_line *) (dpkt->data +
471                                (query_states[dns->s.id].namelen));
472
473   struct dns_record_line *drec_data =
474     (struct dns_record_line *) (dpkt->data +
475                                 (query_states[dns->s.id].namelen) +
476                                 sizeof (struct dns_query_line) + 2);
477   if (16 == answer->pkt.addrsize)
478     {
479       answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_REMOTE_AAAA;
480       dque->type = htons (28);      /* AAAA */
481       drec_data->type = htons (28); /* AAAA */
482       drec_data->data_len = htons (16);
483     }
484   else
485     {
486       answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_REMOTE_A;
487       dque->type = htons (1);      /* A */
488       drec_data->type = htons (1); /* A*/
489       drec_data->data_len = htons (4);
490     }
491   dque->class = htons (1);      /* IN */
492
493   char *anname =
494     (char *) (dpkt->data + (query_states[dns->s.id].namelen) +
495               sizeof (struct dns_query_line));
496   memcpy (anname, "\xc0\x0c", 2);
497   drec_data->class = htons (1); /* IN */
498
499   drec_data->ttl = pdns->answers[0]->ttl;
500
501   /* Calculate at which offset in the packet the IPv6-Address belongs, it is
502    * filled in by the daemon-vpn */
503   answer->pkt.addroffset =
504     htons ((unsigned short) ((unsigned long) (&drec_data->data) -
505                              (unsigned long) (&answer->pkt)));
506
507   GNUNET_CONTAINER_DLL_insert_after (head, tail, tail, answer);
508
509   GNUNET_SERVER_notify_transmit_ready (query_states[dns->s.id].client,
510                                        len,
511                                        GNUNET_TIME_UNIT_FOREVER_REL,
512                                        &send_answer,
513                                        query_states[dns->s.id].client);
514
515   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sent answer of length %d on to client, addroffset = %d\n", len, answer->pkt.addroffset);
516
517   free_parsed_dns_packet(pdns);
518   return GNUNET_OK;
519 }
520
521
522 static void
523 send_rev_query(void * cls, const struct GNUNET_SCHEDULER_TaskContext *tc) {
524     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
525       return;
526
527     struct dns_pkt_parsed* pdns = (struct dns_pkt_parsed*) cls;
528
529     unsigned short id = pdns->s.id;
530
531     free_parsed_dns_packet(pdns);
532
533     if (query_states[id].valid != GNUNET_YES) return;
534     query_states[id].valid = GNUNET_NO;
535
536     GNUNET_assert(query_states[id].namelen == 74);
537
538     size_t len = sizeof(struct answer_packet) - 1 \
539                  + sizeof(struct dns_static) \
540                  + 74 /* this is the length of a reverse ipv6-lookup */ \
541                  + sizeof(struct dns_query_line) \
542                  + 2 /* To hold the pointer (as defined in RFC1035) to the name */ \
543                  + sizeof(struct dns_record_line) - 1 \
544                  - 2 /* We do not know the lenght of the answer yet*/;
545
546     struct answer_packet_list* answer = GNUNET_malloc(len + 2*sizeof(struct answer_packet_list*));
547     memset(answer, 0, len + 2*sizeof(struct answer_packet_list*));
548
549     answer->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS);
550     answer->pkt.hdr.size = htons(len);
551     answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_REV;
552
553     answer->pkt.from = query_states[id].remote_ip;
554
555     answer->pkt.to = query_states[id].local_ip;
556     answer->pkt.dst_port = query_states[id].local_port;
557
558     struct dns_pkt *dpkt = (struct dns_pkt*)answer->pkt.data;
559
560     dpkt->s.id = id;
561     dpkt->s.aa = 1;
562     dpkt->s.qr = 1;
563     dpkt->s.ra = 1;
564     dpkt->s.qdcount = htons(1);
565     dpkt->s.ancount = htons(1);
566
567     memcpy(dpkt->data, query_states[id].name, query_states[id].namelen);
568     GNUNET_free(query_states[id].name);
569
570     struct dns_query_line* dque = (struct dns_query_line*)(dpkt->data+(query_states[id].namelen));
571     dque->type = htons(12); /* PTR */
572     dque->class = htons(1); /* IN */
573
574     char* anname = (char*)(dpkt->data+(query_states[id].namelen)+sizeof(struct dns_query_line));
575     memcpy(anname, "\xc0\x0c", 2);
576
577     struct dns_record_line *drec_data = (struct dns_record_line*)(dpkt->data+(query_states[id].namelen)+sizeof(struct dns_query_line)+2);
578     drec_data->type = htons(12); /* AAAA */
579     drec_data->class = htons(1); /* IN */
580     /* FIXME: read the TTL from block:
581      * GNUNET_TIME_absolute_get_remaining(rec->expiration_time)
582      *
583      * But how to get the seconds out of this?
584      */
585     drec_data->ttl = htonl(3600);
586
587     /* Calculate at which offset in the packet the length of the name and the
588      * name, it is filled in by the daemon-vpn */
589     answer->pkt.addroffset = htons((unsigned short)((unsigned long)(&drec_data->data_len)-(unsigned long)(&answer->pkt)));
590
591     GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, answer);
592
593     GNUNET_SERVER_notify_transmit_ready(query_states[id].client,
594                                         len,
595                                         GNUNET_TIME_UNIT_FOREVER_REL,
596                                         &send_answer,
597                                         query_states[id].client);
598 }
599
600 /**
601  * Receive a block from the dht.
602  */
603 static void
604 receive_dht(void *cls,
605             struct GNUNET_TIME_Absolute exp __attribute__((unused)),
606             const GNUNET_HashCode *key __attribute__((unused)),
607             const struct GNUNET_PeerIdentity *const *get_path __attribute__((unused)),
608             const struct GNUNET_PeerIdentity *const *put_path __attribute__((unused)),
609             enum GNUNET_BLOCK_Type type,
610             size_t size,
611             const void *data) {
612
613     unsigned short id = ((struct receive_dht_cls*)cls)->id;
614     struct GNUNET_DHT_GetHandle* handle = ((struct receive_dht_cls*)cls)->handle;
615     GNUNET_free(cls);
616
617     GNUNET_assert(type == GNUNET_BLOCK_TYPE_DNS);
618
619     /* If no query with this id is pending, ignore the block */
620     if (query_states[id].valid != GNUNET_YES) return;
621     query_states[id].valid = GNUNET_NO;
622
623     const struct GNUNET_DNS_Record* rec = data;
624     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
625                "Got block of size %d, peer: %08x, desc: %08x\n",
626                size,
627                *((unsigned int*)&rec->peer),
628                *((unsigned int*)&rec->service_descriptor));
629
630     size_t len = sizeof(struct answer_packet) - 1 \
631                  + sizeof(struct dns_static) \
632                  + query_states[id].namelen \
633                  + sizeof(struct dns_query_line) \
634                  + 2 /* To hold the pointer (as defined in RFC1035) to the name */ \
635                  + sizeof(struct dns_record_line) - 1 \
636                  + 16; /* To hold the IPv6-Address */
637
638     struct answer_packet_list* answer = GNUNET_malloc(len + 2*sizeof(struct answer_packet_list*));
639     memset(answer, 0, len + 2*sizeof(struct answer_packet_list*));
640
641     answer->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS);
642     answer->pkt.hdr.size = htons(len);
643     answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_SERVICE;
644
645     GNUNET_CRYPTO_hash(&rec->peer,
646                        sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
647                        &answer->pkt.service_descr.peer);
648
649     memcpy(&answer->pkt.service_descr.service_descriptor,
650            &rec->service_descriptor,
651            sizeof(GNUNET_HashCode));
652     memcpy(&answer->pkt.service_descr.service_type,
653            &rec->service_type,
654            sizeof(answer->pkt.service_descr.service_type));
655     memcpy(&answer->pkt.service_descr.ports, &rec->ports, sizeof(answer->pkt.service_descr.ports));
656
657     answer->pkt.from = query_states[id].remote_ip;
658
659     answer->pkt.to = query_states[id].local_ip;
660     answer->pkt.dst_port = query_states[id].local_port;
661
662     struct dns_pkt *dpkt = (struct dns_pkt*)answer->pkt.data;
663
664     dpkt->s.id = id;
665     dpkt->s.aa = 1;
666     dpkt->s.qr = 1;
667     dpkt->s.ra = 1;
668     dpkt->s.qdcount = htons(1);
669     dpkt->s.ancount = htons(1);
670
671     memcpy(dpkt->data, query_states[id].name, query_states[id].namelen);
672     GNUNET_free(query_states[id].name);
673
674     struct dns_query_line* dque = (struct dns_query_line*)(dpkt->data+(query_states[id].namelen));
675     dque->type = htons(28); /* AAAA */
676     dque->class = htons(1); /* IN */
677
678     char* anname = (char*)(dpkt->data+(query_states[id].namelen)+sizeof(struct dns_query_line));
679     memcpy(anname, "\xc0\x0c", 2);
680
681     struct dns_record_line *drec_data = (struct dns_record_line*)(dpkt->data+(query_states[id].namelen)+sizeof(struct dns_query_line)+2);
682     drec_data->type = htons(28); /* AAAA */
683     drec_data->class = htons(1); /* IN */
684
685     /* FIXME: read the TTL from block:
686      * GNUNET_TIME_absolute_get_remaining(rec->expiration_time)
687      *
688      * But how to get the seconds out of this?
689      */
690     drec_data->ttl = htonl(3600);
691     drec_data->data_len = htons(16);
692
693     /* Calculate at which offset in the packet the IPv6-Address belongs, it is
694      * filled in by the daemon-vpn */
695     answer->pkt.addroffset = htons((unsigned short)((unsigned long)(&drec_data->data)-(unsigned long)(&answer->pkt)));
696
697     GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, answer);
698
699     GNUNET_SERVER_notify_transmit_ready(query_states[id].client,
700                                         len,
701                                         GNUNET_TIME_UNIT_FOREVER_REL,
702                                         &send_answer,
703                                         query_states[id].client);
704
705     GNUNET_DHT_get_stop(handle);
706 }
707
708 /**
709  * This receives a GNUNET_MESSAGE_TYPE_REHIJACK and rehijacks the DNS
710  */
711 static void
712 rehijack(void *cls __attribute__((unused)),
713          struct GNUNET_SERVER_Client *client,
714          const struct GNUNET_MessageHeader *message __attribute__((unused))) {
715     unhijack(dnsoutport);
716     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, hijack, NULL);
717
718     GNUNET_SERVER_receive_done(client, GNUNET_OK);
719 }
720
721 /**
722  * This receives the dns-payload from the daemon-vpn and sends it on over the udp-socket
723  */
724 static void
725 receive_query(void *cls __attribute__((unused)),
726               struct GNUNET_SERVER_Client *client,
727               const struct GNUNET_MessageHeader *message) {
728     struct query_packet* pkt = (struct query_packet*)message;
729     struct dns_pkt* dns = (struct dns_pkt*)pkt->data;
730     struct dns_pkt_parsed* pdns = parse_dns_packet(dns);
731
732     query_states[dns->s.id].valid = GNUNET_YES;
733     query_states[dns->s.id].client = client;
734     query_states[dns->s.id].local_ip = pkt->orig_from;
735     query_states[dns->s.id].local_port = pkt->src_port;
736     query_states[dns->s.id].remote_ip = pkt->orig_to;
737     query_states[dns->s.id].namelen = strlen((char*)dns->data) + 1;
738     if (query_states[dns->s.id].name != NULL)
739       GNUNET_free(query_states[dns->s.id].name);
740     query_states[dns->s.id].name = GNUNET_malloc(query_states[dns->s.id].namelen);
741     memcpy(query_states[dns->s.id].name, dns->data, query_states[dns->s.id].namelen);
742
743     /* The query is for a .gnunet-address */
744     if (pdns->queries[0]->namelen > 9 &&
745         0 == strncmp(pdns->queries[0]->name+(pdns->queries[0]->namelen - 9), ".gnunet.", 9))
746       {
747         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Query for .gnunet!\n");
748         GNUNET_HashCode key;
749         GNUNET_CRYPTO_hash(pdns->queries[0]->name, pdns->queries[0]->namelen, &key);
750
751         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
752                    "Getting with key %08x, len is %d\n",
753                    *((unsigned int*)&key),
754                    pdns->queries[0]->namelen);
755
756         struct receive_dht_cls* cls = GNUNET_malloc(sizeof(struct receive_dht_cls));
757         cls->id = dns->s.id;
758
759         cls->handle = GNUNET_DHT_get_start(dht,
760                                            GNUNET_TIME_UNIT_MINUTES,
761                                            GNUNET_BLOCK_TYPE_DNS,
762                                            &key,
763                                            DEFAULT_GET_REPLICATION,
764                                            GNUNET_DHT_RO_NONE,
765                                            NULL,
766                                            0,
767                                            NULL,
768                                            0,
769                                            receive_dht,
770                                            cls);
771
772         goto outfree;
773       }
774
775     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Query for '%s'; namelen=%d\n", pdns->queries[0]->name, pdns->queries[0]->namelen);
776
777     /* This is a PTR-Query. Check if it is for "our" network */
778     if (htons(pdns->queries[0]->qtype) == 12 &&
779         74 == pdns->queries[0]->namelen)
780       {
781         char* ipv6addr;
782         char ipv6[16];
783         char ipv6rev[74] = "X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.X.ip6.arpa.";
784         unsigned int i;
785         unsigned long long ipv6prefix;
786         unsigned int comparelen;
787
788         GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "vpn", "IPV6ADDR", &ipv6addr));
789         inet_pton (AF_INET6, ipv6addr, ipv6);
790         GNUNET_free(ipv6addr);
791
792         GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "vpn", "IPV6PREFIX", &ipv6prefix));
793         GNUNET_assert(ipv6prefix < 127);
794         ipv6prefix = (ipv6prefix + 7)/8;
795
796         for (i = ipv6prefix; i < 16; i++)
797           ipv6[i] = 0;
798
799         for (i = 0; i < 16; i++)
800           {
801             unsigned char c1 = ipv6[i] >> 4;
802             unsigned char c2 = ipv6[i] & 0xf;
803
804             if (c1 <= 9)
805               ipv6rev[62-(4*i)] = c1 + '0';
806             else
807               ipv6rev[62-(4*i)] = c1 + 87; /* 87 is the difference between 'a' and 10 */
808
809             if (c2 <= 9)
810               ipv6rev[62-((4*i)+2)] = c2 + '0';
811             else
812               ipv6rev[62-((4*i)+2)] = c2 + 87;
813           }
814         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "My network is %s'.\n", ipv6rev);
815         comparelen = 10 + 4*ipv6prefix;
816         if(0 == strncmp(pdns->queries[0]->name+(pdns->queries[0]->namelen - comparelen),
817                         ipv6rev + (74 - comparelen),
818                         comparelen))
819           {
820             GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Reverse-Query for .gnunet!\n");
821
822             GNUNET_SCHEDULER_add_now(send_rev_query, pdns);
823
824             goto out;
825           }
826       }
827
828     char* virt_dns;
829     unsigned int virt_dns_bytes;
830     if (GNUNET_SYSERR ==
831         GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "VIRTDNS",
832                                                &virt_dns))
833       {
834         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
835                     "No entry 'VIRTDNS' in configuration!\n");
836         exit (1);
837       }
838
839     if (1 != inet_pton (AF_INET, virt_dns, &virt_dns_bytes))
840       {
841         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
842                     "Error parsing 'VIRTDNS': %s; %m!\n", virt_dns);
843         exit(1);
844       }
845
846     GNUNET_free(virt_dns);
847
848     if (virt_dns_bytes == pkt->orig_to)
849       {
850         /* This is a packet that was sent directly to the virtual dns-server
851          *
852          * This means we have to send this query over gnunet
853          */
854
855         size_t size = sizeof(struct GNUNET_MESH_Tunnel*) + sizeof(struct GNUNET_MessageHeader) + (ntohs(message->size) - sizeof(struct query_packet) + 1);
856         struct tunnel_cls *cls_ =  GNUNET_malloc(size);
857         cls_->hdr.size = size - sizeof(struct GNUNET_MESH_Tunnel*);
858
859         cls_->hdr.type = ntohs(GNUNET_MESSAGE_TYPE_REMOTE_QUERY_DNS);
860         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "size: %d\n", size);
861
862         memcpy(&cls_->dns, dns, cls_->hdr.size - sizeof(struct GNUNET_MessageHeader));
863         GNUNET_SCHEDULER_add_now(send_mesh_query, cls_);
864
865         goto outfree;
866       }
867
868
869     /* The query should be sent to the network */
870
871     struct sockaddr_in dest;
872     memset(&dest, 0, sizeof dest);
873     dest.sin_port = htons(53);
874     dest.sin_addr.s_addr = pkt->orig_to;
875
876     GNUNET_NETWORK_socket_sendto(dnsout,
877                                  dns,
878                                  ntohs(pkt->hdr.size) - sizeof(struct query_packet) + 1,
879                                  (struct sockaddr*) &dest,
880                                  sizeof dest);
881
882 outfree:
883     free_parsed_dns_packet(pdns);
884     pdns = NULL;
885 out:
886     GNUNET_SERVER_receive_done(client, GNUNET_OK);
887 }
888
889 static void read_response (void *cls,
890                            const struct GNUNET_SCHEDULER_TaskContext *tc);
891
892 static int
893 open_port ()
894 {
895   struct sockaddr_in addr;
896
897   dnsout = GNUNET_NETWORK_socket_create (AF_INET, SOCK_DGRAM, 0);
898   if (dnsout == NULL)
899     return GNUNET_SYSERR;
900   memset (&addr, 0, sizeof (struct sockaddr_in));
901
902   addr.sin_family = AF_INET;
903   int err = GNUNET_NETWORK_socket_bind (dnsout,
904                                         (struct sockaddr *) &addr,
905                                         sizeof (struct sockaddr_in));
906
907   if (err != GNUNET_OK)
908     {
909       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
910                   "Could not bind a port: %m\n");
911       return GNUNET_SYSERR;
912     }
913
914   /* Read the port we bound to */
915   socklen_t addrlen = sizeof (struct sockaddr_in);
916   err = getsockname (GNUNET_NETWORK_get_fd (dnsout),
917                      (struct sockaddr *) &addr, &addrlen);
918
919   dnsoutport = htons (addr.sin_port);
920
921   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Bound to port %d.\n", dnsoutport);
922
923   GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, dnsout,
924                                  &read_response, NULL);
925
926   return GNUNET_YES;
927 }
928
929 /**
930  * Read a response-packet of the UDP-Socket
931  */
932 static void
933 read_response (void *cls
934                __attribute__ ((unused)),
935                const struct GNUNET_SCHEDULER_TaskContext *tc)
936 {
937   struct sockaddr_in addr;
938   socklen_t addrlen = sizeof (addr);
939   int r;
940   int len;
941
942   if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
943     return;
944
945   memset (&addr, 0, sizeof addr);
946
947 #ifndef MINGW
948   if (0 != ioctl (GNUNET_NETWORK_get_fd (dnsout), FIONREAD, &len))
949     {
950       unhijack (dnsoutport);
951       if (GNUNET_YES == open_port ())
952         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, hijack, NULL);
953       return;
954     }
955 #else
956   /* port the code above? */
957   len = 65536;
958 #endif
959   {
960     unsigned char buf[len];
961     struct dns_pkt *dns = (struct dns_pkt *) buf;
962
963     r = GNUNET_NETWORK_socket_recvfrom (dnsout,
964                                         buf,
965                                         sizeof (buf),
966                                         (struct sockaddr *) &addr, &addrlen);
967
968     if (r < 0)
969       {
970         unhijack (dnsoutport);
971         if (GNUNET_YES == open_port ())
972           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, hijack, NULL);
973         return;
974       }
975
976     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Answer to query %d\n", ntohs(dns->s.id));
977
978     if (query_states[dns->s.id].valid == GNUNET_YES)
979       {
980         if (query_states[dns->s.id].tunnel != NULL)
981           {
982             GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Answer to query %d for a remote peer!\n", ntohs(dns->s.id));
983             /* This response should go through a tunnel */
984             uint32_t *c = GNUNET_malloc (4 + sizeof(struct GNUNET_MESH_Tunnel*) + r);
985             *c = r;
986             struct GNUNET_MESH_Tunnel** t = (struct GNUNET_MESH_Tunnel**)(c + 1);
987             *t = query_states[dns->s.id].tunnel;
988             memcpy (t + 1, dns, r);
989             if (NULL ==
990                 GNUNET_MESH_tunnel_get_data (query_states[dns->s.id].tunnel))
991               {
992                 struct GNUNET_MESH_TransmitHandle *th =
993                   GNUNET_MESH_notify_transmit_ready (query_states[dns->s.id].tunnel,
994                                                      GNUNET_YES,
995                                                      32,
996                                                      GNUNET_TIME_UNIT_MINUTES,
997                                                      NULL,
998                                                      r +
999                                                      sizeof (struct
1000                                                              GNUNET_MessageHeader),
1001                                                      mesh_send_response, c);
1002                 GNUNET_MESH_tunnel_set_data (query_states[dns->s.id].tunnel,
1003                                              th);
1004               }
1005             else
1006               {
1007                 struct tunnel_notify_queue* head = GNUNET_MESH_tunnel_get_head(query_states[dns->s.id].tunnel);
1008                 struct tunnel_notify_queue* tail = GNUNET_MESH_tunnel_get_tail(query_states[dns->s.id].tunnel);
1009
1010                 struct tunnel_notify_queue* element = GNUNET_malloc(sizeof(struct tunnel_notify_queue));
1011                 element->cls = c;
1012                 element->len = r+sizeof(struct GNUNET_MessageHeader);
1013                 element->cb = mesh_send_response;
1014
1015                 GNUNET_CONTAINER_DLL_insert_tail(head, tail, element);
1016                 GNUNET_MESH_tunnel_set_head(query_states[dns->s.id].tunnel, head);
1017                 GNUNET_MESH_tunnel_set_tail(query_states[dns->s.id].tunnel, tail);
1018               }
1019           }
1020         else
1021           {
1022             query_states[dns->s.id].valid = GNUNET_NO;
1023
1024             size_t len = sizeof (struct answer_packet) + r - 1; /* 1 for the unsigned char data[1]; */
1025             struct answer_packet_list *answer =
1026               GNUNET_malloc (len + 2 * sizeof (struct answer_packet_list *));
1027             answer->pkt.hdr.type =
1028               htons (GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS);
1029             answer->pkt.hdr.size = htons (len);
1030             answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_IP;
1031             answer->pkt.from = addr.sin_addr.s_addr;
1032             answer->pkt.to = query_states[dns->s.id].local_ip;
1033             answer->pkt.dst_port = query_states[dns->s.id].local_port;
1034             memcpy (answer->pkt.data, buf, r);
1035
1036             GNUNET_CONTAINER_DLL_insert_after (head, tail, tail, answer);
1037
1038             GNUNET_SERVER_notify_transmit_ready (query_states
1039                                                  [dns->s.id].client, len,
1040                                                  GNUNET_TIME_UNIT_FOREVER_REL,
1041                                                  &send_answer,
1042                                                  query_states[dns->s.
1043                                                               id].client);
1044           }
1045       }
1046   }
1047   GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
1048                                  dnsout, &read_response, NULL);
1049 }
1050
1051
1052 /**
1053  * Task run during shutdown.
1054  *
1055  * @param cls unused
1056  * @param tc unused
1057  */
1058 static void
1059 cleanup_task (void *cls __attribute__((unused)),
1060               const struct GNUNET_SCHEDULER_TaskContext *tc)
1061 {
1062   GNUNET_assert(0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN));
1063
1064   unhijack(dnsoutport);
1065   GNUNET_DHT_disconnect(dht);
1066   GNUNET_MESH_disconnect(mesh_handle);
1067 }
1068
1069 /**
1070  * @brief Create a port-map from udp and tcp redirects
1071  *
1072  * @param udp_redirects
1073  * @param tcp_redirects
1074  *
1075  * @return 
1076  */
1077 uint64_t
1078 get_port_from_redirects (const char *udp_redirects, const char *tcp_redirects)
1079 {
1080   uint64_t ret = 0;
1081   char* cpy, *hostname, *redirect;
1082   int local_port, count = 0;
1083
1084   if (NULL != udp_redirects)
1085     {
1086       cpy = GNUNET_strdup (udp_redirects);
1087       for (redirect = strtok (cpy, " "); redirect != NULL; redirect = strtok (NULL, " "))
1088         {
1089           if (NULL == (hostname = strstr (redirect, ":")))
1090             {
1091               GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: option %s is not formatted correctly!\n", redirect);
1092               continue;
1093             }
1094           hostname[0] = '\0';
1095           local_port = atoi (redirect);
1096           if (!((local_port > 0) && (local_port < 65536)))
1097             GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: %s is not a correct port.", redirect);
1098
1099           ret |= (0xFFFF & htons(local_port));
1100           ret <<= 16;
1101           count ++;
1102
1103           if(count > 4)
1104             {
1105               ret = 0;
1106               goto out;
1107             }
1108         }
1109       GNUNET_free(cpy);
1110       cpy = NULL;
1111     }
1112
1113   if (NULL != tcp_redirects)
1114     {
1115       cpy = GNUNET_strdup (tcp_redirects);
1116       for (redirect = strtok (cpy, " "); redirect != NULL; redirect = strtok (NULL, " "))
1117         {
1118           if (NULL == (hostname = strstr (redirect, ":")))
1119             {
1120               GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: option %s is not formatted correctly!\n", redirect);
1121               continue;
1122             }
1123           hostname[0] = '\0';
1124           local_port = atoi (redirect);
1125           if (!((local_port > 0) && (local_port < 65536)))
1126             GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: %s is not a correct port.", redirect);
1127
1128           ret |= (0xFFFF & htons(local_port));
1129           ret <<= 16;
1130           count ++;
1131
1132           if(count > 4)
1133             {
1134               ret = 0;
1135               goto out;
1136             }
1137         }
1138       GNUNET_free(cpy);
1139       cpy = NULL;
1140     }
1141
1142 out:
1143   if (NULL != cpy)
1144     GNUNET_free(cpy);
1145   return ret;
1146 }
1147
1148 void
1149 publish_name (const char *name, uint64_t ports, uint32_t service_type,
1150               struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key)
1151 {
1152   size_t size = sizeof (struct GNUNET_DNS_Record);
1153   struct GNUNET_DNS_Record data;
1154   memset (&data, 0, size);
1155
1156   data.purpose.size =
1157     htonl (size - sizeof (struct GNUNET_CRYPTO_RsaSignature));
1158   data.purpose.purpose = GNUNET_SIGNATURE_PURPOSE_DNS_RECORD;
1159
1160   GNUNET_CRYPTO_hash (name, strlen (name) + 1, &data.service_descriptor);
1161   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Store with key1 %x\n",
1162               *((unsigned long long *) &data.service_descriptor));
1163
1164   data.service_type = service_type;
1165   data.ports = ports;
1166
1167   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &data.peer);
1168
1169   data.expiration_time =
1170     GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_HOURS, 2));
1171
1172   /* Sign the block */
1173   if (GNUNET_OK != GNUNET_CRYPTO_rsa_sign (my_private_key,
1174                                            &data.purpose, &data.signature))
1175     {
1176       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not sign DNS_Record\n");
1177       return;
1178     }
1179
1180   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1181               "Putting with key %08x, size = %d\n",
1182               *((unsigned int *) &data.service_descriptor), size);
1183
1184   GNUNET_DHT_put (dht,
1185                   &data.service_descriptor,
1186                   DEFAULT_PUT_REPLICATION,
1187                   GNUNET_DHT_RO_NONE,
1188                   GNUNET_BLOCK_TYPE_DNS,
1189                   size,
1190                   (char *) &data,
1191                   GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS),
1192                   GNUNET_TIME_UNIT_MINUTES, NULL, NULL);
1193 }
1194
1195 /**
1196  * @brief Publishes the record defined by the section section
1197  *
1198  * @param cls closure
1199  * @param section the current section
1200  */
1201 void
1202 publish_iterate (void *cls __attribute__((unused)), const char *section)
1203 {
1204   if ((strlen(section) < 8) || (0 != strcmp (".gnunet.", section + (strlen(section) - 8))))
1205     return;
1206
1207   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Parsing dns-name %s\n", section);
1208
1209   char *udp_redirects, *tcp_redirects, *alternative_names, *alternative_name,
1210     *keyfile;
1211
1212   GNUNET_CONFIGURATION_get_value_string (cfg, section,
1213                                          "UDP_REDIRECTS", &udp_redirects);
1214   GNUNET_CONFIGURATION_get_value_string (cfg, section, "TCP_REDIRECTS",
1215                                          &tcp_redirects);
1216
1217   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD",
1218                                                             "HOSTKEY",
1219                                                             &keyfile))
1220     {
1221       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not read keyfile-value\n");
1222       if (keyfile != NULL)
1223         GNUNET_free (keyfile);
1224       return;
1225     }
1226
1227   struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key =
1228     GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1229   GNUNET_free (keyfile);
1230   GNUNET_assert (my_private_key != NULL);
1231
1232   uint64_t ports = get_port_from_redirects (udp_redirects, tcp_redirects);
1233   uint32_t service_type = 0;
1234
1235   if (NULL != udp_redirects)
1236     service_type = GNUNET_DNS_SERVICE_TYPE_UDP;
1237
1238   if (NULL != tcp_redirects)
1239     service_type |= GNUNET_DNS_SERVICE_TYPE_TCP;
1240
1241   service_type = htonl (service_type);
1242
1243
1244   publish_name (section, ports, service_type, my_private_key);
1245
1246   GNUNET_CONFIGURATION_get_value_string (cfg, section,
1247                                          "ALTERNATIVE_NAMES",
1248                                          &alternative_names);
1249   for (alternative_name = strtok (alternative_names, " ");
1250        alternative_name != NULL; alternative_name = strtok (NULL, " "))
1251     {
1252       char *altname =
1253         alloca (strlen (alternative_name) + strlen (section) + 1 + 1);
1254       strcpy (altname, alternative_name);
1255       strcpy (altname + strlen (alternative_name) + 1, section);
1256       altname[strlen (alternative_name)] = '.';
1257
1258       publish_name (altname, ports, service_type, my_private_key);
1259     }
1260
1261   GNUNET_free_non_null(alternative_names);
1262   GNUNET_CRYPTO_rsa_key_free (my_private_key);
1263   GNUNET_free_non_null (udp_redirects);
1264   GNUNET_free_non_null (tcp_redirects);
1265 }
1266
1267 /**
1268  * Publish a DNS-record in the DHT.
1269  */
1270 static void
1271 publish_names (void *cls __attribute__((unused)),
1272                const struct GNUNET_SCHEDULER_TaskContext *tc) {
1273     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1274       return;
1275
1276     GNUNET_CONFIGURATION_iterate_sections(cfg, publish_iterate, NULL);
1277
1278     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_HOURS,
1279                                   publish_names,
1280                                   NULL);
1281 }
1282
1283 /**
1284  * @param cls closure
1285  * @param server the initialized server
1286  * @param cfg_ configuration to use
1287  */
1288 static void
1289 run (void *cls,
1290      struct GNUNET_SERVER_Handle *server,
1291      const struct GNUNET_CONFIGURATION_Handle *cfg_)
1292 {
1293   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1294     /* callback, cls, type, size */
1295     {&receive_query, NULL, GNUNET_MESSAGE_TYPE_LOCAL_QUERY_DNS, 0},
1296     {&rehijack, NULL, GNUNET_MESSAGE_TYPE_REHIJACK,
1297      sizeof (struct GNUNET_MessageHeader)},
1298     {NULL, NULL, 0, 0}
1299   };
1300
1301   static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
1302     {receive_mesh_query, GNUNET_MESSAGE_TYPE_REMOTE_QUERY_DNS, 0},
1303     {receive_mesh_answer, GNUNET_MESSAGE_TYPE_REMOTE_ANSWER_DNS, 0},
1304     {NULL, 0, 0}
1305   };
1306
1307   static GNUNET_MESH_ApplicationType *apptypes;
1308
1309   if (GNUNET_YES != open_port ())
1310     {
1311       GNUNET_SCHEDULER_shutdown();
1312       return;
1313     }
1314
1315   if (GNUNET_YES ==
1316       GNUNET_CONFIGURATION_get_value_yesno (cfg_, "dns", "PROVIDE_EXIT"))
1317     apptypes = (GNUNET_MESH_ApplicationType[])
1318     {
1319     GNUNET_APPLICATION_TYPE_INTERNET_RESOLVER,
1320     GNUNET_APPLICATION_TYPE_END};
1321   else
1322   apptypes = (GNUNET_MESH_ApplicationType[])
1323   {
1324   GNUNET_APPLICATION_TYPE_END};
1325
1326   mesh_handle =
1327     GNUNET_MESH_connect (cfg_, NULL, NULL, mesh_handlers, apptypes);
1328
1329   cfg = cfg_;
1330
1331   unsigned int i;
1332   for (i = 0; i < 65536; i++)
1333     {
1334       query_states[i].valid = GNUNET_NO;
1335     }
1336
1337   dht = GNUNET_DHT_connect (cfg, 1024);
1338
1339   GNUNET_SCHEDULER_add_now (publish_names, NULL);
1340
1341   GNUNET_SERVER_add_handlers (server, handlers);
1342   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1343                                 &cleanup_task, cls);
1344 }
1345
1346 /**
1347  * The main function for the dns service.
1348  *
1349  * @param argc number of arguments from the command line
1350  * @param argv command line arguments
1351  * @return 0 ok, 1 on error
1352  */
1353 int
1354 main (int argc, char *const *argv)
1355 {
1356   return (GNUNET_OK ==
1357           GNUNET_SERVICE_run (argc,
1358                               argv,
1359                               "dns",
1360                               GNUNET_SERVICE_OPTION_NONE,
1361                               &run, NULL)) ? 0 : 1;
1362 }