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