queue transmits to tunnels
[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-vpn-packet.h"
30 #include "gnunet_common.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_applications.h"
33 #include <gnunet_mesh_service.h>
34 #include "gnunet_client_lib.h"
35 #include "gnunet_container_lib.h"
36 #include "gnunet_constants.h"
37 #include <block_dns.h>
38 #include "gnunet-daemon-vpn-helper.h"
39 #include "gnunet-daemon-vpn-dns.h"
40 #include "gnunet-daemon-vpn.h"
41 #include "gnunet-vpn-checksum.h"
42
43 const struct GNUNET_CONFIGURATION_Handle *cfg;
44 struct GNUNET_MESH_Handle *mesh_handle;
45 struct GNUNET_CONTAINER_MultiHashMap* hashmap;
46 static struct GNUNET_CONTAINER_Heap *heap;
47
48 struct tunnel_notify_queue
49 {
50   struct tunnel_notify_queue* next;
51   struct tunnel_notify_queue* prev;
52   size_t len;
53   void* cls;
54 };
55
56 /**
57  * If there are at least this many address-mappings, old ones will be removed
58  */
59 static long long unsigned int max_mappings = 200;
60
61 /**
62  * Final status code.
63  */
64 static int ret;
65
66 /**
67  * This hashmap contains the mapping from peer, service-descriptor,
68  * source-port and destination-port to a socket
69  */
70 static struct GNUNET_CONTAINER_MultiHashMap *udp_connections;
71
72 GNUNET_SCHEDULER_TaskIdentifier conn_task;
73
74 GNUNET_SCHEDULER_TaskIdentifier shs_task;
75
76 /**
77  * Function scheduled as very last function, cleans up after us
78  *{{{
79  */
80 static void
81 cleanup(void* cls __attribute__((unused)), const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
82     GNUNET_assert (0 != (tskctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN));
83
84     /* stop the helper */
85     cleanup_helper(helper_handle);
86
87     /* close the connection to the service-dns */
88     if (dns_connection != NULL)
89       {
90         GNUNET_CLIENT_disconnect (dns_connection, GNUNET_NO);
91         dns_connection = NULL;
92       }
93
94     if (mesh_handle != NULL)
95       {
96         GNUNET_MESH_disconnect(mesh_handle);
97         mesh_handle = NULL;
98       }
99     if (GNUNET_SCHEDULER_NO_TASK != shs_task)
100       {
101         GNUNET_SCHEDULER_cancel (shs_task);
102         shs_task = GNUNET_SCHEDULER_NO_TASK;
103       }
104     if (GNUNET_SCHEDULER_NO_TASK != conn_task)
105       {
106         GNUNET_SCHEDULER_cancel (conn_task);
107         conn_task = GNUNET_SCHEDULER_NO_TASK;
108       }
109 }
110 /*}}}*/
111
112 /**
113  * @return the hash of the IP-Address if a mapping exists, NULL otherwise
114  */
115 GNUNET_HashCode*
116 address_mapping_exists(unsigned char addr[]) {
117     GNUNET_HashCode* key = GNUNET_malloc(sizeof(GNUNET_HashCode));
118     unsigned char* k = (unsigned char*)key;
119     memset(key, 0, sizeof(GNUNET_HashCode));
120     unsigned int i;
121     for (i = 0; i < 16; i++)
122         k[15-i] = addr[i];
123
124     if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(hashmap, key))
125       return key;
126     else
127       {
128         GNUNET_free(key);
129         return NULL;
130       }
131 }
132
133 static void
134 collect_mappings(void* cls __attribute__((unused)), const struct GNUNET_SCHEDULER_TaskContext* tc) {
135     if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
136       return;
137
138     struct map_entry* me = GNUNET_CONTAINER_heap_remove_root(heap);
139
140     /* This is free()ed memory! */
141     me->heap_node = NULL;
142
143     /* FIXME! GNUNET_MESH_close_tunnel(me->tunnel); */
144
145     GNUNET_CONTAINER_multihashmap_remove(hashmap, &me->hash, me);
146
147     GNUNET_free(me);
148 }
149
150 void
151 send_icmp_response(void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc) {
152     if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
153       return;
154
155     struct ip6_icmp* request = cls;
156
157     struct ip6_icmp* response = alloca(ntohs(request->shdr.size));
158     GNUNET_assert(response != NULL);
159     memset(response, 0, ntohs(request->shdr.size));
160
161     response->shdr.size = request->shdr.size;
162     response->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
163
164     response->tun.flags = 0;
165     response->tun.type = htons(0x86dd);
166
167     response->ip6_hdr.hoplmt = 255;
168     response->ip6_hdr.paylgth = request->ip6_hdr.paylgth;
169     response->ip6_hdr.nxthdr = 0x3a;
170     response->ip6_hdr.version = 6;
171     memcpy(&response->ip6_hdr.sadr, &request->ip6_hdr.dadr, 16);
172     memcpy(&response->ip6_hdr.dadr, &request->ip6_hdr.sadr, 16);
173
174     response->icmp_hdr.code = 0;
175     response->icmp_hdr.type = 0x81;
176
177     /* Magic, more Magic! */
178     response->icmp_hdr.chks = request->icmp_hdr.chks - 0x1;
179
180     /* Copy the rest of the packet */
181     memcpy(response+1, request+1, ntohs(request->shdr.size) - sizeof(struct ip6_icmp));
182
183     write_to_helper(response, ntohs(response->shdr.size));
184
185     GNUNET_free(request);
186 }
187
188 /**
189  * cls is the pointer to a GNUNET_MessageHeader that is
190  * followed by the service-descriptor and the packet that should be sent;
191  */
192 static size_t
193 send_pkt_to_peer_notify_callback (void *cls, size_t size, void *buf)
194 {
195   struct GNUNET_MESH_Tunnel **tunnel = cls;
196   GNUNET_MESH_tunnel_set_data(*tunnel, NULL);
197   struct GNUNET_MessageHeader *hdr =
198     (struct GNUNET_MessageHeader *) (tunnel + 1);
199   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "send_pkt_to_peer_notify_callback: buf = %x; size = %u;\n", buf, size);
200   GNUNET_assert (size >= ntohs (hdr->size));
201   memcpy (buf, hdr, ntohs (hdr->size));
202   size = ntohs(hdr->size);
203   GNUNET_free (cls);
204   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sent!\n");
205
206   if (NULL != GNUNET_MESH_tunnel_get_head(*tunnel))
207     {
208       struct tunnel_notify_queue* element = GNUNET_MESH_tunnel_get_head(*tunnel);
209       struct tunnel_notify_queue* head = GNUNET_MESH_tunnel_get_head(*tunnel);
210       struct tunnel_notify_queue* tail = GNUNET_MESH_tunnel_get_tail(*tunnel);
211
212       GNUNET_CONTAINER_DLL_remove(head, tail, element);
213
214       GNUNET_MESH_tunnel_set_head(*tunnel, head);
215       GNUNET_MESH_tunnel_set_tail(*tunnel, tail);
216
217       struct GNUNET_MESH_TransmitHandle* th = GNUNET_MESH_notify_transmit_ready (*tunnel,
218                                                                                  GNUNET_NO,
219                                                                                  42,
220                                                                                  GNUNET_TIME_relative_divide
221                                                                                  (GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
222                                                                                  (const struct GNUNET_PeerIdentity *)
223                                                                                  NULL, element->len,
224                                                                                  send_pkt_to_peer_notify_callback, element->cls);
225       /* save the handle */
226       GNUNET_MESH_tunnel_set_data(*tunnel, th);
227     }
228
229   return size;
230 }
231
232 unsigned int
233 port_in_ports (uint64_t ports, uint16_t port)
234 {
235   uint16_t *ps = (uint16_t *) & ports;
236   return ps[0] == port || ps[1] == port || ps[2] == port || ps[3] == port;
237 }
238
239 void
240 send_pkt_to_peer (void *cls, 
241                   const struct GNUNET_PeerIdentity *peer,
242                   const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
243 {
244   /* peer == NULL means that all peers in this request are connected */
245   if (peer == NULL) return;
246   struct GNUNET_MESH_Tunnel **tunnel = cls;
247   struct GNUNET_MessageHeader *hdr =
248     (struct GNUNET_MessageHeader *) (tunnel + 1);
249
250   GNUNET_assert(NULL != tunnel);
251   GNUNET_assert(NULL != *tunnel);
252
253   if (NULL == GNUNET_MESH_tunnel_get_data(*tunnel))
254     {
255       struct GNUNET_MESH_TransmitHandle* th = GNUNET_MESH_notify_transmit_ready (*tunnel,
256                                                                                  GNUNET_NO,
257                                                                                  42,
258                                                                                  GNUNET_TIME_relative_divide(GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
259                                                                                  (const struct GNUNET_PeerIdentity *)NULL,
260                                                                                  ntohs(hdr->size),
261                                                                                  send_pkt_to_peer_notify_callback,
262                                                                                  cls);
263       GNUNET_MESH_tunnel_set_data(*tunnel, th);
264     }
265   else
266     {
267      struct tunnel_notify_queue* head = GNUNET_MESH_tunnel_get_head(*tunnel);
268      struct tunnel_notify_queue* tail = GNUNET_MESH_tunnel_get_tail(*tunnel);
269      struct tunnel_notify_queue* element = GNUNET_malloc(sizeof *element);
270
271      element->cls = cls;
272      element->len = ntohs(hdr->size);
273
274      GNUNET_CONTAINER_DLL_insert_tail(head, tail, element);
275
276      GNUNET_MESH_tunnel_set_head(*tunnel, head);
277      GNUNET_MESH_tunnel_set_tail(*tunnel, tail);
278     }
279 }
280
281 /**
282  * Create a new Address from an answer-packet
283  */
284 void
285 new_ip6addr(unsigned char* buf, const GNUNET_HashCode *peer, const GNUNET_HashCode *service_desc) { /* {{{ */
286     char* ipv6addr;
287     unsigned long long ipv6prefix;
288     GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "vpn", "IPV6ADDR", &ipv6addr));
289     GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "vpn", "IPV6PREFIX", &ipv6prefix));
290     GNUNET_assert(ipv6prefix < 127);
291     ipv6prefix = (ipv6prefix + 7)/8;
292
293     inet_pton (AF_INET6, ipv6addr, buf);
294     GNUNET_free(ipv6addr);
295
296     int peer_length = 16 - ipv6prefix - 6;
297     if (peer_length <= 0)
298       peer_length = 0;
299
300     int service_length = 16 - ipv6prefix - peer_length;
301     if (service_length <= 0)
302       service_length = 0;
303
304     memcpy(buf+ipv6prefix, service_desc, service_length);
305     memcpy(buf+ipv6prefix+service_length, peer, peer_length);
306 }
307 /*}}}*/
308
309
310 /**
311  * Create a new Address from an answer-packet
312  */
313 void
314 new_ip6addr_remote (unsigned char *buf, unsigned char *addr, char addrlen)
315 {                               /* {{{ */
316   char *ipv6addr;
317   unsigned long long ipv6prefix;
318   GNUNET_assert (GNUNET_OK ==
319                  GNUNET_CONFIGURATION_get_value_string (cfg, "vpn",
320                                                         "IPV6ADDR",
321                                                         &ipv6addr));
322   GNUNET_assert (GNUNET_OK ==
323                  GNUNET_CONFIGURATION_get_value_number (cfg, "vpn",
324                                                         "IPV6PREFIX",
325                                                         &ipv6prefix));
326   GNUNET_assert (ipv6prefix < 127);
327   ipv6prefix = (ipv6prefix + 7) / 8;
328
329   inet_pton (AF_INET6, ipv6addr, buf);
330   GNUNET_free (ipv6addr);
331
332   int local_length = 16 - ipv6prefix;
333
334   memcpy (buf + ipv6prefix, addr, GNUNET_MAX (addrlen, local_length));
335 }
336 /*}}}*/
337
338 /**
339  * This gets scheduled with cls pointing to an answer_packet and does everything
340  * needed in order to send it to the helper.
341  *
342  * At the moment this means "inventing" and IPv6-Address for .gnunet-services and
343  * doing nothing for "real" services.
344  */
345 void
346 process_answer(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tc) {
347     if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
348       return;
349
350     struct answer_packet* pkt = cls;
351     struct answer_packet_list* list;
352
353     /* This answer is about a .gnunet-service
354      *
355      * It contains an almost complete DNS-Response, we have to fill in the ip
356      * at the offset pkt->addroffset
357      */
358     if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_SERVICE)
359       {
360         pkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
361
362         GNUNET_HashCode key;
363         memset(&key, 0, sizeof(GNUNET_HashCode));
364
365         unsigned char* c = ((unsigned char*)pkt)+ntohs(pkt->addroffset);
366         unsigned char* k = (unsigned char*)&key;
367         new_ip6addr(c, &pkt->service_descr.peer, &pkt->service_descr.service_descriptor);
368         /*
369          * Copy the newly generated ip-address to the key backwarts (as only the first part is hashed)
370          */
371         unsigned int i;
372         for (i = 0; i < 16; i++)
373             k[15-i] = c[i];
374
375         uint16_t namelen = strlen((char*)pkt->data+12)+1;
376
377         struct map_entry* value = GNUNET_malloc(sizeof(struct map_entry) + namelen);
378         char* name = (char*)(value +1);
379
380         value->namelen = namelen;
381         memcpy(name, pkt->data+12, namelen);
382
383         memcpy(&value->desc, &pkt->service_descr, sizeof(struct GNUNET_vpn_service_descriptor));
384
385         memset(value->additional_ports, 0, 8192);
386
387         memcpy(&value->hash, &key, sizeof(GNUNET_HashCode));
388
389         if (GNUNET_NO ==
390             GNUNET_CONTAINER_multihashmap_contains (hashmap, &key))
391           {
392             GNUNET_CONTAINER_multihashmap_put (hashmap, &key, value,
393                                                GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
394
395             value->heap_node = GNUNET_CONTAINER_heap_insert (heap, value,
396                                                              GNUNET_TIME_absolute_get ().abs_value);
397             if (GNUNET_CONTAINER_heap_get_size(heap) > max_mappings)
398               GNUNET_SCHEDULER_add_now(collect_mappings, NULL);
399           }
400         else
401           GNUNET_free(value);
402
403
404         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
405
406         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
407
408       }
409     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_REV)
410       {
411         GNUNET_HashCode key;
412         memset(&key, 0, sizeof key);
413         unsigned char* k = (unsigned char*)&key;
414         unsigned char* s = pkt->data+12;
415         int i = 0;
416         /* Whoever designed the reverse IPv6-lookup is batshit insane */
417         for (i = 0; i < 16; i++)
418           {
419             unsigned char c1 = s[(4*i)+1];
420             unsigned char c2 = s[(4*i)+3];
421             if (c1 <= '9')
422               k[i] = c1 - '0';
423             else
424               k[i] = c1 - 87; /* 87 is the difference between 'a' and 10 */
425             if (c2 <= '9')
426               k[i] += 16*(c2 - '0');
427             else
428               k[i] += 16*(c2 - 87);
429           }
430
431         struct map_entry* map_entry = GNUNET_CONTAINER_multihashmap_get(hashmap, &key);
432         uint16_t offset = ntohs(pkt->addroffset);
433
434         if (map_entry == NULL)
435           {
436             GNUNET_free(pkt);
437             return;
438           }
439
440         GNUNET_CONTAINER_heap_update_cost (heap, map_entry->heap_node,
441                                            GNUNET_TIME_absolute_get ().abs_value);
442
443
444         unsigned short namelen = htons(map_entry->namelen);
445         char* name = (char*)(map_entry + 1);
446
447         list = GNUNET_malloc(2*sizeof(struct answer_packet_list*) + offset + 2 + ntohs(namelen));
448
449         struct answer_packet* rpkt = &list->pkt;
450
451         /* The offset points to the first byte belonging to the address */
452         memcpy(rpkt, pkt, offset - 1);
453
454         rpkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
455         rpkt->hdr.size = ntohs(offset + 2 + ntohs(namelen));
456
457         memcpy(((char*)rpkt)+offset, &namelen, 2);
458         memcpy(((char*)rpkt)+offset+2, name, ntohs(namelen));
459
460       }
461     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_IP)
462       {
463         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
464         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
465       }
466     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_REMOTE)
467       {
468         pkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
469
470         GNUNET_HashCode key;
471         memset(&key, 0, sizeof(GNUNET_HashCode));
472
473         unsigned char* c = ((unsigned char*)pkt)+ntohs(pkt->addroffset);
474         new_ip6addr_remote(c, pkt->addr, pkt->addrsize);
475         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "New mapping to %02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x\n",
476                    c[0],
477                    c[1],
478                    c[2],
479                    c[3],
480                    c[4],
481                    c[5],
482                    c[6],
483                    c[7],
484                    c[8],
485                    c[9],
486                    c[10],
487                    c[11],
488                    c[12],
489                    c[13],
490                    c[14],
491                    c[15]);
492         unsigned char* k = (unsigned char*)&key;
493         /*
494          * Copy the newly generated ip-address to the key backwards (as only the first part is used in the hash-table)
495          */
496         unsigned int i;
497         for (i = 0; i < 16; i++)
498             k[15-i] = c[i];
499
500         uint16_t namelen = strlen((char*)pkt->data+12)+1;
501
502         struct map_entry* value = GNUNET_malloc(sizeof(struct map_entry) + namelen);
503         char* name = (char*)(value +1);
504
505         value->namelen = namelen;
506         memcpy(name, pkt->data+12, namelen);
507
508         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Setting addrlen to %d\n", pkt->addrsize);
509         value->addrlen = pkt->addrsize;
510         memcpy(&value->addr, &pkt->addr, pkt->addrsize);
511         memset(value->additional_ports, 0, 8192);
512
513         memcpy(&value->hash, &key, sizeof(GNUNET_HashCode));
514
515         if (GNUNET_NO ==
516             GNUNET_CONTAINER_multihashmap_contains (hashmap, &key))
517           {
518             GNUNET_CONTAINER_multihashmap_put (hashmap, &key, value,
519                                                GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
520             value->heap_node = GNUNET_CONTAINER_heap_insert (heap, value,
521                                                              GNUNET_TIME_absolute_get ().abs_value);
522             if (GNUNET_CONTAINER_heap_get_size(heap) > max_mappings)
523               GNUNET_SCHEDULER_add_now(collect_mappings, NULL);
524           }
525         else
526           GNUNET_free(value);
527
528         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
529
530         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
531       }
532     else
533       {
534         GNUNET_break(0);
535         GNUNET_free(pkt);
536         return;
537       }
538
539     GNUNET_free(pkt);
540
541     GNUNET_CONTAINER_DLL_insert_after(answer_proc_head, answer_proc_tail, answer_proc_tail, list);
542
543     schedule_helper_write(GNUNET_TIME_UNIT_FOREVER_REL, NULL);
544
545     return;
546 }
547
548 /**
549  * Sets a bit active in a bitArray.
550  *
551  * @param bitArray memory area to set the bit in
552  * @param bitIdx which bit to set
553  */
554 void
555 setBit (char *bitArray, unsigned int bitIdx)
556 {
557   size_t arraySlot;
558   unsigned int targetBit;
559
560   arraySlot = bitIdx / 8;
561   targetBit = (1L << (bitIdx % 8));
562   bitArray[arraySlot] |= targetBit;
563 }
564
565 /**
566  * Clears a bit from bitArray.
567  *
568  * @param bitArray memory area to set the bit in
569  * @param bitIdx which bit to unset
570  */
571 void
572 clearBit (char *bitArray, unsigned int bitIdx)
573 {
574   size_t slot;
575   unsigned int targetBit;
576
577   slot = bitIdx / 8;
578   targetBit = (1L << (bitIdx % 8));
579   bitArray[slot] = bitArray[slot] & (~targetBit);
580 }
581
582 /**
583  * Checks if a bit is active in the bitArray
584  *
585  * @param bitArray memory area to set the bit in
586  * @param bitIdx which bit to test
587  * @return GNUNET_YES if the bit is set, GNUNET_NO if not.
588  */
589 int
590 testBit (char *bitArray, unsigned int bitIdx)
591 {
592   size_t slot;
593   unsigned int targetBit;
594
595   slot = bitIdx / 8;
596   targetBit = (1L << (bitIdx % 8));
597   if (bitArray[slot] & targetBit)
598     return GNUNET_YES;
599   else
600     return GNUNET_NO;
601 }
602
603 /**
604  * @brief Add the port to the list of additional ports in the map_entry
605  *
606  * @param me the map_entry
607  * @param port the port in host-byte-order
608  */
609 static void
610 add_additional_port (struct map_entry *me, uint16_t port)
611 {
612   setBit(me->additional_ports, port);
613 }
614
615 static int
616 receive_udp_back (void *cls __attribute__((unused)), struct GNUNET_MESH_Tunnel* tunnel,
617                   void **tunnel_ctx __attribute__((unused)),
618                   const struct GNUNET_PeerIdentity *sender __attribute__((unused)),
619                   const struct GNUNET_MessageHeader *message,
620                   const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
621 {
622   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
623   struct remote_addr* s = (struct remote_addr*)desc;
624   struct udp_pkt *pkt = (struct udp_pkt *) (desc + 1);
625   const struct GNUNET_PeerIdentity* other = GNUNET_MESH_get_peer(tunnel);
626
627   size_t size = sizeof(struct ip6_udp) + ntohs(pkt->len) - 1 - sizeof(struct udp_pkt);
628
629   struct ip6_udp* pkt6 = alloca(size);
630
631   GNUNET_assert(pkt6 != NULL);
632
633   if (ntohs(message->type) == GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK)
634     new_ip6addr(pkt6->ip6_hdr.sadr, &other->hashPubKey, desc);
635   else
636     new_ip6addr_remote(pkt6->ip6_hdr.sadr, s->addr, s->addrlen);
637
638   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Relaying calc:%d gnu:%d udp:%d bytes!\n", size, ntohs(message->size), ntohs(pkt->len));
639
640   pkt6->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
641   pkt6->shdr.size = htons(size);
642
643   pkt6->tun.flags = 0;
644   pkt6->tun.type = htons(0x86dd);
645
646   pkt6->ip6_hdr.version = 6;
647   pkt6->ip6_hdr.tclass_h = 0;
648   pkt6->ip6_hdr.tclass_l = 0;
649   pkt6->ip6_hdr.flowlbl = 0;
650   pkt6->ip6_hdr.paylgth = pkt->len;
651   pkt6->ip6_hdr.nxthdr = 0x11;
652   pkt6->ip6_hdr.hoplmt = 0xff;
653
654   {
655     char* ipv6addr;
656     GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "vpn", "IPV6ADDR", &ipv6addr));
657     inet_pton (AF_INET6, ipv6addr, pkt6->ip6_hdr.dadr);
658     GNUNET_free(ipv6addr);
659   }
660   memcpy(&pkt6->udp_hdr, pkt, ntohs(pkt->len));
661
662   GNUNET_HashCode* key = address_mapping_exists(pkt6->ip6_hdr.sadr);
663   GNUNET_assert (key != NULL);
664
665   struct map_entry *me = GNUNET_CONTAINER_multihashmap_get(hashmap, key);
666   GNUNET_CONTAINER_heap_update_cost (heap, me->heap_node,
667                                      GNUNET_TIME_absolute_get ().abs_value);
668
669   GNUNET_free(key);
670
671   GNUNET_assert (me != NULL);
672   if (ntohs(message->type) == GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK)
673     {
674       GNUNET_assert (me->desc.service_type & htonl(GNUNET_DNS_SERVICE_TYPE_UDP));
675       if (!port_in_ports(me->desc.ports, pkt6->udp_hdr.spt) &&
676           !testBit(me->additional_ports, ntohs(pkt6->udp_hdr.spt))) {
677           add_additional_port(me, ntohs(pkt6->udp_hdr.spt));
678       }
679     }
680
681   pkt6->udp_hdr.crc = 0;
682   uint32_t sum = 0;
683   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->ip6_hdr.sadr, 16);
684   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->ip6_hdr.dadr, 16);
685   uint32_t tmp = (pkt6->udp_hdr.len & 0xffff);
686   sum = calculate_checksum_update(sum, (uint16_t*)&tmp, 4);
687   tmp = htons(((pkt6->ip6_hdr.nxthdr & 0x00ff)));
688   sum = calculate_checksum_update(sum, (uint16_t*)&tmp, 4);
689
690   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->udp_hdr, ntohs(pkt->len));
691   pkt6->udp_hdr.crc = calculate_checksum_end(sum);
692
693   write_to_helper(pkt6, size);
694
695   return GNUNET_OK;
696 }
697
698 static int
699 receive_tcp_back (void *cls __attribute__((unused)), struct GNUNET_MESH_Tunnel* tunnel,
700                   void **tunnel_ctx __attribute__((unused)),
701                   const struct GNUNET_PeerIdentity *sender __attribute__((unused)),
702                   const struct GNUNET_MessageHeader *message,
703                   const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
704 {
705   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
706   struct remote_addr* s = (struct remote_addr*)desc;
707   struct tcp_pkt *pkt = (struct tcp_pkt *) (desc + 1);
708   const struct GNUNET_PeerIdentity* other = GNUNET_MESH_get_peer(tunnel);
709
710   size_t pktlen = ntohs(message->size) - sizeof(struct GNUNET_MessageHeader) - sizeof(GNUNET_HashCode);
711   size_t size = pktlen + sizeof(struct ip6_tcp) - 1;
712
713   struct ip6_tcp* pkt6 = alloca(size);
714   memset(pkt6, 0, size);
715
716   GNUNET_assert(pkt6 != NULL);
717
718   if (ntohs(message->type) == GNUNET_MESSAGE_TYPE_SERVICE_TCP_BACK)
719     new_ip6addr(pkt6->ip6_hdr.sadr, &other->hashPubKey, desc);
720   else
721     new_ip6addr_remote(pkt6->ip6_hdr.sadr, s->addr, s->addrlen);
722
723   pkt6->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
724   pkt6->shdr.size = htons(size);
725
726   pkt6->tun.flags = 0;
727   pkt6->tun.type = htons(0x86dd);
728
729   pkt6->ip6_hdr.version = 6;
730   pkt6->ip6_hdr.tclass_h = 0;
731   pkt6->ip6_hdr.tclass_l = 0;
732   pkt6->ip6_hdr.flowlbl = 0;
733   pkt6->ip6_hdr.paylgth = htons(pktlen);
734   pkt6->ip6_hdr.nxthdr = 0x06;
735   pkt6->ip6_hdr.hoplmt = 0xff;
736
737   {
738     char* ipv6addr;
739     GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "vpn", "IPV6ADDR", &ipv6addr));
740     inet_pton (AF_INET6, ipv6addr, pkt6->ip6_hdr.dadr);
741     GNUNET_free(ipv6addr);
742   }
743   memcpy(&pkt6->tcp_hdr, pkt, pktlen);
744
745   GNUNET_HashCode* key = address_mapping_exists(pkt6->ip6_hdr.sadr);
746   GNUNET_assert (key != NULL);
747
748   struct map_entry *me = GNUNET_CONTAINER_multihashmap_get(hashmap, key);
749   GNUNET_CONTAINER_heap_update_cost (heap, me->heap_node,
750                                      GNUNET_TIME_absolute_get ().abs_value);
751
752   GNUNET_free(key);
753
754   GNUNET_assert (me != NULL);
755   if (ntohs(message->type) == GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK)
756     GNUNET_assert (me->desc.service_type & htonl(GNUNET_DNS_SERVICE_TYPE_TCP));
757
758   pkt6->tcp_hdr.crc = 0;
759   uint32_t sum = 0;
760   uint32_t tmp;
761   sum =
762     calculate_checksum_update (sum, (uint16_t *) & pkt6->ip6_hdr.sadr, 16);
763   sum =
764     calculate_checksum_update (sum, (uint16_t *) & pkt6->ip6_hdr.dadr, 16);
765   tmp = htonl(pktlen);
766   sum = calculate_checksum_update (sum, (uint16_t *) & tmp, 4);
767   tmp = htonl (((pkt6->ip6_hdr.nxthdr & 0x000000ff)));
768   sum = calculate_checksum_update (sum, (uint16_t *) & tmp, 4);
769
770   sum =
771     calculate_checksum_update (sum, (uint16_t *) & pkt6->tcp_hdr,
772                                ntohs (pkt6->ip6_hdr.paylgth));
773   pkt6->tcp_hdr.crc = calculate_checksum_end (sum);
774
775   write_to_helper(pkt6, size);
776
777   return GNUNET_OK;
778 }
779
780 /**
781  * Main function that will be run by the scheduler.
782  *
783  * @param cls closure
784  * @param args remaining command-line arguments
785  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
786  * @param cfg_ configuration
787  */
788 static void
789 run (void *cls,
790      char *const *args __attribute__((unused)),
791      const char *cfgfilep __attribute__((unused)),
792      const struct GNUNET_CONFIGURATION_Handle *cfg_)
793 {
794     static const struct GNUNET_MESH_MessageHandler handlers[] = {
795           {receive_udp_back, GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK, 0},
796           {receive_tcp_back, GNUNET_MESSAGE_TYPE_SERVICE_TCP_BACK, 0},
797           {receive_udp_back, GNUNET_MESSAGE_TYPE_REMOTE_UDP_BACK, 0},
798           {receive_tcp_back, GNUNET_MESSAGE_TYPE_REMOTE_TCP_BACK, 0},
799           {NULL, 0, 0}
800     };
801
802     static const GNUNET_MESH_ApplicationType types[] = {
803         GNUNET_APPLICATION_TYPE_END
804     };
805
806     mesh_handle = GNUNET_MESH_connect(cfg_,
807                                       NULL,
808                                       NULL,
809                                       handlers,
810                                       types);
811     cfg = cfg_;
812     restart_hijack = 0;
813     hashmap = GNUNET_CONTAINER_multihashmap_create(65536);
814     heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
815     GNUNET_CONFIGURATION_get_value_number (cfg, "vpn", "MAX_MAPPINGg",
816                                            &max_mappings);
817     udp_connections = GNUNET_CONTAINER_multihashmap_create(65536);
818     conn_task = GNUNET_SCHEDULER_add_now (connect_to_service_dns, NULL);
819     shs_task = GNUNET_SCHEDULER_add_after (conn_task, start_helper_and_schedule, NULL);
820     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls);
821 }
822
823 /**
824  * The main function to obtain template from gnunetd.
825  *
826  * @param argc number of arguments from the command line
827  * @param argv command line arguments
828  * @return 0 ok, 1 on error
829  */
830 int
831 main (int argc, char *const *argv) {
832     static const struct GNUNET_GETOPT_CommandLineOption options[] = {
833         GNUNET_GETOPT_OPTION_END
834     };
835
836     return (GNUNET_OK ==
837             GNUNET_PROGRAM_run (argc,
838                                 argv,
839                                 "vpn",
840                                 gettext_noop ("help text"),
841                                 options, &run, NULL)) ? ret : 1;
842 }
843
844 /* end of gnunet-daemon-vpn.c */
845