Simplified notification messages
[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     drec_data->ttl = htonl(3600); /* FIXME: read from block */
249
250     /* Calculate at which offset in the packet the length of the name and the
251      * name, it is filled in by the daemon-vpn */
252     answer->pkt.addroffset = htons((unsigned short)((unsigned long)(&drec_data->data_len)-(unsigned long)(&answer->pkt)));
253
254     GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, answer);
255
256     GNUNET_SERVER_notify_transmit_ready(query_states[id].client,
257                                         len,
258                                         GNUNET_TIME_UNIT_FOREVER_REL,
259                                         &send_answer,
260                                         query_states[id].client);
261
262     /*
263      * build
264      * complete dns-packet with empty name in the answer
265      * provide offsett of the name
266      */
267 }
268
269 /**
270  * Receive a block from the dht.
271  */
272 static void
273 receive_dht(void *cls,
274             struct GNUNET_TIME_Absolute exp,
275             const GNUNET_HashCode *key,
276             const struct GNUNET_PeerIdentity *const *get_path,
277             const struct GNUNET_PeerIdentity *const *put_path,
278             enum GNUNET_BLOCK_Type type,
279             size_t size,
280             const void *data) {
281
282     unsigned short id = ((struct receive_dht_cls*)cls)->id;
283     struct GNUNET_DHT_GetHandle* handle = ((struct receive_dht_cls*)cls)->handle;
284     GNUNET_free(cls);
285
286     GNUNET_assert(type == GNUNET_BLOCK_TYPE_DNS);
287
288     /* If no query with this id is pending, ignore the block */
289     if (query_states[id].valid != GNUNET_YES) return;
290     query_states[id].valid = GNUNET_NO;
291
292     const struct GNUNET_DNS_Record* rec = data;
293     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
294                "Got block of size %d, peer: %08x, desc: %08x\n",
295                size,
296                *((unsigned int*)&rec->peer),
297                *((unsigned int*)&rec->service_descriptor));
298
299     size_t len = sizeof(struct answer_packet) - 1 \
300                  + sizeof(struct dns_static) \
301                  + query_states[id].namelen \
302                  + sizeof(struct dns_query_line) \
303                  + 2 /* To hold the pointer (as defined in RFC1035) to the name */ \
304                  + sizeof(struct dns_record_line) - 1 \
305                  + 16; /* To hold the IPv6-Address */
306
307     struct answer_packet_list* answer = GNUNET_malloc(len + 2*sizeof(struct answer_packet_list*));
308     memset(answer, 0, len + 2*sizeof(struct answer_packet_list*));
309
310     answer->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS);
311     answer->pkt.hdr.size = htons(len);
312     answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_SERVICE;
313
314     GNUNET_CRYPTO_hash(&rec->peer,
315                        sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
316                        &answer->pkt.service_descr.peer);
317
318     memcpy(&answer->pkt.service_descr.service_descriptor,
319            &rec->service_descriptor,
320            sizeof(GNUNET_HashCode));
321     memcpy(&answer->pkt.service_descr.service_type,
322            &rec->service_type,
323            sizeof(answer->pkt.service_descr.service_type));
324     memcpy(&answer->pkt.service_descr.ports, &rec->ports, sizeof(answer->pkt.service_descr.ports));
325
326     answer->pkt.from = query_states[id].remote_ip;
327
328     answer->pkt.to = query_states[id].local_ip;
329     answer->pkt.dst_port = query_states[id].local_port;
330
331     struct dns_pkt *dpkt = (struct dns_pkt*)answer->pkt.data;
332
333     dpkt->s.id = id;
334     dpkt->s.aa = 1;
335     dpkt->s.qr = 1;
336     dpkt->s.ra = 1;
337     dpkt->s.qdcount = htons(1);
338     dpkt->s.ancount = htons(1);
339
340     memcpy(dpkt->data, query_states[id].name, query_states[id].namelen);
341     GNUNET_free(query_states[id].name);
342
343     struct dns_query_line* dque = (struct dns_query_line*)(dpkt->data+(query_states[id].namelen));
344     dque->type = htons(28); /* AAAA */
345     dque->class = htons(1); /* IN */
346
347     char* anname = (char*)(dpkt->data+(query_states[id].namelen)+sizeof(struct dns_query_line));
348     memcpy(anname, (char[]){0xc0, 0x0c}, 2);
349
350     struct dns_record_line *drec_data = (struct dns_record_line*)(dpkt->data+(query_states[id].namelen)+sizeof(struct dns_query_line)+2);
351     drec_data->type = htons(28); /* AAAA */
352     drec_data->class = htons(1); /* IN */
353     drec_data->ttl = htonl(3600); /* FIXME: read from block */
354     drec_data->data_len = htons(16);
355
356     /* Calculate at which offset in the packet the IPv6-Address belongs, it is
357      * filled in by the daemon-vpn */
358     answer->pkt.addroffset = htons((unsigned short)((unsigned long)(&drec_data->data)-(unsigned long)(&answer->pkt)));
359
360     GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, answer);
361
362     GNUNET_SERVER_notify_transmit_ready(query_states[id].client,
363                                         len,
364                                         GNUNET_TIME_UNIT_FOREVER_REL,
365                                         &send_answer,
366                                         query_states[id].client);
367
368     GNUNET_DHT_get_stop(handle);
369 }
370
371 /**
372  * This receives a GNUNET_MESSAGE_TYPE_REHIJACK and rehijacks the DNS
373  */
374 static void
375 rehijack(void *cls,
376          struct GNUNET_SERVER_Client *client,
377          const struct GNUNET_MessageHeader *message) {
378     unhijack(dnsoutport);
379     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, hijack, NULL);
380
381     GNUNET_SERVER_receive_done(client, GNUNET_OK);
382 }
383
384 /**
385  * This receives the dns-payload from the daemon-vpn and sends it on over the udp-socket
386  */
387 static void
388 receive_query(void *cls,
389               struct GNUNET_SERVER_Client *client,
390               const struct GNUNET_MessageHeader *message) {
391     struct query_packet* pkt = (struct query_packet*)message;
392     struct dns_pkt* dns = (struct dns_pkt*)pkt->data;
393     struct dns_pkt_parsed* pdns = parse_dns_packet(dns);
394
395     query_states[dns->s.id].valid = GNUNET_YES;
396     query_states[dns->s.id].client = client;
397     query_states[dns->s.id].local_ip = pkt->orig_from;
398     query_states[dns->s.id].local_port = pkt->src_port;
399     query_states[dns->s.id].remote_ip = pkt->orig_to;
400     query_states[dns->s.id].namelen = strlen((char*)dns->data) + 1;
401     query_states[dns->s.id].name = GNUNET_malloc(query_states[dns->s.id].namelen);
402     memcpy(query_states[dns->s.id].name, dns->data, query_states[dns->s.id].namelen);
403
404     /* The query is for a .gnunet-address */
405     if (pdns->queries[0]->namelen > 9 &&
406         0 == strncmp(pdns->queries[0]->name+(pdns->queries[0]->namelen - 9), ".gnunet.", 9))
407       {
408         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Query for .gnunet!\n");
409         GNUNET_HashCode key;
410         GNUNET_CRYPTO_hash(pdns->queries[0]->name, pdns->queries[0]->namelen, &key);
411
412         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
413                    "Getting with key %08x, len is %d\n",
414                    *((unsigned int*)&key),
415                    pdns->queries[0]->namelen);
416
417         struct receive_dht_cls* cls = GNUNET_malloc(sizeof(struct receive_dht_cls));
418         cls->id = dns->s.id;
419
420         cls->handle = GNUNET_DHT_get_start(dht,
421                                            GNUNET_TIME_UNIT_MINUTES,
422                                            GNUNET_BLOCK_TYPE_DNS,
423                                            &key,
424                                            DEFAULT_GET_REPLICATION,
425                                            GNUNET_DHT_RO_NONE,
426                                            NULL,
427                                            0,
428                                            NULL,
429                                            0,
430                                            receive_dht,
431                                            cls);
432
433         goto outfree;
434       }
435
436     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Query for '%s'; namelen=%d\n", pdns->queries[0]->name, pdns->queries[0]->namelen);
437     /* The query is for a PTR of a previosly resolved virtual IP */
438     if (htons(pdns->queries[0]->qtype) == 12 &&
439         74 == pdns->queries[0]->namelen)
440       {
441         char* ipv6addr;
442         char ipv6[16];
443         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.";
444         unsigned int i;
445         unsigned long long ipv6prefix;
446         unsigned int comparelen;
447
448         GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "vpn", "IPV6ADDR", &ipv6addr));
449         inet_pton (AF_INET6, ipv6addr, ipv6);
450         GNUNET_free(ipv6addr);
451
452         GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "vpn", "IPV6PREFIX", &ipv6prefix));
453         GNUNET_assert(ipv6prefix < 127);
454         ipv6prefix = (ipv6prefix + 7)/8;
455
456         for (i = ipv6prefix; i < 16; i++)
457           ipv6[i] = 0;
458
459         for (i = 0; i < 16; i++)
460           {
461             unsigned char c1 = ipv6[i] >> 4;
462             unsigned char c2 = ipv6[i] & 0xf;
463
464             if (c1 <= 9)
465               ipv6rev[62-(4*i)] = c1 + '0';
466             else
467               ipv6rev[62-(4*i)] = c1 + 87; /* 87 is the difference between 'a' and 10 */
468
469             if (c2 <= 9)
470               ipv6rev[62-((4*i)+2)] = c2 + '0';
471             else
472               ipv6rev[62-((4*i)+2)] = c2 + 87;
473           }
474         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "My network is %s'.\n", ipv6rev);
475         comparelen = 10 + 4*ipv6prefix;
476         if(0 == strncmp(pdns->queries[0]->name+(pdns->queries[0]->namelen - comparelen),
477                         ipv6rev + (74 - comparelen),
478                         comparelen))
479           {
480             GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Reverse-Query for .gnunet!\n");
481
482             GNUNET_SCHEDULER_add_now(send_rev_query, pdns);
483
484             goto out;
485           }
486       }
487
488     /* The query should be sent to the network */
489
490     struct sockaddr_in dest;
491     memset(&dest, 0, sizeof dest);
492     dest.sin_port = htons(53);
493     dest.sin_addr.s_addr = pkt->orig_to;
494
495     GNUNET_NETWORK_socket_sendto(dnsout,
496                                  dns,
497                                  ntohs(pkt->hdr.size) - sizeof(struct query_packet) + 1,
498                                  (struct sockaddr*) &dest,
499                                  sizeof dest);
500
501 outfree:
502     free_parsed_dns_packet(pdns);
503     pdns = NULL;
504 out:
505     GNUNET_SERVER_receive_done(client, GNUNET_OK);
506 }
507
508 static void read_response (void *cls,
509                            const struct GNUNET_SCHEDULER_TaskContext *tc);
510
511 static void
512 open_port ()
513 {
514   struct sockaddr_in addr;
515
516   dnsout = GNUNET_NETWORK_socket_create (AF_INET, SOCK_DGRAM, 0);
517   if (dnsout == NULL)
518     return;
519   memset (&addr, 0, sizeof (struct sockaddr_in));
520
521   int err = GNUNET_NETWORK_socket_bind (dnsout,
522                                         (struct sockaddr *) &addr,
523                                         sizeof (struct sockaddr_in));
524
525   if (err != GNUNET_YES)
526     {
527       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
528                   "Could not bind a port, exiting\n");
529       return;
530     }
531
532   /* Read the port we bound to */
533   socklen_t addrlen = sizeof (struct sockaddr_in);
534   err = getsockname (GNUNET_NETWORK_get_fd (dnsout),
535                      (struct sockaddr *) &addr, &addrlen);
536
537   dnsoutport = htons (addr.sin_port);
538
539   GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, dnsout,
540                                  &read_response, NULL);
541 }
542
543 /**
544  * Read a response-packet of the UDP-Socket
545  */
546 static void
547 read_response (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc) {
548     struct sockaddr_in addr;
549     socklen_t addrlen = sizeof (addr);
550     int r;
551     int len;
552
553     if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
554       return;
555
556     memset(&addr, 0, sizeof addr);
557
558 #ifndef MINGW
559     if (0 != ioctl (GNUNET_NETWORK_get_fd (dnsout), 
560                     FIONREAD, &len))
561       {
562         unhijack(dnsoutport);
563         open_port();
564         GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, hijack, NULL);
565         return;
566       }
567 #else
568     /* port the code above? */
569     len = 65536;
570 #endif
571     {
572       unsigned char buf[len];
573       struct dns_pkt* dns = (struct dns_pkt*)buf;
574
575       r = GNUNET_NETWORK_socket_recvfrom (dnsout,
576                                           buf,
577                                           sizeof (buf),
578                                           (struct sockaddr*)&addr,
579                                           &addrlen);
580       
581       if (r < 0)
582         {
583           unhijack(dnsoutport);
584           open_port();
585           GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS, hijack, NULL);
586           return;
587         }
588       
589       if (query_states[dns->s.id].valid == GNUNET_YES) 
590         {
591           query_states[dns->s.id].valid = GNUNET_NO;
592           
593           size_t len = sizeof(struct answer_packet) + r - 1; /* 1 for the unsigned char data[1]; */
594           struct answer_packet_list* answer = GNUNET_malloc(len + 2*sizeof(struct answer_packet_list*));
595           answer->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS);
596           answer->pkt.hdr.size = htons(len);
597           answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_IP;
598           answer->pkt.from = addr.sin_addr.s_addr;
599           answer->pkt.to = query_states[dns->s.id].local_ip;
600           answer->pkt.dst_port = query_states[dns->s.id].local_port;
601           memcpy(answer->pkt.data, buf, r);
602           
603           GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, answer);
604           
605           GNUNET_SERVER_notify_transmit_ready(query_states[dns->s.id].client,
606                                               len,
607                                               GNUNET_TIME_UNIT_FOREVER_REL,
608                                               &send_answer,
609                                               query_states[dns->s.id].client);
610         }
611     }
612     GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
613                                   dnsout,
614                                   &read_response,
615                                   NULL);
616 }
617
618
619 /**
620  * Task run during shutdown.
621  *
622  * @param cls unused
623  * @param tc unused
624  */
625 static void
626 cleanup_task (void *cls,
627               const struct GNUNET_SCHEDULER_TaskContext *tc)
628 {
629   unhijack(dnsoutport);
630   GNUNET_DHT_disconnect(dht);
631 }
632
633 /**
634  * @brief Create a port-map from udp and tcp redirects
635  *
636  * @param udp_redirects
637  * @param tcp_redirects
638  *
639  * @return 
640  */
641 uint64_t
642 get_port_from_redirects (const char *udp_redirects, const char *tcp_redirects)
643 {
644   uint64_t ret = 0;
645   char* cpy, *hostname, *redirect;
646   int local_port, count = 0;
647
648   if (NULL != udp_redirects)
649     {
650       cpy = GNUNET_strdup (udp_redirects);
651       for (redirect = strtok (cpy, " "); redirect != NULL; redirect = strtok (NULL, " "))
652         {
653           if (NULL == (hostname = strstr (redirect, ":")))
654             {
655               GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: option %s is not formatted correctly!\n", redirect);
656               continue;
657             }
658           hostname[0] = '\0';
659           local_port = atoi (redirect);
660           if (!((local_port > 0) && (local_port < 65536)))
661             GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: %s is not a correct port.", redirect);
662
663           ret |= (0xFFFF & htons(local_port));
664           ret <<= 16;
665           count ++;
666
667           if(count > 4)
668             {
669               ret = 0;
670               goto out;
671             }
672         }
673       GNUNET_free(cpy);
674       cpy = NULL;
675     }
676
677   if (NULL != tcp_redirects)
678     {
679       cpy = GNUNET_strdup (tcp_redirects);
680       for (redirect = strtok (cpy, " "); redirect != NULL; redirect = strtok (NULL, " "))
681         {
682           if (NULL == (hostname = strstr (redirect, ":")))
683             {
684               GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: option %s is not formatted correctly!\n", redirect);
685               continue;
686             }
687           hostname[0] = '\0';
688           local_port = atoi (redirect);
689           if (!((local_port > 0) && (local_port < 65536)))
690             GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Warning: %s is not a correct port.", redirect);
691
692           ret |= (0xFFFF & htons(local_port));
693           ret <<= 16;
694           count ++;
695
696           if(count > 4)
697             {
698               ret = 0;
699               goto out;
700             }
701         }
702       GNUNET_free(cpy);
703       cpy = NULL;
704     }
705
706 out:
707   if (NULL != cpy)
708     GNUNET_free(cpy);
709   return ret;
710 }
711
712 void
713 publish_name (const char *name, uint64_t ports, uint32_t service_type,
714               struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key)
715 {
716   size_t size = sizeof (struct GNUNET_DNS_Record);
717   struct GNUNET_DNS_Record data;
718   memset (&data, 0, size);
719
720   data.purpose.size =
721     htonl (size - sizeof (struct GNUNET_CRYPTO_RsaSignature));
722   data.purpose.purpose = GNUNET_SIGNATURE_PURPOSE_DNS_RECORD;
723
724   GNUNET_CRYPTO_hash (name, strlen (name) + 1, &data.service_descriptor);
725   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Store with key1 %x\n",
726               *((unsigned long long *) &data.service_descriptor));
727
728   data.service_type = service_type;
729   data.ports = ports;
730
731   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &data.peer);
732
733   data.expiration_time =
734     GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_HOURS, 2));
735
736   /* Sign the block */
737   if (GNUNET_OK != GNUNET_CRYPTO_rsa_sign (my_private_key,
738                                            &data.purpose, &data.signature))
739     {
740       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not sign DNS_Record\n");
741       return;
742     }
743
744   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
745               "Putting with key %08x, size = %d\n",
746               *((unsigned int *) &data.service_descriptor), size);
747
748   GNUNET_DHT_put (dht,
749                   &data.service_descriptor,
750                   DEFAULT_PUT_REPLICATION,
751                   GNUNET_DHT_RO_NONE,
752                   GNUNET_BLOCK_TYPE_DNS,
753                   size,
754                   (char *) &data,
755                   GNUNET_TIME_relative_to_absolute (GNUNET_TIME_UNIT_HOURS),
756                   GNUNET_TIME_UNIT_MINUTES, NULL, NULL);
757 }
758
759 /**
760  * @brief Publishes the record defined by the section section
761  *
762  * @param cls closure
763  * @param section the current section
764  */
765 void
766 publish_iterate (void *cls, const char *section)
767 {
768   char *udp_redirects, *tcp_redirects, *alternative_names, *alternative_name,
769     *keyfile;
770
771   GNUNET_CONFIGURATION_get_value_string (servicecfg, section,
772                                          "UDP_REDIRECTS", &udp_redirects);
773   GNUNET_CONFIGURATION_get_value_string (servicecfg, section, "TCP_REDIRECTS",
774                                          &tcp_redirects);
775
776   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD",
777                                                             "HOSTKEY",
778                                                             &keyfile))
779     {
780       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not read keyfile-value\n");
781       if (keyfile != NULL)
782         GNUNET_free (keyfile);
783       return;
784     }
785
786   struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key =
787     GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
788   GNUNET_free (keyfile);
789   GNUNET_assert (my_private_key != NULL);
790
791   uint64_t ports = get_port_from_redirects (udp_redirects, tcp_redirects);
792   uint32_t service_type = 0;
793
794   if (NULL != udp_redirects)
795     service_type = GNUNET_DNS_SERVICE_TYPE_UDP;
796
797   if (NULL != tcp_redirects)
798     service_type |= GNUNET_DNS_SERVICE_TYPE_TCP;
799
800   service_type = htonl (service_type);
801
802
803   publish_name (section, ports, service_type, my_private_key);
804
805   GNUNET_CONFIGURATION_get_value_string (servicecfg, section,
806                                          "ALTERNATIVE_NAMES",
807                                          &alternative_names);
808   for (alternative_name = strtok (alternative_names, " ");
809        alternative_name != NULL; alternative_name = strtok (NULL, " "))
810     {
811       char *altname =
812         alloca (strlen (alternative_name) + strlen (section) + 1 + 1);
813       strcpy (altname, alternative_name);
814       strcpy (altname + strlen (alternative_name) + 1, section);
815       altname[strlen (alternative_name)] = '.';
816
817       publish_name (altname, ports, service_type, my_private_key);
818     }
819
820   GNUNET_free_non_null(alternative_names);
821   GNUNET_CRYPTO_rsa_key_free (my_private_key);
822   GNUNET_free_non_null (udp_redirects);
823   GNUNET_free_non_null (tcp_redirects);
824 }
825
826 /**
827  * Publish a DNS-record in the DHT. This is up to now just for testing.
828  */
829 static void
830 publish_names (void *cls,
831                const struct GNUNET_SCHEDULER_TaskContext *tc) {
832     char *services;
833     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
834       return;
835
836     if (NULL != servicecfg)
837       GNUNET_CONFIGURATION_destroy(servicecfg);
838
839     GNUNET_CONFIGURATION_get_value_filename(cfg, "dns", "SERVICES", &services);
840
841     servicecfg = GNUNET_CONFIGURATION_create();
842     if (GNUNET_OK == GNUNET_CONFIGURATION_parse(servicecfg, services))
843       {
844         GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Parsing services %s\n", services);
845         GNUNET_CONFIGURATION_iterate_sections(servicecfg, publish_iterate, NULL);
846       }
847     if (NULL != services)
848       GNUNET_free(services);
849
850     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_HOURS,
851                                   publish_names,
852                                   NULL);
853 }
854
855 /**
856  * @param cls closure
857  * @param server the initialized server
858  * @param cfg_ configuration to use
859  */
860 static void
861 run (void *cls,
862      struct GNUNET_SERVER_Handle *server,
863      const struct GNUNET_CONFIGURATION_Handle *cfg_)
864 {
865   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
866       /* callback, cls, type, size */
867         {&receive_query, NULL, GNUNET_MESSAGE_TYPE_LOCAL_QUERY_DNS, 0},
868         {&rehijack, NULL, GNUNET_MESSAGE_TYPE_REHIJACK, sizeof(struct GNUNET_MessageHeader)},
869         {NULL, NULL, 0, 0}
870   };
871
872   cfg = cfg_;
873
874   unsigned int i;
875   for (i = 0; i < 65536; i++) {
876       query_states[i].valid = GNUNET_NO;
877   }
878
879   dht = GNUNET_DHT_connect(cfg, 1024);
880
881   open_port();
882
883   GNUNET_SCHEDULER_add_now (publish_names, NULL);
884
885   GNUNET_SERVER_add_handlers (server, handlers);
886   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
887                                 &cleanup_task,
888                                 cls);
889 }
890
891 /**
892  * The main function for the dns service.
893  *
894  * @param argc number of arguments from the command line
895  * @param argv command line arguments
896  * @return 0 ok, 1 on error
897  */
898 int
899 main (int argc, char *const *argv)
900 {
901   return (GNUNET_OK ==
902           GNUNET_SERVICE_run (argc,
903                               argv,
904                               "dns",
905                               GNUNET_SERVICE_OPTION_NONE,
906                               &run, NULL)) ? 0 : 1;
907 }