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