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