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