a8c3254efdad344dd8dec03befc77f0de817295b
[oweals/gnunet.git] / src / dns / 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_dns_service.h"
32 #include "gnunet_connection_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_applications.h"
35 #include "gnunet_container_lib.h"
36 #include "gnunet_dnsparser_lib.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 #include "dns.h"
45
46
47
48 static struct GNUNET_MESH_Handle *mesh_handle;
49
50 static struct GNUNET_CONNECTION_TransmitHandle *server_notify;
51
52 /**
53  * The UDP-Socket through which DNS-Resolves will be sent if they are not to be
54  * sent through gnunet. The port of this socket will not be hijacked.
55  */
56 static struct GNUNET_NETWORK_Handle *dnsout;
57 static struct GNUNET_NETWORK_Handle *dnsout6;
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 {
95   unsigned valid:1;
96   struct GNUNET_SERVER_Client *client;
97   struct GNUNET_MESH_Tunnel *tunnel;
98   char local_ip[16];
99   char remote_ip[16];
100   char addrlen;
101   uint16_t local_port;
102   char *name;
103   uint8_t namelen;
104   uint16_t qtype;
105 } query_states[UINT16_MAX + 1];
106
107 /**
108  * A struct used to give more than one value as
109  * closure to receive_dht
110  */
111 struct receive_dht_cls
112 {
113   uint16_t id;
114   struct GNUNET_DHT_GetHandle *handle;
115 };
116
117 struct tunnel_notify_queue
118 {
119   struct tunnel_notify_queue *next;
120   struct tunnel_notify_queue *prev;
121   void *cls;
122   size_t len;
123   GNUNET_CONNECTION_TransmitReadyNotify cb;
124 };
125
126 struct tunnel_state
127 {
128   struct tunnel_notify_queue *head, *tail;
129   struct GNUNET_MESH_TransmitHandle *th;
130 };
131
132 static size_t
133 send_answer (void *cls, size_t size, void *buf);
134
135 static void
136 client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
137 {
138   if (NULL == head)
139     return;
140
141   if (head->client == client)
142   {
143     GNUNET_CONNECTION_notify_transmit_ready_cancel (server_notify);
144     server_notify =
145         GNUNET_SERVER_notify_transmit_ready (head->next->client,
146                                              ntohs (head->next->pkt.hdr.size),
147                                              GNUNET_TIME_UNIT_FOREVER_REL,
148                                              &send_answer, NULL);
149   }
150
151   struct answer_packet_list *element = head;
152
153   while (element != NULL)
154   {
155     if (element->client == client)
156     {
157       GNUNET_SERVER_client_drop (client);
158       GNUNET_CONTAINER_DLL_remove (head, tail, element);
159       struct answer_packet_list *t = element;
160
161       element = element->next;
162       GNUNET_free (t);
163     }
164     else
165       element = element->next;
166   }
167 }
168
169 /**
170  * Hijack all outgoing DNS-Traffic but for traffic leaving "our" port.
171  */
172 static void
173 hijack (void *cls GNUNET_UNUSED, const struct GNUNET_SCHEDULER_TaskContext *tc)
174 {
175   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
176     return;
177
178   if (0 == dnsoutport)
179   {
180     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
181                 "Delaying the hijacking, port is still %d!\n", dnsoutport);
182     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &hijack, NULL);
183     return;
184   }
185
186   char port_s[6];
187   char *virt_dns;
188   struct GNUNET_OS_Process *proc;
189
190   if (GNUNET_SYSERR ==
191       GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "VIRTDNS", &virt_dns))
192   {
193     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
194                 "No entry 'VIRTDNS' in configuration!\n");
195     exit (1);
196   }
197
198   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Hijacking, port is %d\n", dnsoutport);
199   snprintf (port_s, 6, "%d", dnsoutport);
200   if (NULL !=
201       (proc =
202        GNUNET_OS_start_process (NULL, NULL, "gnunet-helper-hijack-dns",
203                                 "gnunet-hijack-dns", port_s, virt_dns, NULL)))
204   {
205     GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (proc));
206     GNUNET_OS_process_close (proc);
207   }
208   GNUNET_free (virt_dns);
209 }
210
211 static void *
212 new_tunnel (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
213             const struct GNUNET_PeerIdentity *initiator GNUNET_UNUSED,
214             const struct GNUNET_ATS_Information *ats GNUNET_UNUSED)
215 {
216   struct tunnel_state *s = GNUNET_malloc (sizeof *s);
217
218   s->head = NULL;
219   s->tail = NULL;
220   s->th = NULL;
221   return s;
222 }
223
224 static void
225 clean_tunnel (void *cls GNUNET_UNUSED, const struct GNUNET_MESH_Tunnel *tunnel,
226               void *tunnel_ctx)
227 {
228   GNUNET_free (tunnel_ctx);
229 }
230
231 /**
232  * Delete the hijacking-routes
233  */
234 static void
235 unhijack (unsigned short port)
236 {
237   char port_s[6];
238   char *virt_dns;
239   struct GNUNET_OS_Process *proc;
240
241   if (GNUNET_SYSERR ==
242       GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "VIRTDNS", &virt_dns))
243   {
244     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
245                 "No entry 'VIRTDNS' in configuration!\n");
246     exit (1);
247   }
248
249   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "unHijacking, port is %d\n", port);
250   snprintf (port_s, 6, "%d", port);
251   if (NULL !=
252       (proc =
253        GNUNET_OS_start_process (NULL, NULL, "gnunet-helper-hijack-dns",
254                                 "gnunet-hijack-dns", "-d", port_s, virt_dns,
255                                 NULL)))
256   {
257     GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (proc));
258     GNUNET_OS_process_close (proc);
259   }
260   GNUNET_free (virt_dns);
261 }
262
263 /**
264  * Send the DNS-Response to the client. Gets called via the notify_transmit_ready-
265  * system.
266  */
267 static size_t
268 send_answer (void *cls, size_t size, void *buf)
269 {
270   server_notify = NULL;
271   struct answer_packet_list *query = head;
272   size_t len = ntohs (query->pkt.hdr.size);
273
274   GNUNET_assert (len <= size);
275
276   memcpy (buf, &query->pkt.hdr, len);
277
278   GNUNET_CONTAINER_DLL_remove (head, tail, query);
279
280   /* When more data is to be sent, reschedule */
281   if (head != NULL)
282     server_notify =
283         GNUNET_SERVER_notify_transmit_ready (head->client,
284                                              ntohs (head->pkt.hdr.size),
285                                              GNUNET_TIME_UNIT_FOREVER_REL,
286                                              &send_answer, NULL);
287
288   GNUNET_SERVER_client_drop (query->client);
289   GNUNET_free (query);
290   return len;
291 }
292
293 GNUNET_NETWORK_STRUCT_BEGIN
294
295 struct tunnel_cls
296 {
297   struct GNUNET_MESH_Tunnel *tunnel GNUNET_PACKED;
298   struct GNUNET_MessageHeader hdr;
299   struct dns_pkt dns;
300 };
301 GNUNET_NETWORK_STRUCT_END
302
303 struct tunnel_cls *remote_pending[UINT16_MAX];
304
305 static size_t
306 mesh_send_response (void *cls, size_t size, void *buf)
307 {
308   GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader));
309   struct GNUNET_MessageHeader *hdr = buf;
310   uint32_t *sz = cls;
311   struct GNUNET_MESH_Tunnel **tunnel = (struct GNUNET_MESH_Tunnel **) (sz + 1);
312   struct dns_pkt *dns = (struct dns_pkt *) (tunnel + 1);
313
314   GNUNET_MESH_tunnel_set_data (*tunnel, NULL);
315
316   hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_REMOTE_ANSWER_DNS);
317   hdr->size = htons (*sz + sizeof (struct GNUNET_MessageHeader));
318
319   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
320               "Sending response, size=%d, sz=%d, sz+hdr=%d\n", size, *sz,
321               *sz + sizeof (struct GNUNET_MessageHeader));
322
323   GNUNET_assert (size >= (*sz + sizeof (struct GNUNET_MessageHeader)));
324
325   memcpy (hdr + 1, dns, *sz);
326   struct tunnel_state *s = GNUNET_MESH_tunnel_get_data (*tunnel);
327
328   if (NULL != s->head)
329   {
330     struct tunnel_notify_queue *element = s->head;
331     struct tunnel_notify_queue *head = s->head;
332     struct tunnel_notify_queue *tail = s->tail;
333
334     GNUNET_CONTAINER_DLL_remove (head, tail, element);
335
336     s->th =
337         GNUNET_MESH_notify_transmit_ready (*tunnel, GNUNET_NO, 42,
338                                            GNUNET_TIME_relative_divide
339                                            (GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
340                                            (const struct GNUNET_PeerIdentity *)
341                                            NULL, element->len, element->cb,
342                                            element->cls);
343   }
344
345   GNUNET_free (cls);
346
347   return ntohs (hdr->size);
348 }
349
350 static size_t
351 mesh_send (void *cls, size_t size, void *buf)
352 {
353   struct tunnel_cls *cls_ = (struct tunnel_cls *) cls;
354
355   GNUNET_MESH_tunnel_set_data (cls_->tunnel, NULL);
356
357   GNUNET_assert (cls_->hdr.size <= size);
358
359   size = cls_->hdr.size;
360   cls_->hdr.size = htons (cls_->hdr.size);
361
362   memcpy (buf, &cls_->hdr, size);
363
364   struct tunnel_state *s = GNUNET_MESH_tunnel_get_data (cls_->tunnel);
365
366   if (NULL != s->head)
367   {
368     struct tunnel_notify_queue *element = s->head;
369     struct tunnel_notify_queue *head = s->head;
370     struct tunnel_notify_queue *tail = s->tail;;
371
372     GNUNET_CONTAINER_DLL_remove (head, tail, element);
373
374     s->th =
375         GNUNET_MESH_notify_transmit_ready (cls_->tunnel, GNUNET_NO, 42,
376                                            GNUNET_TIME_relative_divide
377                                            (GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
378                                            (const struct GNUNET_PeerIdentity *)
379                                            NULL, element->len, element->cb,
380                                            element->cls);
381
382     GNUNET_free (element);
383   }
384
385   return size;
386 }
387
388
389 void
390 mesh_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
391               const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
392 {
393   if (NULL == peer)
394     return;
395   struct tunnel_cls *cls_ = (struct tunnel_cls *) cls;
396
397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
398               "Connected to peer %s, %x, sending query with id %d\n",
399               GNUNET_i2s (peer), peer, ntohs (cls_->dns.s.id));
400
401   struct tunnel_state *s = GNUNET_MESH_tunnel_get_data (cls_->tunnel);
402
403   if (NULL == s->head)
404   {
405     s->th =
406         GNUNET_MESH_notify_transmit_ready (cls_->tunnel, GNUNET_YES, 42,
407                                            GNUNET_TIME_UNIT_MINUTES, NULL,
408                                            cls_->hdr.size, mesh_send, cls);
409
410   }
411   else
412   {
413     struct tunnel_notify_queue *head = s->head;
414     struct tunnel_notify_queue *tail = s->tail;
415
416     struct tunnel_notify_queue *element =
417         GNUNET_malloc (sizeof (struct tunnel_notify_queue));
418     element->cls = cls;
419     element->len = cls_->hdr.size;
420     element->cb = mesh_send;
421
422     GNUNET_CONTAINER_DLL_insert_tail (head, tail, element);
423   }
424 }
425
426
427 static void
428 send_mesh_query (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
429 {
430   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
431     return;
432
433   struct tunnel_cls *cls_ = (struct tunnel_cls *) cls;
434
435   struct tunnel_state *s = GNUNET_malloc (sizeof *s);
436
437   s->head = NULL;
438   s->tail = NULL;
439   s->th = NULL;
440
441   cls_->tunnel =
442       GNUNET_MESH_tunnel_create (mesh_handle, s, mesh_connect, NULL, cls_);
443
444   GNUNET_MESH_peer_request_connect_by_type (cls_->tunnel,
445                                             GNUNET_APPLICATION_TYPE_INTERNET_RESOLVER);
446
447   remote_pending[cls_->dns.s.id] = cls_;
448 }
449
450 static int
451 receive_mesh_query (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
452                     void **ctx GNUNET_UNUSED,
453                     const struct GNUNET_PeerIdentity *sender GNUNET_UNUSED,
454                     const struct GNUNET_MessageHeader *message,
455                     const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
456 {
457   struct dns_pkt *dns = (struct dns_pkt *) (message + 1);
458
459   struct sockaddr_in dest;
460
461   struct dns_pkt_parsed *pdns = parse_dns_packet (dns);
462
463   memset (&dest, 0, sizeof dest);
464   dest.sin_port = htons (53);
465   char *dns_resolver;
466
467   if (GNUNET_OK !=
468       GNUNET_CONFIGURATION_get_value_string (cfg, "dns", "EXTERNAL_DNS",
469                                              &dns_resolver) ||
470       1 != inet_pton (AF_INET, dns_resolver, &dest.sin_addr))
471     inet_pton (AF_INET, "8.8.8.8", &dest.sin_addr);
472
473   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Querying for remote, id=%d\n",
474               ntohs (dns->s.id));
475   query_states[dns->s.id].tunnel = tunnel;
476   query_states[dns->s.id].valid = GNUNET_YES;
477
478   int i;
479
480   for (i = 0; i < ntohs (pdns->s.qdcount); i++)
481   {
482     if (pdns->queries[i]->qtype == htons (28) ||
483         pdns->queries[i]->qtype == htons (1))
484     {
485       query_states[dns->s.id].qtype = pdns->queries[i]->qtype;
486       break;
487     }
488   }
489   free_parsed_dns_packet (pdns);
490
491   GNUNET_NETWORK_socket_sendto (dnsout, dns,
492                                 ntohs (message->size) -
493                                 sizeof (struct GNUNET_MessageHeader),
494                                 (struct sockaddr *) &dest, sizeof dest);
495
496   return GNUNET_SYSERR;
497 }
498
499 static int
500 receive_mesh_answer (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
501                      void **ctx GNUNET_UNUSED,
502                      const struct GNUNET_PeerIdentity *sender,
503                      const struct GNUNET_MessageHeader *message,
504                      const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
505 {
506   /* TODo: size check */
507   struct dns_pkt *dns = (struct dns_pkt *) (message + 1);
508
509   /* They sent us a packet we were not waiting for */
510   if (remote_pending[dns->s.id] == NULL ||
511       remote_pending[dns->s.id]->tunnel != tunnel)
512     return GNUNET_OK;
513
514   GNUNET_free (remote_pending[dns->s.id]);
515   remote_pending[dns->s.id] = NULL;
516
517   if (query_states[dns->s.id].valid != GNUNET_YES)
518     return GNUNET_SYSERR;
519   query_states[dns->s.id].valid = GNUNET_NO;
520
521   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
522               "Received answer from peer %s, dns-id %d\n", GNUNET_i2s (sender),
523               ntohs (dns->s.id));
524
525   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 */
526       + sizeof (struct dns_record_line) - 1 + 16;       /* To hold the IPv6-Address */
527
528   struct answer_packet_list *answer =
529       GNUNET_malloc (len + sizeof (struct answer_packet_list) -
530                      sizeof (struct answer_packet));
531
532   answer->pkt.hdr.type = htons (GNUNET_MESSAGE_TYPE_VPN_DNS_LOCAL_RESPONSE_DNS);
533   answer->pkt.hdr.size = htons (len);
534
535   struct dns_pkt_parsed *pdns = parse_dns_packet (dns);
536
537   if (ntohs (pdns->s.ancount) < 1)
538   {
539     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Answer only contains %d answers.\n",
540                 ntohs (pdns->s.ancount));
541     free_parsed_dns_packet (pdns);
542     GNUNET_free (answer);
543     return GNUNET_OK;
544   }
545
546   int i = 0;
547
548   while (i < ntohs (pdns->s.ancount) && ntohs (pdns->answers[i]->type) != 28 &&
549          ntohs (pdns->answers[i]->type) != 1)
550   {
551     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Answer contains %d.\n",
552                 ntohs (pdns->answers[i]->type));
553     i++;
554   }
555
556   if (i >= ntohs (pdns->s.ancount))
557   {
558     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
559                 "Answer does not contain any usable answers.\n");
560     free_parsed_dns_packet (pdns);
561     GNUNET_free (answer);
562     return GNUNET_OK;
563   }
564
565   answer->pkt.addrsize = ntohs (pdns->answers[i]->data_len);
566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "The first answer has the addrlen %d\n",
567               answer->pkt.addrsize);
568   memcpy (answer->pkt.addr, pdns->answers[i]->data,
569           ntohs (pdns->answers[i]->data_len));
570
571   memcpy (answer->pkt.from, query_states[dns->s.id].remote_ip,
572           query_states[dns->s.id].addrlen);
573   memcpy (answer->pkt.to, query_states[dns->s.id].local_ip,
574           query_states[dns->s.id].addrlen);
575   answer->pkt.addrlen = query_states[dns->s.id].addrlen;
576   answer->pkt.dst_port = query_states[dns->s.id].local_port;
577
578   struct dns_pkt *dpkt = (struct dns_pkt *) answer->pkt.data;
579
580   dpkt->s.id = dns->s.id;
581   dpkt->s.aa = 1;
582   dpkt->s.qr = 1;
583   dpkt->s.ra = 1;
584   dpkt->s.qdcount = htons (1);
585   dpkt->s.ancount = htons (1);
586
587   memcpy (dpkt->data, query_states[dns->s.id].name,
588           query_states[dns->s.id].namelen);
589   GNUNET_free (query_states[dns->s.id].name);
590   query_states[dns->s.id].name = NULL;
591
592   struct dns_query_line *dque =
593       (struct dns_query_line *) (dpkt->data +
594                                  (query_states[dns->s.id].namelen));
595
596   struct dns_record_line *drec_data =
597       (struct dns_record_line *) (dpkt->data +
598                                   (query_states[dns->s.id].namelen) +
599                                   sizeof (struct dns_query_line) + 2);
600   if (htons (28) == query_states[dns->s.id].qtype)
601   {
602     answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_REMOTE_AAAA;
603     dque->type = htons (28);    /* AAAA */
604     drec_data->type = htons (28);       /* AAAA */
605     drec_data->data_len = htons (16);
606   }
607   else if (htons (1) == query_states[dns->s.id].qtype)
608   {
609     answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_REMOTE_A;
610     dque->type = htons (1);     /* A */
611     drec_data->type = htons (1);        /* A */
612     drec_data->data_len = htons (4);
613   }
614   else
615   {
616     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "dns-answer with pending qtype = %d\n",
617                 query_states[dns->s.id].qtype);
618     GNUNET_assert (0);
619   }
620   dque->class = htons (1);      /* IN */
621
622   char *anname =
623       (char *) (dpkt->data + (query_states[dns->s.id].namelen) +
624                 sizeof (struct dns_query_line));
625   memcpy (anname, "\xc0\x0c", 2);
626   drec_data->class = htons (1); /* IN */
627
628   drec_data->ttl = pdns->answers[i]->ttl;
629
630   /* Calculate at which offset in the packet the IPv6-Address belongs, it is
631    * filled in by the daemon-vpn */
632   answer->pkt.addroffset =
633       htons ((unsigned short) ((unsigned long) (&drec_data->data) -
634                                (unsigned long) (&answer->pkt)));
635
636   GNUNET_CONTAINER_DLL_insert_after (head, tail, tail, answer);
637   answer->client = query_states[dns->s.id].client;
638
639   if (server_notify == NULL)
640     server_notify =
641         GNUNET_SERVER_notify_transmit_ready (query_states[dns->s.id].client,
642                                              len, GNUNET_TIME_UNIT_FOREVER_REL,
643                                              &send_answer, NULL);
644
645   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
646               "Sent answer of length %d on to client, addroffset = %d\n", len,
647               answer->pkt.addroffset);
648
649   free_parsed_dns_packet (pdns);
650   return GNUNET_OK;
651 }
652
653
654 static void
655 send_rev_query (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
656 {
657   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
658     return;
659
660   struct dns_pkt_parsed *pdns = (struct dns_pkt_parsed *) cls;
661
662   unsigned short id = pdns->s.id;
663
664   free_parsed_dns_packet (pdns);
665
666   if (query_states[id].valid != GNUNET_YES)
667     return;
668   query_states[id].valid = GNUNET_NO;
669
670   GNUNET_assert (query_states[id].namelen == 74);
671
672   size_t len = sizeof (struct answer_packet) - 1 + sizeof (struct dns_static) + 74      /* this is the length of a reverse ipv6-lookup */
673       + sizeof (struct dns_query_line) + 2      /* To hold the pointer (as defined in RFC1035) to the name */
674       + sizeof (struct dns_record_line) - 1 -
675       2 /* We do not know the lenght of the answer yet */ ;
676
677   struct answer_packet_list *answer =
678       GNUNET_malloc (len + sizeof (struct answer_packet_list) -
679                      sizeof (struct answer_packet));
680
681   answer->pkt.hdr.type = htons (GNUNET_MESSAGE_TYPE_VPN_DNS_LOCAL_RESPONSE_DNS);
682   answer->pkt.hdr.size = htons (len);
683   answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_REV;
684
685   memcpy (answer->pkt.from, query_states[id].remote_ip,
686           query_states[id].addrlen);
687   memcpy (answer->pkt.to, query_states[id].local_ip, query_states[id].addrlen);
688
689   answer->pkt.dst_port = query_states[id].local_port;
690
691   struct dns_pkt *dpkt = (struct dns_pkt *) answer->pkt.data;
692
693   dpkt->s.id = id;
694   dpkt->s.aa = 1;
695   dpkt->s.qr = 1;
696   dpkt->s.ra = 1;
697   dpkt->s.qdcount = htons (1);
698   dpkt->s.ancount = htons (1);
699
700   memcpy (dpkt->data, query_states[id].name, query_states[id].namelen);
701   GNUNET_free (query_states[id].name);
702   query_states[id].name = NULL;
703
704   struct dns_query_line *dque =
705       (struct dns_query_line *) (dpkt->data + (query_states[id].namelen));
706   dque->type = htons (12);      /* PTR */
707   dque->class = htons (1);      /* IN */
708
709   char *anname =
710       (char *) (dpkt->data + (query_states[id].namelen) +
711                 sizeof (struct dns_query_line));
712   memcpy (anname, "\xc0\x0c", 2);
713
714   struct dns_record_line *drec_data =
715       (struct dns_record_line *) (dpkt->data + (query_states[id].namelen) +
716                                   sizeof (struct dns_query_line) + 2);
717   drec_data->type = htons (12); /* AAAA */
718   drec_data->class = htons (1); /* IN */
719   /* FIXME: read the TTL from block:
720    * GNUNET_TIME_absolute_get_remaining(rec->expiration_time)
721    *
722    * But how to get the seconds out of this?
723    */
724   drec_data->ttl = htonl (3600);
725
726   /* Calculate at which offset in the packet the length of the name and the
727    * name, it is filled in by the daemon-vpn */
728   answer->pkt.addroffset =
729       htons ((unsigned short) ((unsigned long) (&drec_data->data_len) -
730                                (unsigned long) (&answer->pkt)));
731
732   GNUNET_CONTAINER_DLL_insert_after (head, tail, tail, answer);
733   answer->client = query_states[id].client;
734
735   if (server_notify == NULL)
736     server_notify =
737         GNUNET_SERVER_notify_transmit_ready (query_states[id].client, len,
738                                              GNUNET_TIME_UNIT_FOREVER_REL,
739                                              &send_answer, NULL);
740 }
741
742 /**
743  * Receive a block from the dht.
744  */
745 static void
746 receive_dht (void *cls, struct GNUNET_TIME_Absolute exp GNUNET_UNUSED,
747              const GNUNET_HashCode * key GNUNET_UNUSED,
748              const struct GNUNET_PeerIdentity *get_path GNUNET_UNUSED,
749              unsigned int get_path_length GNUNET_UNUSED,
750              const struct GNUNET_PeerIdentity *put_path GNUNET_UNUSED,
751              unsigned int put_path_length GNUNET_UNUSED,
752              enum GNUNET_BLOCK_Type type, size_t size, const void *data)
753 {
754
755   unsigned short id = ((struct receive_dht_cls *) cls)->id;
756   struct GNUNET_DHT_GetHandle *handle =
757       ((struct receive_dht_cls *) cls)->handle;
758   GNUNET_free (cls);
759
760   GNUNET_DHT_get_stop (handle);
761
762   GNUNET_assert (type == GNUNET_BLOCK_TYPE_DNS);
763
764   /* If no query with this id is pending, ignore the block */
765   if (query_states[id].valid != GNUNET_YES)
766     return;
767   query_states[id].valid = GNUNET_NO;
768
769   const struct GNUNET_DNS_Record *rec = data;
770
771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
772               "Got block of size %d, peer: %08x, desc: %08x\n", size,
773               *((unsigned int *) &rec->peer),
774               *((unsigned int *) &rec->service_descriptor));
775
776   size_t len = sizeof (struct answer_packet) - 1 + sizeof (struct dns_static) + query_states[id].namelen + sizeof (struct dns_query_line) + 2   /* To hold the pointer (as defined in RFC1035) to the name */
777       + sizeof (struct dns_record_line) - 1 + 16;       /* To hold the IPv6-Address */
778
779   struct answer_packet_list *answer =
780       GNUNET_malloc (len + sizeof (struct answer_packet_list) -
781                      sizeof (struct answer_packet));
782
783   answer->pkt.hdr.type = htons (GNUNET_MESSAGE_TYPE_VPN_DNS_LOCAL_RESPONSE_DNS);
784   answer->pkt.hdr.size = htons (len);
785   answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_SERVICE;
786   answer->client = query_states[id].client;
787
788   GNUNET_CRYPTO_hash (&rec->peer,
789                       sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
790                       &answer->pkt.service_descr.peer);
791
792   memcpy (&answer->pkt.service_descr.service_descriptor,
793           &rec->service_descriptor, sizeof (GNUNET_HashCode));
794   memcpy (&answer->pkt.service_descr.service_type, &rec->service_type,
795           sizeof (answer->pkt.service_descr.service_type));
796   memcpy (&answer->pkt.service_descr.ports, &rec->ports,
797           sizeof (answer->pkt.service_descr.ports));
798
799   memcpy (answer->pkt.from, query_states[id].remote_ip,
800           query_states[id].addrlen);
801   memcpy (answer->pkt.to, query_states[id].local_ip, query_states[id].addrlen);
802   answer->pkt.addrlen = query_states[id].addrlen;
803
804   answer->pkt.dst_port = query_states[id].local_port;
805
806   struct dns_pkt *dpkt = (struct dns_pkt *) answer->pkt.data;
807
808   dpkt->s.id = id;
809   dpkt->s.aa = 1;
810   dpkt->s.qr = 1;
811   dpkt->s.ra = 1;
812   dpkt->s.qdcount = htons (1);
813   dpkt->s.ancount = htons (1);
814
815   memcpy (dpkt->data, query_states[id].name, query_states[id].namelen);
816   GNUNET_free (query_states[id].name);
817   query_states[id].name = NULL;
818
819   struct dns_query_line *dque =
820       (struct dns_query_line *) (dpkt->data + (query_states[id].namelen));
821   dque->type = htons (28);      /* AAAA */
822   dque->class = htons (1);      /* IN */
823
824   char *anname =
825       (char *) (dpkt->data + (query_states[id].namelen) +
826                 sizeof (struct dns_query_line));
827   memcpy (anname, "\xc0\x0c", 2);
828
829   struct dns_record_line *drec_data =
830       (struct dns_record_line *) (dpkt->data + (query_states[id].namelen) +
831                                   sizeof (struct dns_query_line) + 2);
832   drec_data->type = htons (28); /* AAAA */
833   drec_data->class = htons (1); /* IN */
834
835   /* FIXME: read the TTL from block:
836    * GNUNET_TIME_absolute_get_remaining(rec->expiration_time)
837    *
838    * But how to get the seconds out of this?
839    */
840   drec_data->ttl = htonl (3600);
841   drec_data->data_len = htons (16);
842
843   /* Calculate at which offset in the packet the IPv6-Address belongs, it is
844    * filled in by the daemon-vpn */
845   answer->pkt.addroffset =
846       htons ((unsigned short) ((unsigned long) (&drec_data->data) -
847                                (unsigned long) (&answer->pkt)));
848
849   GNUNET_CONTAINER_DLL_insert_after (head, tail, tail, answer);
850
851   if (server_notify == NULL)
852     server_notify =
853         GNUNET_SERVER_notify_transmit_ready (answer->client, len,
854                                              GNUNET_TIME_UNIT_FOREVER_REL,
855                                              &send_answer, NULL);
856 }
857
858 /**
859  * This receives a GNUNET_MESSAGE_TYPE_REHIJACK and rehijacks the DNS
860  */
861 static void
862 rehijack (void *cls GNUNET_UNUSED, struct GNUNET_SERVER_Client *client,
863           const struct GNUNET_MessageHeader *message GNUNET_UNUSED)
864 {
865   unhijack (dnsoutport);
866   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &hijack, NULL);
867
868   GNUNET_SERVER_receive_done (client, GNUNET_OK);
869 }
870
871 /**
872  * This receives the dns-payload from the daemon-vpn and sends it on over the udp-socket
873  */
874 static void
875 receive_query (void *cls GNUNET_UNUSED, struct GNUNET_SERVER_Client *client,
876                const struct GNUNET_MessageHeader *message)
877 {
878   struct query_packet *pkt = (struct query_packet *) message;
879   struct dns_pkt *dns = (struct dns_pkt *) pkt->data;
880   struct dns_pkt_parsed *pdns = parse_dns_packet (dns);
881
882   query_states[dns->s.id].valid = GNUNET_YES;
883   query_states[dns->s.id].client = client;
884   GNUNET_SERVER_client_keep (client);
885   memcpy (query_states[dns->s.id].local_ip, pkt->orig_from, pkt->addrlen);
886   query_states[dns->s.id].addrlen = pkt->addrlen;
887   query_states[dns->s.id].local_port = pkt->src_port;
888   memcpy (query_states[dns->s.id].remote_ip, pkt->orig_to, pkt->addrlen);
889   query_states[dns->s.id].namelen = strlen ((char *) dns->data) + 1;
890   if (query_states[dns->s.id].name != NULL)
891     GNUNET_free (query_states[dns->s.id].name);
892   query_states[dns->s.id].name =
893       GNUNET_malloc (query_states[dns->s.id].namelen);
894   memcpy (query_states[dns->s.id].name, dns->data,
895           query_states[dns->s.id].namelen);
896
897   int i;
898
899   for (i = 0; i < ntohs (pdns->s.qdcount); i++)
900   {
901     if (pdns->queries[i]->qtype == htons (28) ||
902         pdns->queries[i]->qtype == htons (1))
903     {
904       query_states[dns->s.id].qtype = pdns->queries[i]->qtype;
905       break;
906     }
907   }
908
909   /* The query is for a .gnunet-address */
910   if (pdns->queries[0]->namelen > 9 &&
911       0 == strncmp (pdns->queries[0]->name + (pdns->queries[0]->namelen - 9),
912                     ".gnunet.", 9))
913   {
914     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Query for .gnunet!\n");
915     GNUNET_HashCode key;
916
917     GNUNET_CRYPTO_hash (pdns->queries[0]->name, pdns->queries[0]->namelen,
918                         &key);
919
920     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Getting with key %08x, len is %d\n",
921                 *((unsigned int *) &key), pdns->queries[0]->namelen);
922
923     struct receive_dht_cls *cls =
924         GNUNET_malloc (sizeof (struct receive_dht_cls));
925     cls->id = dns->s.id;
926
927     cls->handle =
928         GNUNET_DHT_get_start (dht, GNUNET_TIME_UNIT_MINUTES,
929                               GNUNET_BLOCK_TYPE_DNS, &key,
930                               5 /* DEFAULT_GET_REPLICATION */ ,
931                               GNUNET_DHT_RO_NONE, NULL, 0, &receive_dht, cls);
932
933     goto outfree;
934   }
935
936   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Query for '%s'; namelen=%d\n",
937               pdns->queries[0]->name, pdns->queries[0]->namelen);
938
939   /* This is a PTR-Query. Check if it is for "our" network */
940   if (htons (pdns->queries[0]->qtype) == 12 && 74 == pdns->queries[0]->namelen)
941   {
942     char *ipv6addr;
943     char ipv6[16];
944     char ipv6rev[74] =
945         "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.";
946     unsigned int i;
947     unsigned long long ipv6prefix;
948     unsigned int comparelen;
949
950     GNUNET_assert (GNUNET_OK ==
951                    GNUNET_CONFIGURATION_get_value_string (cfg, "vpn",
952                                                           "IPV6ADDR",
953                                                           &ipv6addr));
954     inet_pton (AF_INET6, ipv6addr, ipv6);
955     GNUNET_free (ipv6addr);
956
957     GNUNET_assert (GNUNET_OK ==
958                    GNUNET_CONFIGURATION_get_value_number (cfg, "vpn",
959                                                           "IPV6PREFIX",
960                                                           &ipv6prefix));
961     GNUNET_assert (ipv6prefix < 127);
962     ipv6prefix = (ipv6prefix + 7) / 8;
963
964     for (i = ipv6prefix; i < 16; i++)
965       ipv6[i] = 0;
966
967     for (i = 0; i < 16; i++)
968     {
969       unsigned char c1 = ipv6[i] >> 4;
970       unsigned char c2 = ipv6[i] & 0xf;
971
972       if (c1 <= 9)
973         ipv6rev[62 - (4 * i)] = c1 + '0';
974       else
975         ipv6rev[62 - (4 * i)] = c1 + 87;        /* 87 is the difference between 'a' and 10 */
976
977       if (c2 <= 9)
978         ipv6rev[62 - ((4 * i) + 2)] = c2 + '0';
979       else
980         ipv6rev[62 - ((4 * i) + 2)] = c2 + 87;
981     }
982     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "My network is %s'.\n", ipv6rev);
983     comparelen = 10 + 4 * ipv6prefix;
984     if (0 ==
985         strncmp (pdns->queries[0]->name +
986                  (pdns->queries[0]->namelen - comparelen),
987                  ipv6rev + (74 - comparelen), comparelen))
988     {
989       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Reverse-Query for .gnunet!\n");
990
991       GNUNET_SCHEDULER_add_now (send_rev_query, pdns);
992
993       goto out;
994     }
995   }
996
997   unsigned char virt_dns_bytes[16];
998
999   if (pkt->addrlen == 4)
1000   {
1001     char *virt_dns;
1002
1003     if (GNUNET_SYSERR ==
1004         GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "VIRTDNS",
1005                                                &virt_dns))
1006     {
1007       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1008                   "No entry 'VIRTDNS' in configuration!\n");
1009       exit (1);
1010     }
1011
1012     if (1 != inet_pton (AF_INET, virt_dns, &virt_dns_bytes))
1013     {
1014       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Error parsing 'VIRTDNS': %s; %m!\n",
1015                   virt_dns);
1016       exit (1);
1017     }
1018
1019     GNUNET_free (virt_dns);
1020   }
1021   else if (pkt->addrlen == 16)
1022   {
1023     char *virt_dns;
1024
1025     if (GNUNET_SYSERR ==
1026         GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "VIRTDNS6",
1027                                                &virt_dns))
1028     {
1029       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1030                   "No entry 'VIRTDNS6' in configuration!\n");
1031       exit (1);
1032     }
1033
1034     if (1 != inet_pton (AF_INET6, virt_dns, &virt_dns_bytes))
1035     {
1036       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1037                   "Error parsing 'VIRTDNS6': %s; %m!\n", virt_dns);
1038       exit (1);
1039     }
1040
1041     GNUNET_free (virt_dns);
1042   }
1043   else
1044   {
1045     GNUNET_assert (0);
1046   }
1047
1048   if (memcmp (virt_dns_bytes, pkt->orig_to, pkt->addrlen) == 0)
1049   {
1050     /* This is a packet that was sent directly to the virtual dns-server
1051      *
1052      * This means we have to send this query over gnunet
1053      */
1054
1055     size_t size =
1056         sizeof (struct GNUNET_MESH_Tunnel *) +
1057         sizeof (struct GNUNET_MessageHeader) + (ntohs (message->size) -
1058                                                 sizeof (struct query_packet) +
1059                                                 1);
1060     struct tunnel_cls *cls_ = GNUNET_malloc (size);
1061
1062     cls_->hdr.size = size - sizeof (struct GNUNET_MESH_Tunnel *);
1063
1064     cls_->hdr.type = ntohs (GNUNET_MESSAGE_TYPE_VPN_REMOTE_QUERY_DNS);
1065     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "size: %d\n", size);
1066
1067     memcpy (&cls_->dns, dns,
1068             cls_->hdr.size - sizeof (struct GNUNET_MessageHeader));
1069     GNUNET_SCHEDULER_add_now (send_mesh_query, cls_);
1070
1071     if (ntohs (pdns->s.qdcount) == 1)
1072     {
1073       if (ntohs (pdns->queries[0]->qtype) == 1)
1074         pdns->queries[0]->qtype = htons (28);
1075       else if (ntohs (pdns->queries[0]->qtype) == 28)
1076         pdns->queries[0]->qtype = htons (1);
1077       else
1078       {
1079         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "not sending second packet\n");
1080         goto outfree;
1081       }
1082       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending second packet\n");
1083       struct dns_pkt *rdns = unparse_dns_packet (pdns);
1084       size_t size =
1085           sizeof (struct GNUNET_MESH_Tunnel *) +
1086           sizeof (struct GNUNET_MessageHeader) + (ntohs (message->size) -
1087                                                   sizeof (struct query_packet) +
1088                                                   1);
1089       struct tunnel_cls *cls_ = GNUNET_malloc (size);
1090
1091       cls_->hdr.size = size - sizeof (struct GNUNET_MESH_Tunnel *);
1092
1093       cls_->hdr.type = ntohs (GNUNET_MESSAGE_TYPE_VPN_REMOTE_QUERY_DNS);
1094       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "size: %d\n", size);
1095
1096       memcpy (&cls_->dns, rdns,
1097               cls_->hdr.size - sizeof (struct GNUNET_MessageHeader));
1098       GNUNET_SCHEDULER_add_now (send_mesh_query, cls_);
1099       GNUNET_free (rdns);
1100     }
1101
1102     goto outfree;
1103   }
1104
1105
1106   /* The query should be sent to the network */
1107   if (pkt->addrlen == 4)
1108   {
1109     struct sockaddr_in dest;
1110
1111     memset (&dest, 0, sizeof dest);
1112     dest.sin_port = htons (53);
1113     memcpy (&dest.sin_addr.s_addr, pkt->orig_to, pkt->addrlen);
1114
1115     GNUNET_NETWORK_socket_sendto (dnsout, dns,
1116                                   ntohs (pkt->hdr.size) -
1117                                   sizeof (struct query_packet) + 1,
1118                                   (struct sockaddr *) &dest, sizeof dest);
1119   }
1120   else if (pkt->addrlen == 16)
1121   {
1122     struct sockaddr_in6 dest;
1123
1124     memset (&dest, 0, sizeof dest);
1125     dest.sin6_port = htons (53);
1126     memcpy (&dest.sin6_addr, pkt->orig_to, pkt->addrlen);
1127
1128     GNUNET_NETWORK_socket_sendto (dnsout6, dns,
1129                                   ntohs (pkt->hdr.size) -
1130                                   sizeof (struct query_packet) + 1,
1131                                   (struct sockaddr *) &dest, sizeof dest);
1132   }
1133
1134 outfree:
1135   free_parsed_dns_packet (pdns);
1136   pdns = NULL;
1137 out:
1138   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1139 }
1140
1141 static void
1142 read_response (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1143
1144 static void
1145 read_response6 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1146
1147 static int
1148 open_port6 ()
1149 {
1150   struct sockaddr_in6 addr;
1151
1152   dnsout6 = GNUNET_NETWORK_socket_create (AF_INET6, SOCK_DGRAM, 0);
1153   if (dnsout6 == NULL)
1154   {
1155     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not create socket: %m\n");
1156     return GNUNET_SYSERR;
1157   }
1158   memset (&addr, 0, sizeof (struct sockaddr_in6));
1159
1160   addr.sin6_family = AF_INET6;
1161   int err = GNUNET_NETWORK_socket_bind (dnsout6,
1162                                         (struct sockaddr *) &addr,
1163                                         sizeof (struct sockaddr_in6));
1164
1165   if (err != GNUNET_OK)
1166   {
1167     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not bind a port: %m\n");
1168     return GNUNET_SYSERR;
1169   }
1170
1171   GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, dnsout6,
1172                                  &read_response6, NULL);
1173
1174   return GNUNET_YES;
1175 }
1176
1177 static int
1178 open_port ()
1179 {
1180   struct sockaddr_in addr;
1181
1182   dnsout = GNUNET_NETWORK_socket_create (AF_INET, SOCK_DGRAM, 0);
1183   if (dnsout == NULL)
1184     return GNUNET_SYSERR;
1185   memset (&addr, 0, sizeof (struct sockaddr_in));
1186
1187   addr.sin_family = AF_INET;
1188   int err = GNUNET_NETWORK_socket_bind (dnsout,
1189                                         (struct sockaddr *) &addr,
1190                                         sizeof (struct sockaddr_in));
1191
1192   if (err != GNUNET_OK)
1193   {
1194     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Could not bind a port: %m\n");
1195     return GNUNET_SYSERR;
1196   }
1197
1198   /* Read the port we bound to */
1199   socklen_t addrlen = sizeof (struct sockaddr_in);
1200
1201   err =
1202       getsockname (GNUNET_NETWORK_get_fd (dnsout), (struct sockaddr *) &addr,
1203                    &addrlen);
1204
1205   dnsoutport = htons (addr.sin_port);
1206
1207   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Bound to port %d.\n", dnsoutport);
1208
1209   GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, dnsout,
1210                                  &read_response, NULL);
1211
1212   return GNUNET_YES;
1213 }
1214
1215 void
1216 handle_response (struct dns_pkt *dns, struct sockaddr *addr, socklen_t addrlen,
1217                  int r);
1218
1219 /**
1220  * Read a response-packet of the UDP-Socket
1221  */
1222 static void
1223 read_response6 (void *cls GNUNET_UNUSED,
1224                 const struct GNUNET_SCHEDULER_TaskContext *tc)
1225 {
1226   struct sockaddr_in6 addr;
1227   socklen_t addrlen = sizeof (addr);
1228   int r;
1229   int len;
1230
1231   if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
1232     return;
1233
1234   memset (&addr, 0, sizeof addr);
1235
1236 #ifndef MINGW
1237   if (0 != ioctl (GNUNET_NETWORK_get_fd (dnsout6), FIONREAD, &len))
1238   {
1239     (void) open_port6 ();
1240     return;
1241   }
1242 #else
1243   /* port the code above? */
1244   len = 65536;
1245 #endif
1246
1247   unsigned char buf[len];
1248   struct dns_pkt *dns = (struct dns_pkt *) buf;
1249
1250   r = GNUNET_NETWORK_socket_recvfrom (dnsout, buf, sizeof (buf),
1251                                       (struct sockaddr *) &addr, &addrlen);
1252
1253   if (r < 0)
1254   {
1255     (void) open_port6 ();
1256     return;
1257   }
1258
1259   struct sockaddr *addr_ = GNUNET_malloc (sizeof addr);
1260
1261   memcpy (addr_, &addr, sizeof addr);
1262   handle_response (dns, addr_, 4, r);
1263
1264   GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, dnsout6,
1265                                  &read_response6, NULL);
1266 }
1267
1268 /**
1269  * Read a response-packet of the UDP-Socket
1270  */
1271 static void
1272 read_response (void *cls GNUNET_UNUSED,
1273                const struct GNUNET_SCHEDULER_TaskContext *tc)
1274 {
1275   struct sockaddr_in addr;
1276   socklen_t addrlen = sizeof (addr);
1277   int r;
1278   int len;
1279
1280   if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
1281     return;
1282
1283   memset (&addr, 0, sizeof addr);
1284
1285 #ifndef MINGW
1286   if (0 != ioctl (GNUNET_NETWORK_get_fd (dnsout), FIONREAD, &len))
1287   {
1288     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "ioctl");
1289     unhijack (dnsoutport);
1290     if (GNUNET_YES == open_port ())
1291       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &hijack, NULL);
1292     return;
1293   }
1294 #else
1295   /* port the code above? */
1296   len = 65536;
1297 #endif
1298
1299   unsigned char buf[len];
1300   struct dns_pkt *dns = (struct dns_pkt *) buf;
1301
1302   r = GNUNET_NETWORK_socket_recvfrom (dnsout, buf, sizeof (buf),
1303                                       (struct sockaddr *) &addr, &addrlen);
1304
1305   if (r < 0)
1306   {
1307     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "recvfrom");
1308     unhijack (dnsoutport);
1309     if (GNUNET_YES == open_port ())
1310       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &hijack, NULL);
1311     return;
1312   }
1313
1314   struct sockaddr *addr_ = GNUNET_malloc (sizeof addr);
1315
1316   memcpy (addr_, &addr, sizeof addr);
1317   handle_response (dns, addr_, 4, r);
1318
1319   GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, dnsout,
1320                                  &read_response, NULL);
1321 }
1322
1323 void
1324 handle_response (struct dns_pkt *dns, struct sockaddr *addr, socklen_t addrlen,
1325                  int r)
1326 {
1327   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Answer to query %d\n",
1328               ntohs (dns->s.id));
1329
1330
1331   if (query_states[dns->s.id].valid == GNUNET_YES)
1332   {
1333     if (query_states[dns->s.id].tunnel != NULL)
1334     {
1335       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1336                   "Answer to query %d for a remote peer!\n", ntohs (dns->s.id));
1337       /* This response should go through a tunnel */
1338       uint32_t *c =
1339           GNUNET_malloc (4 + sizeof (struct GNUNET_MESH_Tunnel *) + r);
1340       *c = r;
1341       struct GNUNET_MESH_Tunnel **t = (struct GNUNET_MESH_Tunnel **) (c + 1);
1342
1343       *t = query_states[dns->s.id].tunnel;
1344       memcpy (t + 1, dns, r);
1345       struct tunnel_state *s =
1346           GNUNET_MESH_tunnel_get_data (query_states[dns->s.id].tunnel);
1347       if (NULL == s->th)
1348       {
1349         s->th =
1350             GNUNET_MESH_notify_transmit_ready (query_states[dns->s.id].tunnel,
1351                                                GNUNET_YES, 32,
1352                                                GNUNET_TIME_UNIT_MINUTES, NULL,
1353                                                r +
1354                                                sizeof (struct
1355                                                        GNUNET_MessageHeader),
1356                                                mesh_send_response, c);
1357       }
1358       else
1359       {
1360         struct tunnel_notify_queue *element =
1361             GNUNET_malloc (sizeof (struct tunnel_notify_queue));
1362         element->cls = c;
1363         element->len = r + sizeof (struct GNUNET_MessageHeader);
1364         element->cb = mesh_send_response;
1365
1366         GNUNET_CONTAINER_DLL_insert_tail (s->head, s->tail, element);
1367       }
1368     }
1369     else
1370     {
1371       query_states[dns->s.id].valid = GNUNET_NO;
1372
1373       size_t len = sizeof (struct answer_packet) + r - 1;       /* 1 for the unsigned char data[1]; */
1374       struct answer_packet_list *answer =
1375           GNUNET_malloc (len + sizeof (struct answer_packet_list) -
1376                          (sizeof (struct answer_packet)));
1377       answer->pkt.hdr.type =
1378           htons (GNUNET_MESSAGE_TYPE_VPN_DNS_LOCAL_RESPONSE_DNS);
1379       answer->pkt.hdr.size = htons (len);
1380       answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_IP;
1381       answer->pkt.addrlen = addrlen;
1382       if (addrlen == 16)
1383       {
1384         struct sockaddr_in6 *addr_ = (struct sockaddr_in6 *) addr;
1385
1386         memcpy (answer->pkt.from, &addr_->sin6_addr, addrlen);
1387         memcpy (answer->pkt.to, query_states[dns->s.id].local_ip, addrlen);
1388       }
1389       else if (addrlen == 4)
1390       {
1391         struct sockaddr_in *addr_ = (struct sockaddr_in *) addr;
1392
1393         memcpy (answer->pkt.from, &addr_->sin_addr.s_addr, addrlen);
1394         memcpy (answer->pkt.to, query_states[dns->s.id].local_ip, addrlen);
1395       }
1396       else
1397       {
1398         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "addrlen = %d\n", addrlen);
1399         GNUNET_assert (0);
1400       }
1401       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "sending answer with addrlen = %d\n",
1402                   addrlen);
1403       answer->pkt.dst_port = query_states[dns->s.id].local_port;
1404       memcpy (answer->pkt.data, dns, r);
1405       answer->client = query_states[dns->s.id].client;
1406
1407       GNUNET_CONTAINER_DLL_insert_after (head, tail, tail, answer);
1408
1409       if (server_notify == NULL)
1410         server_notify =
1411             GNUNET_SERVER_notify_transmit_ready (query_states[dns->s.id].client,
1412                                                  len,
1413                                                  GNUNET_TIME_UNIT_FOREVER_REL,
1414                                                  &send_answer, NULL);
1415     }
1416   }
1417   GNUNET_free (addr);
1418 }
1419
1420
1421 /**
1422  * Task run during shutdown.
1423  *
1424  * @param cls unused
1425  * @param tc unused
1426  */
1427 static void
1428 cleanup_task (void *cls GNUNET_UNUSED,
1429               const struct GNUNET_SCHEDULER_TaskContext *tc)
1430 {
1431   GNUNET_assert (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN));
1432
1433   unhijack (dnsoutport);
1434   GNUNET_DHT_disconnect (dht);
1435   GNUNET_MESH_disconnect (mesh_handle);
1436 }
1437
1438 /**
1439  * @brief Create a port-map from udp and tcp redirects
1440  *
1441  * @param udp_redirects
1442  * @param tcp_redirects
1443  *
1444  * @return
1445  */
1446 static uint64_t
1447 get_port_from_redirects (const char *udp_redirects, const char *tcp_redirects)
1448 {
1449   uint64_t ret = 0;
1450   char *cpy, *hostname, *redirect;
1451   int local_port;
1452   unsigned int count = 0;
1453
1454   cpy = NULL;
1455   if (NULL != udp_redirects)
1456   {
1457     cpy = GNUNET_strdup (udp_redirects);
1458     for (redirect = strtok (cpy, " "); redirect != NULL;
1459          redirect = strtok (NULL, " "))
1460     {
1461       if (NULL == (hostname = strstr (redirect, ":")))
1462       {
1463         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1464                     "Warning: option %s is not formatted correctly!\n",
1465                     redirect);
1466         continue;
1467       }
1468       hostname[0] = '\0';
1469       local_port = atoi (redirect);
1470       if (!((local_port > 0) && (local_port < 65536)))
1471         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1472                     "Warning: %s is not a correct port.", redirect);
1473
1474       ret |= (0xFFFF & htons (local_port));
1475       ret <<= 16;
1476       count++;
1477
1478       if (count > 4)
1479       {
1480         ret = 0;
1481         goto out;
1482       }
1483     }
1484     GNUNET_free (cpy);
1485     cpy = NULL;
1486   }
1487
1488   if (NULL != tcp_redirects)
1489   {
1490     cpy = GNUNET_strdup (tcp_redirects);
1491     for (redirect = strtok (cpy, " "); redirect != NULL;
1492          redirect = strtok (NULL, " "))
1493     {
1494       if (NULL == (hostname = strstr (redirect, ":")))
1495       {
1496         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1497                     "Warning: option %s is not formatted correctly!\n",
1498                     redirect);
1499         continue;
1500       }
1501       hostname[0] = '\0';
1502       local_port = atoi (redirect);
1503       if (!((local_port > 0) && (local_port < 65536)))
1504         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1505                     "Warning: %s is not a correct port.", redirect);
1506
1507       ret |= (0xFFFF & htons (local_port));
1508       ret <<= 16;
1509       count++;
1510
1511       if (count > 4)
1512       {
1513         ret = 0;
1514         goto out;
1515       }
1516     }
1517     GNUNET_free (cpy);
1518     cpy = NULL;
1519   }
1520
1521 out:
1522   GNUNET_free_non_null (cpy);
1523   return ret;
1524 }
1525
1526 static void
1527 publish_name (const char *name, uint64_t ports, uint32_t service_type,
1528               struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key)
1529 {
1530   size_t size = sizeof (struct GNUNET_DNS_Record);
1531   struct GNUNET_DNS_Record data;
1532
1533   memset (&data, 0, size);
1534
1535   data.purpose.size = htonl (size - sizeof (struct GNUNET_CRYPTO_RsaSignature));
1536   data.purpose.purpose = GNUNET_SIGNATURE_PURPOSE_DNS_RECORD;
1537
1538   GNUNET_CRYPTO_hash (name, strlen (name) + 1, &data.service_descriptor);
1539   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Store with key1 %x\n",
1540               *((unsigned long long *) &data.service_descriptor));
1541
1542   data.service_type = service_type;
1543   data.ports = ports;
1544
1545   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &data.peer);
1546
1547   data.expiration_time =
1548       GNUNET_TIME_absolute_hton (GNUNET_TIME_relative_to_absolute
1549                                  (GNUNET_TIME_relative_multiply
1550                                   (GNUNET_TIME_UNIT_HOURS, 2)));
1551
1552   /* Sign the block */
1553   if (GNUNET_OK !=
1554       GNUNET_CRYPTO_rsa_sign (my_private_key, &data.purpose, &data.signature))
1555   {
1556     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not sign DNS_Record\n");
1557     return;
1558   }
1559
1560   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Putting with key %08x, size = %d\n",
1561               *((unsigned int *) &data.service_descriptor), size);
1562
1563   GNUNET_DHT_put (dht, &data.service_descriptor,
1564                   5 /* DEFAULT_PUT_REPLICATION */ ,
1565                   GNUNET_DHT_RO_NONE, GNUNET_BLOCK_TYPE_DNS, size,
1566                   (char *) &data,
1567                   GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS),
1568                   GNUNET_TIME_UNIT_MINUTES, NULL, NULL);
1569 }
1570
1571
1572 /**
1573  * @brief Publishes the record defined by the section section
1574  *
1575  * @param cls closure
1576  * @param section the current section
1577  */
1578 static void
1579 publish_iterate (void *cls GNUNET_UNUSED, const char *section)
1580 {
1581   char *udp_redirects;
1582   char *tcp_redirects;
1583   char *alternative_names;
1584   char *alternative_name;
1585   char *keyfile;
1586
1587   if ((strlen (section) < 8) ||
1588       (0 != strcmp (".gnunet.", section + (strlen (section) - 8))))
1589     return;
1590   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Parsing dns-name %s\n", section);
1591   if (GNUNET_OK !=
1592       GNUNET_CONFIGURATION_get_value_string (cfg, section, "UDP_REDIRECTS",
1593                                              &udp_redirects))
1594     udp_redirects = NULL;
1595   if (GNUNET_OK !=
1596       GNUNET_CONFIGURATION_get_value_string (cfg, section, "TCP_REDIRECTS",
1597                                              &tcp_redirects))
1598     tcp_redirects = NULL;
1599
1600   if (GNUNET_OK !=
1601       GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
1602                                                &keyfile))
1603   {
1604     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not read keyfile-value\n");
1605     if (keyfile != NULL)
1606       GNUNET_free (keyfile);
1607     return;
1608   }
1609
1610   struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key =
1611       GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1612   GNUNET_free (keyfile);
1613   GNUNET_assert (my_private_key != NULL);
1614
1615   uint64_t ports = get_port_from_redirects (udp_redirects, tcp_redirects);
1616   uint32_t service_type = 0;
1617
1618   if (NULL != udp_redirects)
1619     service_type = GNUNET_DNS_SERVICE_TYPE_UDP;
1620
1621   if (NULL != tcp_redirects)
1622     service_type |= GNUNET_DNS_SERVICE_TYPE_TCP;
1623
1624   service_type = htonl (service_type);
1625
1626
1627   publish_name (section, ports, service_type, my_private_key);
1628   if (GNUNET_OK ==
1629       GNUNET_CONFIGURATION_get_value_string (cfg, section, "ALTERNATIVE_NAMES",
1630                                              &alternative_names))
1631   {
1632     for (alternative_name = strtok (alternative_names, " ");
1633          alternative_name != NULL; alternative_name = strtok (NULL, " "))
1634     {
1635       char *altname =
1636           alloca (strlen (alternative_name) + strlen (section) + 1 + 1);
1637       strcpy (altname, alternative_name);
1638       strcpy (altname + strlen (alternative_name) + 1, section);
1639       altname[strlen (alternative_name)] = '.';
1640
1641       publish_name (altname, ports, service_type, my_private_key);
1642     }
1643     GNUNET_free (alternative_names);
1644   }
1645   GNUNET_CRYPTO_rsa_key_free (my_private_key);
1646   GNUNET_free_non_null (udp_redirects);
1647   GNUNET_free_non_null (tcp_redirects);
1648 }
1649
1650 /**
1651  * Publish a DNS-record in the DHT.
1652  */
1653 static void
1654 publish_names (void *cls GNUNET_UNUSED,
1655                const struct GNUNET_SCHEDULER_TaskContext *tc)
1656 {
1657   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1658     return;
1659
1660   GNUNET_CONFIGURATION_iterate_sections (cfg, &publish_iterate, NULL);
1661
1662   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_HOURS, &publish_names, NULL);
1663 }
1664
1665 /**
1666  * @param cls closure
1667  * @param server the initialized server
1668  * @param cfg_ configuration to use
1669  */
1670 static void
1671 run (void *cls, struct GNUNET_SERVER_Handle *server,
1672      const struct GNUNET_CONFIGURATION_Handle *cfg_)
1673 {
1674   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1675     /* callback, cls, type, size */
1676     {&receive_query, NULL, GNUNET_MESSAGE_TYPE_VPN_DNS_LOCAL_QUERY_DNS, 0},
1677     {&rehijack, NULL, GNUNET_MESSAGE_TYPE_REHIJACK,
1678      sizeof (struct GNUNET_MessageHeader)},
1679     {NULL, NULL, 0, 0}
1680   };
1681
1682   static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
1683     {receive_mesh_query, GNUNET_MESSAGE_TYPE_VPN_REMOTE_QUERY_DNS, 0},
1684     {receive_mesh_answer, GNUNET_MESSAGE_TYPE_VPN_REMOTE_ANSWER_DNS, 0},
1685     {NULL, 0, 0}
1686   };
1687
1688   static GNUNET_MESH_ApplicationType apptypes[] = {
1689     GNUNET_APPLICATION_TYPE_END,
1690     GNUNET_APPLICATION_TYPE_END
1691   };
1692
1693   if (GNUNET_YES != open_port6 ())
1694   {
1695     GNUNET_SCHEDULER_shutdown ();
1696     return;
1697   }
1698
1699   if (GNUNET_YES != open_port ())
1700   {
1701     GNUNET_SCHEDULER_shutdown ();
1702     return;
1703   }
1704
1705   if (GNUNET_YES ==
1706       GNUNET_CONFIGURATION_get_value_yesno (cfg_, "dns", "PROVIDE_EXIT"))
1707     apptypes[0] = GNUNET_APPLICATION_TYPE_INTERNET_RESOLVER;
1708   mesh_handle =
1709       GNUNET_MESH_connect (cfg_, 42, NULL, new_tunnel, clean_tunnel,
1710                            mesh_handlers, apptypes);
1711
1712   cfg = cfg_;
1713   dht = GNUNET_DHT_connect (cfg, 1024);
1714   GNUNET_SCHEDULER_add_now (publish_names, NULL);
1715   GNUNET_SERVER_add_handlers (server, handlers);
1716   GNUNET_SERVER_disconnect_notify (server, &client_disconnect, NULL);
1717   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1718                                 cls);
1719 }
1720
1721 /**
1722  * The main function for the dns service.
1723  *
1724  * @param argc number of arguments from the command line
1725  * @param argv command line arguments
1726  * @return 0 ok, 1 on error
1727  */
1728 int
1729 main (int argc, char *const *argv)
1730 {
1731   return (GNUNET_OK ==
1732           GNUNET_SERVICE_run (argc, argv, "dns", GNUNET_SERVICE_OPTION_NONE,
1733                               &run, NULL)) ? 0 : 1;
1734 }