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