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