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