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