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