-sane defaults
[oweals/gnunet.git] / src / vpn / gnunet-service-vpn.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010, 2011, 2012 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-service-vpn.c
23  * @brief service that opens a virtual interface and allows its clients
24  *        to allocate IPs on the virtual interface and to then redirect
25  *        IP traffic received on those IPs via the GNUnet mesh 
26  * @author Philipp Toelke
27  * @author Christian Grothoff
28  *
29  * TODO:
30  * Basics:
31  * - test!
32  * - better message queue management (bounded state, drop oldest/RED?)
33  * - actually destroy "stale" tunnels once we have too many!
34  *
35  * Features:
36  * - add back ICMP support (especially needed for IPv6)
37  *
38  * Code cleanup:
39  * - consider moving IP-header building / checksumming code into shared library
40  *   with dns/exit/vpn (libgnunettun_tcpip?)
41  */
42 #include "platform.h"
43 #include "gnunet_util_lib.h"
44 #include "gnunet_common.h"
45 #include "gnunet_protocols.h"
46 #include "gnunet_applications.h"
47 #include "gnunet_mesh_service.h"
48 #include "gnunet_constants.h"
49 #include "tcpip_tun.h"
50 #include "vpn.h"
51 #include "exit.h"
52
53
54 /**
55  * State we keep for each of our tunnels.
56  */
57 struct TunnelState;
58
59
60 /**
61  * Information we track for each IP address to determine which tunnel
62  * to send the traffic over to the destination.
63  */
64 struct DestinationEntry
65 {
66
67   /**
68    * Key under which this entry is in the 'destination_map' (only valid
69    * if 'heap_node != NULL'.
70    */
71   GNUNET_HashCode key;
72
73   /**
74    * Pre-allocated tunnel for this destination, or NULL for none.
75    */
76   struct TunnelState *ts;
77
78   /**
79    * Entry for this entry in the destination_heap.
80    */
81   struct GNUNET_CONTAINER_HeapNode *heap_node;
82
83   /**
84    * GNUNET_NO if this is a tunnel to an Internet-exit,
85    * GNUNET_YES if this tunnel is to a service.
86    */
87   int is_service;
88
89   /**
90    * Details about the connection (depending on is_service).
91    */
92   union
93   {
94
95     struct
96     {
97       /**
98        * The description of the service (only used for service tunnels).
99        */
100       GNUNET_HashCode service_descriptor;
101
102       /**
103        * Peer offering the service.
104        */
105       struct GNUNET_PeerIdentity target;
106
107     } service_destination;
108
109     struct 
110     {
111   
112       /**
113        * Address family used (AF_INET or AF_INET6).
114        */
115       int af;
116       
117       /**
118        * IP address of the ultimate destination (only used for exit tunnels).
119        */
120       union
121       {
122         /**
123          * Address if af is AF_INET.
124          */
125         struct in_addr v4;
126         
127         /**
128          * Address if af is AF_INET6.
129          */
130         struct in6_addr v6;
131       } ip;
132
133     } exit_destination;
134
135   } details;
136     
137 };
138
139
140 /**
141  * A messages we have in queue for a particular tunnel.
142  */
143 struct TunnelMessageQueueEntry
144 {
145   /**
146    * This is a doubly-linked list.
147    */
148   struct TunnelMessageQueueEntry *next;
149
150   /**
151    * This is a doubly-linked list.
152    */
153   struct TunnelMessageQueueEntry *prev;
154   
155   /**
156    * Number of bytes in 'msg'.
157    */
158   size_t len;
159
160   /**
161    * Message to transmit, allocated at the end of this struct.
162    */
163   const void *msg;
164 };
165
166
167 /**
168  * State we keep for each of our tunnels.
169  */
170 struct TunnelState
171 {
172   /**
173    * Information about the tunnel to use, NULL if no tunnel
174    * is available right now.
175    */
176   struct GNUNET_MESH_Tunnel *tunnel;
177
178   /**
179    * Active transmission handle, NULL for none.
180    */
181   struct GNUNET_MESH_TransmitHandle *th;
182
183   /**
184    * Entry for this entry in the tunnel_heap, NULL as long as this
185    * tunnel state is not fully bound.
186    */
187   struct GNUNET_CONTAINER_HeapNode *heap_node;
188
189   /**
190    * Head of list of messages scheduled for transmission.
191    */
192   struct TunnelMessageQueueEntry *head;
193
194   /**
195    * Tail of list of messages scheduled for transmission.
196    */
197   struct TunnelMessageQueueEntry *tail;
198
199   /**
200    * Client that needs to be notified about the tunnel being
201    * up as soon as a peer is connected; NULL for none.
202    */
203   struct GNUNET_SERVER_Client *client;
204
205   /**
206    * ID of the client request that caused us to setup this entry.
207    */ 
208   uint64_t request_id;
209
210   /**
211    * Destination to which this tunnel leads.  Note that
212    * this struct is NOT in the destination_map (but a
213    * local copy) and that the 'heap_node' should always
214    * be NULL.
215    */
216   struct DestinationEntry destination;
217
218   /**
219    * Destination entry that has a pointer to this tunnel state;
220    * NULL if this tunnel state is in the tunnel map.
221    */
222   struct DestinationEntry *destination_container;
223
224   /**
225    * Addess family used for this tunnel on the local TUN interface.
226    */
227   int af;
228
229   /**
230    * IPPROTO_TCP or IPPROTO_UDP once bound.
231    */
232   uint8_t protocol;
233
234   /**
235    * IP address of the source on our end, initially uninitialized.
236    */
237   union
238   {
239     /**
240      * Address if af is AF_INET.
241      */
242     struct in_addr v4;
243     
244     /**
245      * Address if af is AF_INET6.
246      */
247     struct in6_addr v6;
248
249   } source_ip;
250
251   /**
252    * Destination IP address used by the source on our end (this is the IP
253    * that we pick freely within the VPN's tunnel IP range).
254    */
255   union
256   {
257     /**
258      * Address if af is AF_INET.
259      */
260     struct in_addr v4;
261     
262     /**
263      * Address if af is AF_INET6.
264      */
265     struct in6_addr v6;
266
267   } destination_ip;
268
269   /**
270    * Source port used by the sender on our end; 0 for uninitialized.
271    */
272   uint16_t source_port;
273
274   /**
275    * Destination port used by the sender on our end; 0 for uninitialized.
276    */
277   uint16_t destination_port;
278
279 };
280
281
282 /**
283  * Configuration we use.
284  */
285 static const struct GNUNET_CONFIGURATION_Handle *cfg;
286
287 /**
288  * Handle to the mesh service.
289  */
290 static struct GNUNET_MESH_Handle *mesh_handle;
291
292 /**
293  * Map from IP address to destination information (possibly with a
294  * MESH tunnel handle for fast setup).
295  */
296 static struct GNUNET_CONTAINER_MultiHashMap *destination_map;
297
298 /**
299  * Min-Heap sorted by activity time to expire old mappings.
300  */
301 static struct GNUNET_CONTAINER_Heap *destination_heap;
302
303 /**
304  * Map from source and destination address (IP+port) to connection
305  * information (mostly with the respective MESH tunnel handle).
306  */
307 static struct GNUNET_CONTAINER_MultiHashMap *tunnel_map;
308
309 /**
310  * Min-Heap sorted by activity time to expire old mappings; values are
311  * of type 'struct TunnelState'.
312  */
313 static struct GNUNET_CONTAINER_Heap *tunnel_heap;
314
315 /**
316  * The handle to the VPN helper process "gnunet-helper-vpn".
317  */
318 static struct GNUNET_HELPER_Handle *helper_handle;
319
320 /**
321  * Arguments to the vpn helper.
322  */
323 static char *vpn_argv[7];
324
325 /**
326  * Length of the prefix of the VPN's IPv6 network.
327  */
328 static unsigned long long ipv6prefix;
329
330 /**
331  * Notification context for sending replies to clients.
332  */
333 static struct GNUNET_SERVER_NotificationContext *nc;
334
335 /**
336  * If there are more than this number of address-mappings, old ones
337  * will be removed
338  */
339 static unsigned long long max_destination_mappings;
340
341 /**
342  * If there are more than this number of open tunnels, old ones
343  * will be removed
344  */
345 static unsigned long long max_tunnel_mappings;
346
347
348 /**
349  * Compute the key under which we would store an entry in the
350  * destination_map for the given IP address.
351  *
352  * @param af address family (AF_INET or AF_INET6)
353  * @param address IP address, struct in_addr or struct in6_addr
354  * @param key where to store the key
355  */
356 static void
357 get_destination_key_from_ip (int af,
358                              const void *address,
359                              GNUNET_HashCode *key)
360 {
361   switch (af)
362   {
363   case AF_INET:
364     GNUNET_CRYPTO_hash (address,
365                         sizeof (struct in_addr),
366                         key);
367     break;
368   case AF_INET6:
369     GNUNET_CRYPTO_hash (address,
370                         sizeof (struct in6_addr),
371                         key);
372     break;
373   default:
374     GNUNET_assert (0);
375     break;
376   }
377 }
378
379
380 /**
381  * Compute the key under which we would store an entry in the
382  * tunnel_map for the given socket address pair.
383  *
384  * @param af address family (AF_INET or AF_INET6)
385  * @param protocol IPPROTO_TCP or IPPROTO_UDP
386  * @param source_ip sender's source IP, struct in_addr or struct in6_addr
387  * @param source_port sender's source port
388  * @param destination_ip sender's destination IP, struct in_addr or struct in6_addr
389  * @param destination_port sender's destination port
390  * @param key where to store the key
391  */
392 static void
393 get_tunnel_key_from_ips (int af,
394                          uint8_t protocol,
395                          const void *source_ip,
396                          uint16_t source_port,
397                          const void *destination_ip,
398                          uint16_t destination_port,
399                          GNUNET_HashCode *key)
400 {
401   char *off;
402
403   memset (key, 0, sizeof (GNUNET_HashCode));
404   /* the GNUnet hashmap only uses the first sizeof(unsigned int) of the hash,
405      so we put the ports in there (and hope for few collisions) */
406   off = (char*) key;
407   memcpy (off, &source_port, sizeof (uint16_t));
408   off += sizeof (uint16_t);
409   memcpy (off, &destination_port, sizeof (uint16_t));
410   off += sizeof (uint16_t);
411   switch (af)
412   {
413   case AF_INET:
414     memcpy (off, source_ip, sizeof (struct in_addr));
415     off += sizeof (struct in_addr);
416     memcpy (off, destination_ip, sizeof (struct in_addr));
417     off += sizeof (struct in_addr);
418     break;
419   case AF_INET6:
420     memcpy (off, source_ip, sizeof (struct in6_addr));
421     off += sizeof (struct in6_addr);
422     memcpy (off, destination_ip, sizeof (struct in6_addr));
423     off += sizeof (struct in6_addr);
424     break;
425   default:
426     GNUNET_assert (0);
427     break;
428   }
429   memcpy (off, &protocol, sizeof (uint8_t));
430   off += sizeof (uint8_t);  
431 }
432
433
434 /**
435  * Notify the client about the result of its request.
436  *
437  * @param client client to notify
438  * @param request_id original request ID to include in response
439  * @param result_af resulting address family
440  * @param addr resulting IP address
441  */
442 static void
443 send_client_reply (struct GNUNET_SERVER_Client *client,
444                    uint64_t request_id,
445                    int result_af,
446                    const void *addr)
447 {
448   char buf[sizeof (struct RedirectToIpResponseMessage) + sizeof (struct in6_addr)];
449   struct RedirectToIpResponseMessage *res;
450   size_t rlen;
451
452   switch (result_af)
453   {
454   case AF_INET:
455     rlen = sizeof (struct in_addr);    
456     break;
457   case AF_INET6:
458     rlen = sizeof (struct in6_addr);
459     break;
460   case AF_UNSPEC:
461     rlen = 0;
462     break;
463   default:
464     GNUNET_assert (0);
465     return;
466   }
467   res = (struct RedirectToIpResponseMessage *) buf;
468   res->header.size = htons (sizeof (struct RedirectToIpResponseMessage) + rlen);
469   res->header.type = htons (GNUNET_MESSAGE_TYPE_VPN_CLIENT_USE_IP);
470   res->result_af = htonl (result_af);
471   res->request_id = request_id;
472   memcpy (&res[1], addr, rlen);
473   GNUNET_SERVER_notification_context_add (nc, client);
474   GNUNET_SERVER_notification_context_unicast (nc,
475                                               client,
476                                               &res->header,
477                                               GNUNET_NO);
478 }
479
480
481 /**
482  * Method called whenever a peer has disconnected from the tunnel.
483  *
484  * @param cls closure
485  * @param peer peer identity the tunnel stopped working with
486  */
487 static void
488 tunnel_peer_disconnect_handler (void *cls,
489                                 const struct
490                                 GNUNET_PeerIdentity * peer)
491 {
492   struct TunnelState *ts = cls;
493   
494   if (NULL != ts->th)
495   {
496     GNUNET_MESH_notify_transmit_ready_cancel (ts->th);
497     ts->th = NULL;
498   }
499   if (ts->destination.is_service)
500     return; /* hope for reconnect eventually */
501   /* as we are most likely going to change the exit node now,
502      we should just destroy the tunnel entirely... */
503   GNUNET_MESH_tunnel_destroy (ts->tunnel);
504 }
505
506
507 /**
508  * Method called whenever a peer has connected to the tunnel.  Notifies
509  * the waiting client that the tunnel is now up.
510  *
511  * @param cls closure
512  * @param peer peer identity the tunnel was created to, NULL on timeout
513  * @param atsi performance data for the connection
514  */
515 static void
516 tunnel_peer_connect_handler (void *cls,
517                              const struct GNUNET_PeerIdentity
518                              * peer,
519                              const struct
520                              GNUNET_ATS_Information * atsi)
521 {
522   struct TunnelState *ts = cls;
523
524   if (NULL == ts->client)
525     return; /* nothing to do */
526   send_client_reply (ts->client,
527                      ts->request_id,
528                      ts->af,
529                      &ts->destination_ip);
530   GNUNET_SERVER_client_drop (ts->client);
531   ts->client = NULL;
532 }
533
534
535 /**
536  * Send a message from the message queue via mesh.
537  *
538  * @param cls the 'struct TunnelState' with the message queue
539  * @param size number of bytes available in buf
540  * @param buf where to copy the message
541  * @return number of bytes copied to buf
542  */
543 static size_t
544 send_to_peer_notify_callback (void *cls, size_t size, void *buf)
545 {
546   struct TunnelState *ts = cls;
547   struct TunnelMessageQueueEntry *tnq;
548   size_t ret;
549
550   ts->th = NULL;
551   if (NULL == buf)
552     return 0;
553   tnq = ts->head;
554   GNUNET_assert (NULL != tnq);
555   GNUNET_assert (size >= tnq->len);
556   GNUNET_CONTAINER_DLL_remove (ts->head,
557                                ts->tail,
558                                tnq);
559   memcpy (buf, tnq->msg, tnq->len);
560   ret = tnq->len;
561   GNUNET_free (tnq);
562   if (NULL != (tnq = ts->head))
563     ts->th = GNUNET_MESH_notify_transmit_ready (ts->tunnel, 
564                                                 GNUNET_NO /* cork */, 
565                                                 42 /* priority */,
566                                                 GNUNET_TIME_UNIT_FOREVER_REL,
567                                                 NULL, 
568                                                 tnq->len,
569                                                 &send_to_peer_notify_callback,
570                                                 ts);
571   return ret;
572 }
573
574
575 /**
576  * Add the given message to the given tunnel and trigger the
577  * transmission process.
578  *
579  * FIXME: bound queue length!
580  *
581  * @param tnq message to queue
582  * @param ts tunnel to queue the message for
583  */
584 static void
585 send_to_tunnel (struct TunnelMessageQueueEntry *tnq,
586                 struct TunnelState *ts)
587 {
588   GNUNET_CONTAINER_DLL_insert_tail (ts->head,
589                                     ts->tail,
590                                     tnq);
591   if (NULL == ts->th)
592     ts->th = GNUNET_MESH_notify_transmit_ready (ts->tunnel, 
593                                                 GNUNET_NO /* cork */,
594                                                 42 /* priority */,
595                                                 GNUNET_TIME_UNIT_FOREVER_REL,
596                                                 NULL, 
597                                                 tnq->len,
598                                                 &send_to_peer_notify_callback,
599                                                 ts);
600 }
601
602
603 /**
604  * Initialize the given destination entry's mesh tunnel.
605  *
606  * @param de destination entry for which we need to setup a tunnel
607  * @param client client to notify on successful tunnel setup, or NULL for none
608  * @param request_id request ID to send in client notification (unused if client is NULL)
609  * @return tunnel state of the tunnel that was created
610  */
611 static struct TunnelState *
612 create_tunnel_to_destination (struct DestinationEntry *de,
613                               struct GNUNET_SERVER_Client *client,
614                               uint64_t request_id)
615 {
616   struct TunnelState *ts;
617
618   GNUNET_assert (NULL == de->ts);
619   ts = GNUNET_malloc (sizeof (struct TunnelState));
620   if (NULL != client)
621   {
622     ts->request_id = request_id;
623     ts->client = client;
624     GNUNET_SERVER_client_keep (client);
625   }
626   ts->destination = *de;
627   ts->destination.heap_node = NULL; /* copy is NOT in destination heap */
628   de->ts = ts;
629   ts->destination_container = de; /* we are referenced from de */
630   ts->af = AF_UNSPEC; /* so far, unknown */
631   ts->tunnel = GNUNET_MESH_tunnel_create (mesh_handle,
632                                           ts,
633                                           &tunnel_peer_connect_handler,
634                                           &tunnel_peer_disconnect_handler,
635                                           ts);
636   if (de->is_service)
637   {
638     GNUNET_MESH_peer_request_connect_add (ts->tunnel,
639                                           &de->details.service_destination.target);  
640   }
641   else
642   {
643     switch (de->details.exit_destination.af)
644     {
645     case AF_INET:
646       GNUNET_MESH_peer_request_connect_by_type (ts->tunnel,
647                                                 GNUNET_APPLICATION_TYPE_IPV4_GATEWAY);
648      break;
649     case AF_INET6:
650       GNUNET_MESH_peer_request_connect_by_type (ts->tunnel,
651                                                 GNUNET_APPLICATION_TYPE_IPV6_GATEWAY);
652       break;
653     default:
654       GNUNET_assert (0);
655       break;
656     }
657   }  
658   return ts;
659 }
660
661
662 /**
663  * Route a packet via mesh to the given destination.  
664  *
665  * @param destination description of the destination
666  * @param af address family on this end (AF_INET or AF_INET6)
667  * @param protocol IPPROTO_TCP or IPPROTO_UDP
668  * @param source_ip source IP used by the sender (struct in_addr or struct in6_addr)
669  * @param destination_ip destination IP used by the sender (struct in_addr or struct in6_addr)
670  * @param payload payload of the packet after the IP header
671  * @param payload_length number of bytes in payload
672  */
673 static void
674 route_packet (struct DestinationEntry *destination,
675               int af,
676               uint8_t protocol,
677               const void *source_ip,
678               const void *destination_ip,
679               const void *payload,
680               size_t payload_length)
681 {
682   GNUNET_HashCode key;
683   struct TunnelState *ts;
684   struct TunnelMessageQueueEntry *tnq;
685   size_t alen;
686   size_t mlen;
687   GNUNET_MESH_ApplicationType app_type;
688   int is_new;
689   const struct udp_packet *udp;
690   const struct tcp_packet *tcp;
691   uint16_t spt;
692   uint16_t dpt;
693
694   switch (protocol)
695   {
696   case IPPROTO_UDP:
697     {
698       if (payload_length < sizeof (struct udp_packet))
699       {
700         /* blame kernel? */
701         GNUNET_break (0);
702         return;
703       }
704       udp = payload;
705       spt = ntohs (udp->spt);
706       dpt = ntohs (udp->dpt);
707       get_tunnel_key_from_ips (af,
708                                IPPROTO_UDP,
709                                source_ip,
710                                spt,
711                                destination_ip,
712                                dpt,
713                                &key);
714     }
715     break;
716   case IPPROTO_TCP:
717     {
718       if (payload_length < sizeof (struct tcp_packet))
719       {
720         /* blame kernel? */
721         GNUNET_break (0);
722         return;
723       }
724       tcp = payload;
725       spt = ntohs (tcp->spt);
726       dpt = ntohs (tcp->dpt);
727       get_tunnel_key_from_ips (af,
728                                IPPROTO_TCP,
729                                source_ip,
730                                spt,
731                                destination_ip,
732                                dpt,
733                                &key);
734     }
735     break;
736   default:
737     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
738                 _("Protocol %u not supported, dropping\n"),
739                 (unsigned int) protocol);
740     return;
741   }
742
743   if (! destination->is_service)
744   {  
745     switch (destination->details.exit_destination.af)
746     {
747     case AF_INET:
748       alen = sizeof (struct in_addr);
749       app_type = GNUNET_APPLICATION_TYPE_IPV4_GATEWAY; 
750      break;
751     case AF_INET6:
752       alen = sizeof (struct in6_addr);
753       app_type = GNUNET_APPLICATION_TYPE_IPV6_GATEWAY; 
754       break;
755     default:
756       alen = 0;
757       GNUNET_assert (0);
758     }
759   }
760   else
761   {
762     /* make compiler happy */
763     alen = 0;
764     app_type = 0;
765   }
766
767   /* see if we have an existing tunnel for this destination */
768   ts = GNUNET_CONTAINER_multihashmap_get (tunnel_map,
769                                           &key);
770   if (NULL == ts)
771   {
772     /* need to either use the existing tunnel from the destination (if still
773        available) or create a fresh one */
774     is_new = GNUNET_YES;
775     if (NULL == destination->ts)
776       ts = create_tunnel_to_destination (destination, NULL, 0);
777     else
778       ts = destination->ts;
779     destination->ts = NULL;
780     ts->destination_container = NULL; /* no longer 'contained' */
781     /* now bind existing "unbound" tunnel to our IP/port tuple */
782     ts->protocol = protocol;
783     ts->af = af; 
784     if (af == AF_INET)
785     {
786       ts->source_ip.v4 = * (const struct in_addr *) source_ip;
787       ts->destination_ip.v4 = * (const struct in_addr *) destination_ip;
788     }
789     else
790     {
791       ts->source_ip.v6 = * (const struct in6_addr *) source_ip;
792       ts->destination_ip.v6 = * (const struct in6_addr *) destination_ip;
793     }
794     ts->source_port = spt;
795     ts->destination_port = dpt;
796     ts->heap_node = GNUNET_CONTAINER_heap_insert (tunnel_heap,
797                                                   ts,
798                                                   GNUNET_TIME_absolute_get ().abs_value);
799     GNUNET_assert (GNUNET_YES ==
800                    GNUNET_CONTAINER_multihashmap_put (tunnel_map,
801                                                       &key,
802                                                       ts,
803                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); 
804     /* FIXME: expire OLD tunnels if we have too many! */
805   }
806   else
807   {
808     is_new = GNUNET_NO;
809     GNUNET_CONTAINER_heap_update_cost (tunnel_heap, 
810                                        ts->heap_node,
811                                        GNUNET_TIME_absolute_get ().abs_value);
812   }
813   
814   /* send via tunnel */
815   switch (protocol)
816   {
817   case IPPROTO_UDP:
818     if (destination->is_service)
819     {
820       struct GNUNET_EXIT_UdpServiceMessage *usm;
821
822       mlen = sizeof (struct GNUNET_EXIT_UdpServiceMessage) + 
823         payload_length - sizeof (struct udp_packet);
824       if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
825       {
826         GNUNET_break (0);
827         return;
828       }
829       tnq = GNUNET_malloc (sizeof (struct TunnelMessageQueueEntry) + mlen);
830       usm = (struct GNUNET_EXIT_UdpServiceMessage *) &tnq[1];
831       usm->header.size = htons ((uint16_t) mlen);
832       usm->header.type = htons (GNUNET_MESSAGE_TYPE_VPN_UDP_TO_SERVICE);
833       /* if the source port is below 32000, we assume it has a special
834          meaning; if not, we pick a random port (this is a heuristic) */
835       usm->source_port = (ntohs (udp->spt) < 32000) ? udp->spt : 0;
836       usm->destination_port = udp->dpt;
837       usm->service_descriptor = destination->details.service_destination.service_descriptor;
838       memcpy (&usm[1],
839               &udp[1],
840               payload_length - sizeof (struct udp_packet));
841     }
842     else
843     {
844       struct GNUNET_EXIT_UdpInternetMessage *uim;
845       struct in_addr *ip4dst;
846       struct in6_addr *ip6dst;
847       void *payload;
848
849       mlen = sizeof (struct GNUNET_EXIT_UdpInternetMessage) + 
850         alen + payload_length - sizeof (struct udp_packet);
851       if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
852       {
853         GNUNET_break (0);
854         return;
855       }
856       tnq = GNUNET_malloc (sizeof (struct TunnelMessageQueueEntry) + 
857                            mlen);
858       uim = (struct GNUNET_EXIT_UdpInternetMessage *) &tnq[1];
859       uim->header.size = htons ((uint16_t) mlen);
860       uim->header.type = htons (GNUNET_MESSAGE_TYPE_VPN_UDP_TO_INTERNET); 
861       uim->af = htonl (destination->details.exit_destination.af);
862       uim->source_port = (ntohs (udp->spt) < 32000) ? udp->spt : 0;
863       uim->destination_port = udp->dpt;
864       switch (destination->details.exit_destination.af)
865       {
866       case AF_INET:
867         ip4dst = (struct in_addr *) &uim[1];
868         *ip4dst = destination->details.exit_destination.ip.v4;
869         payload = &ip4dst[1];
870         break;
871       case AF_INET6:
872         ip6dst = (struct in6_addr *) &uim[1];
873         *ip6dst = destination->details.exit_destination.ip.v6;
874         payload = &ip6dst[1];
875         break;
876       default:
877         GNUNET_assert (0);
878       }
879       memcpy (payload,
880               &udp[1],
881               payload_length - sizeof (struct udp_packet));
882     }
883     break;
884   case IPPROTO_TCP:
885     if (is_new)
886     {
887       if (destination->is_service)
888       {
889         struct GNUNET_EXIT_TcpServiceStartMessage *tsm;
890
891         mlen = sizeof (struct GNUNET_EXIT_TcpServiceStartMessage) + 
892           payload_length - sizeof (struct tcp_packet);
893         if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
894         {
895           GNUNET_break (0);
896           return;
897         }
898         tnq = GNUNET_malloc (sizeof (struct TunnelMessageQueueEntry) + mlen);
899         tsm = (struct  GNUNET_EXIT_TcpServiceStartMessage *) &tnq[1];
900         tsm->header.size = htons ((uint16_t) mlen);
901         tsm->header.type = htons (GNUNET_MESSAGE_TYPE_VPN_TCP_TO_SERVICE_START);
902         tsm->reserved = htonl (0);
903         tsm->service_descriptor = destination->details.service_destination.service_descriptor;
904         tsm->tcp_header = *tcp;
905         memcpy (&tsm[1],
906                 &tcp[1],
907                 payload_length - sizeof (struct tcp_packet));
908       }
909       else
910       {
911         struct GNUNET_EXIT_TcpInternetStartMessage *tim;
912         struct in_addr *ip4dst;
913         struct in6_addr *ip6dst;
914         void *payload;
915
916         mlen = sizeof (struct GNUNET_EXIT_TcpInternetStartMessage) + 
917           alen + payload_length - sizeof (struct tcp_packet);
918         if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
919         {
920           GNUNET_break (0);
921           return;
922         }
923         tnq = GNUNET_malloc (sizeof (struct TunnelMessageQueueEntry) + mlen);
924         tim = (struct  GNUNET_EXIT_TcpInternetStartMessage *) &tnq[1];
925         tim->header.size = htons ((uint16_t) mlen);
926         tim->header.type = htons (GNUNET_MESSAGE_TYPE_VPN_TCP_TO_INTERNET_START);
927         tim->af = htonl (destination->details.exit_destination.af);     
928         tim->tcp_header = *tcp;
929         switch (destination->details.exit_destination.af)
930         {
931         case AF_INET:
932           ip4dst = (struct in_addr *) &tim[1];
933           *ip4dst = destination->details.exit_destination.ip.v4;
934           payload = &ip4dst[1];
935           break;
936         case AF_INET6:
937           ip6dst = (struct in6_addr *) &tim[1];
938           *ip6dst = destination->details.exit_destination.ip.v6;
939           payload = &ip6dst[1];
940           break;
941         default:
942           GNUNET_assert (0);
943         }
944         memcpy (payload,
945                 &tcp[1],
946                 payload_length - sizeof (struct tcp_packet));
947       }
948     }
949     else
950     {
951       struct GNUNET_EXIT_TcpDataMessage *tdm;
952
953       mlen = sizeof (struct GNUNET_EXIT_TcpDataMessage) + 
954         alen + payload_length - sizeof (struct tcp_packet);
955       if (mlen >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
956       {
957         GNUNET_break (0);
958         return;
959       }
960       tnq = GNUNET_malloc (sizeof (struct TunnelMessageQueueEntry) + mlen);
961       tdm = (struct  GNUNET_EXIT_TcpDataMessage *) &tnq[1];
962       tdm->header.size = htons ((uint16_t) mlen);
963       tdm->header.type = htons (GNUNET_MESSAGE_TYPE_VPN_TCP_DATA);
964       tdm->reserved = htonl (0);
965       tdm->tcp_header = *tcp;
966       memcpy (&tdm[1],
967               &tcp[1],
968               payload_length - sizeof (struct tcp_packet));
969      }
970     break;
971   default:
972     /* not supported above, how can we get here !? */
973     GNUNET_assert (0);
974     break;
975   }
976   send_to_tunnel (tnq, ts);
977 }
978
979
980 /**
981  * Receive packets from the helper-process (someone send to the local
982  * virtual tunnel interface).  Find the destination mapping, and if it
983  * exists, identify the correct MESH tunnel (or possibly create it)
984  * and forward the packet.
985  *
986  * @param cls closure, NULL
987  * @param client NULL
988  * @param message message we got from the client (VPN tunnel interface)
989  */
990 static void
991 message_token (void *cls GNUNET_UNUSED, void *client GNUNET_UNUSED,
992                const struct GNUNET_MessageHeader *message)
993 {
994   const struct tun_header *tun;
995   size_t mlen;
996   GNUNET_HashCode key;
997   struct DestinationEntry *de;
998
999   mlen = ntohs (message->size);
1000   if ( (ntohs (message->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1001        (mlen < sizeof (struct GNUNET_MessageHeader) + sizeof (struct tun_header)) )
1002   {
1003     GNUNET_break (0);
1004     return;
1005   }
1006   tun = (const struct tun_header *) &message[1];
1007   mlen -= (sizeof (struct GNUNET_MessageHeader) + sizeof (struct tun_header));
1008   switch (ntohs (tun->proto))
1009   {
1010   case ETH_P_IPV6:
1011     {
1012       const struct ip6_header *pkt6;
1013       
1014       if (mlen < sizeof (struct ip6_header))
1015       {
1016         /* blame kernel */
1017         GNUNET_break (0);
1018         return;
1019       }
1020       pkt6 = (const struct ip6_header *) &tun[1];
1021       get_destination_key_from_ip (AF_INET6,
1022                                    &pkt6->destination_address,
1023                                    &key);
1024       de = GNUNET_CONTAINER_multihashmap_get (destination_map, &key);
1025       /* FIXME: do we need to guard against hash collision? 
1026          (if so, we need to also store the local destination IP in the
1027          destination entry and then compare here; however, the risk
1028          of collision seems minimal AND the impact is unlikely to be
1029          super-problematic as well... */
1030       if (NULL == de)
1031       {
1032         char buf[INET6_ADDRSTRLEN];
1033         
1034         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1035                     _("Packet received for unmapped destination `%s' (dropping it)\n"),
1036                     inet_ntop (AF_INET6,
1037                                &pkt6->destination_address,
1038                                buf,
1039                                sizeof (buf)));
1040         return;
1041       }
1042       route_packet (de,
1043                     AF_INET6,
1044                     pkt6->next_header,
1045                     &pkt6->source_address,                  
1046                     &pkt6->destination_address,             
1047                     &pkt6[1],
1048                     mlen - sizeof (struct ip6_header));
1049     }
1050     break;
1051   case ETH_P_IPV4:
1052     {
1053       struct ip4_header *pkt4;
1054
1055       if (mlen < sizeof (struct ip4_header))
1056       {
1057         /* blame kernel */
1058         GNUNET_break (0);
1059         return;
1060       }
1061       pkt4 = (struct ip4_header *) &tun[1];
1062       get_destination_key_from_ip (AF_INET,
1063                                    &pkt4->destination_address,
1064                                    &key);
1065       de = GNUNET_CONTAINER_multihashmap_get (destination_map, &key);
1066       /* FIXME: do we need to guard against hash collision? 
1067          (if so, we need to also store the local destination IP in the
1068          destination entry and then compare here; however, the risk
1069          of collision seems minimal AND the impact is unlikely to be
1070          super-problematic as well... */
1071       if (NULL == de)
1072       {
1073         char buf[INET_ADDRSTRLEN];
1074         
1075         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1076                     _("Packet received for unmapped destination `%s' (dropping it)\n"),
1077                     inet_ntop (AF_INET,
1078                                &pkt4->destination_address,
1079                                buf,
1080                                sizeof (buf)));
1081         return;
1082       }
1083       if (pkt4->header_length * 4 != sizeof (struct ip4_header))
1084       {
1085         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1086                     _("Received IPv4 packet with options (dropping it)\n"));                
1087         return;
1088       }
1089       route_packet (de,
1090                     AF_INET,
1091                     pkt4->protocol,
1092                     &pkt4->source_address,                  
1093                     &pkt4->destination_address,             
1094                     &pkt4[1],
1095                     mlen - sizeof (struct ip4_header));
1096     }
1097     break;
1098   default:
1099     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1100                 _("Received packet of unknown protocol %d from TUN (dropping it)\n"),
1101                 (unsigned int) ntohs (tun->proto));
1102     break;
1103   }
1104 }
1105
1106
1107 /**
1108  * We got a UDP packet back from the MESH tunnel.  Pass it on to the
1109  * local virtual interface via the helper.
1110  *
1111  * @param cls closure, NULL
1112  * @param tunnel connection to the other end
1113  * @param tunnel_ctx pointer to our 'struct TunnelState *'
1114  * @param sender who sent the message
1115  * @param message the actual message
1116  * @param atsi performance data for the connection
1117  * @return GNUNET_OK to keep the connection open,
1118  *         GNUNET_SYSERR to close it (signal serious error)
1119  */ 
1120 static int
1121 receive_udp_back (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
1122                   void **tunnel_ctx, const struct GNUNET_PeerIdentity *sender,
1123                   const struct GNUNET_MessageHeader *message,
1124                   const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
1125 {
1126   struct TunnelState *ts = *tunnel_ctx;
1127   const struct GNUNET_EXIT_UdpReplyMessage *reply;
1128   size_t mlen;
1129
1130   mlen = ntohs (message->size);
1131   if (mlen < sizeof (struct GNUNET_EXIT_UdpReplyMessage))
1132   {
1133     GNUNET_break_op (0);
1134     return GNUNET_SYSERR;
1135   }
1136   if (NULL == ts->heap_node)
1137   {
1138     GNUNET_break_op (0);
1139     return GNUNET_SYSERR;
1140   }
1141   if (AF_UNSPEC == ts->af)
1142   {
1143     GNUNET_break_op (0);
1144     return GNUNET_SYSERR;
1145   }
1146   reply = (const struct GNUNET_EXIT_UdpReplyMessage *) message;
1147   mlen -= sizeof (struct GNUNET_EXIT_UdpReplyMessage);
1148   switch (ts->af)
1149   {
1150   case AF_INET:
1151     {
1152       size_t size = sizeof (struct ip4_header) 
1153         + sizeof (struct udp_packet) 
1154         + sizeof (struct GNUNET_MessageHeader) +
1155         sizeof (struct tun_header) +
1156         mlen;
1157       {
1158         char buf[size];
1159         struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) buf;
1160         struct tun_header *tun = (struct tun_header*) &msg[1];
1161         struct ip4_header *ipv4 = (struct ip4_header *) &tun[1];
1162         struct udp_packet *udp = (struct udp_packet *) &ipv4[1];
1163         msg->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1164         msg->size = htons (size);
1165         tun->flags = htons (0);
1166         tun->proto = htons (ETH_P_IPV4);
1167         ipv4->version = 4;
1168         ipv4->header_length = sizeof (struct ip4_header) / 4;
1169         ipv4->diff_serv = 0;
1170         ipv4->total_length = htons (sizeof (struct ip4_header) +
1171                                     sizeof (struct udp_packet) +
1172                                     mlen);
1173         ipv4->identification = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 
1174                                                                     UINT16_MAX + 1);
1175         ipv4->flags = 0;
1176         ipv4->fragmentation_offset = 0;
1177         ipv4->ttl = 255;
1178         ipv4->protocol = IPPROTO_UDP;
1179         ipv4->checksum = 0; 
1180         ipv4->source_address = ts->destination_ip.v4;
1181         ipv4->destination_address = ts->source_ip.v4;
1182         ipv4->checksum =
1183           GNUNET_CRYPTO_crc16_n (ipv4, sizeof (struct ip4_header));
1184         if (0 == ntohs (reply->source_port))
1185           udp->spt = htons (ts->destination_port);
1186         else
1187           udp->spt = reply->source_port;
1188         if (0 == ntohs (reply->destination_port))
1189           udp->dpt = htons (ts->source_port);
1190         else
1191           udp->dpt = reply->destination_port;
1192         udp->len = htons (mlen + sizeof (struct udp_packet));
1193         udp->crc = 0; // FIXME: optional, but we might want to calculate this one anyway
1194         memcpy (&udp[1],
1195                 &reply[1],
1196                 mlen);
1197         (void) GNUNET_HELPER_send (helper_handle,
1198                                    msg,
1199                                    GNUNET_YES,
1200                                    NULL, NULL);
1201       }
1202     }
1203     break;
1204   case AF_INET6:
1205     {
1206       size_t size = sizeof (struct ip6_header) 
1207         + sizeof (struct udp_packet) 
1208         + sizeof (struct GNUNET_MessageHeader) +
1209         sizeof (struct tun_header) +
1210         mlen;
1211       {
1212         char buf[size];
1213         struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) buf;
1214         struct tun_header *tun = (struct tun_header*) &msg[1];
1215         struct ip6_header *ipv6 = (struct ip6_header *) &tun[1];
1216         struct udp_packet *udp = (struct udp_packet *) &ipv6[1];
1217         msg->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1218         msg->size = htons (size);
1219         tun->flags = htons (0);
1220         tun->proto = htons (ETH_P_IPV6);
1221         ipv6->traffic_class_h = 0;
1222         ipv6->version = 6;
1223         ipv6->traffic_class_l = 0;
1224         ipv6->flow_label = 0;
1225         ipv6->payload_length = htons (sizeof (struct udp_packet) + sizeof (struct ip6_header) + mlen);
1226         ipv6->next_header = IPPROTO_UDP;
1227         ipv6->hop_limit = 255;
1228         ipv6->source_address = ts->destination_ip.v6;
1229         ipv6->destination_address = ts->source_ip.v6;
1230         if (0 == ntohs (reply->source_port))
1231           udp->spt = htons (ts->destination_port);
1232         else
1233           udp->spt = reply->source_port;
1234         if (0 == ntohs (reply->destination_port))
1235           udp->dpt = htons (ts->source_port);
1236         else
1237           udp->dpt = reply->destination_port;
1238         udp->len = htons (mlen + sizeof (struct udp_packet));
1239         udp->crc = 0;
1240         memcpy (&udp[1],
1241                 &reply[1],
1242                 mlen);
1243         {
1244           uint32_t sum = 0;
1245           sum =
1246             GNUNET_CRYPTO_crc16_step (sum, &ipv6->source_address, 
1247                                       sizeof (struct in6_addr) * 2);
1248           uint32_t tmp = udp->len;
1249           sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint32_t));
1250           tmp = htons (IPPROTO_UDP);
1251           sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint32_t));
1252           sum = GNUNET_CRYPTO_crc16_step (sum, 
1253                                           udp,
1254                                           ntohs (udp->len));
1255           udp->crc = GNUNET_CRYPTO_crc16_finish (sum);
1256         }
1257         (void) GNUNET_HELPER_send (helper_handle,
1258                                    msg,
1259                                    GNUNET_YES,
1260                                    NULL, NULL);
1261       }
1262     }
1263     break;
1264   default:
1265     GNUNET_assert (0);
1266   }
1267   GNUNET_CONTAINER_heap_update_cost (tunnel_heap, 
1268                                      ts->heap_node,
1269                                      GNUNET_TIME_absolute_get ().abs_value);
1270   return GNUNET_OK;
1271 }
1272
1273
1274 /**
1275  * We got a TCP packet back from the MESH tunnel.  Pass it on to the
1276  * local virtual interface via the helper.
1277  *
1278  * @param cls closure, NULL
1279  * @param tunnel connection to the other end
1280  * @param tunnel_ctx pointer to our 'struct TunnelState *'
1281  * @param sender who sent the message
1282  * @param message the actual message
1283  * @param atsi performance data for the connection
1284  * @return GNUNET_OK to keep the connection open,
1285  *         GNUNET_SYSERR to close it (signal serious error)
1286  */ 
1287 static int
1288 receive_tcp_back (void *cls GNUNET_UNUSED, struct GNUNET_MESH_Tunnel *tunnel,
1289                   void **tunnel_ctx,
1290                   const struct GNUNET_PeerIdentity *sender GNUNET_UNUSED,
1291                   const struct GNUNET_MessageHeader *message,
1292                   const struct GNUNET_ATS_Information *atsi GNUNET_UNUSED)
1293 {
1294   struct TunnelState *ts = *tunnel_ctx;
1295   const struct GNUNET_EXIT_TcpDataMessage *data;
1296   size_t mlen;
1297
1298   mlen = ntohs (message->size);
1299   if (mlen < sizeof (struct GNUNET_EXIT_TcpDataMessage))
1300   {
1301     GNUNET_break_op (0);
1302     return GNUNET_SYSERR;
1303   }
1304   if (NULL == ts->heap_node)
1305   {
1306     GNUNET_break_op (0);
1307     return GNUNET_SYSERR;
1308   }
1309   data = (const struct GNUNET_EXIT_TcpDataMessage *) message;
1310   mlen -= sizeof (struct GNUNET_EXIT_TcpDataMessage);
1311   switch (ts->af)
1312   {
1313   case AF_INET:
1314     {
1315       size_t size = sizeof (struct ip4_header) 
1316         + sizeof (struct tcp_packet) 
1317         + sizeof (struct GNUNET_MessageHeader) +
1318         sizeof (struct tun_header) +
1319         mlen;
1320       {
1321         char buf[size];
1322         struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) buf;
1323         struct tun_header *tun = (struct tun_header*) &msg[1];
1324         struct ip4_header *ipv4 = (struct ip4_header *) &tun[1];
1325         struct tcp_packet *tcp = (struct tcp_packet *) &ipv4[1];
1326         msg->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1327         msg->size = htons (size);
1328         tun->flags = htons (0);
1329         tun->proto = htons (ETH_P_IPV4);
1330         ipv4->version = 4;
1331         ipv4->header_length = sizeof (struct ip4_header) / 4;
1332         ipv4->diff_serv = 0;
1333         ipv4->total_length = htons (sizeof (struct ip4_header) +
1334                                     sizeof (struct tcp_packet) +
1335                                     mlen);
1336         ipv4->identification = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 
1337                                                                     UINT16_MAX + 1);
1338         ipv4->flags = 0;
1339         ipv4->fragmentation_offset = 0;
1340         ipv4->ttl = 255;
1341         ipv4->protocol = IPPROTO_TCP;
1342         ipv4->checksum = 0; 
1343         ipv4->source_address = ts->destination_ip.v4;
1344         ipv4->destination_address = ts->source_ip.v4;
1345         ipv4->checksum =
1346           GNUNET_CRYPTO_crc16_n (ipv4, sizeof (struct ip4_header));
1347         *tcp = data->tcp_header;
1348         tcp->spt = htons (ts->destination_port);
1349         tcp->dpt = htons (ts->source_port);
1350         tcp->crc = 0;
1351         memcpy (&tcp[1],
1352                 &data[1],
1353                 mlen);
1354         {
1355           uint32_t sum = 0;
1356           uint32_t tmp;
1357           
1358           sum = GNUNET_CRYPTO_crc16_step (sum, 
1359                                           &ipv4->source_address,
1360                                           2 * sizeof (struct in_addr));   
1361           tmp = htonl ((IPPROTO_TCP << 16) | (mlen + sizeof (struct tcp_packet)));
1362           sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint32_t));
1363           sum = GNUNET_CRYPTO_crc16_step (sum, tcp, mlen + sizeof (struct tcp_packet));
1364           tcp->crc = GNUNET_CRYPTO_crc16_finish (sum);
1365         }
1366         (void) GNUNET_HELPER_send (helper_handle,
1367                                    msg,
1368                                    GNUNET_YES,
1369                                    NULL, NULL);
1370       }
1371     }
1372     break;
1373   case AF_INET6:
1374     {
1375       size_t size = sizeof (struct ip6_header) 
1376         + sizeof (struct tcp_packet) 
1377         + sizeof (struct GNUNET_MessageHeader) +
1378         sizeof (struct tun_header) +
1379         mlen;
1380       {
1381         char buf[size];
1382         struct GNUNET_MessageHeader *msg = (struct GNUNET_MessageHeader *) buf;
1383         struct tun_header *tun = (struct tun_header*) &msg[1];
1384         struct ip6_header *ipv6 = (struct ip6_header *) &tun[1];
1385         struct tcp_packet *tcp = (struct tcp_packet *) &ipv6[1];
1386         msg->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1387         msg->size = htons (size);
1388         tun->flags = htons (0);
1389         tun->proto = htons (ETH_P_IPV6);
1390         ipv6->traffic_class_h = 0;
1391         ipv6->version = 6;
1392         ipv6->traffic_class_l = 0;
1393         ipv6->flow_label = 0;
1394         ipv6->payload_length = htons (sizeof (struct tcp_packet) + sizeof (struct ip6_header) + mlen);
1395         ipv6->next_header = IPPROTO_TCP;
1396         ipv6->hop_limit = 255;
1397         ipv6->source_address = ts->destination_ip.v6;
1398         ipv6->destination_address = ts->source_ip.v6;
1399         tcp->spt = htons (ts->destination_port);
1400         tcp->dpt = htons (ts->source_port);
1401         tcp->crc = 0;
1402         {
1403           uint32_t sum = 0;
1404           uint32_t tmp;
1405
1406           sum = GNUNET_CRYPTO_crc16_step (sum, &ipv6->source_address, 2 * sizeof (struct in6_addr));
1407           tmp = htonl (sizeof (struct tcp_packet) + mlen);
1408           sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint32_t));
1409           tmp = htonl (IPPROTO_TCP);
1410           sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint32_t));
1411           sum = GNUNET_CRYPTO_crc16_step (sum, tcp,
1412                                           sizeof (struct tcp_packet) + mlen);
1413           tcp->crc = GNUNET_CRYPTO_crc16_finish (sum);
1414         }
1415         (void) GNUNET_HELPER_send (helper_handle,
1416                                    msg,
1417                                    GNUNET_YES,
1418                                    NULL, NULL);
1419       }
1420     }
1421     break;
1422   }
1423   GNUNET_CONTAINER_heap_update_cost (tunnel_heap, 
1424                                      ts->heap_node,
1425                                      GNUNET_TIME_absolute_get ().abs_value);
1426   return GNUNET_OK;
1427 }
1428
1429
1430 /**
1431  * Allocate an IPv4 address from the range of the tunnel
1432  * for a new redirection.
1433  *
1434  * @param v4 where to store the address
1435  * @return GNUNET_OK on success,
1436  *         GNUNET_SYSERR on error
1437  */
1438 static int
1439 allocate_v4_address (struct in_addr *v4)
1440 {
1441   const char *ipv4addr = vpn_argv[4];
1442   const char *ipv4mask = vpn_argv[5];
1443   struct in_addr addr;
1444   struct in_addr mask;
1445   struct in_addr rnd;
1446   GNUNET_HashCode key;
1447   unsigned int tries;
1448
1449   GNUNET_assert (1 == inet_pton (AF_INET, ipv4addr, &addr));
1450   GNUNET_assert (1 == inet_pton (AF_INET, ipv4mask, &mask));           
1451   /* Given 192.168.0.1/255.255.0.0, we want a mask 
1452      of '192.168.255.255', thus:  */
1453   mask.s_addr = addr.s_addr | ~mask.s_addr;  
1454   tries = 0;
1455   do
1456     {
1457       tries++;
1458       if (tries > 16)
1459       {
1460         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1461                     _("Failed to find unallocated IPv4 address in VPN's range\n"));
1462         return GNUNET_SYSERR;
1463       }
1464       /* Pick random IPv4 address within the subnet, except 'addr' or 'mask' itself */
1465       rnd.s_addr = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 
1466                                              UINT32_MAX);       
1467       v4->s_addr = (addr.s_addr | rnd.s_addr) & mask.s_addr;          
1468       get_destination_key_from_ip (AF_INET,
1469                                    v4,
1470                                    &key);
1471     }
1472   while ( (GNUNET_YES ==
1473            GNUNET_CONTAINER_multihashmap_contains (destination_map,
1474                                                    &key)) ||
1475           (v4->s_addr == addr.s_addr) ||
1476           (v4->s_addr == mask.s_addr) );
1477   return GNUNET_OK;
1478 }
1479
1480
1481 /**
1482  * Allocate an IPv6 address from the range of the tunnel
1483  * for a new redirection.
1484  *
1485  * @param v6 where to store the address
1486  * @return GNUNET_OK on success,
1487  *         GNUNET_SYSERR on error
1488  */
1489 static int
1490 allocate_v6_address (struct in6_addr *v6)
1491 {
1492   const char *ipv6addr = vpn_argv[2];
1493   struct in6_addr addr;
1494   struct in6_addr mask;
1495   struct in6_addr rnd;
1496   int i;
1497   GNUNET_HashCode key;
1498   unsigned int tries;
1499
1500   GNUNET_assert (1 == inet_pton (AF_INET6, ipv6addr, &addr));
1501   GNUNET_assert (ipv6prefix < 128);
1502   /* Given ABCD::/96, we want a mask of 'ABCD::FFFF:FFFF,
1503      thus: */
1504   mask = addr;
1505   for (i=127;i>=128-ipv6prefix;i--)
1506     mask.s6_addr[i / 8] |= (1 << (i % 8));
1507   
1508   /* Pick random IPv6 address within the subnet, except 'addr' or 'mask' itself */
1509   tries = 0;
1510   do
1511     {
1512       tries++;
1513       if (tries > 16)
1514         {
1515           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1516                       _("Failed to find unallocated IPv6 address in VPN's range\n"));
1517           return GNUNET_SYSERR;
1518
1519         }
1520       for (i=0;i<16;i++)
1521         {
1522           rnd.s6_addr[i] = (unsigned char) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 
1523                                                                      256);
1524           v6->s6_addr[i]
1525             = (addr.s6_addr[i] | rnd.s6_addr[i]) & mask.s6_addr[i];
1526         }
1527       get_destination_key_from_ip (AF_INET6,
1528                                    v6,
1529                                    &key);
1530     }
1531   while ( (GNUNET_YES ==
1532            GNUNET_CONTAINER_multihashmap_contains (destination_map,
1533                                                    &key)) ||
1534           (0 == memcmp (v6,
1535                         &addr,
1536                         sizeof (struct in6_addr))) ||
1537           (0 == memcmp (v6,
1538                         &mask,
1539                         sizeof (struct in6_addr))) );
1540   return GNUNET_OK;
1541 }
1542
1543
1544 /**
1545  * A client asks us to setup a redirection via some exit
1546  * node to a particular IP.  Setup the redirection and
1547  * give the client the allocated IP.
1548  *
1549  * @param cls unused
1550  * @param client requesting client
1551  * @param message redirection request (a 'struct RedirectToIpRequestMessage')
1552  */
1553 static void
1554 service_redirect_to_ip (void *cls GNUNET_UNUSED, struct GNUNET_SERVER_Client *client,
1555                         const struct GNUNET_MessageHeader *message)
1556 {
1557   size_t mlen;
1558   size_t alen;
1559   const struct RedirectToIpRequestMessage *msg;
1560   int addr_af;
1561   int result_af;
1562   struct in_addr v4;
1563   struct in6_addr v6;
1564   void *addr;
1565   struct DestinationEntry *de;
1566   GNUNET_HashCode key;
1567   GNUNET_MESH_ApplicationType app_type;
1568   
1569   /* validate and parse request */
1570   mlen = ntohs (message->size);
1571   if (mlen < sizeof (struct RedirectToIpRequestMessage))
1572   {
1573     GNUNET_break (0);
1574     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1575     return;
1576   }
1577   alen = mlen - sizeof (struct RedirectToIpRequestMessage);
1578   msg = (const struct RedirectToIpRequestMessage *) message;
1579   addr_af = (int) htonl (msg->addr_af);
1580   switch (addr_af)
1581   {
1582   case AF_INET:
1583     if (alen != sizeof (struct in_addr))
1584     {
1585       GNUNET_break (0);
1586       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1587       return;      
1588     }
1589     app_type = GNUNET_APPLICATION_TYPE_IPV4_GATEWAY; 
1590     break;
1591   case AF_INET6:
1592     if (alen != sizeof (struct in6_addr))
1593     {
1594       GNUNET_break (0);
1595       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1596       return;      
1597     }
1598     app_type = GNUNET_APPLICATION_TYPE_IPV6_GATEWAY; 
1599     break;
1600   default:
1601     GNUNET_break (0);
1602     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1603     return;      
1604   }
1605
1606   /* allocate response IP */
1607   addr = NULL;
1608   result_af = (int) htonl (msg->result_af);
1609   switch (result_af)
1610   {
1611   case AF_INET:
1612     if (GNUNET_OK !=
1613         allocate_v4_address (&v4))
1614       result_af = AF_UNSPEC;
1615     else
1616       addr = &v4;
1617     break;
1618   case AF_INET6:
1619     if (GNUNET_OK !=
1620         allocate_v6_address (&v6))
1621       result_af = AF_UNSPEC;
1622     else
1623       addr = &v6;
1624     break;
1625   case AF_UNSPEC:
1626     if (GNUNET_OK ==
1627         allocate_v4_address (&v4))
1628     {
1629       addr = &v4;
1630       result_af = AF_INET;
1631     }
1632     else if (GNUNET_OK ==
1633         allocate_v6_address (&v6))
1634     {
1635       addr = &v6;
1636       result_af = AF_INET6;
1637     }
1638     break;
1639   default:
1640     GNUNET_break (0);
1641     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1642     return;      
1643   }
1644   if ( (result_af == AF_UNSPEC) ||
1645        (GNUNET_NO == ntohl (msg->nac)) )
1646   {
1647     /* send reply "instantly" */
1648     send_client_reply (client,
1649                        msg->request_id,
1650                        result_af,
1651                        addr);
1652   }
1653   if (result_af == AF_UNSPEC)
1654   {
1655     /* failure, we're done */
1656     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1657     return;
1658   }
1659   
1660   /* setup destination record */
1661   de = GNUNET_malloc (sizeof (struct DestinationEntry));
1662   de->is_service = GNUNET_NO;
1663   de->details.exit_destination.af = addr_af;
1664   memcpy (&de->details.exit_destination.ip,
1665           &msg[1],
1666           alen);
1667   get_destination_key_from_ip (result_af,
1668                                addr,
1669                                &key);
1670   de->key = key;
1671   GNUNET_assert (GNUNET_OK ==
1672                  GNUNET_CONTAINER_multihashmap_put (destination_map,
1673                                                     &key,
1674                                                     de,
1675                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1676   de->heap_node = GNUNET_CONTAINER_heap_insert (destination_heap,
1677                                                 de,
1678                                                 GNUNET_TIME_absolute_ntoh (msg->expiration_time).abs_value);
1679   /* FIXME: expire OLD destinations if we have too many! */
1680   /* setup tunnel to destination */
1681   (void) create_tunnel_to_destination (de, 
1682                                        (GNUNET_NO == ntohl (msg->nac)) ? NULL : client,
1683                                        msg->request_id);
1684   GNUNET_assert (NULL != de->ts);
1685   /* we're done */
1686   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1687 }
1688
1689
1690 /**
1691  * A client asks us to setup a redirection to a particular peer
1692  * offering a service.  Setup the redirection and give the client the
1693  * allocated IP.
1694  *
1695  * @param cls unused
1696  * @param client requesting client
1697  * @param message redirection request (a 'struct RedirectToPeerRequestMessage')
1698  */
1699 static void
1700 service_redirect_to_service (void *cls GNUNET_UNUSED, struct GNUNET_SERVER_Client *client,
1701                              const struct GNUNET_MessageHeader *message)
1702 {
1703   const struct RedirectToServiceRequestMessage *msg;
1704   int result_af;
1705   struct in_addr v4;
1706   struct in6_addr v6;
1707   void *addr;
1708   struct DestinationEntry *de;
1709   GNUNET_HashCode key;
1710   
1711   /*  parse request */
1712   msg = (const struct RedirectToServiceRequestMessage *) message;
1713
1714   /* allocate response IP */
1715   addr = NULL;
1716   result_af = (int) htonl (msg->result_af);
1717   switch (result_af)
1718   {
1719   case AF_INET:
1720     if (GNUNET_OK !=
1721         allocate_v4_address (&v4))
1722       result_af = AF_UNSPEC;
1723     else
1724       addr = &v4;
1725     break;
1726   case AF_INET6:
1727     if (GNUNET_OK !=
1728         allocate_v6_address (&v6))
1729       result_af = AF_UNSPEC;
1730     else
1731       addr = &v6;
1732     break;
1733   case AF_UNSPEC:
1734     if (GNUNET_OK ==
1735         allocate_v4_address (&v4))
1736     {
1737       addr = &v4;
1738       result_af = AF_INET;
1739     }
1740     else if (GNUNET_OK ==
1741         allocate_v6_address (&v6))
1742     {
1743       addr = &v6;
1744       result_af = AF_INET6;
1745     }
1746     break;
1747   default:
1748     GNUNET_break (0);
1749     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1750     return;      
1751   }
1752   if ( (result_af == AF_UNSPEC) ||
1753        (GNUNET_NO == ntohl (msg->nac)) )
1754   {
1755     /* send reply "instantly" */
1756     send_client_reply (client,
1757                        msg->request_id,
1758                        result_af,
1759                        addr);
1760   }
1761   if (result_af == AF_UNSPEC)
1762   {
1763     /* failure, we're done */
1764     GNUNET_SERVER_receive_done (client, GNUNET_OK);
1765     return;
1766   }
1767   
1768   /* setup destination record */
1769   de = GNUNET_malloc (sizeof (struct DestinationEntry));
1770   de->is_service = GNUNET_YES;
1771   de->details.service_destination.service_descriptor = msg->service_descriptor;
1772   de->details.service_destination.target = msg->target;
1773   get_destination_key_from_ip (result_af,
1774                                addr,
1775                                &key);
1776   de->key = key;
1777   GNUNET_assert (GNUNET_OK ==
1778                  GNUNET_CONTAINER_multihashmap_put (destination_map,
1779                                                     &key,
1780                                                     de,
1781                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
1782   de->heap_node = GNUNET_CONTAINER_heap_insert (destination_heap,
1783                                                 de,
1784                                                 GNUNET_TIME_absolute_ntoh (msg->expiration_time).abs_value);
1785   /* FIXME: expire OLD destinations if we have too many! */
1786   (void) create_tunnel_to_destination (de,
1787                                        (GNUNET_NO == ntohl (msg->nac)) ? NULL : client,
1788                                        msg->request_id);
1789   /* we're done */
1790   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1791 }
1792
1793
1794
1795 /**
1796  * Function called for inbound tunnels.  As we don't offer
1797  * any mesh services, this function should never be called.
1798  *
1799  * @param cls closure
1800  * @param tunnel new handle to the tunnel
1801  * @param initiator peer that started the tunnel
1802  * @param atsi performance information for the tunnel
1803  * @return initial tunnel context for the tunnel
1804  *         (can be NULL -- that's not an error)
1805  */ 
1806 static void *
1807 inbound_tunnel_cb (void *cls, struct GNUNET_MESH_Tunnel *tunnel,
1808                    const struct GNUNET_PeerIdentity *initiator,
1809                    const struct GNUNET_ATS_Information *atsi)
1810 {
1811   /* How can and why should anyone open an inbound tunnel to vpn? */
1812   GNUNET_break (0);
1813   return NULL;
1814 }
1815
1816
1817 /**
1818  * Free resources associated with a tunnel state.
1819  *
1820  * @param ts state to free
1821  */
1822 static void
1823 free_tunnel_state (struct TunnelState *ts)
1824 {
1825   GNUNET_HashCode key;
1826   struct TunnelMessageQueueEntry *tnq;
1827
1828   while (NULL != (tnq = ts->head))
1829   {
1830     GNUNET_CONTAINER_DLL_remove (ts->head,
1831                                  ts->tail,
1832                                  tnq);
1833     GNUNET_free (tnq);
1834   }
1835   if (NULL != ts->client)
1836   {
1837     GNUNET_SERVER_client_drop (ts->client);
1838     ts->client = NULL;
1839   }
1840   if (NULL != ts->th)
1841   {
1842     GNUNET_MESH_notify_transmit_ready_cancel (ts->th);
1843     ts->th = NULL;
1844   }
1845   GNUNET_assert (NULL == ts->destination.heap_node);
1846   if (NULL != ts->tunnel)
1847   {
1848     GNUNET_MESH_tunnel_destroy (ts->tunnel);
1849     ts->tunnel = NULL;
1850   }
1851   if (NULL != ts->heap_node)
1852   {
1853     GNUNET_CONTAINER_heap_remove_node (ts->heap_node);
1854     ts->heap_node = NULL;
1855     get_tunnel_key_from_ips (ts->af,
1856                              ts->protocol,
1857                              &ts->source_ip,
1858                              ts->source_port,
1859                              &ts->destination_ip,
1860                              ts->destination_port,
1861                              &key);
1862     GNUNET_assert (GNUNET_YES ==
1863                    GNUNET_CONTAINER_multihashmap_remove (tunnel_map,
1864                                                          &key,
1865                                                          ts));
1866   }
1867   if (NULL != ts->destination_container)
1868   {
1869     GNUNET_assert (ts == ts->destination_container->ts);
1870     ts->destination_container->ts = NULL;
1871     ts->destination_container = NULL;
1872   }
1873   GNUNET_free (ts);
1874 }
1875
1876
1877 /**
1878  * Free resources occupied by a destination entry.
1879  *
1880  * @param de entry to free
1881  */
1882 static void
1883 free_destination_entry (struct DestinationEntry *de)
1884 {
1885   if (NULL != de->ts)
1886   {
1887     free_tunnel_state (de->ts);
1888     GNUNET_assert (NULL == de->ts);
1889   }
1890   if (NULL != de->heap_node)
1891   {
1892     GNUNET_CONTAINER_heap_remove_node (de->heap_node);
1893     de->heap_node = NULL;  
1894     GNUNET_assert (GNUNET_YES ==
1895                    GNUNET_CONTAINER_multihashmap_remove (destination_map,
1896                                                          &de->key,
1897                                                          de));
1898   }
1899   GNUNET_free (de);
1900 }
1901
1902
1903 /**
1904  * Function called whenever an inbound tunnel is destroyed.  Should clean up
1905  * any associated state.
1906  *
1907  * @param cls closure (set from GNUNET_MESH_connect)
1908  * @param tunnel connection to the other end (henceforth invalid)
1909  * @param tunnel_ctx place where local state associated
1910  *                   with the tunnel is stored (our 'struct TunnelState')
1911  */ 
1912 static void
1913 tunnel_cleaner (void *cls, const struct GNUNET_MESH_Tunnel *tunnel, void *tunnel_ctx)
1914 {
1915   struct TunnelState *ts = tunnel_ctx;
1916
1917   if (NULL == ts)
1918   {
1919     GNUNET_break (0);
1920     return;     
1921   }
1922   GNUNET_assert (ts->tunnel == tunnel);
1923   ts->tunnel = NULL;
1924   free_tunnel_state (ts);
1925 }
1926
1927
1928 /**
1929  * Free memory occupied by an entry in the destination map.
1930  *
1931  * @param cls unused
1932  * @param key unused
1933  * @param value a 'struct DestinationEntry *'
1934  * @return GNUNET_OK (continue to iterate)
1935  */
1936 static int
1937 cleanup_destination (void *cls,
1938                      const GNUNET_HashCode *key,
1939                      void *value)
1940 {
1941   struct DestinationEntry *de = value;
1942
1943   free_destination_entry (de);
1944   return GNUNET_OK;
1945 }
1946
1947
1948 /**
1949  * Free memory occupied by an entry in the tunnel map.
1950  *
1951  * @param cls unused
1952  * @param key unused
1953  * @param value a 'struct TunnelState *'
1954  * @return GNUNET_OK (continue to iterate)
1955  */
1956 static int
1957 cleanup_tunnel (void *cls,
1958                 const GNUNET_HashCode *key,
1959                 void *value)
1960 {
1961   struct TunnelState *ts = value;
1962
1963   free_tunnel_state (ts);
1964   return GNUNET_OK;
1965 }
1966
1967
1968 /**
1969  * Function scheduled as very last function, cleans up after us
1970  *
1971  * @param cls unused
1972  * @param tc unused
1973  */
1974 static void
1975 cleanup (void *cls GNUNET_UNUSED,
1976          const struct GNUNET_SCHEDULER_TaskContext *tc)
1977 {
1978   unsigned int i;
1979
1980   if (NULL != destination_map)
1981   {  
1982     GNUNET_CONTAINER_multihashmap_iterate (destination_map,
1983                                            &cleanup_destination,
1984                                            NULL);
1985     GNUNET_CONTAINER_multihashmap_destroy (destination_map);
1986     destination_map = NULL;
1987   }
1988   if (NULL != destination_heap)
1989   {
1990     GNUNET_CONTAINER_heap_destroy (destination_heap);
1991     destination_heap = NULL;
1992   }
1993   if (NULL != tunnel_map)
1994   {  
1995     GNUNET_CONTAINER_multihashmap_iterate (tunnel_map,
1996                                            &cleanup_tunnel,
1997                                            NULL);
1998     GNUNET_CONTAINER_multihashmap_destroy (tunnel_map);
1999     tunnel_map = NULL;
2000   }
2001   if (NULL != tunnel_heap)
2002   {
2003     GNUNET_CONTAINER_heap_destroy (tunnel_heap);
2004     tunnel_heap = NULL;
2005   }
2006   if (NULL != mesh_handle)
2007   {
2008     GNUNET_MESH_disconnect (mesh_handle);
2009     mesh_handle = NULL;
2010   }
2011   if (NULL != helper_handle)
2012     {
2013     GNUNET_HELPER_stop (helper_handle);
2014     helper_handle = NULL;
2015   }
2016   if (NULL != nc)
2017   {
2018     GNUNET_SERVER_notification_context_destroy (nc);
2019     nc = NULL;
2020   }
2021   for (i=0;i<5;i++)
2022     GNUNET_free_non_null (vpn_argv[i]);
2023 }
2024
2025
2026 /**
2027  * A client disconnected, clean up all references to it.
2028  *
2029  * @param cls the client that disconnected
2030  * @param key unused
2031  * @param value a 'struct TunnelState *'
2032  * @return GNUNET_OK (continue to iterate)
2033  */
2034 static int
2035 cleanup_tunnel_client (void *cls,
2036                        const GNUNET_HashCode *key,
2037                        void *value)
2038 {
2039   struct GNUNET_SERVER_Client *client = cls;
2040   struct TunnelState *ts = value;
2041
2042   if (client == ts->client)
2043   {
2044     GNUNET_SERVER_client_drop (ts->client);
2045     ts->client = NULL;
2046   }
2047   return GNUNET_OK;
2048 }
2049
2050
2051 /**
2052  * A client disconnected, clean up all references to it.
2053  *
2054  * @param cls the client that disconnected
2055  * @param key unused
2056  * @param value a 'struct DestinationEntry *'
2057  * @return GNUNET_OK (continue to iterate)
2058  */
2059 static int
2060 cleanup_destination_client (void *cls,
2061                             const GNUNET_HashCode *key,
2062                             void *value)
2063 {
2064   struct GNUNET_SERVER_Client *client = cls;
2065   struct DestinationEntry *de = value;
2066   struct TunnelState *ts;
2067
2068   if (NULL == (ts = de->ts))
2069     return GNUNET_OK;
2070   if (client == ts->client)
2071   {
2072     GNUNET_SERVER_client_drop (ts->client);
2073     ts->client = NULL;
2074   }
2075   return GNUNET_OK;
2076 }
2077
2078   
2079 /**
2080  * A client has disconnected from us.  If we are currently building
2081  * a tunnel for it, cancel the operation.
2082  *
2083  * @param cls unused
2084  * @param client handle to the client that disconnected
2085  */
2086 static void
2087 client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2088 {
2089   GNUNET_CONTAINER_multihashmap_iterate (tunnel_map,
2090                                          &cleanup_tunnel_client,
2091                                          client);
2092   GNUNET_CONTAINER_multihashmap_iterate (destination_map,
2093                                          &cleanup_destination_client,
2094                                          client);
2095 }
2096
2097
2098 /**
2099  * Main function that will be run by the scheduler.
2100  *
2101  * @param cls closure
2102  * @param server the initialized server
2103  * @param cfg_ configuration
2104  */
2105 static void
2106 run (void *cls,
2107      struct GNUNET_SERVER_Handle *server,
2108      const struct GNUNET_CONFIGURATION_Handle *cfg_)
2109 {
2110   static const struct GNUNET_SERVER_MessageHandler service_handlers[] = {
2111     /* callback, cls, type, size */
2112     {&service_redirect_to_ip, NULL, GNUNET_MESSAGE_TYPE_VPN_CLIENT_REDIRECT_TO_IP, 0},
2113     {&service_redirect_to_service, NULL, 
2114      GNUNET_MESSAGE_TYPE_VPN_CLIENT_REDIRECT_TO_SERVICE, 
2115      sizeof (struct RedirectToServiceRequestMessage) },
2116     {NULL, NULL, 0, 0}
2117   };
2118   static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2119     {receive_udp_back, GNUNET_MESSAGE_TYPE_VPN_SERVICE_UDP_BACK, 0},
2120     {receive_tcp_back, GNUNET_MESSAGE_TYPE_VPN_SERVICE_TCP_BACK, 0},
2121     {receive_udp_back, GNUNET_MESSAGE_TYPE_VPN_REMOTE_UDP_BACK, 0},
2122     {receive_tcp_back, GNUNET_MESSAGE_TYPE_VPN_REMOTE_TCP_BACK, 0},
2123     {NULL, 0, 0}
2124   };
2125   static const GNUNET_MESH_ApplicationType types[] = {
2126     GNUNET_APPLICATION_TYPE_END
2127   };
2128   char *ifname;
2129   char *ipv6addr;
2130   char *ipv6prefix_s;
2131   char *ipv4addr;
2132   char *ipv4mask;
2133   struct in_addr v4;
2134   struct in6_addr v6;
2135
2136   cfg = cfg_;
2137   if (GNUNET_OK !=
2138       GNUNET_CONFIGURATION_get_value_number (cfg, "vpn", "MAX_MAPPING",
2139                                              &max_destination_mappings))
2140     max_destination_mappings = 200;
2141   if (GNUNET_OK !=
2142       GNUNET_CONFIGURATION_get_value_number (cfg, "vpn", "MAX_TUNNELS",
2143                                              &max_tunnel_mappings))
2144     max_tunnel_mappings = 200;
2145
2146   destination_map = GNUNET_CONTAINER_multihashmap_create (max_destination_mappings * 2);
2147   destination_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2148   tunnel_map = GNUNET_CONTAINER_multihashmap_create (max_tunnel_mappings * 2);
2149   tunnel_heap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
2150
2151
2152   vpn_argv[0] = GNUNET_strdup ("vpn-gnunet");
2153   if (GNUNET_SYSERR ==
2154       GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "IFNAME", &ifname))
2155   {
2156     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2157                 "No entry 'IFNAME' in configuration!\n");
2158     GNUNET_SCHEDULER_shutdown ();
2159     return;
2160   }
2161   vpn_argv[1] = ifname;
2162   if ( (GNUNET_SYSERR ==
2163         GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "IPV6ADDR",
2164                                                &ipv6addr) ||
2165         (1 != inet_pton (AF_INET6, ipv6addr, &v6))) )
2166   {
2167     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2168                 "No valid entry 'IPV6ADDR' in configuration!\n");
2169     GNUNET_SCHEDULER_shutdown ();
2170     return;
2171   }
2172   vpn_argv[2] = ipv6addr;
2173   if (GNUNET_SYSERR ==
2174       GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "IPV6PREFIX",
2175                                              &ipv6prefix_s))
2176   {
2177     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2178                 "No entry 'IPV6PREFIX' in configuration!\n");
2179     GNUNET_SCHEDULER_shutdown ();
2180     return;
2181   }
2182   vpn_argv[3] = ipv6prefix_s;
2183   if ( (GNUNET_OK !=
2184         GNUNET_CONFIGURATION_get_value_number (cfg, "vpn",
2185                                                "IPV6PREFIX",
2186                                                &ipv6prefix)) ||
2187        (ipv6prefix >= 127) )
2188   {
2189     GNUNET_SCHEDULER_shutdown ();
2190     return;
2191   }
2192
2193   if ( (GNUNET_SYSERR ==
2194         GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "IPV4ADDR",
2195                                                &ipv4addr) ||
2196         (1 != inet_pton (AF_INET, ipv4addr, &v4))) )
2197   {
2198     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2199                 "No valid entry for 'IPV4ADDR' in configuration!\n");
2200     GNUNET_SCHEDULER_shutdown ();
2201     return;
2202   }
2203   vpn_argv[4] = ipv4addr;
2204   if ( (GNUNET_SYSERR ==
2205         GNUNET_CONFIGURATION_get_value_string (cfg, "vpn", "IPV4MASK",
2206                                                &ipv4mask) ||
2207         (1 != inet_pton (AF_INET, ipv4mask, &v4))) )
2208   {
2209     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2210                 "No valid entry 'IPV4MASK' in configuration!\n");
2211     GNUNET_SCHEDULER_shutdown ();
2212     return;
2213   }
2214   vpn_argv[5] = ipv4mask;
2215   vpn_argv[6] = NULL;
2216
2217   mesh_handle =
2218     GNUNET_MESH_connect (cfg_, 42 /* queue length */, NULL, 
2219                          &inbound_tunnel_cb, 
2220                          &tunnel_cleaner, 
2221                          mesh_handlers,
2222                          types);
2223   helper_handle = GNUNET_HELPER_start ("gnunet-helper-vpn", vpn_argv,
2224                                        &message_token, NULL);
2225   nc = GNUNET_SERVER_notification_context_create (server, 1);
2226   GNUNET_SERVER_add_handlers (server, service_handlers);
2227   GNUNET_SERVER_disconnect_notify (server, &client_disconnect, NULL);
2228   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls);
2229 }
2230
2231
2232 /**
2233  * The main function of the VPN service.
2234  *
2235  * @param argc number of arguments from the command line
2236  * @param argv command line arguments
2237  * @return 0 ok, 1 on error
2238  */
2239 int
2240 main (int argc, char *const *argv)
2241 {
2242   return (GNUNET_OK ==
2243           GNUNET_SERVICE_run (argc, argv, "vpn", 
2244                               GNUNET_SERVICE_OPTION_NONE,
2245                               &run, NULL)) ? 0 : 1;
2246 }
2247
2248 /* end of gnunet-service-vpn.c */