let -vpn send back v4 packets
[oweals/gnunet.git] / src / vpn / gnunet-daemon-exit.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-exit.c
23  * @brief
24  * @author Philipp Toelke
25  */
26 #include <platform.h>
27 #include <gnunet_common.h>
28 #include <gnunet_program_lib.h>
29 #include <gnunet_protocols.h>
30 #include <gnunet_applications.h>
31 #include <gnunet_mesh_service.h>
32 #include <gnunet_constants.h>
33 #include <string.h>
34
35 #include "gnunet-vpn-packet.h"
36 #include "gnunet-helper-vpn-api.h"
37 #include "gnunet-vpn-checksum.h"
38
39 GNUNET_SCHEDULER_TaskIdentifier shs_task;
40
41 /**
42  * The handle to the configuration used throughout the process
43  */
44 static const struct GNUNET_CONFIGURATION_Handle *cfg;
45
46 /**
47  * The handle to the helper
48  */
49 struct GNUNET_VPN_HELPER_Handle *helper_handle;
50
51 /**
52  * Final status code.
53  */
54 static int ret;
55
56 /**
57  * The handle to mesh
58  */
59 static struct GNUNET_MESH_Handle *mesh_handle;
60
61 /**
62  * This hashmaps contains the mapping from peer, service-descriptor,
63  * source-port and destination-port to a struct redirect_state
64  */
65 static struct GNUNET_CONTAINER_MultiHashMap *udp_connections;
66 static struct GNUNET_CONTAINER_Heap *udp_connections_heap;
67 static struct GNUNET_CONTAINER_MultiHashMap *tcp_connections;
68 static struct GNUNET_CONTAINER_Heap *tcp_connections_heap;
69
70 /**
71  * If there are at least this many udp-Connections, old ones will be removed
72  */
73 static long long unsigned int max_udp_connections = 200;
74
75 /**
76  * If there are at least this many tcp-Connections, old ones will be removed
77  */
78 static long long unsigned int max_tcp_connections = 200;
79
80 struct remote_addr
81 {
82   char addrlen;
83   unsigned char addr[16];
84   char proto;
85 };
86
87 /**
88  * This struct is saved into the services-hashmap
89  */
90 struct redirect_service
91 {
92   /**
93    * One of 4 or 6
94    */
95   unsigned int version;
96   uint16_t my_port;
97   uint16_t remote_port;
98
99   union
100   {
101     struct
102     {
103       char ip4address[4];
104     } v4;
105     struct
106     {
107       char ip6address[16];
108     } v6;
109   };
110 };
111
112 struct redirect_info
113 {
114     /**
115      * The source-address of this connection. When a packet to this address is
116      * received, this tunnel is used to forward it.  ipv4-addresses will be put
117      * here left-aligned */
118   char addr[16];
119     /**
120      * The source-port of this connection
121      */
122   uint16_t pt;
123 };
124
125 /**
126  * This struct is saved into {tcp,udp}_connections;
127  */
128 struct redirect_state
129 {
130   struct GNUNET_MESH_Tunnel *tunnel;
131   GNUNET_HashCode desc;
132   struct redirect_service *serv;
133   struct remote_addr remote;
134
135   struct GNUNET_CONTAINER_HeapNode* heap_node;
136   struct GNUNET_CONTAINER_MultiHashMap *hashmap;
137   GNUNET_HashCode hash;
138
139   enum { SERVICE, REMOTE } type;
140
141   /**
142    * The source-address and -port of this connection
143    */
144   struct redirect_info redirect_info;
145 };
146
147 /**
148  * This hashmaps saves interesting things about the configured services
149  */
150 static struct GNUNET_CONTAINER_MultiHashMap *udp_services;
151 static struct GNUNET_CONTAINER_MultiHashMap *tcp_services;
152
153 struct tunnel_notify_queue
154 {
155   struct tunnel_notify_queue* next;
156   struct tunnel_notify_queue* prev;
157   void* cls;
158   size_t len;
159 };
160
161 /**
162  * Function that frees everything from a hashmap
163  */
164 static int
165 free_iterate(void* cls __attribute__((unused)), const GNUNET_HashCode* hash __attribute__((unused)), void* value)
166 {
167   GNUNET_free(value);
168   return GNUNET_YES;
169 }
170
171 /**
172  * Function scheduled as very last function, cleans up after us
173  */
174 static void
175 cleanup(void* cls __attribute__((unused)), const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
176     GNUNET_assert (0 != (tskctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN));
177
178     GNUNET_CONTAINER_multihashmap_iterate(udp_connections,
179                                           free_iterate,
180                                           NULL);
181
182     GNUNET_CONTAINER_multihashmap_iterate(tcp_connections,
183                                           free_iterate,
184                                           NULL);
185
186     if (mesh_handle != NULL)
187       {
188         GNUNET_MESH_disconnect(mesh_handle);
189         mesh_handle = NULL;
190       }
191 }
192
193 static void
194 collect_connections(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tc) {
195           if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
196       return;
197
198
199     struct GNUNET_CONTAINER_Heap *heap = cls;
200
201     struct redirect_state* state = GNUNET_CONTAINER_heap_remove_root(heap);
202
203     /* This is free()ed memory! */
204     state->heap_node = NULL;
205
206     /* FIXME! GNUNET_MESH_close_tunnel(state->tunnel); */
207
208     GNUNET_CONTAINER_multihashmap_remove(state->hashmap, &state->hash, state);
209
210     GNUNET_free(state);
211 }
212
213 static void
214 hash_redirect_info(GNUNET_HashCode* hash, struct redirect_info* u_i, size_t addrlen)
215 {
216
217   /* the gnunet hashmap only uses the first sizeof(unsigned int) of the hash
218    *
219    * build the hash out of the last bytes of the address and the 2 bytes of
220    * the port
221    */
222   memcpy(hash, &u_i->pt, sizeof(u_i->pt));
223   memcpy(((unsigned char*)hash)+2, u_i->addr+(addrlen-(sizeof(unsigned int) - 2)), (sizeof(unsigned int) - 2));
224   memset(((unsigned char*)hash)+sizeof(unsigned int), 0, sizeof(GNUNET_HashCode) - sizeof(unsigned int));
225 }
226
227 /**
228  * cls is the pointer to a GNUNET_MessageHeader that is
229  * followed by the service-descriptor and the udp-packet that should be sent;
230  */
231 static size_t
232 send_udp_to_peer_notify_callback (void *cls, size_t size, void *buf)
233 {
234   struct GNUNET_MESH_Tunnel** tunnel = cls;
235   GNUNET_MESH_tunnel_set_data(*tunnel, NULL);
236   struct GNUNET_MessageHeader *hdr = (struct GNUNET_MessageHeader*)(tunnel + 1);
237   GNUNET_assert (size >= ntohs (hdr->size));
238   memcpy (buf, hdr, ntohs (hdr->size));
239   size = ntohs(hdr->size);
240
241   if (NULL != GNUNET_MESH_tunnel_get_head(*tunnel))
242     {
243       struct tunnel_notify_queue* element = GNUNET_MESH_tunnel_get_head(*tunnel);
244       struct tunnel_notify_queue* head = GNUNET_MESH_tunnel_get_head(*tunnel);
245       struct tunnel_notify_queue* tail = GNUNET_MESH_tunnel_get_tail(*tunnel);
246
247       GNUNET_CONTAINER_DLL_remove(head, tail, element);
248
249       GNUNET_MESH_tunnel_set_head(*tunnel, head);
250       GNUNET_MESH_tunnel_set_tail(*tunnel, tail);
251
252       struct GNUNET_MESH_TransmitHandle* th = GNUNET_MESH_notify_transmit_ready (*tunnel,
253                                                                                  GNUNET_NO,
254                                                                                  42,
255                                                                                  GNUNET_TIME_relative_divide
256                                                                                  (GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
257                                                                                  (const struct GNUNET_PeerIdentity *)
258                                                                                  NULL, element->len,
259                                                                                  send_udp_to_peer_notify_callback, element->cls);
260       /* save the handle */
261       GNUNET_MESH_tunnel_set_data(*tunnel, th);
262     }
263
264   GNUNET_free (cls);
265
266   return size;
267 }
268
269 /**
270  * @brief Handles an UDP-Packet received from the helper.
271  *
272  * @param udp A pointer to the Packet
273  * @param dadr The IP-Destination-address
274  * @param addrlen The length of the address
275  * @param version 4 or 6
276  */
277 static void
278 udp_from_helper (struct udp_pkt *udp, unsigned char *dadr, size_t addrlen)
279 {
280   struct redirect_info u_i;
281   struct GNUNET_MESH_Tunnel *tunnel;
282   uint32_t len;
283   struct GNUNET_MessageHeader *msg;
284
285   memset (&u_i, 0, sizeof (struct redirect_info));
286
287   memcpy (&u_i.addr, dadr, addrlen);
288
289   u_i.pt = udp->dpt;
290
291   /* get tunnel and service-descriptor from this */
292   GNUNET_HashCode hash;
293   hash_redirect_info(&hash, &u_i, addrlen);
294
295   struct redirect_state *state =
296     GNUNET_CONTAINER_multihashmap_get (udp_connections, &hash);
297
298   /* Mark this connection as freshly used */
299   GNUNET_CONTAINER_heap_update_cost (udp_connections_heap, state->heap_node,
300                                      GNUNET_TIME_absolute_get ().abs_value);
301
302   tunnel = state->tunnel;
303
304   if (state->type == SERVICE)
305     {
306       /* check if spt == serv.remote if yes: set spt = serv.myport ("nat") */
307       if (ntohs (udp->spt) == state->serv->remote_port)
308         {
309           udp->spt = htons (state->serv->my_port);
310         }
311       else
312         {
313           /* otherwise the answer came from a different port (tftp does this)
314            * add this new port to the list of all services, so that the packets
315            * coming back from the client to this new port will be routed correctly
316            */
317           struct redirect_service *serv =
318             GNUNET_malloc (sizeof (struct redirect_service));
319           memcpy (serv, state->serv, sizeof (struct redirect_service));
320           serv->my_port = ntohs (udp->spt);
321           serv->remote_port = ntohs (udp->spt);
322           uint16_t *desc = alloca (sizeof (GNUNET_HashCode) + 2);
323           memcpy ((GNUNET_HashCode *) (desc + 1), &state->desc,
324                   sizeof (GNUNET_HashCode));
325           *desc = ntohs (udp->spt);
326           GNUNET_assert (GNUNET_OK ==
327                          GNUNET_CONTAINER_multihashmap_put (udp_services,
328                                                             (GNUNET_HashCode*)desc, serv,
329                                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
330
331           state->serv = serv;
332         }
333     }
334
335   /* send udp-packet back */
336   len =
337     sizeof (struct GNUNET_MessageHeader) + sizeof (GNUNET_HashCode) +
338     ntohs (udp->len);
339   struct GNUNET_MESH_Tunnel** ctunnel = GNUNET_malloc (sizeof(struct GNUNET_MESH_TUNNEL*) + len);
340   *ctunnel = tunnel;
341   msg = (struct GNUNET_MessageHeader*)(ctunnel + 1);
342   msg->size = htons (len);
343   msg->type = htons (state->type == SERVICE ? GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK : GNUNET_MESSAGE_TYPE_REMOTE_UDP_BACK);
344   GNUNET_HashCode *desc = (GNUNET_HashCode *) (msg + 1);
345   if (state->type == SERVICE)
346     memcpy (desc, &state->desc, sizeof (GNUNET_HashCode));
347   else
348     memcpy (desc, &state->remote, sizeof (struct remote_addr));
349   void *_udp = desc + 1;
350   memcpy (_udp, udp, ntohs (udp->len));
351
352   if (NULL == GNUNET_MESH_tunnel_get_data(tunnel))
353     {
354       /* No notify is pending */
355       struct GNUNET_MESH_TransmitHandle* th = GNUNET_MESH_notify_transmit_ready (tunnel,
356                                                                                  GNUNET_NO,
357                                                                                  42,
358                                                                                  GNUNET_TIME_relative_divide
359                                                                                  (GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
360                                                                                  (const struct GNUNET_PeerIdentity *)
361                                                                                  NULL, len,
362                                                                                  send_udp_to_peer_notify_callback, ctunnel);
363       /* save the handle */
364       GNUNET_MESH_tunnel_set_data(tunnel, th);
365     }
366   else
367     {
368       struct tunnel_notify_queue* head = GNUNET_MESH_tunnel_get_head(tunnel);
369       struct tunnel_notify_queue* tail = GNUNET_MESH_tunnel_get_tail(tunnel);
370
371       struct tunnel_notify_queue* element = GNUNET_malloc(sizeof(struct tunnel_notify_queue));
372       element->cls = ctunnel;
373       element->len = len;
374
375       GNUNET_CONTAINER_DLL_insert_tail(head, tail, element);
376       GNUNET_MESH_tunnel_set_head(tunnel, head);
377       GNUNET_MESH_tunnel_set_tail(tunnel, tail);
378     }
379 }
380
381 /**
382  * @brief Handles a TCP-Packet received from the helper.
383  *
384  * @param tcp A pointer to the Packet
385  * @param dadr The IP-Destination-address
386  * @param addrlen The length of the address
387  * @param version 4 or 6
388  * @param pktlen the length of the packet, including its header
389  */
390 static void
391 tcp_from_helper (struct tcp_pkt *tcp, unsigned char *dadr, size_t addrlen,
392                  size_t pktlen)
393 {
394   struct redirect_info u_i;
395   struct GNUNET_MESH_Tunnel *tunnel;
396   uint32_t len;
397   struct GNUNET_MessageHeader *msg;
398
399   memset (&u_i, 0, sizeof (struct redirect_info));
400
401   memcpy (&u_i.addr, dadr, addrlen);
402   u_i.pt = tcp->dpt;
403
404   /* get tunnel and service-descriptor from this */
405   GNUNET_HashCode hash;
406   hash_redirect_info(&hash, &u_i, addrlen);
407
408   struct redirect_state *state =
409     GNUNET_CONTAINER_multihashmap_get (tcp_connections, &hash);
410
411   if (state == NULL)
412     {
413       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "No mapping for this connection; hash is %x\n", *((uint32_t*)&hash));
414       return;
415     }
416
417   /* Mark this connection as freshly used */
418   GNUNET_CONTAINER_heap_update_cost (tcp_connections_heap, state->heap_node,
419                                      GNUNET_TIME_absolute_get ().abs_value);
420
421   tunnel = state->tunnel;
422
423   if (state->type == SERVICE)
424     {
425       /* check if spt == serv.remote if yes: set spt = serv.myport ("nat") */
426       if (ntohs (tcp->spt) == state->serv->remote_port)
427         {
428           tcp->spt = htons (state->serv->my_port);
429         }
430       else
431         {
432           // This is an illegal packet.
433           return;
434         }
435     }
436
437   /* send tcp-packet back */
438   len =
439     sizeof (struct GNUNET_MessageHeader) + sizeof (GNUNET_HashCode) + pktlen;
440   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "len: %d\n", pktlen);
441   struct GNUNET_MESH_Tunnel** ctunnel = GNUNET_malloc (sizeof(struct GNUNET_MESH_TUNNEL*) + len);
442   *ctunnel = tunnel;
443   msg = (struct GNUNET_MessageHeader*)(ctunnel + 1);
444   msg->size = htons (len);
445   msg->type = htons (state->type == SERVICE ? GNUNET_MESSAGE_TYPE_SERVICE_TCP_BACK : GNUNET_MESSAGE_TYPE_REMOTE_TCP_BACK);
446   GNUNET_HashCode *desc = (GNUNET_HashCode *) (msg + 1);
447   if (state->type == SERVICE)
448     memcpy (desc, &state->desc, sizeof (GNUNET_HashCode));
449   else
450     memcpy (desc, &state->remote, sizeof (struct remote_addr));
451   void *_tcp = desc + 1;
452   memcpy (_tcp, tcp, pktlen);
453
454   if (NULL == GNUNET_MESH_tunnel_get_data(tunnel))
455     {
456       /* No notify is pending */
457       struct GNUNET_MESH_TransmitHandle* th = GNUNET_MESH_notify_transmit_ready (tunnel,
458                                      GNUNET_NO,
459                                      42,
460                                      GNUNET_TIME_relative_divide
461                                      (GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
462                                      (const struct GNUNET_PeerIdentity *)NULL,
463                                      len, send_udp_to_peer_notify_callback,
464                                      ctunnel);
465       /* save the handle */
466       GNUNET_MESH_tunnel_set_data(tunnel, th);
467     }
468   else
469     {
470       struct tunnel_notify_queue* head = GNUNET_MESH_tunnel_get_head(tunnel);
471       struct tunnel_notify_queue* tail = GNUNET_MESH_tunnel_get_tail(tunnel);
472
473       struct tunnel_notify_queue* element = GNUNET_malloc(sizeof(struct tunnel_notify_queue));
474       element->cls = ctunnel;
475       element->len = len;
476
477       GNUNET_CONTAINER_DLL_insert_tail(head, tail, element);
478     }
479 }
480
481
482 /**
483  * Receive packets from the helper-process
484  */
485 static void
486 message_token (void *cls __attribute__((unused)),
487                void *client __attribute__((unused)), const struct GNUNET_MessageHeader *message)
488 {
489   GNUNET_assert (ntohs (message->type) == GNUNET_MESSAGE_TYPE_VPN_HELPER);
490
491   struct tun_pkt *pkt_tun = (struct tun_pkt *) message;
492
493   /* ethertype is ipv6 */
494   if (ntohs (pkt_tun->tun.type) == 0x86dd)
495     {
496       struct ip6_pkt *pkt6 = (struct ip6_pkt *) pkt_tun;
497       if (0x11 == pkt6->ip6_hdr.nxthdr)
498         udp_from_helper (&((struct ip6_udp *) pkt6)->udp_hdr,
499                          (unsigned char *) &pkt6->ip6_hdr.dadr, 16);
500       else if (0x06 == pkt6->ip6_hdr.nxthdr)
501         tcp_from_helper (&((struct ip6_tcp *) pkt6)->tcp_hdr,
502                          (unsigned char *) &pkt6->ip6_hdr.dadr, 16,
503                          ntohs (pkt6->ip6_hdr.paylgth));
504     }
505   else if (ntohs (pkt_tun->tun.type) == 0x0800)
506     {
507       struct ip_pkt *pkt4 = (struct ip_pkt *) pkt_tun;
508       uint32_t tmp = pkt4->ip_hdr.dadr;
509       if (0x11 == pkt4->ip_hdr.proto)
510         udp_from_helper (&((struct ip_udp *) pkt4)->udp_hdr,
511                          (unsigned char *) &tmp, 4);
512       else if (0x06 == pkt4->ip_hdr.proto)
513         {
514           size_t pktlen = ntohs(pkt4->ip_hdr.tot_lngth);
515           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "tot: %d\n", pktlen);
516           pktlen -= 4*pkt4->ip_hdr.hdr_lngth;
517           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "-hdr: %d\n", pktlen);
518           tcp_from_helper (&((struct ip_tcp *) pkt4)->tcp_hdr,
519                            (unsigned char *) &tmp, 4, pktlen);
520         }
521     }
522   else
523     {
524       return;
525     }
526 }
527
528 /**
529  * Reads the configuration servicecfg and populates udp_services
530  *
531  * @param cls unused
532  * @param section name of section in config, equal to hostname
533  */
534 static void
535 read_service_conf (void *cls __attribute__((unused)), const char *section)
536 {
537   if ((strlen(section) < 8) || (0 != strcmp (".gnunet.", section + (strlen(section) - 8))))
538     return;
539
540   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Parsing dns-name %d %s %s\n", strlen(section), section, section + (strlen(section) - 8));
541
542   char *cpy;
543   char *redirect;
544   char *hostname;
545   char *hostport;
546   uint16_t *desc = alloca (sizeof (GNUNET_HashCode) + 2);
547   GNUNET_CRYPTO_hash (section, strlen (section) + 1,
548                       (GNUNET_HashCode *) (desc + 1));
549
550 #define TCP 2
551 #define UDP 1
552
553   int proto = UDP;
554
555   do
556     {
557       if (proto == UDP && (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, section, "UDP_REDIRECTS", &cpy)))
558         goto next;
559       else if (proto == TCP && (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, section, "TCP_REDIRECTS", &cpy)))
560         goto next;
561
562       for (redirect = strtok (cpy, " "); redirect != NULL; redirect = strtok
563            (NULL, " "))
564         {
565           if (NULL == (hostname = strstr (redirect, ":")))
566             {
567               GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Warning: option %s is not formatted correctly!\n",
568                           redirect);
569               continue;
570             }
571           hostname[0] = '\0';
572           hostname++;
573           if (NULL == (hostport = strstr (hostname, ":")))
574             {
575               GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Warning: option %s is not formatted correctly!\n",
576                           redirect);
577               continue;
578             }
579           hostport[0] = '\0';
580           hostport++;
581
582           int local_port = atoi (redirect);
583           if (!((local_port > 0) && (local_port < 65536)))
584             GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Warning: %s is not a correct port.",
585                         redirect);
586
587           *desc = local_port;
588
589           struct redirect_service *serv =
590             GNUNET_malloc (sizeof (struct redirect_service));
591           memset (serv, 0, sizeof (struct redirect_service));
592           serv->my_port = local_port;
593
594           if (0 == strcmp ("localhost4", hostname))
595             {
596               serv->version = 4;
597
598               char *ip4addr;
599               GNUNET_assert (GNUNET_OK ==
600                              GNUNET_CONFIGURATION_get_value_string (cfg,
601                                                                     "exit",
602                                                                     "IPV4ADDR",
603                                                                     &ip4addr));
604               GNUNET_assert (1 ==
605                              inet_pton (AF_INET, ip4addr,
606                                         serv->v4.ip4address));
607               GNUNET_free (ip4addr);
608             }
609           else if (0 == strcmp ("localhost6", hostname))
610             {
611               serv->version = 6;
612
613               char *ip6addr;
614               GNUNET_assert (GNUNET_OK ==
615                              GNUNET_CONFIGURATION_get_value_string (cfg,
616                                                                     "exit",
617                                                                     "IPV6ADDR",
618                                                                     &ip6addr));
619               GNUNET_assert (1 ==
620                              inet_pton (AF_INET6, ip6addr,
621                                         serv->v6.ip6address));
622               GNUNET_free (ip6addr);
623             }
624           else
625             {
626               // TODO Lookup, yadayadayada
627               GNUNET_assert (0);
628             }
629           serv->remote_port = atoi (hostport);
630           if (UDP == proto)
631             GNUNET_assert (GNUNET_OK ==
632                            GNUNET_CONTAINER_multihashmap_put (udp_services,
633                                                               (GNUNET_HashCode*)desc, serv,
634                                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
635           else
636             GNUNET_assert (GNUNET_OK ==
637                            GNUNET_CONTAINER_multihashmap_put (tcp_services,
638                                                               (GNUNET_HashCode*)desc, serv,
639                                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
640
641         }
642       GNUNET_free (cpy);
643 next:
644       proto = (proto == UDP) ? TCP : UDP;
645     }
646   while (proto != UDP);
647 }
648
649 /**
650  * Start the helper-process
651  *
652  * If cls != NULL it is assumed that this function is called as a result of a dying
653  * helper. cls is then taken as handle to the old helper and is cleaned up.
654  */
655 static void
656 start_helper_and_schedule(void *cls,
657                           const struct GNUNET_SCHEDULER_TaskContext *tc) {
658     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
659       return;
660
661     if (cls != NULL)
662       cleanup_helper(cls);
663     cls = NULL;
664
665     char* ifname;
666     char* ipv6addr;
667     char* ipv6prefix;
668     char* ipv4addr;
669     char* ipv4mask;
670
671     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, "exit", "IFNAME", &ifname))
672       {
673         GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No entry 'IFNAME' in configuration!\n");
674         exit(1);
675       }
676
677     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, "exit", "IPV6ADDR", &ipv6addr))
678       {
679         GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No entry 'IPV6ADDR' in configuration!\n");
680         exit(1);
681       }
682
683     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, "exit", "IPV6PREFIX", &ipv6prefix))
684       {
685         GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No entry 'IPV6PREFIX' in configuration!\n");
686         exit(1);
687       }
688
689     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, "exit", "IPV4ADDR", &ipv4addr))
690       {
691         GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No entry 'IPV4ADDR' in configuration!\n");
692         exit(1);
693       }
694
695     if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string(cfg, "exit", "IPV4MASK", &ipv4mask))
696       {
697         GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "No entry 'IPV4MASK' in configuration!\n");
698         exit(1);
699       }
700
701     /* Start the helper
702      * Messages get passed to the function message_token
703      * When the helper dies, this function will be called again with the
704      * helper_handle as cls.
705      */
706     helper_handle = start_helper(ifname,
707                                  ipv6addr,
708                                  ipv6prefix,
709                                  ipv4addr,
710                                  ipv4mask,
711                                  "exit-gnunet",
712                                  start_helper_and_schedule,
713                                  message_token,
714                                  NULL);
715
716     GNUNET_free(ipv6addr);
717     GNUNET_free(ipv6prefix);
718     GNUNET_free(ipv4addr);
719     GNUNET_free(ipv4mask);
720     GNUNET_free(ifname);
721 }
722
723 static void
724 prepare_ipv4_packet (ssize_t len, ssize_t pktlen, void *payload,
725                      uint16_t protocol, void *ipaddress, void *tunnel,
726                      struct redirect_state *state, struct ip_pkt *pkt4)
727 {
728   uint32_t tmp, tmp2;
729
730   pkt4->shdr.type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
731   pkt4->shdr.size = htons (len);
732   pkt4->tun.flags = 0;
733   pkt4->tun.type = htons (0x0800);
734
735   memcpy (&pkt4->data, payload, pktlen);
736
737   pkt4->ip_hdr.version = 4;
738   pkt4->ip_hdr.hdr_lngth = 5;
739   pkt4->ip_hdr.diff_serv = 0;
740   pkt4->ip_hdr.tot_lngth = htons (20 + pktlen);
741   pkt4->ip_hdr.ident = 0;
742   pkt4->ip_hdr.flags = 0;
743   pkt4->ip_hdr.frag_off = 0;
744   pkt4->ip_hdr.ttl = 255;
745   pkt4->ip_hdr.proto = protocol;
746   pkt4->ip_hdr.chks = 0;        /* Will be calculated later */
747
748   memcpy (&tmp, ipaddress, 4);
749   pkt4->ip_hdr.dadr = tmp;
750
751   /* Generate a new src-address */
752   char *ipv4addr;
753   char *ipv4mask;
754   GNUNET_assert (GNUNET_OK ==
755                  GNUNET_CONFIGURATION_get_value_string (cfg, "exit",
756                                                         "IPV4ADDR",
757                                                         &ipv4addr));
758   GNUNET_assert (GNUNET_OK ==
759                  GNUNET_CONFIGURATION_get_value_string (cfg, "exit",
760                                                         "IPV4MASK",
761                                                         &ipv4mask));
762   inet_pton (AF_INET, ipv4addr, &tmp);
763   inet_pton (AF_INET, ipv4mask, &tmp2);
764   GNUNET_free (ipv4addr);
765   GNUNET_free (ipv4mask);
766
767   /* This should be a noop */
768   tmp = tmp & tmp2;
769
770   tmp |= ntohl (*((uint32_t *) tunnel)) & (~tmp2);
771
772   pkt4->ip_hdr.sadr = tmp;
773
774   memcpy (&state->redirect_info.addr, &tmp, 4);
775   if (0x11 == protocol)
776     {
777       struct ip_udp* pkt4_udp = (struct ip_udp*)pkt4;
778       state->redirect_info.pt = pkt4_udp->udp_hdr.spt;
779
780       pkt4_udp->udp_hdr.crc = 0;        /* Optional for IPv4 */
781     }
782   else if (0x06 == protocol)
783     {
784       struct ip_tcp* pkt4_tcp = (struct ip_tcp*)pkt4;
785       state->redirect_info.pt = pkt4_tcp->tcp_hdr.spt;
786
787       pkt4_tcp->tcp_hdr.crc = 0;
788       uint32_t sum = 0;
789       tmp = pkt4->ip_hdr.sadr;
790       sum =
791         calculate_checksum_update (sum, (uint16_t *) & tmp, 4);
792       tmp = pkt4->ip_hdr.dadr;
793       sum =
794         calculate_checksum_update (sum, (uint16_t *) & tmp, 4);
795
796       tmp = (protocol << 16) | (0xffff & pktlen);
797
798       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "line: %08x, %x \n", tmp, (0xffff & pktlen));
799
800       tmp = htonl(tmp);
801
802       sum = calculate_checksum_update (sum, (uint16_t *) & tmp, 4);
803
804       sum =
805         calculate_checksum_update (sum, (uint16_t *) & pkt4_tcp->tcp_hdr, pktlen);
806       pkt4_tcp->tcp_hdr.crc = calculate_checksum_end (sum);
807     }
808
809   pkt4->ip_hdr.chks =
810     calculate_ip_checksum ((uint16_t *) & pkt4->ip_hdr, 5 * 4);
811 }
812
813 static void
814 prepare_ipv6_packet (ssize_t len, ssize_t pktlen, void *payload,
815                      uint16_t protocol, void *ipaddress, void *tunnel,
816                      struct redirect_state *state, struct ip6_pkt *pkt6)
817 {
818   uint32_t tmp;
819
820   pkt6->shdr.type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
821   pkt6->shdr.size = htons (len);
822   pkt6->tun.flags = 0;
823
824   pkt6->tun.type = htons (0x86dd);
825
826   memcpy (&pkt6->data, payload, pktlen);
827
828   pkt6->ip6_hdr.version = 6;
829   pkt6->ip6_hdr.nxthdr = protocol;
830   pkt6->ip6_hdr.paylgth = htons (pktlen);
831   pkt6->ip6_hdr.hoplmt = 64;
832
833   memcpy (pkt6->ip6_hdr.dadr, ipaddress, 16);
834
835   /* Generate a new src-address
836    * This takes as much from the address of the tunnel as fits into
837    * the host-mask*/
838   char *ipv6addr;
839   unsigned long long ipv6prefix;
840   GNUNET_assert (GNUNET_OK ==
841                  GNUNET_CONFIGURATION_get_value_string (cfg, "exit",
842                                                         "IPV6ADDR",
843                                                         &ipv6addr));
844   GNUNET_assert (GNUNET_OK ==
845                  GNUNET_CONFIGURATION_get_value_number (cfg, "exit",
846                                                         "IPV6PREFIX",
847                                                         &ipv6prefix));
848   GNUNET_assert (ipv6prefix < 127);
849   ipv6prefix = (ipv6prefix + 7) / 8;
850
851   inet_pton (AF_INET6, ipv6addr, &pkt6->ip6_hdr.sadr);
852   GNUNET_free (ipv6addr);
853
854   if (ipv6prefix < (16 - sizeof (void *)))
855     ipv6prefix = 16 - sizeof (void *);
856
857   unsigned int offset = ipv6prefix - (16 - sizeof (void *));
858   memcpy ((((char *) &pkt6->ip6_hdr.sadr)) + ipv6prefix,
859           ((char *) &tunnel) + offset, 16 - ipv6prefix);
860
861   /* copy the needed information into the state */
862   memcpy (&state->redirect_info.addr, &pkt6->ip6_hdr.sadr, 16);
863
864   if (0x11 == protocol)
865     {
866       struct ip6_udp* pkt6_udp = (struct ip6_udp*)pkt6;
867       state->redirect_info.pt = pkt6_udp->udp_hdr.spt;
868
869       pkt6_udp->udp_hdr.crc = 0;
870       uint32_t sum = 0;
871       sum =
872         calculate_checksum_update (sum, (uint16_t *) & pkt6_udp->ip6_hdr.sadr, 16);
873       sum =
874         calculate_checksum_update (sum, (uint16_t *) & pkt6_udp->ip6_hdr.dadr, 16);
875       tmp = (htons (pktlen) & 0xffff);
876       sum = calculate_checksum_update (sum, (uint16_t *) & tmp, 4);
877       tmp = htons (((pkt6_udp->ip6_hdr.nxthdr & 0x00ff)));
878       sum = calculate_checksum_update (sum, (uint16_t *) & tmp, 4);
879
880       sum =
881         calculate_checksum_update (sum, (uint16_t *) & pkt6_udp->udp_hdr,
882                                    ntohs (pkt6_udp->udp_hdr.len));
883       pkt6_udp->udp_hdr.crc = calculate_checksum_end (sum);
884     }
885   else if (0x06 == protocol)
886     {
887       struct ip6_tcp* pkt6_tcp = (struct ip6_tcp*)pkt6;
888       state->redirect_info.pt = pkt6_tcp->tcp_hdr.spt;
889
890       pkt6_tcp->tcp_hdr.crc = 0;
891       uint32_t sum = 0;
892       sum =
893         calculate_checksum_update (sum, (uint16_t *) & pkt6->ip6_hdr.sadr, 16);
894       sum =
895         calculate_checksum_update (sum, (uint16_t *) & pkt6->ip6_hdr.dadr, 16);
896       tmp = htonl(pktlen);
897       sum = calculate_checksum_update (sum, (uint16_t *) & tmp, 4);
898       tmp = htonl (((pkt6->ip6_hdr.nxthdr & 0x000000ff)));
899       sum = calculate_checksum_update (sum, (uint16_t *) & tmp, 4);
900
901       sum =
902         calculate_checksum_update (sum, (uint16_t *) & pkt6_tcp->tcp_hdr,
903                                    ntohs (pkt6->ip6_hdr.paylgth));
904       pkt6_tcp->tcp_hdr.crc = calculate_checksum_end (sum);
905     }
906 }
907
908 /**
909  * The messages are one GNUNET_HashCode for the service followed by a struct tcp_pkt
910  */
911 static int
912 receive_tcp_service (void *cls __attribute__((unused)),
913                      struct GNUNET_MESH_Tunnel *tunnel,
914                      void **tunnel_ctx __attribute__((unused)),
915                      const struct GNUNET_PeerIdentity *sender __attribute__((unused)),
916                      const struct GNUNET_MessageHeader *message,
917                      const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
918 {
919   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received TCP-Packet\n");
920   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
921   struct tcp_pkt *pkt = (struct tcp_pkt *) (desc + 1);
922   unsigned int pkt_len = ntohs (message->size) - sizeof (struct
923                                                          GNUNET_MessageHeader)
924     - sizeof (GNUNET_HashCode);
925
926   /** Get the configuration from the services-hashmap.
927    *
928    * Which service is needed only depends on the service-descriptor and the
929    * destination-port
930    */
931   uint16_t *tcp_desc = alloca (sizeof (GNUNET_HashCode) + 2);
932
933   memcpy (tcp_desc + 1, desc, sizeof (GNUNET_HashCode));
934   *tcp_desc = ntohs (pkt->dpt);
935   struct redirect_service *serv =
936     GNUNET_CONTAINER_multihashmap_get (tcp_services, (GNUNET_HashCode*)tcp_desc);
937   if (NULL == serv)
938     {
939       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
940                   "No service found for TCP dpt %d!\n", *tcp_desc);
941       return GNUNET_YES;
942     }
943
944   pkt->dpt = htons (serv->remote_port);
945
946   /*
947    * At this point it would be possible to check against some kind of ACL.
948    */
949
950   char *buf;
951   size_t len;
952
953   /* Prepare the state.
954    * This will be saved in the hashmap, so that the receiving procedure knows
955    * through which tunnel this connection has to be routed.
956    */
957   struct redirect_state *state =
958     GNUNET_malloc (sizeof (struct redirect_state));
959   memset (state, 0, sizeof (struct redirect_state));
960   state->tunnel = tunnel;
961   state->serv = serv;
962   state->type = SERVICE;
963   state->hashmap = tcp_connections;
964   memcpy (&state->desc, desc, sizeof (GNUNET_HashCode));
965
966   len = sizeof (struct GNUNET_MessageHeader) + sizeof (struct pkt_tun) +
967     sizeof (struct ip6_hdr) + pkt_len;
968   buf = alloca (len);
969
970   memset (buf, 0, len);
971
972   switch (serv->version)
973     {
974     case 4:
975       prepare_ipv4_packet (len, pkt_len, pkt, 0x06,     /* TCP */
976                            &serv->v4.ip4address,
977                            tunnel, state, (struct ip_pkt *) buf);
978       break;
979     case 6:
980       prepare_ipv6_packet (len, pkt_len, pkt, 0x06,     /* TCP */
981                            &serv->v6.ip6address,
982                            tunnel, state, (struct ip6_pkt *) buf);
983
984       break;
985     default:
986       GNUNET_assert (0);
987       break;
988     }
989
990   hash_redirect_info(&state->hash, &state->redirect_info, serv->version == 4 ? 4 : 16);
991
992   if (GNUNET_NO ==
993       GNUNET_CONTAINER_multihashmap_contains (tcp_connections, &state->hash))
994     {
995       GNUNET_CONTAINER_multihashmap_put (tcp_connections, &state->hash, state,
996                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
997
998       state->heap_node =
999         GNUNET_CONTAINER_heap_insert (tcp_connections_heap, state,
1000                                       GNUNET_TIME_absolute_get ().abs_value);
1001
1002       if (GNUNET_CONTAINER_heap_get_size(tcp_connections_heap) > max_tcp_connections)
1003         GNUNET_SCHEDULER_add_now(collect_connections, tcp_connections_heap);
1004     }
1005   else
1006     GNUNET_free (state);
1007
1008   (void) GNUNET_DISK_file_write (helper_handle->fh_to_helper, buf, len);
1009   return GNUNET_YES;
1010 }
1011
1012 static int
1013 receive_tcp_remote (void *cls __attribute__((unused)),
1014                      struct GNUNET_MESH_Tunnel *tunnel,
1015                      void **tunnel_ctx __attribute__((unused)),
1016                      const struct GNUNET_PeerIdentity *sender __attribute__((unused)),
1017                      const struct GNUNET_MessageHeader *message,
1018                      const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
1019 {
1020   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
1021   struct tcp_pkt *pkt = (struct tcp_pkt *) (desc + 1);
1022   struct remote_addr *s = (struct remote_addr *) desc;
1023   char *buf;
1024   size_t len;
1025   unsigned int pkt_len = ntohs (message->size) - sizeof (struct GNUNET_MessageHeader) - sizeof (GNUNET_HashCode);
1026
1027   struct redirect_state *state =
1028     GNUNET_malloc (sizeof (struct redirect_state));
1029   memset (state, 0, sizeof (struct redirect_state));
1030   state->tunnel = tunnel;
1031   state->type = REMOTE;
1032   state->hashmap = tcp_connections;
1033   memcpy (&state->remote, s, sizeof (struct remote_addr));
1034
1035   len = sizeof (struct GNUNET_MessageHeader) + sizeof (struct pkt_tun) +
1036     sizeof (struct ip6_hdr) + pkt_len;
1037   buf = alloca (len);
1038
1039   memset (buf, 0, len);
1040
1041   switch (s->addrlen)
1042     {
1043     case 4:
1044       prepare_ipv4_packet (len, pkt_len, pkt, 0x06,    /* TCP */
1045                            &s->addr, tunnel, state, (struct ip_pkt *) buf);
1046       break;
1047     case 16:
1048       prepare_ipv6_packet (len, pkt_len, pkt, 0x06,    /* TCP */
1049                            &s->addr, tunnel, state, (struct ip6_pkt *) buf);
1050       break;
1051     default:
1052       GNUNET_assert (0);
1053       break;
1054     }
1055
1056   hash_redirect_info (&state->hash, &state->redirect_info, s->addrlen);
1057
1058   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Packet from remote; hash is %x\n", *((uint32_t*)&state->hash));
1059
1060   if (GNUNET_NO ==
1061       GNUNET_CONTAINER_multihashmap_contains (tcp_connections, &state->hash))
1062     {
1063       GNUNET_CONTAINER_multihashmap_put (tcp_connections, &state->hash, state,
1064                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1065
1066       state->heap_node =
1067         GNUNET_CONTAINER_heap_insert (tcp_connections_heap, state,
1068                                       GNUNET_TIME_absolute_get ().abs_value);
1069
1070       if (GNUNET_CONTAINER_heap_get_size (tcp_connections_heap) >
1071           max_tcp_connections)
1072         GNUNET_SCHEDULER_add_now (collect_connections, tcp_connections_heap);
1073     }
1074   else
1075     GNUNET_free (state);
1076
1077   (void) GNUNET_DISK_file_write (helper_handle->fh_to_helper, buf, len);
1078   return GNUNET_YES;
1079
1080 }
1081
1082 static int
1083 receive_udp_remote (void *cls __attribute__((unused)),
1084                     struct GNUNET_MESH_Tunnel *tunnel,
1085                     void **tunnel_ctx __attribute__((unused)),
1086                     const struct GNUNET_PeerIdentity *sender __attribute__((unused)),
1087                     const struct GNUNET_MessageHeader *message,
1088                     const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
1089 {
1090   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
1091   struct udp_pkt *pkt = (struct udp_pkt *) (desc + 1);
1092   struct remote_addr *s = (struct remote_addr *) desc;
1093   char *buf;
1094   size_t len;
1095
1096   GNUNET_assert (ntohs (pkt->len) ==
1097                  ntohs (message->size) -
1098                  sizeof (struct GNUNET_MessageHeader) -
1099                  sizeof (GNUNET_HashCode));
1100
1101   /* Prepare the state.
1102    * This will be saved in the hashmap, so that the receiving procedure knows
1103    * through which tunnel this connection has to be routed.
1104    */
1105   struct redirect_state *state =
1106     GNUNET_malloc (sizeof (struct redirect_state));
1107   memset (state, 0, sizeof (struct redirect_state));
1108   state->tunnel = tunnel;
1109   state->hashmap = udp_connections;
1110   state->type = REMOTE;
1111   memcpy (&state->remote, s, sizeof (struct remote_addr));
1112
1113   len = sizeof (struct GNUNET_MessageHeader) + sizeof (struct pkt_tun) +
1114     sizeof (struct ip6_hdr) + ntohs (pkt->len);
1115   buf = alloca (len);
1116
1117   memset (buf, 0, len);
1118
1119   switch (s->addrlen)
1120     {
1121     case 4:
1122       prepare_ipv4_packet (len, ntohs (pkt->len), pkt, 0x11,    /* UDP */
1123                            &s->addr, tunnel, state, (struct ip_pkt *) buf);
1124       break;
1125     case 16:
1126       prepare_ipv6_packet (len, ntohs (pkt->len), pkt, 0x11,    /* UDP */
1127                            &s->addr, tunnel, state, (struct ip6_pkt *) buf);
1128       break;
1129     default:
1130       GNUNET_assert (0);
1131       break;
1132     }
1133
1134   hash_redirect_info (&state->hash, &state->redirect_info, s->addrlen);
1135
1136   if (GNUNET_NO ==
1137       GNUNET_CONTAINER_multihashmap_contains (udp_connections, &state->hash))
1138     {
1139       GNUNET_CONTAINER_multihashmap_put (udp_connections, &state->hash, state,
1140                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1141
1142       state->heap_node =
1143         GNUNET_CONTAINER_heap_insert (udp_connections_heap, state,
1144                                       GNUNET_TIME_absolute_get ().abs_value);
1145
1146       if (GNUNET_CONTAINER_heap_get_size (udp_connections_heap) >
1147           max_udp_connections)
1148         GNUNET_SCHEDULER_add_now (collect_connections, udp_connections_heap);
1149     }
1150   else
1151     GNUNET_free (state);
1152
1153   (void) GNUNET_DISK_file_write (helper_handle->fh_to_helper, buf, len);
1154   return GNUNET_YES;
1155 }
1156
1157 /**
1158  * The messages are one GNUNET_HashCode for the service, followed by a struct udp_pkt
1159  */
1160 static int
1161 receive_udp_service (void *cls __attribute__((unused)),
1162                      struct GNUNET_MESH_Tunnel *tunnel,
1163                      void **tunnel_ctx __attribute__((unused)),
1164                      const struct GNUNET_PeerIdentity *sender __attribute__((unused)),
1165                      const struct GNUNET_MessageHeader *message,
1166                      const struct GNUNET_TRANSPORT_ATS_Information *atsi __attribute__((unused)))
1167 {
1168   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
1169   struct udp_pkt *pkt = (struct udp_pkt *) (desc + 1);
1170
1171   GNUNET_assert (ntohs (pkt->len) ==
1172                  ntohs (message->size) -
1173                  sizeof (struct GNUNET_MessageHeader) -
1174                  sizeof (GNUNET_HashCode));
1175
1176   /* Get the configuration from the hashmap */
1177   uint16_t *udp_desc = alloca (sizeof (GNUNET_HashCode) + 2);
1178   memcpy (udp_desc + 1, desc, sizeof (GNUNET_HashCode));
1179   *udp_desc = ntohs (pkt->dpt);
1180   struct redirect_service *serv =
1181     GNUNET_CONTAINER_multihashmap_get (udp_services, (GNUNET_HashCode*)udp_desc);
1182   if (NULL == serv)
1183     {
1184       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1185                   "No service found for UDP dpt %d!\n", *udp_desc);
1186       return GNUNET_YES;
1187     }
1188
1189   pkt->dpt = htons (serv->remote_port);
1190
1191   /*
1192    * At this point it would be possible to check against some kind of ACL.
1193    */
1194
1195   char *buf;
1196   size_t len;
1197
1198   /* Prepare the state.
1199    * This will be saved in the hashmap, so that the receiving procedure knows
1200    * through which tunnel this connection has to be routed.
1201    */
1202   struct redirect_state *state =
1203     GNUNET_malloc (sizeof (struct redirect_state));
1204   memset (state, 0, sizeof (struct redirect_state));
1205   state->tunnel = tunnel;
1206   state->serv = serv;
1207   state->type = SERVICE;
1208   state->hashmap = udp_connections;
1209   memcpy (&state->desc, desc, sizeof (GNUNET_HashCode));
1210
1211   len = sizeof (struct GNUNET_MessageHeader) + sizeof (struct pkt_tun) +
1212     sizeof (struct ip6_hdr) + ntohs (pkt->len);
1213   buf = alloca (len);
1214
1215   memset (buf, 0, len);
1216
1217   switch (serv->version)
1218     {
1219     case 4:
1220       prepare_ipv4_packet (len, ntohs (pkt->len), pkt, 0x11,    /* UDP */
1221                            &serv->v4.ip4address,
1222                            tunnel, state, (struct ip_pkt *) buf);
1223       break;
1224     case 6:
1225       prepare_ipv6_packet (len, ntohs (pkt->len), pkt, 0x11,    /* UDP */
1226                            &serv->v6.ip6address,
1227                            tunnel, state, (struct ip6_pkt *) buf);
1228
1229       break;
1230     default:
1231       GNUNET_assert (0);
1232       break;
1233     }
1234
1235   hash_redirect_info(&state->hash, &state->redirect_info, serv->version == 4 ? 4 : 16);
1236
1237   if (GNUNET_NO ==
1238       GNUNET_CONTAINER_multihashmap_contains (udp_connections, &state->hash))
1239     {
1240       GNUNET_CONTAINER_multihashmap_put (udp_connections, &state->hash, state,
1241                                          GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1242
1243       state->heap_node =
1244         GNUNET_CONTAINER_heap_insert (udp_connections_heap, state,
1245                                       GNUNET_TIME_absolute_get ().abs_value);
1246
1247       if (GNUNET_CONTAINER_heap_get_size(udp_connections_heap) > max_udp_connections)
1248         GNUNET_SCHEDULER_add_now(collect_connections, udp_connections_heap);
1249     }
1250   else
1251     GNUNET_free (state);
1252
1253   (void) GNUNET_DISK_file_write (helper_handle->fh_to_helper, buf, len);
1254   return GNUNET_YES;
1255 }
1256
1257 static void
1258 connect_to_mesh()
1259 {
1260   int udp, tcp;
1261   int handler_idx, app_idx;
1262
1263   udp = GNUNET_CONFIGURATION_get_value_yesno(cfg, "exit", "ENABLE_UDP");
1264   tcp = GNUNET_CONFIGURATION_get_value_yesno(cfg, "exit", "ENABLE_TCP");
1265
1266   static struct GNUNET_MESH_MessageHandler handlers[] = {
1267     {receive_udp_service, GNUNET_MESSAGE_TYPE_SERVICE_UDP, 0},
1268     {receive_tcp_service, GNUNET_MESSAGE_TYPE_SERVICE_TCP, 0},
1269     {NULL, 0, 0},
1270     {NULL, 0, 0},
1271     {NULL, 0, 0}
1272   };
1273
1274   static GNUNET_MESH_ApplicationType apptypes[] =
1275     {
1276       GNUNET_APPLICATION_TYPE_END,
1277       GNUNET_APPLICATION_TYPE_END,
1278       GNUNET_APPLICATION_TYPE_END
1279     };
1280
1281   app_idx = 0;
1282   handler_idx = 2;
1283
1284   if (GNUNET_YES == udp)
1285     {
1286       handlers[handler_idx].callback = receive_udp_remote;
1287       handlers[handler_idx].expected_size = 0;
1288       handlers[handler_idx].type = GNUNET_MESSAGE_TYPE_REMOTE_UDP;
1289       apptypes[app_idx] = GNUNET_APPLICATION_TYPE_INTERNET_UDP_GATEWAY;
1290       handler_idx++;
1291       app_idx++;
1292     }
1293
1294   if (GNUNET_YES == tcp)
1295     {
1296       handlers[handler_idx].callback = receive_tcp_remote;
1297       handlers[handler_idx].expected_size = 0;
1298       handlers[handler_idx].type = GNUNET_MESSAGE_TYPE_REMOTE_TCP;
1299       apptypes[app_idx] = GNUNET_APPLICATION_TYPE_INTERNET_TCP_GATEWAY;
1300       handler_idx++;
1301       app_idx++;
1302     }
1303
1304   mesh_handle = GNUNET_MESH_connect (cfg, NULL, NULL, handlers, apptypes);
1305 }
1306
1307 /**
1308  * @brief Main function that will be run by the scheduler.
1309  *
1310  * @param cls closure
1311  * @param args remaining command-line arguments
1312  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1313  * @param cfg_ configuration
1314  */
1315 static void
1316 run (void *cls,
1317      char *const *args __attribute__((unused)),
1318      const char *cfgfile __attribute__((unused)), const struct GNUNET_CONFIGURATION_Handle *cfg_)
1319 {
1320   cfg = cfg_;
1321
1322   connect_to_mesh();
1323
1324   udp_connections = GNUNET_CONTAINER_multihashmap_create (65536);
1325   udp_connections_heap =
1326     GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1327   tcp_connections = GNUNET_CONTAINER_multihashmap_create (65536);
1328   tcp_connections_heap =
1329     GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
1330   udp_services = GNUNET_CONTAINER_multihashmap_create (65536);
1331   tcp_services = GNUNET_CONTAINER_multihashmap_create (65536);
1332
1333   GNUNET_CONFIGURATION_get_value_number (cfg, "exit", "MAX_UDP_CONNECTIONS",
1334                                          &max_udp_connections);
1335   GNUNET_CONFIGURATION_get_value_number (cfg, "exit", "MAX_TCP_CONNECTIONS",
1336                                          &max_tcp_connections);
1337
1338   GNUNET_CONFIGURATION_iterate_sections (cfg, read_service_conf, NULL);
1339
1340   GNUNET_SCHEDULER_add_now (start_helper_and_schedule, NULL);
1341   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls);
1342 }
1343
1344 /**
1345  * The main function to obtain template from gnunetd.
1346  *
1347  * @param argc number of arguments from the command line
1348  * @param argv command line arguments
1349  * @return 0 ok, 1 on error
1350  */
1351 int
1352 main (int argc, char *const *argv) {
1353     static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1354         GNUNET_GETOPT_OPTION_END
1355     };
1356
1357     return (GNUNET_OK ==
1358             GNUNET_PROGRAM_run (argc,
1359                                 argv,
1360                                 "exit",
1361                                 gettext_noop ("help text"),
1362                                 options, &run, NULL)) ? ret : 1;
1363 }
1364
1365 /* end of gnunet-daemon-exit.c */
1366