reply ipv4-icmp
[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 address6_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 /**
134  * @return the hash of the IP-Address if a mapping exists, NULL otherwise
135  */
136 GNUNET_HashCode *
137 address4_mapping_exists (uint32_t addr)
138 {
139   GNUNET_HashCode *key = GNUNET_malloc (sizeof (GNUNET_HashCode));
140   memset (key, 0, sizeof (GNUNET_HashCode));
141   unsigned char *c = (unsigned char *) &addr;
142   unsigned char *k = (unsigned char *) key;
143   unsigned int i;
144   for (i = 0; i < 4; i++)
145     k[3 - i] = c[i];
146
147   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
148               "a4_m_e: getting with key %08x, addr is %08x, %d.%d.%d.%d\n",
149               *((uint32_t *) (key)), addr, c[0], c[1], c[2], c[3]);
150
151   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (hashmap, key))
152     return key;
153   else
154     {
155       GNUNET_free (key);
156       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Mapping not found!\n");
157       return NULL;
158     }
159 }
160
161 static void
162 collect_mappings(void* cls __attribute__((unused)), const struct GNUNET_SCHEDULER_TaskContext* tc) {
163     if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
164       return;
165
166     struct map_entry* me = GNUNET_CONTAINER_heap_remove_root(heap);
167
168     /* This is free()ed memory! */
169     me->heap_node = NULL;
170
171     /* FIXME! GNUNET_MESH_close_tunnel(me->tunnel); */
172
173     GNUNET_CONTAINER_multihashmap_remove(hashmap, &me->hash, me);
174
175     GNUNET_free(me);
176 }
177
178 void
179 send_icmp4_response(void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc) {
180     if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
181       return;
182
183     struct ip_icmp* request = cls;
184
185     struct ip_icmp* response = alloca(ntohs(request->shdr.size));
186     GNUNET_assert(response != NULL);
187     memset(response, 0, ntohs(request->shdr.size));
188
189     response->shdr.size = request->shdr.size;
190     response->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
191
192     response->tun.flags = 0;
193     response->tun.type = htons(0x0800);
194
195     response->ip_hdr.hdr_lngth = 5;
196     response->ip_hdr.version = 4;
197     response->ip_hdr.proto = 0x01;
198     response->ip_hdr.dadr = request->ip_hdr.sadr;
199     response->ip_hdr.sadr = request->ip_hdr.dadr;
200     response->ip_hdr.tot_lngth = request->ip_hdr.tot_lngth;
201
202     response->ip_hdr.chks = calculate_ip_checksum((uint16_t*)&response->ip_hdr, 20);
203
204     response->icmp_hdr.code = 0;
205     response->icmp_hdr.type = 0x0;
206
207     /* Magic, more Magic! */
208     response->icmp_hdr.chks = request->icmp_hdr.chks + 0x8;
209
210     /* Copy the rest of the packet */
211     memcpy(response+1, request+1, ntohs(request->shdr.size) - sizeof(struct ip_icmp));
212
213     write_to_helper(response, ntohs(response->shdr.size));
214
215     GNUNET_free(request);
216 }
217
218 void
219 send_icmp6_response(void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc) {
220     if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
221       return;
222
223     struct ip6_icmp* request = cls;
224
225     struct ip6_icmp* response = alloca(ntohs(request->shdr.size));
226     GNUNET_assert(response != NULL);
227     memset(response, 0, ntohs(request->shdr.size));
228
229     response->shdr.size = request->shdr.size;
230     response->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
231
232     response->tun.flags = 0;
233     response->tun.type = htons(0x86dd);
234
235     response->ip6_hdr.hoplmt = 255;
236     response->ip6_hdr.paylgth = request->ip6_hdr.paylgth;
237     response->ip6_hdr.nxthdr = 0x3a;
238     response->ip6_hdr.version = 6;
239     memcpy(&response->ip6_hdr.sadr, &request->ip6_hdr.dadr, 16);
240     memcpy(&response->ip6_hdr.dadr, &request->ip6_hdr.sadr, 16);
241
242     response->icmp_hdr.code = 0;
243     response->icmp_hdr.type = 0x81;
244
245     /* Magic, more Magic! */
246     response->icmp_hdr.chks = request->icmp_hdr.chks - 0x1;
247
248     /* Copy the rest of the packet */
249     memcpy(response+1, request+1, ntohs(request->shdr.size) - sizeof(struct ip6_icmp));
250
251     write_to_helper(response, ntohs(response->shdr.size));
252
253     GNUNET_free(request);
254 }
255
256 /**
257  * cls is the pointer to a GNUNET_MessageHeader that is
258  * followed by the service-descriptor and the packet that should be sent;
259  */
260 static size_t
261 send_pkt_to_peer_notify_callback (void *cls, size_t size, void *buf)
262 {
263   struct GNUNET_MESH_Tunnel **tunnel = cls;
264   GNUNET_MESH_tunnel_set_data(*tunnel, NULL);
265   struct GNUNET_MessageHeader *hdr =
266     (struct GNUNET_MessageHeader *) (tunnel + 1);
267   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "send_pkt_to_peer_notify_callback: buf = %x; size = %u;\n", buf, size);
268   GNUNET_assert (size >= ntohs (hdr->size));
269   memcpy (buf, hdr, ntohs (hdr->size));
270   size = ntohs(hdr->size);
271   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sent!\n");
272
273   if (NULL != GNUNET_MESH_tunnel_get_head(*tunnel))
274     {
275       struct tunnel_notify_queue* element = GNUNET_MESH_tunnel_get_head(*tunnel);
276       struct tunnel_notify_queue* head = GNUNET_MESH_tunnel_get_head(*tunnel);
277       struct tunnel_notify_queue* tail = GNUNET_MESH_tunnel_get_tail(*tunnel);
278
279       GNUNET_CONTAINER_DLL_remove(head, tail, element);
280
281       GNUNET_MESH_tunnel_set_head(*tunnel, head);
282       GNUNET_MESH_tunnel_set_tail(*tunnel, tail);
283
284       struct GNUNET_MESH_TransmitHandle* th = GNUNET_MESH_notify_transmit_ready (*tunnel,
285                                                                                  GNUNET_NO,
286                                                                                  42,
287                                                                                  GNUNET_TIME_relative_divide
288                                                                                  (GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
289                                                                                  (const struct GNUNET_PeerIdentity *)
290                                                                                  NULL, element->len,
291                                                                                  send_pkt_to_peer_notify_callback, element->cls);
292       /* save the handle */
293       GNUNET_MESH_tunnel_set_data(*tunnel, th);
294     }
295   GNUNET_free (cls);
296
297   return size;
298 }
299
300 unsigned int
301 port_in_ports (uint64_t ports, uint16_t port)
302 {
303   uint16_t *ps = (uint16_t *) & ports;
304   return ps[0] == port || ps[1] == port || ps[2] == port || ps[3] == port;
305 }
306
307 void
308 send_pkt_to_peer (void *cls, 
309                   const struct GNUNET_PeerIdentity *peer,
310                   const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
311 {
312   /* peer == NULL means that all peers in this request are connected */
313   if (peer == NULL) return;
314   struct GNUNET_MESH_Tunnel **tunnel = cls;
315   struct GNUNET_MessageHeader *hdr =
316     (struct GNUNET_MessageHeader *) (tunnel + 1);
317
318   GNUNET_assert(NULL != tunnel);
319   GNUNET_assert(NULL != *tunnel);
320
321   if (NULL == GNUNET_MESH_tunnel_get_data(*tunnel))
322     {
323       struct GNUNET_MESH_TransmitHandle* th = GNUNET_MESH_notify_transmit_ready (*tunnel,
324                                                                                  GNUNET_NO,
325                                                                                  42,
326                                                                                  GNUNET_TIME_relative_divide(GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
327                                                                                  (const struct GNUNET_PeerIdentity *)NULL,
328                                                                                  ntohs(hdr->size),
329                                                                                  send_pkt_to_peer_notify_callback,
330                                                                                  cls);
331       GNUNET_MESH_tunnel_set_data(*tunnel, th);
332     }
333   else
334     {
335      struct tunnel_notify_queue* head = GNUNET_MESH_tunnel_get_head(*tunnel);
336      struct tunnel_notify_queue* tail = GNUNET_MESH_tunnel_get_tail(*tunnel);
337      struct tunnel_notify_queue* element = GNUNET_malloc(sizeof *element);
338
339      element->cls = cls;
340      element->len = ntohs(hdr->size);
341
342      GNUNET_CONTAINER_DLL_insert_tail(head, tail, element);
343
344      GNUNET_MESH_tunnel_set_head(*tunnel, head);
345      GNUNET_MESH_tunnel_set_tail(*tunnel, tail);
346     }
347 }
348
349 /**
350  * Create a new Address from an answer-packet
351  */
352 void
353 new_ip6addr(unsigned char* buf, const GNUNET_HashCode *peer, const GNUNET_HashCode *service_desc) { /* {{{ */
354     char* ipv6addr;
355     unsigned long long ipv6prefix;
356     GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "vpn", "IPV6ADDR", &ipv6addr));
357     GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "vpn", "IPV6PREFIX", &ipv6prefix));
358     GNUNET_assert(ipv6prefix < 127);
359     ipv6prefix = (ipv6prefix + 7)/8;
360
361     inet_pton (AF_INET6, ipv6addr, buf);
362     GNUNET_free(ipv6addr);
363
364     int peer_length = 16 - ipv6prefix - 6;
365     if (peer_length <= 0)
366       peer_length = 0;
367
368     int service_length = 16 - ipv6prefix - peer_length;
369     if (service_length <= 0)
370       service_length = 0;
371
372     memcpy(buf+ipv6prefix, service_desc, service_length);
373     memcpy(buf+ipv6prefix+service_length, peer, peer_length);
374 }
375 /*}}}*/
376
377
378 /**
379  * Create a new Address from an answer-packet
380  */
381 void
382 new_ip6addr_remote (unsigned char *buf, unsigned char *addr, char addrlen)
383 {                               /* {{{ */
384   char *ipv6addr;
385   unsigned long long ipv6prefix;
386   GNUNET_assert (GNUNET_OK ==
387                  GNUNET_CONFIGURATION_get_value_string (cfg, "vpn",
388                                                         "IPV6ADDR",
389                                                         &ipv6addr));
390   GNUNET_assert (GNUNET_OK ==
391                  GNUNET_CONFIGURATION_get_value_number (cfg, "vpn",
392                                                         "IPV6PREFIX",
393                                                         &ipv6prefix));
394   GNUNET_assert (ipv6prefix < 127);
395   ipv6prefix = (ipv6prefix + 7) / 8;
396
397   inet_pton (AF_INET6, ipv6addr, buf);
398   GNUNET_free (ipv6addr);
399
400   int local_length = 16 - ipv6prefix;
401
402   memcpy (buf + ipv6prefix, addr, GNUNET_MIN (addrlen, local_length));
403 }
404 /*}}}*/
405
406 /**
407  * Create a new Address from an answer-packet
408  */
409 void
410 new_ip4addr_remote (unsigned char *buf, unsigned char *addr, char addrlen)
411 {                               /* {{{ */
412   char *ipv4addr;
413   char *ipv4mask;
414   GNUNET_assert (GNUNET_OK ==
415                  GNUNET_CONFIGURATION_get_value_string (cfg, "vpn",
416                                                         "IPV4ADDR",
417                                                         &ipv4addr));
418   GNUNET_assert (GNUNET_OK ==
419                  GNUNET_CONFIGURATION_get_value_string (cfg, "vpn",
420                                                         "IPV4MASK",
421                                                         &ipv4mask));
422   uint32_t mask;
423   inet_pton (AF_INET, ipv4addr, buf);
424   int r = inet_pton (AF_INET, ipv4mask, &mask);
425   mask = htonl(mask);
426   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "inet_pton: %d; %m; mask: %08x\n", r, mask);
427
428   GNUNET_free (ipv4addr);
429
430   int c;
431
432   if (mask)
433     {
434       mask = (mask ^ (mask - 1)) >> 1;
435       for (c = 0; mask; c++)
436         {
437           mask >>= 1;
438         }
439     }
440   else
441     {
442       c = CHAR_BIT * sizeof(mask);
443     }
444
445   c = 32-c;
446   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "The mask %s has %d leading 1s.\n", ipv4mask, c);
447
448   GNUNET_free (ipv4mask);
449
450   if (c % 8 == 0)
451     c = c / 8;
452   else
453     GNUNET_assert(0);
454
455   memcpy (buf + c, addr, GNUNET_MIN (addrlen, c));
456 }
457 /*}}}*/
458
459 /**
460  * This gets scheduled with cls pointing to an answer_packet and does everything
461  * needed in order to send it to the helper.
462  *
463  * At the moment this means "inventing" and IPv6-Address for .gnunet-services and
464  * doing nothing for "real" services.
465  */
466 void
467 process_answer(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tc) {
468     if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
469       return;
470
471     struct answer_packet* pkt = cls;
472     struct answer_packet_list* list;
473
474     /* This answer is about a .gnunet-service
475      *
476      * It contains an almost complete DNS-Response, we have to fill in the ip
477      * at the offset pkt->addroffset
478      */
479     if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_SERVICE)
480       {
481         pkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
482
483         GNUNET_HashCode key;
484         memset(&key, 0, sizeof(GNUNET_HashCode));
485
486         unsigned char* c = ((unsigned char*)pkt)+ntohs(pkt->addroffset);
487         unsigned char* k = (unsigned char*)&key;
488         new_ip6addr(c, &pkt->service_descr.peer, &pkt->service_descr.service_descriptor);
489         /*
490          * Copy the newly generated ip-address to the key backwarts (as only the first part is hashed)
491          */
492         unsigned int i;
493         for (i = 0; i < 16; i++)
494             k[15-i] = c[i];
495
496         uint16_t namelen = strlen((char*)pkt->data+12)+1;
497
498         struct map_entry* value = GNUNET_malloc(sizeof(struct map_entry) + namelen);
499         char* name = (char*)(value +1);
500
501         value->namelen = namelen;
502         memcpy(name, pkt->data+12, namelen);
503
504         memcpy(&value->desc, &pkt->service_descr, sizeof(struct GNUNET_vpn_service_descriptor));
505
506         memset(value->additional_ports, 0, 8192);
507
508         memcpy(&value->hash, &key, sizeof(GNUNET_HashCode));
509
510         if (GNUNET_NO ==
511             GNUNET_CONTAINER_multihashmap_contains (hashmap, &key))
512           {
513             GNUNET_CONTAINER_multihashmap_put (hashmap, &key, value,
514                                                GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
515
516             value->heap_node = GNUNET_CONTAINER_heap_insert (heap, value,
517                                                              GNUNET_TIME_absolute_get ().abs_value);
518             if (GNUNET_CONTAINER_heap_get_size(heap) > max_mappings)
519               GNUNET_SCHEDULER_add_now(collect_mappings, NULL);
520           }
521         else
522           GNUNET_free(value);
523
524
525         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
526
527         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
528
529       }
530     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_REV)
531       {
532         GNUNET_HashCode key;
533         memset(&key, 0, sizeof key);
534         unsigned char* k = (unsigned char*)&key;
535         unsigned char* s = pkt->data+12;
536         int i = 0;
537         /* Whoever designed the reverse IPv6-lookup is batshit insane */
538         for (i = 0; i < 16; i++)
539           {
540             unsigned char c1 = s[(4*i)+1];
541             unsigned char c2 = s[(4*i)+3];
542             if (c1 <= '9')
543               k[i] = c1 - '0';
544             else
545               k[i] = c1 - 87; /* 87 is the difference between 'a' and 10 */
546             if (c2 <= '9')
547               k[i] += 16*(c2 - '0');
548             else
549               k[i] += 16*(c2 - 87);
550           }
551
552         struct map_entry* map_entry = GNUNET_CONTAINER_multihashmap_get(hashmap, &key);
553         uint16_t offset = ntohs(pkt->addroffset);
554
555         if (map_entry == NULL)
556           {
557             GNUNET_free(pkt);
558             return;
559           }
560
561         GNUNET_CONTAINER_heap_update_cost (heap, map_entry->heap_node,
562                                            GNUNET_TIME_absolute_get ().abs_value);
563
564
565         unsigned short namelen = htons(map_entry->namelen);
566         char* name = (char*)(map_entry + 1);
567
568         list = GNUNET_malloc(2*sizeof(struct answer_packet_list*) + offset + 2 + ntohs(namelen));
569
570         struct answer_packet* rpkt = &list->pkt;
571
572         /* The offset points to the first byte belonging to the address */
573         memcpy(rpkt, pkt, offset - 1);
574
575         rpkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
576         rpkt->hdr.size = ntohs(offset + 2 + ntohs(namelen));
577
578         memcpy(((char*)rpkt)+offset, &namelen, 2);
579         memcpy(((char*)rpkt)+offset+2, name, ntohs(namelen));
580
581       }
582     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_IP)
583       {
584         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
585         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
586       }
587     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_REMOTE_AAAA)
588       {
589         pkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
590
591         GNUNET_HashCode key;
592         memset(&key, 0, sizeof(GNUNET_HashCode));
593
594         unsigned char* c = ((unsigned char*)pkt)+ntohs(pkt->addroffset);
595         new_ip6addr_remote(c, pkt->addr, pkt->addrsize);
596         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",
597                    c[0],
598                    c[1],
599                    c[2],
600                    c[3],
601                    c[4],
602                    c[5],
603                    c[6],
604                    c[7],
605                    c[8],
606                    c[9],
607                    c[10],
608                    c[11],
609                    c[12],
610                    c[13],
611                    c[14],
612                    c[15]);
613         unsigned char* k = (unsigned char*)&key;
614         /*
615          * Copy the newly generated ip-address to the key backwards (as only the first part is used in the hash-table)
616          */
617         unsigned int i;
618         for (i = 0; i < 16; i++)
619             k[15-i] = c[i];
620
621         uint16_t namelen = strlen((char*)pkt->data+12)+1;
622
623         struct map_entry* value = GNUNET_malloc(sizeof(struct map_entry) + namelen);
624         char* name = (char*)(value +1);
625
626         value->namelen = namelen;
627         memcpy(name, pkt->data+12, namelen);
628
629         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Setting addrlen to %d\n", pkt->addrsize);
630         value->addrlen = pkt->addrsize;
631         memcpy(&value->addr, &pkt->addr, pkt->addrsize);
632         memset(value->additional_ports, 0, 8192);
633
634         memcpy(&value->hash, &key, sizeof(GNUNET_HashCode));
635
636         if (GNUNET_NO ==
637             GNUNET_CONTAINER_multihashmap_contains (hashmap, &key))
638           {
639             GNUNET_CONTAINER_multihashmap_put (hashmap, &key, value,
640                                                GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
641             value->heap_node = GNUNET_CONTAINER_heap_insert (heap, value,
642                                                              GNUNET_TIME_absolute_get ().abs_value);
643             if (GNUNET_CONTAINER_heap_get_size(heap) > max_mappings)
644               GNUNET_SCHEDULER_add_now(collect_mappings, NULL);
645           }
646         else
647           GNUNET_free(value);
648
649         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
650
651         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
652       }
653     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_REMOTE_A)
654       {
655         pkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
656
657         GNUNET_HashCode key;
658         memset(&key, 0, sizeof(GNUNET_HashCode));
659
660         unsigned char* c = ((unsigned char*)pkt)+ntohs(pkt->addroffset);
661         new_ip4addr_remote(c, pkt->addr, pkt->addrsize);
662         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "New mapping to %d.%d.%d.%d\n",
663                    c[0],
664                    c[1],
665                    c[2],
666                    c[3]);
667         unsigned char* k = (unsigned char*)&key;
668         /*
669          * Copy the newly generated ip-address to the key backwards (as only the first part is used in the hash-table)
670          */
671         unsigned int i;
672         for (i = 0; i < 4; i++)
673             k[3-i] = c[i];
674
675         uint16_t namelen = strlen((char*)pkt->data+12)+1;
676
677         struct map_entry* value = GNUNET_malloc(sizeof(struct map_entry) + namelen);
678         char* name = (char*)(value +1);
679
680         value->namelen = namelen;
681         memcpy(name, pkt->data+12, namelen);
682
683         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Setting addrlen to %d\n", pkt->addrsize);
684         value->addrlen = pkt->addrsize;
685         memcpy(&value->addr, &pkt->addr, pkt->addrsize);
686         memset(value->additional_ports, 0, 8192);
687
688         memcpy(&value->hash, &key, sizeof(GNUNET_HashCode));
689
690         if (GNUNET_NO ==
691             GNUNET_CONTAINER_multihashmap_contains (hashmap, &key))
692           {
693             GNUNET_CONTAINER_multihashmap_put (hashmap, &key, value,
694                                                GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
695             value->heap_node = GNUNET_CONTAINER_heap_insert (heap, value,
696                                                              GNUNET_TIME_absolute_get ().abs_value);
697             GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Mapping is saved in the hashmap with key %08x.\n",
698                        *((uint32_t*)(&key)));
699             if (GNUNET_CONTAINER_heap_get_size(heap) > max_mappings)
700               GNUNET_SCHEDULER_add_now(collect_mappings, NULL);
701           }
702         else
703           GNUNET_free(value);
704
705         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
706
707         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
708       }
709     else
710       {
711         GNUNET_break(0);
712         GNUNET_free(pkt);
713         return;
714       }
715
716     GNUNET_free(pkt);
717
718     GNUNET_CONTAINER_DLL_insert_after(answer_proc_head, answer_proc_tail, answer_proc_tail, list);
719
720     schedule_helper_write(GNUNET_TIME_UNIT_FOREVER_REL, NULL);
721
722     return;
723 }
724
725 /**
726  * Sets a bit active in a bitArray.
727  *
728  * @param bitArray memory area to set the bit in
729  * @param bitIdx which bit to set
730  */
731 void
732 setBit (char *bitArray, unsigned int bitIdx)
733 {
734   size_t arraySlot;
735   unsigned int targetBit;
736
737   arraySlot = bitIdx / 8;
738   targetBit = (1L << (bitIdx % 8));
739   bitArray[arraySlot] |= targetBit;
740 }
741
742 /**
743  * Clears a bit from bitArray.
744  *
745  * @param bitArray memory area to set the bit in
746  * @param bitIdx which bit to unset
747  */
748 void
749 clearBit (char *bitArray, unsigned int bitIdx)
750 {
751   size_t slot;
752   unsigned int targetBit;
753
754   slot = bitIdx / 8;
755   targetBit = (1L << (bitIdx % 8));
756   bitArray[slot] = bitArray[slot] & (~targetBit);
757 }
758
759 /**
760  * Checks if a bit is active in the bitArray
761  *
762  * @param bitArray memory area to set the bit in
763  * @param bitIdx which bit to test
764  * @return GNUNET_YES if the bit is set, GNUNET_NO if not.
765  */
766 int
767 testBit (char *bitArray, unsigned int bitIdx)
768 {
769   size_t slot;
770   unsigned int targetBit;
771
772   slot = bitIdx / 8;
773   targetBit = (1L << (bitIdx % 8));
774   if (bitArray[slot] & targetBit)
775     return GNUNET_YES;
776   else
777     return GNUNET_NO;
778 }
779
780 /**
781  * @brief Add the port to the list of additional ports in the map_entry
782  *
783  * @param me the map_entry
784  * @param port the port in host-byte-order
785  */
786 static void
787 add_additional_port (struct map_entry *me, uint16_t port)
788 {
789   setBit(me->additional_ports, port);
790 }
791
792 static int
793 receive_udp_back (void *cls __attribute__((unused)), struct GNUNET_MESH_Tunnel* tunnel,
794                   void **tunnel_ctx __attribute__((unused)),
795                   const struct GNUNET_PeerIdentity *sender __attribute__((unused)),
796                   const struct GNUNET_MessageHeader *message,
797                   const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
798 {
799   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
800   struct remote_addr* s = (struct remote_addr*)desc;
801   struct udp_pkt *pkt = (struct udp_pkt *) (desc + 1);
802   const struct GNUNET_PeerIdentity* other = GNUNET_MESH_get_peer(tunnel);
803
804   size_t size = sizeof(struct ip6_udp) + ntohs(pkt->len) - 1 - sizeof(struct udp_pkt);
805
806   struct ip6_udp* pkt6 = alloca(size);
807
808   GNUNET_assert(pkt6 != NULL);
809
810   if (ntohs(message->type) == GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK)
811     new_ip6addr(pkt6->ip6_hdr.sadr, &other->hashPubKey, desc);
812   else
813     new_ip6addr_remote(pkt6->ip6_hdr.sadr, s->addr, s->addrlen);
814
815   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Relaying calc:%d gnu:%d udp:%d bytes!\n", size, ntohs(message->size), ntohs(pkt->len));
816
817   pkt6->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
818   pkt6->shdr.size = htons(size);
819
820   pkt6->tun.flags = 0;
821   pkt6->tun.type = htons(0x86dd);
822
823   pkt6->ip6_hdr.version = 6;
824   pkt6->ip6_hdr.tclass_h = 0;
825   pkt6->ip6_hdr.tclass_l = 0;
826   pkt6->ip6_hdr.flowlbl = 0;
827   pkt6->ip6_hdr.paylgth = pkt->len;
828   pkt6->ip6_hdr.nxthdr = 0x11;
829   pkt6->ip6_hdr.hoplmt = 0xff;
830
831   {
832     char* ipv6addr;
833     GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "vpn", "IPV6ADDR", &ipv6addr));
834     inet_pton (AF_INET6, ipv6addr, pkt6->ip6_hdr.dadr);
835     GNUNET_free(ipv6addr);
836   }
837   memcpy(&pkt6->udp_hdr, pkt, ntohs(pkt->len));
838
839   GNUNET_HashCode* key = address6_mapping_exists(pkt6->ip6_hdr.sadr);
840   GNUNET_assert (key != NULL);
841
842   struct map_entry *me = GNUNET_CONTAINER_multihashmap_get(hashmap, key);
843   GNUNET_CONTAINER_heap_update_cost (heap, me->heap_node,
844                                      GNUNET_TIME_absolute_get ().abs_value);
845
846   GNUNET_free(key);
847
848   GNUNET_assert (me != NULL);
849   if (ntohs(message->type) == GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK)
850     {
851       GNUNET_assert (me->desc.service_type & htonl(GNUNET_DNS_SERVICE_TYPE_UDP));
852       if (!port_in_ports(me->desc.ports, pkt6->udp_hdr.spt) &&
853           !testBit(me->additional_ports, ntohs(pkt6->udp_hdr.spt))) {
854           add_additional_port(me, ntohs(pkt6->udp_hdr.spt));
855       }
856     }
857
858   pkt6->udp_hdr.crc = 0;
859   uint32_t sum = 0;
860   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->ip6_hdr.sadr, 16);
861   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->ip6_hdr.dadr, 16);
862   uint32_t tmp = (pkt6->udp_hdr.len & 0xffff);
863   sum = calculate_checksum_update(sum, (uint16_t*)&tmp, 4);
864   tmp = htons(((pkt6->ip6_hdr.nxthdr & 0x00ff)));
865   sum = calculate_checksum_update(sum, (uint16_t*)&tmp, 4);
866
867   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->udp_hdr, ntohs(pkt->len));
868   pkt6->udp_hdr.crc = calculate_checksum_end(sum);
869
870   write_to_helper(pkt6, size);
871
872   return GNUNET_OK;
873 }
874
875 static int
876 receive_tcp_back (void *cls __attribute__((unused)), struct GNUNET_MESH_Tunnel* tunnel,
877                   void **tunnel_ctx __attribute__((unused)),
878                   const struct GNUNET_PeerIdentity *sender __attribute__((unused)),
879                   const struct GNUNET_MessageHeader *message,
880                   const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
881 {
882   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
883   struct remote_addr* s = (struct remote_addr*)desc;
884   struct tcp_pkt *pkt = (struct tcp_pkt *) (desc + 1);
885   const struct GNUNET_PeerIdentity* other = GNUNET_MESH_get_peer(tunnel);
886
887   size_t pktlen = ntohs(message->size) - sizeof(struct GNUNET_MessageHeader) - sizeof(GNUNET_HashCode);
888   size_t size = pktlen + sizeof(struct ip6_tcp) - 1;
889
890   struct ip6_tcp* pkt6 = alloca(size);
891   memset(pkt6, 0, size);
892
893   GNUNET_assert(pkt6 != NULL);
894
895   if (ntohs(message->type) == GNUNET_MESSAGE_TYPE_SERVICE_TCP_BACK)
896     new_ip6addr(pkt6->ip6_hdr.sadr, &other->hashPubKey, desc);
897   else
898     new_ip6addr_remote(pkt6->ip6_hdr.sadr, s->addr, s->addrlen);
899
900   pkt6->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
901   pkt6->shdr.size = htons(size);
902
903   pkt6->tun.flags = 0;
904   pkt6->tun.type = htons(0x86dd);
905
906   pkt6->ip6_hdr.version = 6;
907   pkt6->ip6_hdr.tclass_h = 0;
908   pkt6->ip6_hdr.tclass_l = 0;
909   pkt6->ip6_hdr.flowlbl = 0;
910   pkt6->ip6_hdr.paylgth = htons(pktlen);
911   pkt6->ip6_hdr.nxthdr = 0x06;
912   pkt6->ip6_hdr.hoplmt = 0xff;
913
914   {
915     char* ipv6addr;
916     GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "vpn", "IPV6ADDR", &ipv6addr));
917     inet_pton (AF_INET6, ipv6addr, pkt6->ip6_hdr.dadr);
918     GNUNET_free(ipv6addr);
919   }
920   memcpy(&pkt6->tcp_hdr, pkt, pktlen);
921
922   GNUNET_HashCode* key = address6_mapping_exists(pkt6->ip6_hdr.sadr);
923   GNUNET_assert (key != NULL);
924
925   struct map_entry *me = GNUNET_CONTAINER_multihashmap_get(hashmap, key);
926   GNUNET_CONTAINER_heap_update_cost (heap, me->heap_node,
927                                      GNUNET_TIME_absolute_get ().abs_value);
928
929   GNUNET_free(key);
930
931   GNUNET_assert (me != NULL);
932   if (ntohs(message->type) == GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK)
933     GNUNET_assert (me->desc.service_type & htonl(GNUNET_DNS_SERVICE_TYPE_TCP));
934
935   pkt6->tcp_hdr.crc = 0;
936   uint32_t sum = 0;
937   uint32_t tmp;
938   sum =
939     calculate_checksum_update (sum, (uint16_t *) & pkt6->ip6_hdr.sadr, 16);
940   sum =
941     calculate_checksum_update (sum, (uint16_t *) & pkt6->ip6_hdr.dadr, 16);
942   tmp = htonl(pktlen);
943   sum = calculate_checksum_update (sum, (uint16_t *) & tmp, 4);
944   tmp = htonl (((pkt6->ip6_hdr.nxthdr & 0x000000ff)));
945   sum = calculate_checksum_update (sum, (uint16_t *) & tmp, 4);
946
947   sum =
948     calculate_checksum_update (sum, (uint16_t *) & pkt6->tcp_hdr,
949                                ntohs (pkt6->ip6_hdr.paylgth));
950   pkt6->tcp_hdr.crc = calculate_checksum_end (sum);
951
952   write_to_helper(pkt6, size);
953
954   return GNUNET_OK;
955 }
956
957 /**
958  * Main function that will be run by the scheduler.
959  *
960  * @param cls closure
961  * @param args remaining command-line arguments
962  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
963  * @param cfg_ configuration
964  */
965 static void
966 run (void *cls,
967      char *const *args __attribute__((unused)),
968      const char *cfgfilep __attribute__((unused)),
969      const struct GNUNET_CONFIGURATION_Handle *cfg_)
970 {
971     static const struct GNUNET_MESH_MessageHandler handlers[] = {
972           {receive_udp_back, GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK, 0},
973           {receive_tcp_back, GNUNET_MESSAGE_TYPE_SERVICE_TCP_BACK, 0},
974           {receive_udp_back, GNUNET_MESSAGE_TYPE_REMOTE_UDP_BACK, 0},
975           {receive_tcp_back, GNUNET_MESSAGE_TYPE_REMOTE_TCP_BACK, 0},
976           {NULL, 0, 0}
977     };
978
979     static const GNUNET_MESH_ApplicationType types[] = {
980         GNUNET_APPLICATION_TYPE_END
981     };
982
983     mesh_handle = GNUNET_MESH_connect(cfg_,
984                                       NULL,
985                                       NULL,
986                                       handlers,
987                                       types);
988     cfg = cfg_;
989     restart_hijack = 0;
990     hashmap = GNUNET_CONTAINER_multihashmap_create(65536);
991     heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
992     GNUNET_CONFIGURATION_get_value_number (cfg, "vpn", "MAX_MAPPINGg",
993                                            &max_mappings);
994     udp_connections = GNUNET_CONTAINER_multihashmap_create(65536);
995     conn_task = GNUNET_SCHEDULER_add_now (connect_to_service_dns, NULL);
996     shs_task = GNUNET_SCHEDULER_add_after (conn_task, start_helper_and_schedule, NULL);
997     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls);
998 }
999
1000 /**
1001  * The main function to obtain template from gnunetd.
1002  *
1003  * @param argc number of arguments from the command line
1004  * @param argv command line arguments
1005  * @return 0 ok, 1 on error
1006  */
1007 int
1008 main (int argc, char *const *argv) {
1009     static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1010         GNUNET_GETOPT_OPTION_END
1011     };
1012
1013     return (GNUNET_OK ==
1014             GNUNET_PROGRAM_run (argc,
1015                                 argv,
1016                                 "vpn",
1017                                 gettext_noop ("help text"),
1018                                 options, &run, NULL)) ? ret : 1;
1019 }
1020
1021 /* end of gnunet-daemon-vpn.c */
1022