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