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