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