clarifying comment
[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
739         memcpy(&cls_->dns, dns, cls_->hdr.size);
740         GNUNET_SCHEDULER_add_now(send_mesh_query, cls_);
741
742         goto out;
743       }
744
745
746     /* The query should be sent to the network */
747
748     struct sockaddr_in dest;
749     memset(&dest, 0, sizeof dest);
750     dest.sin_port = htons(53);
751     dest.sin_addr.s_addr = pkt->orig_to;
752
753     GNUNET_NETWORK_socket_sendto(dnsout,
754                                  dns,
755                                  ntohs(pkt->hdr.size) - sizeof(struct query_packet) + 1,
756                                  (struct sockaddr*) &dest,
757                                  sizeof dest);
758
759 outfree:
760     free_parsed_dns_packet(pdns);
761     pdns = NULL;
762 out:
763     GNUNET_SERVER_receive_done(client, GNUNET_OK);
764 }
765
766 static void read_response (void *cls,
767                            const struct GNUNET_SCHEDULER_TaskContext *tc);
768
769 static void
770 open_port ()
771 {
772   struct sockaddr_in addr;
773
774   dnsout = GNUNET_NETWORK_socket_create (AF_INET, SOCK_DGRAM, 0);
775   if (dnsout == NULL)
776     return;
777   memset (&addr, 0, sizeof (struct sockaddr_in));
778
779   int err = GNUNET_NETWORK_socket_bind (dnsout,
780                                         (struct sockaddr *) &addr,
781                                         sizeof (struct sockaddr_in));
782
783   if (err != GNUNET_YES)
784     {
785       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
786                   "Could not bind a port, exiting\n");
787       return;
788     }
789
790   /* Read the port we bound to */
791   socklen_t addrlen = sizeof (struct sockaddr_in);
792   err = getsockname (GNUNET_NETWORK_get_fd (dnsout),
793                      (struct sockaddr *) &addr, &addrlen);
794
795   dnsoutport = htons (addr.sin_port);
796
797   GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, dnsout,
798                                  &read_response, NULL);
799 }
800
801 /**
802  * Read a response-packet of the UDP-Socket
803  */
804 static void
805 read_response (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
806 {
807   struct sockaddr_in addr;
808   socklen_t addrlen = sizeof (addr);
809   int r;
810   int len;
811
812   if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
813     return;
814
815   memset (&addr, 0, sizeof addr);
816
817 #ifndef MINGW
818   if (0 != ioctl (GNUNET_NETWORK_get_fd (dnsout), FIONREAD, &len))
819     {
820       unhijack (dnsoutport);
821       open_port ();
822       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, hijack, NULL);
823       return;
824     }
825 #else
826   /* port the code above? */
827   len = 65536;
828 #endif
829   {
830     unsigned char buf[len];
831     struct dns_pkt *dns = (struct dns_pkt *) buf;
832
833     r = GNUNET_NETWORK_socket_recvfrom (dnsout,
834                                         buf,
835                                         sizeof (buf),
836                                         (struct sockaddr *) &addr, &addrlen);
837
838     if (r < 0)
839       {
840         unhijack (dnsoutport);
841         open_port ();
842         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, hijack, NULL);
843         return;
844       }
845
846     if (query_states[dns->s.id].valid == GNUNET_YES)
847       {
848         if (query_states[dns->s.id].tunnel != NULL)
849           {
850             uint32_t *c = GNUNET_malloc(4 + r);
851             *c = r;
852             memcpy(c+1, dns, r);
853             GNUNET_MESH_notify_transmit_ready (query_states[dns->s.id].tunnel,
854                                                GNUNET_YES,
855                                                32,
856                                                GNUNET_TIME_UNIT_MINUTES,
857                                                NULL, r + sizeof(struct GNUNET_MessageHeader), mesh_send_response, c);
858           }
859         else
860           {
861             query_states[dns->s.id].valid = GNUNET_NO;
862
863             size_t len = sizeof (struct answer_packet) + r - 1; /* 1 for the unsigned char data[1]; */
864             struct answer_packet_list *answer =
865               GNUNET_malloc (len + 2 * sizeof (struct answer_packet_list *));
866             answer->pkt.hdr.type =
867               htons (GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS);
868             answer->pkt.hdr.size = htons (len);
869             answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_IP;
870             answer->pkt.from = addr.sin_addr.s_addr;
871             answer->pkt.to = query_states[dns->s.id].local_ip;
872             answer->pkt.dst_port = query_states[dns->s.id].local_port;
873             memcpy (answer->pkt.data, buf, r);
874
875             GNUNET_CONTAINER_DLL_insert_after (head, tail, tail, answer);
876
877             GNUNET_SERVER_notify_transmit_ready (query_states[dns->s.id].
878                                                  client, len,
879                                                  GNUNET_TIME_UNIT_FOREVER_REL,
880                                                  &send_answer,
881                                                  query_states[dns->s.id].
882                                                  client);
883           }
884       }
885   }
886   GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
887                                  dnsout, &read_response, NULL);
888 }
889
890
891 /**
892  * Task run during shutdown.
893  *
894  * @param cls unused
895  * @param tc unused
896  */
897 static void
898 cleanup_task (void *cls,
899               const struct GNUNET_SCHEDULER_TaskContext *tc)
900 {
901   unhijack(dnsoutport);
902   GNUNET_DHT_disconnect(dht);
903 }
904
905 /**
906  * @brief Create a port-map from udp and tcp redirects
907  *
908  * @param udp_redirects
909  * @param tcp_redirects
910  *
911  * @return 
912  */
913 uint64_t
914 get_port_from_redirects (const char *udp_redirects, const char *tcp_redirects)
915 {
916   uint64_t ret = 0;
917   char* cpy, *hostname, *redirect;
918   int local_port, count = 0;
919
920   if (NULL != udp_redirects)
921     {
922       cpy = GNUNET_strdup (udp_redirects);
923       for (redirect = strtok (cpy, " "); redirect != NULL; redirect = strtok (NULL, " "))
924         {
925           if (NULL == (hostname = strstr (redirect, ":")))
926             {
927               GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: option %s is not formatted correctly!\n", redirect);
928               continue;
929             }
930           hostname[0] = '\0';
931           local_port = atoi (redirect);
932           if (!((local_port > 0) && (local_port < 65536)))
933             GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: %s is not a correct port.", redirect);
934
935           ret |= (0xFFFF & htons(local_port));
936           ret <<= 16;
937           count ++;
938
939           if(count > 4)
940             {
941               ret = 0;
942               goto out;
943             }
944         }
945       GNUNET_free(cpy);
946       cpy = NULL;
947     }
948
949   if (NULL != tcp_redirects)
950     {
951       cpy = GNUNET_strdup (tcp_redirects);
952       for (redirect = strtok (cpy, " "); redirect != NULL; redirect = strtok (NULL, " "))
953         {
954           if (NULL == (hostname = strstr (redirect, ":")))
955             {
956               GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: option %s is not formatted correctly!\n", redirect);
957               continue;
958             }
959           hostname[0] = '\0';
960           local_port = atoi (redirect);
961           if (!((local_port > 0) && (local_port < 65536)))
962             GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: %s is not a correct port.", redirect);
963
964           ret |= (0xFFFF & htons(local_port));
965           ret <<= 16;
966           count ++;
967
968           if(count > 4)
969             {
970               ret = 0;
971               goto out;
972             }
973         }
974       GNUNET_free(cpy);
975       cpy = NULL;
976     }
977
978 out:
979   if (NULL != cpy)
980     GNUNET_free(cpy);
981   return ret;
982 }
983
984 void
985 publish_name (const char *name, uint64_t ports, uint32_t service_type,
986               struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key)
987 {
988   size_t size = sizeof (struct GNUNET_DNS_Record);
989   struct GNUNET_DNS_Record data;
990   memset (&data, 0, size);
991
992   data.purpose.size =
993     htonl (size - sizeof (struct GNUNET_CRYPTO_RsaSignature));
994   data.purpose.purpose = GNUNET_SIGNATURE_PURPOSE_DNS_RECORD;
995
996   GNUNET_CRYPTO_hash (name, strlen (name) + 1, &data.service_descriptor);
997   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Store with key1 %x\n",
998               *((unsigned long long *) &data.service_descriptor));
999
1000   data.service_type = service_type;
1001   data.ports = ports;
1002
1003   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &data.peer);
1004
1005   data.expiration_time =
1006     GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_HOURS, 2));
1007
1008   /* Sign the block */
1009   if (GNUNET_OK != GNUNET_CRYPTO_rsa_sign (my_private_key,
1010                                            &data.purpose, &data.signature))
1011     {
1012       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not sign DNS_Record\n");
1013       return;
1014     }
1015
1016   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1017               "Putting with key %08x, size = %d\n",
1018               *((unsigned int *) &data.service_descriptor), size);
1019
1020   GNUNET_DHT_put (dht,
1021                   &data.service_descriptor,
1022                   DEFAULT_PUT_REPLICATION,
1023                   GNUNET_DHT_RO_NONE,
1024                   GNUNET_BLOCK_TYPE_DNS,
1025                   size,
1026                   (char *) &data,
1027                   GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS),
1028                   GNUNET_TIME_UNIT_MINUTES, NULL, NULL);
1029 }
1030
1031 /**
1032  * @brief Publishes the record defined by the section section
1033  *
1034  * @param cls closure
1035  * @param section the current section
1036  */
1037 void
1038 publish_iterate (void *cls, const char *section)
1039 {
1040   char *udp_redirects, *tcp_redirects, *alternative_names, *alternative_name,
1041     *keyfile;
1042
1043   GNUNET_CONFIGURATION_get_value_string (servicecfg, section,
1044                                          "UDP_REDIRECTS", &udp_redirects);
1045   GNUNET_CONFIGURATION_get_value_string (servicecfg, section, "TCP_REDIRECTS",
1046                                          &tcp_redirects);
1047
1048   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD",
1049                                                             "HOSTKEY",
1050                                                             &keyfile))
1051     {
1052       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not read keyfile-value\n");
1053       if (keyfile != NULL)
1054         GNUNET_free (keyfile);
1055       return;
1056     }
1057
1058   struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key =
1059     GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1060   GNUNET_free (keyfile);
1061   GNUNET_assert (my_private_key != NULL);
1062
1063   uint64_t ports = get_port_from_redirects (udp_redirects, tcp_redirects);
1064   uint32_t service_type = 0;
1065
1066   if (NULL != udp_redirects)
1067     service_type = GNUNET_DNS_SERVICE_TYPE_UDP;
1068
1069   if (NULL != tcp_redirects)
1070     service_type |= GNUNET_DNS_SERVICE_TYPE_TCP;
1071
1072   service_type = htonl (service_type);
1073
1074
1075   publish_name (section, ports, service_type, my_private_key);
1076
1077   GNUNET_CONFIGURATION_get_value_string (servicecfg, section,
1078                                          "ALTERNATIVE_NAMES",
1079                                          &alternative_names);
1080   for (alternative_name = strtok (alternative_names, " ");
1081        alternative_name != NULL; alternative_name = strtok (NULL, " "))
1082     {
1083       char *altname =
1084         alloca (strlen (alternative_name) + strlen (section) + 1 + 1);
1085       strcpy (altname, alternative_name);
1086       strcpy (altname + strlen (alternative_name) + 1, section);
1087       altname[strlen (alternative_name)] = '.';
1088
1089       publish_name (altname, ports, service_type, my_private_key);
1090     }
1091
1092   GNUNET_free_non_null(alternative_names);
1093   GNUNET_CRYPTO_rsa_key_free (my_private_key);
1094   GNUNET_free_non_null (udp_redirects);
1095   GNUNET_free_non_null (tcp_redirects);
1096 }
1097
1098 /**
1099  * Publish a DNS-record in the DHT. This is up to now just for testing.
1100  */
1101 static void
1102 publish_names (void *cls,
1103                const struct GNUNET_SCHEDULER_TaskContext *tc) {
1104     char *services;
1105     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1106       return;
1107
1108     if (NULL != servicecfg)
1109       GNUNET_CONFIGURATION_destroy(servicecfg);
1110
1111     GNUNET_CONFIGURATION_get_value_filename(cfg, "dns", "SERVICES", &services);
1112
1113     servicecfg = GNUNET_CONFIGURATION_create();
1114     if (GNUNET_OK == GNUNET_CONFIGURATION_parse(servicecfg, services))
1115       {
1116         GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Parsing services %s\n", services);
1117         GNUNET_CONFIGURATION_iterate_sections(servicecfg, publish_iterate, NULL);
1118       }
1119     if (NULL != services)
1120       GNUNET_free(services);
1121
1122     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_HOURS,
1123                                   publish_names,
1124                                   NULL);
1125 }
1126
1127 /**
1128  * @param cls closure
1129  * @param server the initialized server
1130  * @param cfg_ configuration to use
1131  */
1132 static void
1133 run (void *cls,
1134      struct GNUNET_SERVER_Handle *server,
1135      const struct GNUNET_CONFIGURATION_Handle *cfg_)
1136 {
1137   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1138     /* callback, cls, type, size */
1139     {&receive_query, NULL, GNUNET_MESSAGE_TYPE_LOCAL_QUERY_DNS, 0},
1140     {&rehijack, NULL, GNUNET_MESSAGE_TYPE_REHIJACK,
1141      sizeof (struct GNUNET_MessageHeader)},
1142     {NULL, NULL, 0, 0}
1143   };
1144
1145   static struct GNUNET_MESH_MessageHandler *mesh_handlers;
1146
1147   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg_, "dns", "PROVIDE_EXIT"))
1148     mesh_handlers = (struct GNUNET_MESH_MessageHandler[]) {
1149           {receive_mesh_query, GNUNET_MESSAGE_TYPE_REMOTE_QUERY_DNS, 0},
1150           {NULL, 0, 0}
1151     };
1152   else
1153     mesh_handlers = (struct GNUNET_MESH_MessageHandler[]) {
1154           {receive_mesh_answer, GNUNET_MESSAGE_TYPE_REMOTE_ANSWER_DNS, 0},
1155           {NULL, 0, 0}
1156     };
1157
1158   const static GNUNET_MESH_ApplicationType apptypes[] =
1159     { GNUNET_APPLICATION_TYPE_INTERNET_RESOLVER,
1160     GNUNET_APPLICATION_TYPE_END
1161   };
1162
1163   mesh_handle = GNUNET_MESH_connect (cfg_, NULL, NULL, mesh_handlers, apptypes);
1164
1165   cfg = cfg_;
1166
1167   unsigned int i;
1168   for (i = 0; i < 65536; i++)
1169     {
1170       query_states[i].valid = GNUNET_NO;
1171     }
1172
1173   dht = GNUNET_DHT_connect (cfg, 1024);
1174
1175   open_port ();
1176
1177   GNUNET_SCHEDULER_add_now (publish_names, NULL);
1178
1179   GNUNET_SERVER_add_handlers (server, handlers);
1180   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1181                                 &cleanup_task, cls);
1182 }
1183
1184 /**
1185  * The main function for the dns service.
1186  *
1187  * @param argc number of arguments from the command line
1188  * @param argv command line arguments
1189  * @return 0 ok, 1 on error
1190  */
1191 int
1192 main (int argc, char *const *argv)
1193 {
1194   return (GNUNET_OK ==
1195           GNUNET_SERVICE_run (argc,
1196                               argv,
1197                               "dns",
1198                               GNUNET_SERVICE_OPTION_NONE,
1199                               &run, NULL)) ? 0 : 1;
1200 }