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