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