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