fix
[oweals/gnunet.git] / src / vpn / gnunet-daemon-vpn.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010 Christian Grothoff
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file vpn/gnunet-daemon-vpn.c
23  * @brief
24  * @author Philipp Toelke
25  */
26 #include "platform.h"
27 #include "gnunet_getopt_lib.h"
28 #include "gnunet_program_lib.h"
29 #include "gnunet-vpn-packet.h"
30 #include "gnunet-vpn-pretty-print.h"
31 #include "gnunet_common.h"
32 #include "gnunet_protocols.h"
33 #include <gnunet_mesh_service.h>
34 #include "gnunet_client_lib.h"
35 #include "gnunet_container_lib.h"
36 #include "gnunet_constants.h"
37 #include <block_dns.h>
38 #include "gnunet-daemon-vpn-helper.h"
39 #include "gnunet-daemon-vpn-dns.h"
40
41 #include "gnunet-daemon-vpn.h"
42
43 const struct GNUNET_CONFIGURATION_Handle *cfg;
44 struct GNUNET_MESH_Handle *mesh_handle;
45 struct GNUNET_CONTAINER_MultiHashMap* hashmap;
46
47 /**
48  * Final status code.
49  */
50 static int ret;
51
52 /**
53  * This hashmap contains the mapping from peer, service-descriptor,
54  * source-port and destination-port to a socket
55  */
56 static struct GNUNET_CONTAINER_MultiHashMap *udp_connections;
57
58 /**
59  * Function scheduled as very last function, cleans up after us
60  *{{{
61  */
62 static void
63 cleanup(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
64     GNUNET_assert (0 != (tskctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN));
65
66     /* stop the helper */
67     cleanup_helper(helper_handle);
68
69     /* close the connection to the service-dns */
70     if (dns_connection != NULL)
71       {
72         GNUNET_CLIENT_disconnect (dns_connection, GNUNET_NO);
73         dns_connection = NULL;
74       }
75
76     if (mesh_handle != NULL)
77       {
78         GNUNET_MESH_disconnect(mesh_handle);
79         mesh_handle = NULL;
80       }
81 }
82 /*}}}*/
83
84 static uint32_t calculate_checksum_update(uint32_t sum, uint16_t *hdr, short len) {
85     for(; len >= 2; len -= 2)
86       sum += *(hdr++);
87     if (len == 1)
88       sum += *((unsigned char*)hdr);
89     return sum;
90 }
91
92 static uint16_t calculate_checksum_end(uint32_t sum) {
93     while (sum >> 16)
94       sum = (sum >> 16) + (sum & 0xFFFF);
95
96     return ~sum;
97 }
98
99 /**
100  * Calculate the checksum of an IPv4-Header
101  */
102 uint16_t
103 calculate_ip_checksum(uint16_t* hdr, short len) {
104     uint32_t sum = calculate_checksum_update(0, hdr, len);
105     return calculate_checksum_end(sum);
106 }
107
108 /**
109  * @return the hash of the IP-Address if a mapping exists, NULL otherwise
110  */
111 GNUNET_HashCode*
112 address_mapping_exists(unsigned char addr[]) {
113     GNUNET_HashCode* key = GNUNET_malloc(sizeof(GNUNET_HashCode));
114     unsigned char* k = (unsigned char*)key;
115     memset(key, 0, sizeof(GNUNET_HashCode));
116     unsigned int i;
117     for (i = 0; i < 16; i++)
118         k[15-i] = addr[i];
119
120     if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(hashmap, key))
121       return key;
122     else
123       {
124         GNUNET_free(key);
125         return NULL;
126       }
127 }
128
129 void
130 send_icmp_response(void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc) {
131     struct ip6_icmp* request = cls;
132
133     struct ip6_icmp* response = alloca(ntohs(request->shdr.size));
134     GNUNET_assert(response != NULL);
135     memset(response, 0, ntohs(request->shdr.size));
136
137     response->shdr.size = request->shdr.size;
138     response->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
139
140     response->tun.flags = 0;
141     response->tun.type = htons(0x86dd);
142
143     response->ip6_hdr.hoplmt = 255;
144     response->ip6_hdr.paylgth = request->ip6_hdr.paylgth;
145     response->ip6_hdr.nxthdr = 0x3a;
146     response->ip6_hdr.version = 6;
147     memcpy(&response->ip6_hdr.sadr, &request->ip6_hdr.dadr, 16);
148     memcpy(&response->ip6_hdr.dadr, &request->ip6_hdr.sadr, 16);
149
150     response->icmp_hdr.code = 0;
151     response->icmp_hdr.type = 0x81;
152
153     /* Magic, more Magic! */
154     response->icmp_hdr.chks = request->icmp_hdr.chks - 0x1;
155
156     /* Copy the rest of the packet */
157     memcpy(response+1, request+1, ntohs(request->shdr.size) - sizeof(struct ip6_icmp));
158
159     write_to_helper(response, ntohs(response->shdr.size));
160
161     GNUNET_free(request);
162 }
163
164 /**
165  * cls is the pointer to a GNUNET_MessageHeader that is
166  * followed by the service-descriptor and the udp-packet that should be sent;
167  */
168 static size_t
169 send_udp_to_peer_notify_callback (void *cls, size_t size, void *buf)
170 {
171   struct GNUNET_MESH_Tunnel **tunnel = cls;
172   struct GNUNET_MessageHeader *hdr =
173     (struct GNUNET_MessageHeader *) (tunnel + 1);
174   GNUNET_HashCode *hc = (GNUNET_HashCode *) (hdr + 1);
175   struct udp_pkt *udp = (struct udp_pkt *) (hc + 1);
176   hdr->size = htons (sizeof (struct GNUNET_MessageHeader) +
177                      sizeof (GNUNET_HashCode) + ntohs (udp->len));
178   hdr->type = ntohs (GNUNET_MESSAGE_TYPE_SERVICE_UDP);
179   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "send_udp_to_peer_notify_callback: buf = %x; size = %u;\n", buf, size);
180   GNUNET_assert (size >= ntohs (hdr->size));
181   memcpy (buf, hdr, ntohs (hdr->size));
182   size = ntohs(hdr->size);
183   GNUNET_free (cls);
184   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sent!\n");
185   return size;
186 }
187
188 unsigned int
189 port_in_ports (uint64_t ports, uint16_t port)
190 {
191   uint16_t *ps = (uint16_t *) & ports;
192   return ps[0] == port || ps[1] == port || ps[2] == port || ps[3] == port;
193 }
194
195 void
196 send_udp_to_peer (void *cls, 
197                   const struct GNUNET_PeerIdentity *peer,
198                   const struct GNUNET_TRANSPORT_ATS_Information *atsi)
199 {
200   if (peer == NULL) return;
201   struct GNUNET_MESH_Tunnel **tunnel = cls;
202   struct GNUNET_MessageHeader *hdr =
203     (struct GNUNET_MessageHeader *) (tunnel + 1);
204   GNUNET_HashCode *hc = (GNUNET_HashCode *) (hdr + 1);
205   struct udp_pkt *udp = (struct udp_pkt *) (hc + 1);
206   GNUNET_MESH_notify_transmit_ready (*tunnel,
207                                      GNUNET_NO,
208                                      42,
209                                      GNUNET_TIME_relative_divide(GNUNET_CONSTANTS_MAX_CORK_DELAY, 2),
210                                      htons (sizeof
211                                             (struct GNUNET_MessageHeader) +
212                                             sizeof (GNUNET_HashCode) +
213                                             ntohs (udp->len)),
214                                      send_udp_to_peer_notify_callback,
215                                      cls);
216 }
217
218 /**
219  * Create a new Address from an answer-packet
220  */
221 void
222 new_ip6addr(unsigned char* buf, const GNUNET_HashCode *peer, const GNUNET_HashCode *service_desc) { /* {{{ */
223     char* ipv6addr;
224     unsigned long long ipv6prefix;
225     GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "vpn", "IPV6ADDR", &ipv6addr));
226     GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "vpn", "IPV6PREFIX", &ipv6prefix));
227     GNUNET_assert(ipv6prefix < 127);
228     ipv6prefix = (ipv6prefix + 7)/8;
229
230     inet_pton (AF_INET6, ipv6addr, buf);
231     GNUNET_free(ipv6addr);
232
233     int peer_length = 16 - ipv6prefix - 6;
234     if (peer_length <= 0)
235       peer_length = 0;
236
237     int service_length = 16 - ipv6prefix - peer_length;
238     if (service_length <= 0)
239       service_length = 0;
240
241     memcpy(buf+ipv6prefix, service_desc, service_length);
242     memcpy(buf+ipv6prefix+service_length, peer, peer_length);
243 }
244 /*}}}*/
245
246 /**
247  * This gets scheduled with cls pointing to an answer_packet and does everything
248  * needed in order to send it to the helper.
249  *
250  * At the moment this means "inventing" and IPv6-Address for .gnunet-services and
251  * doing nothing for "real" services.
252  */
253 void
254 process_answer(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tc) {
255     struct answer_packet* pkt = cls;
256     struct answer_packet_list* list;
257
258     /* This answer is about a .gnunet-service
259      *
260      * It contains an almost complete DNS-Response, we have to fill in the ip
261      * at the offset pkt->addroffset
262      */
263     //FIXME htons?
264     if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_SERVICE)
265       {
266         pkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
267
268         GNUNET_HashCode key;
269         memset(&key, 0, sizeof(GNUNET_HashCode));
270
271         unsigned char* c = ((unsigned char*)pkt)+ntohs(pkt->addroffset);
272         unsigned char* k = (unsigned char*)&key;
273         new_ip6addr(c, &pkt->service_descr.peer, &pkt->service_descr.service_descriptor);
274         /*
275          * Copy the newly generated ip-address to the key backwarts (as only the first part is hashed)
276          */
277         unsigned int i;
278         for (i = 0; i < 16; i++)
279             k[15-i] = c[i];
280
281         uint16_t namelen = strlen((char*)pkt->data+12)+1;
282
283         struct map_entry* value = GNUNET_malloc(sizeof(struct map_entry) + namelen);
284         char* name = (char*)(value +1);
285
286         value->namelen = namelen;
287         memcpy(name, pkt->data+12, namelen);
288
289         memcpy(&value->desc, &pkt->service_descr, sizeof(struct GNUNET_vpn_service_descriptor));
290
291         value->additional_ports = 0;
292
293         if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put(hashmap,
294                                                            &key,
295                                                            value,
296                                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
297           {
298             GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not store to hashmap\n");
299           }
300
301
302         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
303
304         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
305
306       }
307     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_REV)
308       {
309         GNUNET_HashCode key;
310         memset(&key, 0, sizeof key);
311         unsigned char* k = (unsigned char*)&key;
312         unsigned char* s = pkt->data+12;
313         int i = 0;
314         /* Whoever designed the reverse IPv6-lookup is batshit insane */
315         for (i = 0; i < 16; i++)
316           {
317             unsigned char c1 = s[(4*i)+1];
318             unsigned char c2 = s[(4*i)+3];
319             if (c1 <= '9')
320               k[i] = c1 - '0';
321             else
322               k[i] = c1 - 87; /* 87 is the difference between 'a' and 10 */
323             if (c2 <= '9')
324               k[i] += 16*(c2 - '0');
325             else
326               k[i] += 16*(c2 - 87);
327           }
328
329         struct map_entry* map_entry = GNUNET_CONTAINER_multihashmap_get(hashmap, &key);
330         uint16_t offset = ntohs(pkt->addroffset);
331
332         if (map_entry == NULL)
333           {
334             GNUNET_free(pkt);
335             return;
336           }
337
338         unsigned short namelen = htons(map_entry->namelen);
339         char* name = (char*)(map_entry + 1);
340
341         list = GNUNET_malloc(2*sizeof(struct answer_packet_list*) + offset + 2 + ntohs(namelen));
342
343         struct answer_packet* rpkt = &list->pkt;
344
345         /* The offset points to the first byte belonging to the address */
346         memcpy(rpkt, pkt, offset - 1);
347
348         rpkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
349         rpkt->hdr.size = ntohs(offset + 2 + ntohs(namelen));
350
351         memcpy(((char*)rpkt)+offset, &namelen, 2);
352         memcpy(((char*)rpkt)+offset+2, name, ntohs(namelen));
353
354       }
355     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_IP)
356       {
357         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
358         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
359       }
360     else
361       {
362         GNUNET_break(0);
363         GNUNET_free(pkt);
364         return;
365       }
366
367     GNUNET_free(pkt);
368
369     GNUNET_CONTAINER_DLL_insert_after(answer_proc_head, answer_proc_tail, answer_proc_tail, list);
370
371     schedule_helper_write(GNUNET_TIME_UNIT_FOREVER_REL, NULL);
372
373     return;
374 }
375
376 static void
377 add_additional_port (struct map_entry *me, uint16_t port)
378 {
379   uint16_t *ps = (uint16_t *) & me->additional_ports;
380   unsigned int i;
381   for (i = 0; i < 4; i++)
382     {
383       if (ps[i] == 0)
384         {
385           ps[i] = port;
386           break;
387         }
388     }
389 }
390
391 static int
392 receive_udp_back (void *cls, struct GNUNET_MESH_Tunnel* tunnel,
393                   void **tunnel_ctx,
394                   const struct GNUNET_MessageHeader *message,
395                   const struct GNUNET_TRANSPORT_ATS_Information *atsi)
396 {
397   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
398   struct udp_pkt *pkt = (struct udp_pkt *) (desc + 1);
399   const struct GNUNET_PeerIdentity* other = GNUNET_MESH_get_peer(tunnel);
400
401   size_t size = sizeof(struct ip6_udp) + ntohs(pkt->len) - 1 - sizeof(struct udp_pkt);
402
403   struct ip6_udp* pkt6 = alloca(size);
404
405   GNUNET_assert(pkt6 != NULL);
406
407   new_ip6addr(pkt6->ip6_hdr.sadr, &other->hashPubKey, desc);
408
409   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Relaying calc:%d gnu:%d udp:%d bytes!\n", size, ntohs(message->size), ntohs(pkt->len));
410
411   pkt6->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
412   pkt6->shdr.size = htons(size);
413
414   pkt6->tun.flags = 0;
415   pkt6->tun.type = htons(0x86dd);
416
417   pkt6->ip6_hdr.version = 6;
418   pkt6->ip6_hdr.tclass_h = 0;
419   pkt6->ip6_hdr.tclass_l = 0;
420   pkt6->ip6_hdr.flowlbl = 0;
421   pkt6->ip6_hdr.paylgth = pkt->len;
422   pkt6->ip6_hdr.nxthdr = 0x11;
423   pkt6->ip6_hdr.hoplmt = 0xff;
424
425   {
426     char* ipv6addr;
427     GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "vpn", "IPV6ADDR", &ipv6addr));
428     inet_pton (AF_INET6, ipv6addr, pkt6->ip6_hdr.dadr);
429     GNUNET_free(ipv6addr);
430   }
431   memcpy(&pkt6->udp_hdr, pkt, ntohs(pkt->len));
432
433   GNUNET_HashCode* key = address_mapping_exists(pkt6->ip6_hdr.sadr);
434   GNUNET_assert (key != NULL);
435
436   struct map_entry *me = GNUNET_CONTAINER_multihashmap_get(hashmap, key);
437
438   GNUNET_free(key);
439
440   GNUNET_assert (me != NULL);
441   GNUNET_assert (me->desc.service_type & htonl(GNUNET_DNS_SERVICE_TYPE_UDP));
442   if (!port_in_ports(me->desc.ports, pkt6->udp_hdr.spt) ||
443       !port_in_ports(me->additional_ports, pkt6->udp_hdr.spt)) {
444       add_additional_port(me, pkt6->udp_hdr.spt);
445   }
446
447   pkt6->udp_hdr.crc = 0;
448   uint32_t sum = 0;
449   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->ip6_hdr.sadr, 16);
450   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->ip6_hdr.dadr, 16);
451   uint32_t tmp = (pkt6->udp_hdr.len & 0xffff);
452   sum = calculate_checksum_update(sum, (uint16_t*)&tmp, 4);
453   tmp = htons(((pkt6->ip6_hdr.nxthdr & 0x00ff)));
454   sum = calculate_checksum_update(sum, (uint16_t*)&tmp, 4);
455
456   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->udp_hdr, ntohs(pkt->len));
457   pkt6->udp_hdr.crc = calculate_checksum_end(sum);
458
459   write_to_helper(pkt6, size);
460
461   return GNUNET_OK;
462 }
463
464 void init_mesh (void* cls, struct GNUNET_MESH_Handle* server, const struct GNUNET_PeerIdentity* my_identity, const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pubkey) {
465   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connected to MESH, I am %x\n", *((unsigned long*)my_identity));
466 }
467
468 void connect_mesh (void* cls, const struct GNUNET_PeerIdentity* peer, const struct GNUNET_TRANSPORT_ATS_Information *atsi) {
469   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connected to peer %x\n", *((unsigned long*)peer));
470 }
471
472 /**
473  * Main function that will be run by the scheduler.
474  *
475  * @param cls closure
476  * @param args remaining command-line arguments
477  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
478  * @param cfg_ configuration
479  */
480 static void
481 run (void *cls,
482      char *const *args,
483      const char *cfgfile,
484      const struct GNUNET_CONFIGURATION_Handle *cfg_)
485 {
486     const static struct GNUNET_MESH_MessageHandler handlers[] = {
487           {receive_udp_back, GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK, 0},
488           {NULL, 0, 0}
489     };
490     mesh_handle = GNUNET_MESH_connect(cfg_,
491                                       NULL,
492                                       NULL,
493                                       handlers);
494     cfg = cfg_;
495     restart_hijack = 0;
496     hashmap = GNUNET_CONTAINER_multihashmap_create(65536);
497     udp_connections = GNUNET_CONTAINER_multihashmap_create(65536);
498     GNUNET_SCHEDULER_add_now (connect_to_service_dns, NULL);
499     GNUNET_SCHEDULER_add_now (start_helper_and_schedule, NULL);
500     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls);
501 }
502
503 /**
504  * The main function to obtain template from gnunetd.
505  *
506  * @param argc number of arguments from the command line
507  * @param argv command line arguments
508  * @return 0 ok, 1 on error
509  */
510 int
511 main (int argc, char *const *argv) {
512     static const struct GNUNET_GETOPT_CommandLineOption options[] = {
513         GNUNET_GETOPT_OPTION_END
514     };
515
516     return (GNUNET_OK ==
517             GNUNET_PROGRAM_run (argc,
518                                 argv,
519                                 "gnunet-daemon-vpn",
520                                 gettext_noop ("help text"),
521                                 options, &run, NULL)) ? ret : 1;
522 }
523
524 /* end of gnunet-daemon-vpn.c */
525