31513f2c2eb597af7cb606cb11926ecf1c152ddf
[oweals/gnunet.git] / src / vpn / gnunet-daemon-vpn.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010 Christian Grothoff
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-daemon-vpn.c
23  * @brief 
24  * @author Philipp Toelke
25  */
26 #include "platform.h"
27 #include "gnunet_getopt_lib.h"
28 #include "gnunet_program_lib.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet-vpn-helper-p.h"
31 #include "gnunet-vpn-packet.h"
32 #include "gnunet-vpn-pretty-print.h"
33 #include "gnunet_common.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_server_lib.h"
36 #include "gnunet-service-dns-p.h"
37 #include "gnunet_core_service.h"
38 #include "gnunet_client_lib.h"
39 #include "gnunet_container_lib.h"
40 #include "block_dns.h"
41 #include "gnunet_constants.h"
42
43 /**
44  * Final status code.
45  */
46 static int ret;
47
48 /**
49  * The configuration to use
50  */
51 static const struct GNUNET_CONFIGURATION_Handle *cfg;
52
53 /**
54  * PipeHandle to receive data from the helper
55  */
56 static struct GNUNET_DISK_PipeHandle* helper_in;
57
58 /**
59  * PipeHandle to send data to the helper
60  */
61 static struct GNUNET_DISK_PipeHandle* helper_out;
62
63 /**
64  * FileHandle to receive data from the helper
65  */
66 static const struct GNUNET_DISK_FileHandle* fh_from_helper;
67
68 /**
69  * FileHandle to send data to the helper
70  */
71 static const struct GNUNET_DISK_FileHandle* fh_to_helper;
72
73 /**
74  * The Message-Tokenizer that tokenizes the messages comming from the helper
75  */
76 static struct GNUNET_SERVER_MessageStreamTokenizer* mst;
77
78 /**
79  * The connection to the service-dns
80  */
81 static struct GNUNET_CLIENT_Connection *dns_connection;
82
83 /**
84  * A flag to show that the service-dns has to rehijack the outbound dns-packets
85  *
86  * This gets set when the helper restarts as the routing-tables are flushed when
87  * the interface vanishes.
88  */
89 static unsigned char restart_hijack;
90
91 /**
92  * The process id of the helper
93  */
94 static struct GNUNET_OS_Process *helper_proc;
95
96 /**
97  * a list of outgoing dns-query-packets
98  */
99 static struct query_packet_list *head;
100
101 /**
102  * The last element of the list of outgoing dns-query-packets
103  */
104 static struct query_packet_list *tail;
105
106 /**
107  * A list of processed dns-responses.
108  *
109  * "processed" means that the packet is complete and can be sent out via udp
110  * directly
111  */
112 static struct answer_packet_list *answer_proc_head;
113
114 /**
115  * The last element of the list of processed dns-responses.
116  */
117 static struct answer_packet_list *answer_proc_tail;
118
119 /**
120  * The hashmap containing the mappings from ipv6-addresses to gnunet-descriptors
121  */
122 static struct GNUNET_CONTAINER_MultiHashMap* hashmap;
123
124 /**
125  * This hashmap contains the mapping from peer, service-descriptor,
126  * source-port and destination-port to a socket
127  */
128 static struct GNUNET_CONTAINER_MultiHashMap *udp_connections;
129
130 /**
131  * The handle to core
132  */
133 static struct GNUNET_CORE_Handle *core_handle;
134
135 struct map_entry {
136     struct GNUNET_vpn_service_descriptor desc;
137     uint16_t namelen;
138     uint64_t additional_ports;
139     /**
140      * In DNS-Format!
141      */
142     char name[1];
143 };
144
145 static void helper_read(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx);
146 static void dns_answer_handler(void* cls, const struct GNUNET_MessageHeader *msg);
147
148 /**
149  * Callback called by notify_transmit_ready; sends dns-queries or rehijack-messages
150  * to the service-dns
151  * {{{
152  */
153 static size_t
154 send_query(void* cls, size_t size, void* buf) {
155     size_t len;
156     /*
157      * Send the rehijack-message
158      */
159     if (restart_hijack == 1)
160       {
161         restart_hijack = 0;
162         /*
163          * The message is just a header
164          */
165         GNUNET_assert(sizeof(struct GNUNET_MessageHeader) <= size);
166         struct GNUNET_MessageHeader* hdr = buf;
167         len = sizeof(struct GNUNET_MessageHeader);
168         hdr->size = htons(len);
169         hdr->type = htons(GNUNET_MESSAGE_TYPE_REHIJACK);
170       }
171     else
172       {
173         struct query_packet_list* query = head;
174         len = ntohs(query->pkt.hdr.size);
175
176         GNUNET_assert(len <= size);
177
178         memcpy(buf, &query->pkt.hdr, len);
179
180         GNUNET_CONTAINER_DLL_remove (head, tail, query);
181
182         GNUNET_free(query);
183       }
184
185     /*
186      * Check whether more data is to be sent
187      */
188     if (head != NULL)
189       {
190         GNUNET_CLIENT_notify_transmit_ready(dns_connection, ntohs(head->pkt.hdr.size), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
191       }
192     else if (restart_hijack == 1)
193       {
194         GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
195       }
196
197     return len;
198 }
199 /* }}} */
200
201 /**
202  * Function scheduled as very last function, cleans up after us
203  *{{{
204  */
205 static void
206 cleanup(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
207     GNUNET_assert (0 != (tskctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN));
208
209     /* stop the helper */
210     if (helper_proc != NULL)
211       {
212         if (0 != GNUNET_OS_process_kill (helper_proc, SIGTERM))
213           GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill");
214         GNUNET_OS_process_wait (helper_proc);
215         GNUNET_OS_process_close (helper_proc);
216         helper_proc = NULL;
217       }
218
219     /* close the connection to the service-dns */
220     if (dns_connection != NULL)
221       {
222         GNUNET_CLIENT_disconnect (dns_connection, GNUNET_NO);
223         dns_connection = NULL;
224       }
225
226     if (core_handle != NULL)
227       {
228         GNUNET_CORE_disconnect(core_handle);
229         core_handle = NULL;
230       }
231 }
232 /*}}}*/
233
234 /**
235  * Start the helper-process
236  * {{{
237  */
238 static void
239 start_helper_and_schedule(void *cls,
240                           const struct GNUNET_SCHEDULER_TaskContext *tc) {
241     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
242       return;
243
244     helper_in = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO);
245     helper_out = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
246
247     if (helper_in == NULL || helper_out == NULL) return;
248
249     helper_proc = GNUNET_OS_start_process(helper_in, helper_out, "gnunet-helper-vpn", "gnunet-helper-vpn", NULL);
250
251     fh_from_helper = GNUNET_DISK_pipe_handle (helper_out, GNUNET_DISK_PIPE_END_READ);
252     fh_to_helper = GNUNET_DISK_pipe_handle (helper_in, GNUNET_DISK_PIPE_END_WRITE);
253
254     GNUNET_DISK_pipe_close_end(helper_out, GNUNET_DISK_PIPE_END_WRITE);
255     GNUNET_DISK_pipe_close_end(helper_in, GNUNET_DISK_PIPE_END_READ);
256
257     /* Tell the dns-service to rehijack the dns-port
258      * The routing-table gets flushed if an interface disappears.
259      */
260     restart_hijack = 1;
261     GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
262
263     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, fh_from_helper, &helper_read, NULL);
264 }
265 /*}}}*/
266
267 /**
268  * Restart the helper-process
269  * {{{
270  */
271 static void
272 restart_helper(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
273     // Kill the helper
274     GNUNET_OS_process_kill (helper_proc, SIGKILL);
275     GNUNET_OS_process_wait (helper_proc);
276     GNUNET_OS_process_close (helper_proc);
277     helper_proc = NULL;
278
279     GNUNET_DISK_pipe_close(helper_in);
280     GNUNET_DISK_pipe_close(helper_out);
281
282     /* Restart the helper */
283     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, start_helper_and_schedule, NULL);
284 }
285 /*}}}*/
286
287 /**
288  * Read from the helper-process
289  * {{{
290  */
291 static void
292 helper_read(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx) {
293     /* no message can be bigger then 64k */
294     char buf[65535];
295
296     if (tsdkctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
297       return;
298
299     int t = GNUNET_DISK_file_read(fh_from_helper, &buf, 65535);
300
301     /* On read-error, restart the helper */
302     if (t<=0) {
303         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Read error for header from vpn-helper: %m\n");
304         GNUNET_SCHEDULER_add_now(restart_helper, cls);
305         return;
306     }
307
308     /* FIXME */ GNUNET_SERVER_mst_receive(mst, NULL, buf, t, 0, 0);
309
310     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, fh_from_helper, &helper_read, NULL);
311 }
312 /*}}}*/
313
314 static uint32_t calculate_checksum_update(uint32_t sum, uint16_t *hdr, short len) {
315     for(; len >= 2; len -= 2)
316       sum += *(hdr++);
317     if (len == 1)
318       sum += *((unsigned char*)hdr);
319     return sum;
320 }
321
322 static uint16_t calculate_checksum_end(uint32_t sum) {
323     while (sum >> 16)
324       sum = (sum >> 16) + (sum & 0xFFFF);
325
326     return ~sum;
327 }
328
329 /**
330  * Calculate the checksum of an IPv4-Header
331  */
332 static uint16_t
333 calculate_ip_checksum(uint16_t* hdr, short len) {
334     uint32_t sum = calculate_checksum_update(0, hdr, len);
335     return calculate_checksum_end(sum);
336 }
337
338 /**
339  * Send an dns-answer-packet to the helper
340  */
341 static void
342 helper_write(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx) {
343     if (tsdkctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
344       return;
345
346     struct answer_packet_list* ans = answer_proc_head;
347     size_t len = ntohs(ans->pkt.hdr.size);
348
349     GNUNET_assert(ans->pkt.subtype == GNUNET_DNS_ANSWER_TYPE_IP);
350
351     GNUNET_assert (20 == sizeof (struct ip_hdr));
352     GNUNET_assert (8 == sizeof (struct udp_pkt));
353     size_t data_len = len - sizeof(struct answer_packet) + 1;
354     size_t net_len = sizeof(struct ip_hdr) + sizeof(struct udp_dns) + data_len;
355     size_t pkt_len = sizeof(struct GNUNET_MessageHeader) + sizeof(struct pkt_tun) + net_len;
356
357     struct ip_udp_dns* pkt = alloca(pkt_len);
358     GNUNET_assert(pkt != NULL);
359     memset(pkt, 0, pkt_len);
360
361     /* set the gnunet-header */
362     pkt->shdr.size = htons(pkt_len);
363     pkt->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
364
365     /* set the tun-header (no flags and ethertype of IPv4) */
366     pkt->tun.flags = 0;
367     pkt->tun.type = htons(0x0800);
368
369     /* set the ip-header */
370     pkt->ip_hdr.version = 4;
371     pkt->ip_hdr.hdr_lngth = 5;
372     pkt->ip_hdr.diff_serv = 0;
373     pkt->ip_hdr.tot_lngth = htons(net_len);
374     pkt->ip_hdr.ident = 0;
375     pkt->ip_hdr.flags = 0;
376     pkt->ip_hdr.frag_off = 0;
377     pkt->ip_hdr.ttl = 255;
378     pkt->ip_hdr.proto = 0x11; /* UDP */
379     pkt->ip_hdr.chks = 0; /* Will be calculated later*/
380     pkt->ip_hdr.sadr = ans->pkt.from;
381     pkt->ip_hdr.dadr = ans->pkt.to;
382
383     pkt->ip_hdr.chks = calculate_ip_checksum((uint16_t*)&pkt->ip_hdr, 5*4);
384
385     /* set the udp-header */
386     pkt->udp_dns.udp_hdr.spt = htons(53);
387     pkt->udp_dns.udp_hdr.dpt = ans->pkt.dst_port;
388     pkt->udp_dns.udp_hdr.len = htons(net_len - sizeof(struct ip_hdr));
389     pkt->udp_dns.udp_hdr.crc = 0; /* Optional for IPv4 */
390
391     memcpy(&pkt->udp_dns.data, ans->pkt.data, data_len);
392
393     GNUNET_CONTAINER_DLL_remove (answer_proc_head, answer_proc_tail, ans);
394     GNUNET_free(ans);
395
396     /* FIXME */ GNUNET_DISK_file_write(fh_to_helper, pkt, pkt_len);
397
398     /* if more packets are available, reschedule */
399     if (answer_proc_head != NULL)
400       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
401                                        fh_to_helper,
402                                        &helper_write,
403                                        NULL);
404 }
405
406 /**
407  * @return the hash of the IP-Address if a mapping exists, NULL otherwise
408  */
409 static GNUNET_HashCode*
410 address_mapping_exists(unsigned char addr[]) {
411     GNUNET_HashCode* key = GNUNET_malloc(sizeof(GNUNET_HashCode));
412     unsigned char* k = (unsigned char*)key;
413     memset(key, 0, sizeof(GNUNET_HashCode));
414     unsigned int i;
415     for (i = 0; i < 16; i++)
416         k[15-i] = addr[i];
417
418     if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(hashmap, key))
419       return key;
420     else
421       {
422         GNUNET_free(key);
423         return NULL;
424       }
425 }
426
427 static void
428 send_icmp_response(void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc) {
429     struct ip6_icmp* request = cls;
430
431     struct ip6_icmp* response = alloca(ntohs(request->shdr.size));
432     GNUNET_assert(response != NULL);
433     memset(response, 0, ntohs(request->shdr.size));
434
435     response->shdr.size = request->shdr.size;
436     response->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
437
438     response->tun.flags = 0;
439     response->tun.type = htons(0x86dd);
440
441     response->ip6_hdr.hoplmt = 255;
442     response->ip6_hdr.paylgth = request->ip6_hdr.paylgth;
443     response->ip6_hdr.nxthdr = 0x3a;
444     response->ip6_hdr.version = 6;
445     memcpy(&response->ip6_hdr.sadr, &request->ip6_hdr.dadr, 16);
446     memcpy(&response->ip6_hdr.dadr, &request->ip6_hdr.sadr, 16);
447
448     response->icmp_hdr.code = 0;
449     response->icmp_hdr.type = 0x81;
450
451     /* Magic, more Magic! */
452     response->icmp_hdr.chks = request->icmp_hdr.chks - 0x1;
453
454     /* Copy the rest of the packet */
455     memcpy(response+1, request+1, ntohs(request->shdr.size) - sizeof(struct ip6_icmp));
456
457     /* FIXME */ GNUNET_DISK_file_write(fh_to_helper, response, ntohs(response->shdr.size));
458
459     GNUNET_free(request);
460 }
461
462 /**
463  * cls is the pointer to a GNUNET_MessageHeader that is
464  * followed by the service-descriptor and the udp-packet that should be sent;
465  */
466 static size_t
467 handle_udp (void *cls, size_t size, void *buf)
468 {
469   struct GNUNET_PeerIdentity *peer = cls;
470   struct GNUNET_MessageHeader *hdr =
471     (struct GNUNET_MessageHeader *) (peer + 1);
472   GNUNET_HashCode *hc = (GNUNET_HashCode *) (hdr + 1);
473   struct udp_pkt *udp = (struct udp_pkt *) (hc + 1);
474   hdr->size = htons (sizeof (struct GNUNET_MessageHeader) +
475                      sizeof (GNUNET_HashCode) + ntohs (udp->len));
476   hdr->type = ntohs (GNUNET_MESSAGE_TYPE_SERVICE_UDP);
477   GNUNET_assert (size >= ntohs (hdr->size));
478   memcpy (buf, hdr, ntohs (hdr->size));
479   size = ntohs(hdr->size);
480   GNUNET_free (cls);
481   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sent!\n");
482   return size;
483 }
484
485 static unsigned int
486 port_in_ports (uint64_t ports, uint16_t port)
487 {
488   uint16_t *ps = (uint16_t *) & ports;
489   return ps[0] == port || ps[1] == port || ps[2] == port || ps[3] == port;
490 }
491
492 void
493 send_udp (void *cls, 
494           int success)
495 {
496   struct GNUNET_PeerIdentity *peer = cls;
497   struct GNUNET_MessageHeader *hdr =
498     (struct GNUNET_MessageHeader *) (peer + 1);
499   GNUNET_HashCode *hc = (GNUNET_HashCode *) (hdr + 1);
500   struct udp_pkt *udp = (struct udp_pkt *) (hc + 1);
501   GNUNET_CORE_notify_transmit_ready (core_handle,
502                                      42,
503                                      GNUNET_TIME_relative_divide(GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
504                                      peer,
505                                      htons (sizeof
506                                             (struct GNUNET_MessageHeader) +
507                                             sizeof (GNUNET_HashCode) +
508                                             ntohs (udp->len)), handle_udp,
509                                      cls);
510 }
511
512 /**
513  * Receive packets from the helper-process
514  */
515 static void
516 message_token(void *cls,
517               void *client,
518               const struct GNUNET_MessageHeader *message) {
519     GNUNET_assert(ntohs(message->type) == GNUNET_MESSAGE_TYPE_VPN_HELPER);
520
521     struct tun_pkt *pkt_tun = (struct tun_pkt*) message;
522
523     /* ethertype is ipv6 */
524     if (ntohs(pkt_tun->tun.type) == 0x86dd)
525       {
526         struct ip6_pkt *pkt6 = (struct ip6_pkt*) message;
527         GNUNET_assert(pkt6->ip6_hdr.version == 6);
528         struct ip6_tcp *pkt6_tcp;
529         struct ip6_udp *pkt6_udp;
530         struct ip6_icmp *pkt6_icmp;
531         GNUNET_HashCode* key;
532
533         switch(pkt6->ip6_hdr.nxthdr)
534           {
535           case 0x06:
536             pkt6_tcp = (struct ip6_tcp*)pkt6;
537             pkt_printf_ip6tcp(pkt6_tcp);
538             break;
539           case 0x11:
540             pkt6_udp = (struct ip6_udp*)pkt6;
541             if ((key = address_mapping_exists(pkt6->ip6_hdr.dadr)) != NULL)
542               {
543                 struct map_entry* me = GNUNET_CONTAINER_multihashmap_get(hashmap, key);
544                 GNUNET_assert(me != NULL);
545                 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Mapping exists; type: %d; UDP is %d; port: %x/%x!\n", me->desc.service_type, htonl(GNUNET_DNS_SERVICE_TYPE_UDP), pkt6_udp->udp_hdr.dpt, me->desc.ports);
546                 GNUNET_free(key);
547                 if (me->desc.service_type & htonl(GNUNET_DNS_SERVICE_TYPE_UDP) &&
548                     (port_in_ports(me->desc.ports, pkt6_udp->udp_hdr.dpt) ||
549                      port_in_ports(me->additional_ports, pkt6_udp->udp_hdr.dpt)))
550                   {
551                     size_t size = sizeof(struct GNUNET_PeerIdentity) + sizeof(struct GNUNET_MessageHeader) + sizeof(GNUNET_HashCode) + ntohs(pkt6_udp->udp_hdr.len);
552                     struct GNUNET_PeerIdentity *cls = GNUNET_malloc(size);
553                     struct GNUNET_MessageHeader *hdr = (struct GNUNET_MessageHeader*)(cls+1);
554                     GNUNET_HashCode* hc = (GNUNET_HashCode*)(hdr + 1);
555                     memcpy(cls, &me->desc.peer, sizeof(struct GNUNET_PeerIdentity));
556                     memcpy(hc, &me->desc.service_descriptor, sizeof(GNUNET_HashCode));
557                     memcpy(hc+1, &pkt6_udp->udp_hdr, ntohs(pkt6_udp->udp_hdr.len));
558                     GNUNET_CORE_peer_request_connect(core_handle,
559                                         GNUNET_TIME_UNIT_FOREVER_REL,
560                                         (struct GNUNET_PeerIdentity*)&me->desc.peer,
561                                         send_udp,
562                                         cls);
563                     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Queued to send to peer %x\n", *((unsigned int*)&me->desc.peer));
564                   }
565               }
566             break;
567           case 0x3a:
568             /* ICMPv6 */
569             pkt6_icmp = (struct ip6_icmp*)pkt6;
570             /* If this packet is an icmp-echo-request and a mapping exists, answer */
571             if (pkt6_icmp->icmp_hdr.type == 0x80 && (key = address_mapping_exists(pkt6->ip6_hdr.dadr)) != NULL)
572               {
573                 GNUNET_free(key);
574                 pkt6_icmp = GNUNET_malloc(ntohs(pkt6->shdr.size));
575                 memcpy(pkt6_icmp, pkt6, ntohs(pkt6->shdr.size));
576                 GNUNET_SCHEDULER_add_now(&send_icmp_response, pkt6_icmp);
577               }
578             break;
579           }
580       }
581     /* ethertype is ipv4 */
582     else if (ntohs(pkt_tun->tun.type) == 0x0800)
583       {
584         struct ip_pkt *pkt = (struct ip_pkt*) message;
585         struct ip_udp *udp = (struct ip_udp*) message;
586         GNUNET_assert(pkt->ip_hdr.version == 4);
587
588         /* Send dns-packets to the service-dns */
589         if (pkt->ip_hdr.proto == 0x11 && ntohs(udp->udp_hdr.dpt) == 53 )
590           {
591             /* 9 = 8 for the udp-header + 1 for the unsigned char data[1]; */
592             size_t len = sizeof(struct query_packet) + ntohs(udp->udp_hdr.len) - 9;
593
594             struct query_packet_list* query = GNUNET_malloc(len + 2*sizeof(struct query_packet_list*));
595             query->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_QUERY_DNS);
596             query->pkt.hdr.size = htons(len);
597             query->pkt.orig_to = pkt->ip_hdr.dadr;
598             query->pkt.orig_from = pkt->ip_hdr.sadr;
599             query->pkt.src_port = udp->udp_hdr.spt;
600             memcpy(query->pkt.data, udp->data, ntohs(udp->udp_hdr.len) - 8);
601
602             GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, query);
603
604             if (dns_connection != NULL)
605               GNUNET_CLIENT_notify_transmit_ready(dns_connection,
606                                                   len,
607                                                   GNUNET_TIME_UNIT_FOREVER_REL,
608                                                   GNUNET_YES,
609                                                   &send_query,
610                                                   NULL);
611           }
612       }
613 }
614
615 /**
616  * Connect to the service-dns
617  */
618 static void
619 connect_to_service_dns (void *cls,
620                         const struct GNUNET_SCHEDULER_TaskContext *tc) {
621     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
622       return;
623     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting to service-dns\n");
624     GNUNET_assert (dns_connection == NULL);
625     dns_connection = GNUNET_CLIENT_connect ("dns", cfg);
626     /* This would most likely be a misconfiguration */
627     GNUNET_assert(dns_connection != NULL);
628     GNUNET_CLIENT_receive(dns_connection, &dns_answer_handler, NULL, GNUNET_TIME_UNIT_FOREVER_REL);
629
630     /* If a packet is already in the list, schedule to send it */
631     if (head != NULL)
632       GNUNET_CLIENT_notify_transmit_ready(dns_connection,
633                                           ntohs(head->pkt.hdr.size),
634                                           GNUNET_TIME_UNIT_FOREVER_REL,
635                                           GNUNET_YES,
636                                           &send_query,
637                                           NULL);
638     else if (restart_hijack == 1)
639       {
640         GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
641       }
642 }
643
644 /**
645  * Create a new Address from an answer-packet
646  * {{{
647  */
648 void
649 new_ip6addr(char* buf, const GNUNET_HashCode *peer, const GNUNET_HashCode *service_desc) {
650         memcpy(buf+14, (int[]){htons(0x3412)}, 2);
651         memcpy(buf+8, service_desc, 6);
652         memcpy(buf, peer, 8);
653 }
654 /*}}}*/
655
656 /**
657  * This gets scheduled with cls pointing to an answer_packet and does everything
658  * needed in order to send it to the helper.
659  *
660  * At the moment this means "inventing" and IPv6-Address for .gnunet-services and
661  * doing nothing for "real" services.
662  */
663 static void
664 process_answer(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tc) {
665     struct answer_packet* pkt = cls;
666     struct answer_packet_list* list;
667
668     /* This answer is about a .gnunet-service
669      *
670      * It contains an almost complete DNS-Response, we have to fill in the ip
671      * at the offset pkt->addroffset
672      */
673     //FIXME htons?
674     if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_SERVICE)
675       {
676         pkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
677
678         GNUNET_HashCode key;
679         memset(&key, 0, sizeof(GNUNET_HashCode));
680         new_ip6addr((char*)&key, &pkt->service_descr.peer, &pkt->service_descr.service_descriptor);
681
682         uint16_t namelen = strlen((char*)pkt->data+12)+1;
683
684         struct map_entry* value = GNUNET_malloc(sizeof(struct GNUNET_vpn_service_descriptor) + 2 + 8 + namelen);
685
686         value->namelen = namelen;
687         memcpy(value->name, pkt->data+12, namelen);
688
689         memcpy(&value->desc, &pkt->service_descr, sizeof(struct GNUNET_vpn_service_descriptor));
690
691         value->additional_ports = 0;
692
693         if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put(hashmap,
694                                                            &key,
695                                                            value,
696                                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
697           {
698             GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not store to hashmap\n");
699           }
700
701         /*
702          * Copy the newly generated backward ip-address to the packet
703          */
704         char* c = ((char*)pkt)+ntohs(pkt->addroffset);
705         char* k = (char*)&key;
706         unsigned int i;
707         for (i = 0; i < 16; i++)
708             c[15-i] = k[i];
709
710         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
711
712         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
713
714       }
715     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_REV)
716       {
717         GNUNET_HashCode key;
718         memset(&key, 0, sizeof key);
719         unsigned char* k = (unsigned char*)&key;
720         unsigned char* s = pkt->data+12;
721         int i = 0;
722         /* Whoever designed the reverse IPv6-lookup is batshit insane */
723         for (i = 0; i < 16; i++)
724           {
725             unsigned char c1 = s[(4*i)+1];
726             unsigned char c2 = s[(4*i)+3];
727             if (c1 <= '9')
728               k[i] = c1 - '0';
729             else
730               k[i] = c1 - 87; /* 87 is the difference between 'a' and 10 */
731             if (c2 <= '9')
732               k[i] += 16*(c2 - '0');
733             else
734               k[i] += 16*(c2 - 87);
735           }
736
737         struct map_entry* map_entry = GNUNET_CONTAINER_multihashmap_get(hashmap, &key);
738         unsigned short offset = ntohs(pkt->addroffset);
739
740         if (map_entry == NULL)
741           {
742             GNUNET_free(pkt);
743             return;
744           }
745
746         unsigned short namelen = htons(map_entry->namelen);
747         char* name = map_entry->name;
748
749         list = GNUNET_malloc(2*sizeof(struct answer_packet_list*) + offset + 2 + ntohs(namelen));
750
751         struct answer_packet* rpkt = &list->pkt;
752
753         memcpy(rpkt, pkt, offset);
754
755         rpkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
756         rpkt->hdr.size = ntohs(offset + 2 + ntohs(namelen));
757
758         memcpy(((char*)rpkt)+offset, &namelen, 2);
759         memcpy(((char*)rpkt)+offset+2, name, ntohs(namelen));
760
761       }
762     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_IP)
763       {
764         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
765         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
766       }
767     else
768       {
769         GNUNET_break(0);
770         GNUNET_free(pkt);
771         return;
772       }
773
774     GNUNET_free(pkt);
775
776     GNUNET_CONTAINER_DLL_insert_after(answer_proc_head, answer_proc_tail, answer_proc_tail, list);
777
778     GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, fh_to_helper, &helper_write, NULL);
779
780     return;
781 }
782
783 /**
784  * This receives packets from the service-dns and schedules process_answer to
785  * handle it
786  */
787 static void
788 dns_answer_handler(void* cls, const struct GNUNET_MessageHeader *msg) {
789     /* the service disconnected, reconnect after short wait */
790     if (msg == NULL)
791       {
792         GNUNET_CLIENT_disconnect(dns_connection, GNUNET_NO);
793         dns_connection = NULL;
794         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
795                                       &connect_to_service_dns,
796                                       NULL);
797         return;
798       }
799
800     /* the service did something strange, reconnect immediately */
801     if (msg->type != htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS))
802       {
803         GNUNET_break (0);
804         GNUNET_CLIENT_disconnect(dns_connection, GNUNET_NO);
805         dns_connection = NULL;
806         GNUNET_SCHEDULER_add_now (&connect_to_service_dns,
807                                   NULL);
808         return;
809       }
810     void *pkt = GNUNET_malloc(ntohs(msg->size));
811
812     memcpy(pkt, msg, ntohs(msg->size));
813
814     GNUNET_SCHEDULER_add_now(process_answer, pkt);
815     GNUNET_CLIENT_receive(dns_connection, &dns_answer_handler, NULL, GNUNET_TIME_UNIT_FOREVER_REL);
816 }
817
818 struct udp_state
819 {
820   struct GNUNET_PeerIdentity peer;
821   GNUNET_HashCode desc;
822   short spt;
823   short dpt;
824 };
825
826 struct send_cls
827 {
828   struct GNUNET_NETWORK_Handle *sock;
829   struct udp_state state;
830 };
831
832 static size_t
833 send_udp_service (void *cls, size_t size, void *buf)
834 {
835   struct GNUNET_MessageHeader *hdr = cls;
836   GNUNET_assert(size >= ntohs(hdr->size));
837
838   memcpy(buf, cls, ntohs(hdr->size));
839   size_t ret = ntohs(hdr->size);
840   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending %d bytes back!\n", ntohs(hdr->size));
841   GNUNET_free(cls);
842   return ret;
843 }
844
845 void
846 receive_from_network (void *cls,
847                       const struct GNUNET_SCHEDULER_TaskContext *tc)
848 {
849   if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
850     {
851       GNUNET_free(cls);
852       return;
853     }
854   struct send_cls *data = cls;
855
856   char buf[1400];
857
858   struct sockaddr_in addr_in;
859   socklen_t addr_len = sizeof(struct sockaddr_in);
860   ssize_t len = GNUNET_NETWORK_socket_recvfrom (data->sock, buf, 1400, (struct sockaddr*)&addr_in, &addr_len);
861
862   if (len < 0) {
863     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Problem reading from socket: %m\n");
864     goto out;
865   }
866
867   size_t len_udp = len + sizeof (struct udp_pkt);
868   size_t len_pkt = len_udp + sizeof (struct GNUNET_MessageHeader) + sizeof(GNUNET_HashCode);
869   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending data back: data: %d; udp: %d, pkt:%d\n", len, len_udp, len_pkt);
870
871   struct GNUNET_MessageHeader *hdr = GNUNET_malloc (len_pkt);
872   GNUNET_HashCode *desc = (GNUNET_HashCode *) (hdr + 1);
873   struct udp_pkt *pkt = (struct udp_pkt *) (desc + 1);
874
875   hdr->size = htons (len_pkt);
876   hdr->type = htons (GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK);
877
878   pkt->dpt = htons(data->state.spt);
879   pkt->spt = addr_in.sin_port;
880   pkt->len = htons (len_udp);
881   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "UDP from %d to %d\n", ntohs(pkt->spt), ntohs(pkt->dpt));
882   /* The chksm can only be computed knowing the ip-addresses */
883
884   memcpy (desc, &data->state.desc, sizeof (GNUNET_HashCode));
885   memcpy (pkt + 1, buf, len);
886
887   GNUNET_CORE_notify_transmit_ready (core_handle, 42,
888                                      GNUNET_TIME_relative_divide(GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
889                                      &data->state.peer, len_pkt,
890                                      send_udp_service, hdr);
891
892 out:
893   GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, data->sock,
894                                  receive_from_network, cls);
895 }
896
897 void
898 send_to_network (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
899 {
900   if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
901     return;
902   struct send_cls *data = cls;
903   struct udp_pkt *pkt = (struct udp_pkt *) (data + 1);
904
905   struct sockaddr_in a4;
906   memset(&a4, 0, sizeof(struct sockaddr_in));
907   a4.sin_family = AF_INET;
908   a4.sin_port = htons(data->state.dpt);
909   memcpy(&a4.sin_addr.s_addr, (char[]){127, 0, 0, 1}, 4);
910
911   GNUNET_NETWORK_socket_sendto (data->sock, pkt + 1,
912                                 ntohs (pkt->len) - sizeof (struct udp_pkt),
913                                 (struct sockaddr*)&a4, sizeof a4);
914
915   GNUNET_free(cls);
916
917 }
918
919 static void
920 add_additional_port (struct map_entry *me, uint16_t port)
921 {
922   uint16_t *ps = (uint16_t *) & me->additional_ports;
923   unsigned int i;
924   for (i = 0; i < 4; i++)
925     {
926       if (ps[i] == 0)
927         {
928           ps[i] = port;
929           break;
930         }
931     }
932 }
933
934 static int
935 receive_udp_back (void *cls, const struct GNUNET_PeerIdentity *other,
936              const struct GNUNET_MessageHeader *message,
937              const struct GNUNET_TRANSPORT_ATS_Information *atsi)
938 {
939   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
940   struct udp_pkt *pkt = (struct udp_pkt *) (desc + 1);
941   char addr[16];
942   new_ip6addr(addr, &other->hashPubKey, desc);
943
944   size_t size = sizeof(struct ip6_udp) + ntohs(pkt->len) - 1 - sizeof(struct udp_pkt);
945
946   struct ip6_udp* pkt6 = alloca(size);
947
948   GNUNET_assert(pkt6 != NULL);
949
950   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Relaying calc:%d gnu:%d udp:%d bytes!\n", size, ntohs(message->size), ntohs(pkt->len));
951
952   pkt6->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
953   pkt6->shdr.size = htons(size);
954
955   pkt6->tun.flags = 0;
956   pkt6->tun.type = htons(0x86dd);
957
958   pkt6->ip6_hdr.version = 6;
959   pkt6->ip6_hdr.tclass_h = 0;
960   pkt6->ip6_hdr.tclass_l = 0;
961   pkt6->ip6_hdr.flowlbl = 0;
962   pkt6->ip6_hdr.paylgth = pkt->len;
963   pkt6->ip6_hdr.nxthdr = 0x11;
964   pkt6->ip6_hdr.hoplmt = 0xff;
965
966   unsigned int i;
967   for (i = 0; i < 16; i++)
968     pkt6->ip6_hdr.sadr[15-i] = addr[i];
969
970   memcpy(pkt6->ip6_hdr.dadr, (unsigned char[]){0x12, 0x34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 16);
971
972   memcpy(&pkt6->udp_hdr, pkt, ntohs(pkt->len));
973
974   GNUNET_HashCode* key = address_mapping_exists(pkt6->ip6_hdr.sadr);
975   GNUNET_assert (key != NULL);
976
977   struct map_entry *me = GNUNET_CONTAINER_multihashmap_get(hashmap, key);
978
979   GNUNET_free(key);
980
981   GNUNET_assert (me != NULL);
982   GNUNET_assert (me->desc.service_type & htonl(GNUNET_DNS_SERVICE_TYPE_UDP));
983   if (!port_in_ports(me->desc.ports, pkt6->udp_hdr.spt) ||
984       !port_in_ports(me->additional_ports, pkt6->udp_hdr.spt)) {
985       add_additional_port(me, pkt6->udp_hdr.spt);
986   }
987
988   pkt6->udp_hdr.crc = 0;
989   uint32_t sum = 0;
990   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->ip6_hdr.sadr, 16);
991   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->ip6_hdr.dadr, 16);
992   uint32_t tmp = (pkt6->udp_hdr.len & 0xffff);
993   sum = calculate_checksum_update(sum, (uint16_t*)&tmp, 4);
994   tmp = htons(((pkt6->ip6_hdr.nxthdr & 0x00ff)));
995   sum = calculate_checksum_update(sum, (uint16_t*)&tmp, 4);
996
997   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->udp_hdr, ntohs(pkt->len));
998   pkt6->udp_hdr.crc = calculate_checksum_end(sum);
999
1000
1001   /* FIXME */ GNUNET_DISK_file_write(fh_to_helper, pkt6, size);
1002
1003   return GNUNET_OK;
1004 }
1005
1006 static int
1007 receive_udp_service (void *cls, const struct GNUNET_PeerIdentity *other,
1008                      const struct GNUNET_MessageHeader *message,
1009                      const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1010 {
1011   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received UDP-Packet from peer %s\n",
1012               GNUNET_i2s (other));
1013   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
1014   struct udp_pkt *pkt = (struct udp_pkt *) (desc + 1);
1015
1016   /* FIXME -> check acl etc */
1017   GNUNET_assert (ntohs (pkt->len) ==
1018                  ntohs (message->size) -
1019                  sizeof (struct GNUNET_MessageHeader) -
1020                  sizeof (GNUNET_HashCode));
1021
1022   size_t state_size = sizeof (struct udp_state);
1023   size_t cls_size = sizeof (struct send_cls) + ntohs (pkt->len);
1024   struct send_cls *send = GNUNET_malloc (cls_size);
1025   struct udp_state *state = &send->state;
1026   unsigned int new = GNUNET_NO;
1027
1028   memcpy (&state->peer, other, sizeof (struct GNUNET_PeerIdentity));
1029   memcpy (&state->desc, desc, sizeof (GNUNET_HashCode));
1030   state->spt = ntohs (pkt->spt);
1031
1032   /* Hash without the dpt, so that eg tftp works */
1033   state->dpt = 0;
1034
1035   memcpy (send + 1, pkt, ntohs (pkt->len));
1036
1037   GNUNET_HashCode hash;
1038   GNUNET_CRYPTO_hash (state, state_size, &hash);
1039
1040   state->dpt = ntohs (pkt->dpt);
1041
1042   struct GNUNET_NETWORK_Handle *sock =
1043     GNUNET_CONTAINER_multihashmap_get (udp_connections, &hash);
1044
1045   if (sock == NULL)
1046     {
1047       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating new Socket!\n");
1048       sock = GNUNET_NETWORK_socket_create (AF_INET, SOCK_DGRAM, 0);
1049       GNUNET_assert(sock != NULL);
1050       new = GNUNET_YES;
1051     }
1052
1053   send->sock = sock;
1054
1055   GNUNET_CONTAINER_multihashmap_put (udp_connections, &hash, sock,
1056                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1057
1058
1059   if (new)
1060     {
1061       struct send_cls *recv = GNUNET_malloc (sizeof (struct send_cls));
1062       memcpy (recv, send, sizeof (struct send_cls));
1063       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, sock,
1064                                      receive_from_network, recv);
1065     }
1066
1067   GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL, sock,
1068                                   send_to_network, send);
1069
1070   return GNUNET_OK;
1071 }
1072
1073 /**
1074  * Main function that will be run by the scheduler.
1075  *
1076  * @param cls closure
1077  * @param args remaining command-line arguments
1078  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1079  * @param cfg_ configuration
1080  */
1081 static void
1082 run (void *cls,
1083      char *const *args,
1084      const char *cfgfile,
1085      const struct GNUNET_CONFIGURATION_Handle *cfg_) {
1086     const static struct GNUNET_CORE_MessageHandler handlers[] = {
1087           {receive_udp_service, GNUNET_MESSAGE_TYPE_SERVICE_UDP, 0},
1088           {receive_udp_back, GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK, 0},
1089           {NULL, 0, 0}
1090     };
1091     core_handle = GNUNET_CORE_connect(cfg_,
1092                                       42,
1093                                       NULL,
1094                                       NULL,
1095                                       NULL,
1096                                       NULL,
1097                                       NULL,
1098                                       NULL,
1099                                       0,
1100                                       NULL,
1101                                       0,
1102                                       handlers);
1103     mst = GNUNET_SERVER_mst_create(&message_token, NULL);
1104     cfg = cfg_;
1105     restart_hijack = 0;
1106     hashmap = GNUNET_CONTAINER_multihashmap_create(65536);
1107     udp_connections = GNUNET_CONTAINER_multihashmap_create(65536);
1108     GNUNET_SCHEDULER_add_now (connect_to_service_dns, NULL);
1109     GNUNET_SCHEDULER_add_now (start_helper_and_schedule, NULL);
1110     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls);
1111 }
1112
1113 /**
1114  * The main function to obtain template from gnunetd.
1115  *
1116  * @param argc number of arguments from the command line
1117  * @param argv command line arguments
1118  * @return 0 ok, 1 on error
1119  */
1120 int
1121 main (int argc, char *const *argv) {
1122     static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1123         GNUNET_GETOPT_OPTION_END
1124     };
1125
1126     return (GNUNET_OK ==
1127             GNUNET_PROGRAM_run (argc,
1128                                 argv,
1129                                 "gnunet-daemon-vpn",
1130                                 gettext_noop ("help text"),
1131                                 options, &run, NULL)) ? ret : 1;
1132 }
1133
1134 /* end of gnunet-daemon-vpn.c */