Send the UDP traffic out over a socket and relay the answers back to the
[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_os_lib.h"
30 #include "gnunet-vpn-helper-p.h"
31 #include "gnunet-vpn-packet.h"
32 #include "gnunet-vpn-pretty-print.h"
33 #include "gnunet_common.h"
34 #include "gnunet_protocols.h"
35 #include "gnunet_server_lib.h"
36 #include "gnunet-service-dns-p.h"
37 #include "gnunet_core_service.h"
38 #include "gnunet_client_lib.h"
39 #include "gnunet_container_lib.h"
40 #include "block_dns.h"
41
42 /**
43  * Final status code.
44  */
45 static int ret;
46
47 /**
48  * The configuration to use
49  */
50 static const struct GNUNET_CONFIGURATION_Handle *cfg;
51
52 /**
53  * PipeHandle to receive data from the helper
54  */
55 static struct GNUNET_DISK_PipeHandle* helper_in;
56
57 /**
58  * PipeHandle to send data to the helper
59  */
60 static struct GNUNET_DISK_PipeHandle* helper_out;
61
62 /**
63  * FileHandle to receive data from the helper
64  */
65 static const struct GNUNET_DISK_FileHandle* fh_from_helper;
66
67 /**
68  * FileHandle to send data to the helper
69  */
70 static const struct GNUNET_DISK_FileHandle* fh_to_helper;
71
72 /**
73  * The Message-Tokenizer that tokenizes the messages comming from the helper
74  */
75 static struct GNUNET_SERVER_MessageStreamTokenizer* mst;
76
77 /**
78  * The connection to the service-dns
79  */
80 static struct GNUNET_CLIENT_Connection *dns_connection;
81
82 /**
83  * A flag to show that the service-dns has to rehijack the outbound dns-packets
84  *
85  * This gets set when the helper restarts as the routing-tables are flushed when
86  * the interface vanishes.
87  */
88 static unsigned char restart_hijack;
89
90 /**
91  * The process id of the helper
92  */
93 static struct GNUNET_OS_Process *helper_proc;
94
95 /**
96  * a list of outgoing dns-query-packets
97  */
98 static struct query_packet_list *head;
99
100 /**
101  * The last element of the list of outgoing dns-query-packets
102  */
103 static struct query_packet_list *tail;
104
105 /**
106  * A list of processed dns-responses.
107  *
108  * "processed" means that the packet is complete and can be sent out via udp
109  * directly
110  */
111 static struct answer_packet_list *answer_proc_head;
112
113 /**
114  * The last element of the list of processed dns-responses.
115  */
116 static struct answer_packet_list *answer_proc_tail;
117
118 /**
119  * The hashmap containing the mappings from ipv6-addresses to gnunet-descriptors
120  */
121 static struct GNUNET_CONTAINER_MultiHashMap* hashmap;
122
123 /**
124  * This hashmap contains the mapping from peer, service-descriptor,
125  * source-port and destination-port to a socket
126  */
127 static struct GNUNET_CONTAINER_MultiHashMap *udp_connections;
128
129 /**
130  * The handle to core
131  */
132 static struct GNUNET_CORE_Handle *core_handle;
133
134 struct map_entry {
135     struct GNUNET_vpn_service_descriptor desc;
136     uint16_t namelen;
137     /**
138      * In DNS-Format!
139      */
140     char name[1];
141 };
142
143 static void helper_read(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx);
144 static void dns_answer_handler(void* cls, const struct GNUNET_MessageHeader *msg);
145
146 /**
147  * Callback called by notify_transmit_ready; sends dns-queries or rehijack-messages
148  * to the service-dns
149  * {{{
150  */
151 static size_t
152 send_query(void* cls, size_t size, void* buf) {
153     size_t len;
154     /*
155      * Send the rehijack-message
156      */
157     if (restart_hijack == 1)
158       {
159         restart_hijack = 0;
160         /*
161          * The message is just a header
162          */
163         GNUNET_assert(sizeof(struct GNUNET_MessageHeader) <= size);
164         struct GNUNET_MessageHeader* hdr = buf;
165         len = sizeof(struct GNUNET_MessageHeader);
166         hdr->size = htons(len);
167         hdr->type = htons(GNUNET_MESSAGE_TYPE_REHIJACK);
168       }
169     else
170       {
171         struct query_packet_list* query = head;
172         len = ntohs(query->pkt.hdr.size);
173
174         GNUNET_assert(len <= size);
175
176         memcpy(buf, &query->pkt.hdr, len);
177
178         GNUNET_CONTAINER_DLL_remove (head, tail, query);
179
180         GNUNET_free(query);
181       }
182
183     /*
184      * Check whether more data is to be sent
185      */
186     if (head != NULL)
187       {
188         GNUNET_CLIENT_notify_transmit_ready(dns_connection, ntohs(head->pkt.hdr.size), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
189       }
190     else if (restart_hijack == 1)
191       {
192         GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
193       }
194
195     return len;
196 }
197 /* }}} */
198
199 /**
200  * Function scheduled as very last function, cleans up after us
201  *{{{
202  */
203 static void
204 cleanup(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
205     GNUNET_assert (0 != (tskctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN));
206
207     /* stop the helper */
208     if (helper_proc != NULL)
209       {
210         GNUNET_OS_process_kill (helper_proc, SIGTERM);
211         GNUNET_OS_process_wait (helper_proc);
212         GNUNET_OS_process_close (helper_proc);
213         helper_proc = NULL;
214       }
215
216     /* close the connection to the service-dns */
217     if (dns_connection != NULL)
218       {
219         GNUNET_CLIENT_disconnect (dns_connection, GNUNET_NO);
220         dns_connection = NULL;
221       }
222
223     if (core_handle != NULL)
224       {
225         GNUNET_CORE_disconnect(core_handle);
226         core_handle = NULL;
227       }
228 }
229 /*}}}*/
230
231 /**
232  * Start the helper-process
233  * {{{
234  */
235 static void
236 start_helper_and_schedule(void *cls,
237                           const struct GNUNET_SCHEDULER_TaskContext *tc) {
238     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
239       return;
240
241     helper_in = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO);
242     helper_out = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
243
244     if (helper_in == NULL || helper_out == NULL) return;
245
246     helper_proc = GNUNET_OS_start_process(helper_in, helper_out, "gnunet-helper-vpn", "gnunet-helper-vpn", NULL);
247
248     fh_from_helper = GNUNET_DISK_pipe_handle (helper_out, GNUNET_DISK_PIPE_END_READ);
249     fh_to_helper = GNUNET_DISK_pipe_handle (helper_in, GNUNET_DISK_PIPE_END_WRITE);
250
251     GNUNET_DISK_pipe_close_end(helper_out, GNUNET_DISK_PIPE_END_WRITE);
252     GNUNET_DISK_pipe_close_end(helper_in, GNUNET_DISK_PIPE_END_READ);
253
254     /* Tell the dns-service to rehijack the dns-port
255      * The routing-table gets flushed if an interface disappears.
256      */
257     restart_hijack = 1;
258     GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
259
260     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, fh_from_helper, &helper_read, NULL);
261 }
262 /*}}}*/
263
264 /**
265  * Restart the helper-process
266  * {{{
267  */
268 static void
269 restart_helper(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
270     // Kill the helper
271     GNUNET_OS_process_kill (helper_proc, SIGKILL);
272     GNUNET_OS_process_wait (helper_proc);
273     GNUNET_OS_process_close (helper_proc);
274     helper_proc = NULL;
275
276     GNUNET_DISK_pipe_close(helper_in);
277     GNUNET_DISK_pipe_close(helper_out);
278
279     /* Restart the helper */
280     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, start_helper_and_schedule, NULL);
281 }
282 /*}}}*/
283
284 /**
285  * Read from the helper-process
286  * {{{
287  */
288 static void
289 helper_read(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx) {
290     /* no message can be bigger then 64k */
291     char buf[65535];
292
293     if (tsdkctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
294       return;
295
296     int t = GNUNET_DISK_file_read(fh_from_helper, &buf, 65535);
297
298     /* On read-error, restart the helper */
299     if (t<=0) {
300         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Read error for header from vpn-helper: %m\n");
301         GNUNET_SCHEDULER_add_now(restart_helper, cls);
302         return;
303     }
304
305     /* FIXME */ GNUNET_SERVER_mst_receive(mst, NULL, buf, t, 0, 0);
306
307     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, fh_from_helper, &helper_read, NULL);
308 }
309 /*}}}*/
310
311 static uint32_t calculate_checksum_update(uint32_t sum, uint16_t *hdr, short len) {
312     for(; len >= 2; len -= 2)
313       sum += *(hdr++);
314     if (len == 1)
315       sum += *((unsigned char*)hdr);
316     return sum;
317 }
318
319 static uint16_t calculate_checksum_end(uint32_t sum) {
320     while (sum >> 16)
321       sum = (sum >> 16) + (sum & 0xFFFF);
322
323     return ~sum;
324 }
325
326 /**
327  * Calculate the checksum of an IPv4-Header
328  */
329 static uint16_t
330 calculate_ip_checksum(uint16_t* hdr, short len) {
331     uint32_t sum = calculate_checksum_update(0, hdr, len);
332     return calculate_checksum_end(sum);
333 }
334
335 /**
336  * Send an dns-answer-packet to the helper
337  */
338 static void
339 helper_write(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx) {
340     if (tsdkctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
341       return;
342
343     struct answer_packet_list* ans = answer_proc_head;
344     size_t len = ntohs(ans->pkt.hdr.size);
345
346     GNUNET_assert(ans->pkt.subtype == GNUNET_DNS_ANSWER_TYPE_IP);
347
348     GNUNET_assert (20 == sizeof (struct ip_hdr));
349     GNUNET_assert (8 == sizeof (struct udp_pkt));
350     size_t data_len = len - sizeof(struct answer_packet) + 1;
351     size_t net_len = sizeof(struct ip_hdr) + sizeof(struct udp_dns) + data_len;
352     size_t pkt_len = sizeof(struct GNUNET_MessageHeader) + sizeof(struct pkt_tun) + net_len;
353
354     struct ip_udp_dns* pkt = alloca(pkt_len);
355     memset(pkt, 0, pkt_len);
356
357     /* set the gnunet-header */
358     pkt->shdr.size = htons(pkt_len);
359     pkt->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
360
361     /* set the tun-header (no flags and ethertype of IPv4) */
362     pkt->tun.flags = 0;
363     pkt->tun.type = htons(0x0800);
364
365     /* set the ip-header */
366     pkt->ip_hdr.version = 4;
367     pkt->ip_hdr.hdr_lngth = 5;
368     pkt->ip_hdr.diff_serv = 0;
369     pkt->ip_hdr.tot_lngth = htons(net_len);
370     pkt->ip_hdr.ident = 0;
371     pkt->ip_hdr.flags = 0;
372     pkt->ip_hdr.frag_off = 0;
373     pkt->ip_hdr.ttl = 255;
374     pkt->ip_hdr.proto = 0x11; /* UDP */
375     pkt->ip_hdr.chks = 0; /* Will be calculated later*/
376     pkt->ip_hdr.sadr = ans->pkt.from;
377     pkt->ip_hdr.dadr = ans->pkt.to;
378
379     pkt->ip_hdr.chks = calculate_ip_checksum((uint16_t*)&pkt->ip_hdr, 5*4);
380
381     /* set the udp-header */
382     pkt->udp_dns.udp_hdr.spt = htons(53);
383     pkt->udp_dns.udp_hdr.dpt = ans->pkt.dst_port;
384     pkt->udp_dns.udp_hdr.len = htons(net_len - sizeof(struct ip_hdr));
385     pkt->udp_dns.udp_hdr.crc = 0; /* Optional for IPv4 */
386
387     memcpy(&pkt->udp_dns.data, ans->pkt.data, data_len);
388
389     GNUNET_CONTAINER_DLL_remove (answer_proc_head, answer_proc_tail, ans);
390     GNUNET_free(ans);
391
392     /* FIXME */ GNUNET_DISK_file_write(fh_to_helper, pkt, pkt_len);
393
394     /* if more packets are available, reschedule */
395     if (answer_proc_head != NULL)
396       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
397                                        fh_to_helper,
398                                        &helper_write,
399                                        NULL);
400 }
401
402 /**
403  * @return the hash of the IP-Address if a mapping exists, NULL otherwise
404  */
405 static GNUNET_HashCode*
406 address_mapping_exists(unsigned char addr[]) {
407     GNUNET_HashCode* key = GNUNET_malloc(sizeof(GNUNET_HashCode));
408     unsigned char* k = (unsigned char*)key;
409     memset(key, 0, sizeof(GNUNET_HashCode));
410     unsigned int i;
411     for (i = 0; i < 16; i++)
412         k[15-i] = addr[i];
413
414     if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(hashmap, key))
415       return key;
416     else
417       {
418         GNUNET_free(key);
419         return NULL;
420       }
421 }
422
423 static void
424 send_icmp_response(void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc) {
425     struct ip6_icmp* request = cls;
426
427     struct ip6_icmp* response = alloca(ntohs(request->shdr.size));
428     memset(response, 0, ntohs(request->shdr.size));
429
430     response->shdr.size = request->shdr.size;
431     response->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
432
433     response->tun.flags = 0;
434     response->tun.type = htons(0x86dd);
435
436     response->ip6_hdr.hoplmt = 255;
437     response->ip6_hdr.paylgth = request->ip6_hdr.paylgth;
438     response->ip6_hdr.nxthdr = 0x3a;
439     response->ip6_hdr.version = 6;
440     memcpy(&response->ip6_hdr.sadr, &request->ip6_hdr.dadr, 16);
441     memcpy(&response->ip6_hdr.dadr, &request->ip6_hdr.sadr, 16);
442
443     response->icmp_hdr.code = 0;
444     response->icmp_hdr.type = 0x81;
445
446     /* Magic, more Magic! */
447     response->icmp_hdr.chks = request->icmp_hdr.chks - 0x1;
448
449     /* Copy the rest of the packet */
450     memcpy(response+1, request+1, ntohs(request->shdr.size) - sizeof(struct ip6_icmp));
451
452     /* FIXME */ GNUNET_DISK_file_write(fh_to_helper, response, ntohs(response->shdr.size));
453
454     GNUNET_free(request);
455 }
456
457 /**
458  * cls is the pointer to a GNUNET_MessageHeader that is
459  * followed by the service-descriptor and the udp-packet that should be sent;
460  */
461 static size_t
462 handle_udp (void *cls, size_t size, void *buf)
463 {
464   struct GNUNET_PeerIdentity *peer = cls;
465   struct GNUNET_MessageHeader *hdr =
466     (struct GNUNET_MessageHeader *) (peer + 1);
467   GNUNET_HashCode *hc = (GNUNET_HashCode *) (hdr + 1);
468   struct udp_pkt *udp = (struct udp_pkt *) (hc + 1);
469   hdr->size = htons (sizeof (struct GNUNET_MessageHeader) +
470                      sizeof (GNUNET_HashCode) + ntohs (udp->len));
471   hdr->type = ntohs (GNUNET_MESSAGE_TYPE_SERVICE_UDP);
472   GNUNET_assert (size >= ntohs (hdr->size));
473   memcpy (buf, hdr, ntohs (hdr->size));
474   size = ntohs(hdr->size);
475   GNUNET_free (cls);
476   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sent!\n");
477   return size;
478 }
479
480 static unsigned int
481 port_in_ports (uint64_t ports, uint16_t port)
482 {
483   uint16_t *ps = (uint16_t *) & ports;
484   return ps[0] == port || ps[1] == port || ps[2] == port || ps[3] == port;
485 }
486
487 void
488 send_udp (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
489 {
490   struct GNUNET_PeerIdentity *peer = cls;
491   struct GNUNET_MessageHeader *hdr =
492     (struct GNUNET_MessageHeader *) (peer + 1);
493   GNUNET_HashCode *hc = (GNUNET_HashCode *) (hdr + 1);
494   struct udp_pkt *udp = (struct udp_pkt *) (hc + 1);
495   GNUNET_CORE_notify_transmit_ready (core_handle,
496                                      42,
497                                      GNUNET_TIME_UNIT_FOREVER_REL,
498                                      peer,
499                                      htons (sizeof
500                                             (struct GNUNET_MessageHeader) +
501                                             sizeof (GNUNET_HashCode) +
502                                             ntohs (udp->len)), handle_udp,
503                                      cls);
504 }
505
506 /**
507  * Receive packets from the helper-process
508  */
509 static void
510 message_token(void *cls,
511               void *client,
512               const struct GNUNET_MessageHeader *message) {
513     GNUNET_assert(ntohs(message->type) == GNUNET_MESSAGE_TYPE_VPN_HELPER);
514
515     struct tun_pkt *pkt_tun = (struct tun_pkt*) message;
516
517     /* ethertype is ipv6 */
518     if (ntohs(pkt_tun->tun.type) == 0x86dd)
519       {
520         struct ip6_pkt *pkt6 = (struct ip6_pkt*) message;
521         GNUNET_assert(pkt6->ip6_hdr.version == 6);
522         struct ip6_tcp *pkt6_tcp;
523         struct ip6_udp *pkt6_udp;
524         struct ip6_icmp *pkt6_icmp;
525         GNUNET_HashCode* key;
526
527         pkt_printf(pkt6);
528         switch(pkt6->ip6_hdr.nxthdr)
529           {
530           case 0x06:
531             pkt6_tcp = (struct ip6_tcp*)pkt6;
532             pkt_printf_ip6tcp(pkt6_tcp);
533             break;
534           case 0x11:
535             pkt6_udp = (struct ip6_udp*)pkt6;
536             if ((key = address_mapping_exists(pkt6->ip6_hdr.dadr)) != NULL)
537               {
538                 struct map_entry* me = GNUNET_CONTAINER_multihashmap_get(hashmap, key);
539                 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Mapping exists; type: %d; UDP is %d; port: %x/%x!\n", me->desc.service_type, htonl(GNUNET_DNS_SERVICE_TYPE_UDP), pkt6_udp->udp_hdr.dpt, me->desc.ports);
540                 GNUNET_free(key);
541                 if (me->desc.service_type & htonl(GNUNET_DNS_SERVICE_TYPE_UDP) &&
542                     port_in_ports(me->desc.ports, pkt6_udp->udp_hdr.dpt))
543                   {
544                     size_t size = sizeof(struct GNUNET_PeerIdentity) + sizeof(struct GNUNET_MessageHeader) + sizeof(GNUNET_HashCode) + ntohs(pkt6_udp->udp_hdr.len);
545                     struct GNUNET_PeerIdentity *cls = GNUNET_malloc(size);
546                     struct GNUNET_MessageHeader *hdr = (struct GNUNET_MessageHeader*)(cls+1);
547                     GNUNET_HashCode* hc = (GNUNET_HashCode*)(hdr + 1);
548                     memcpy(cls, &me->desc.peer, sizeof(struct GNUNET_PeerIdentity));
549                     memcpy(hc, &me->desc.service_descriptor, sizeof(GNUNET_HashCode));
550                     memcpy(hc+1, &pkt6_udp->udp_hdr, ntohs(pkt6_udp->udp_hdr.len));
551                     GNUNET_CORE_peer_request_connect(core_handle,
552                                         GNUNET_TIME_UNIT_FOREVER_REL,
553                                         (struct GNUNET_PeerIdentity*)&me->desc.peer,
554                                         send_udp,
555                                         cls);
556                     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Queued to send to peer %x\n", *((unsigned int*)&me->desc.peer));
557                   }
558               }
559             break;
560           case 0x3a:
561             /* ICMPv6 */
562             pkt6_icmp = (struct ip6_icmp*)pkt6;
563             /* If this packet is an icmp-echo-request and a mapping exists, answer */
564             if (pkt6_icmp->icmp_hdr.type == 0x80 && (key = address_mapping_exists(pkt6->ip6_hdr.dadr)) != NULL)
565               {
566                 GNUNET_free(key);
567                 pkt6_icmp = GNUNET_malloc(ntohs(pkt6->shdr.size));
568                 memcpy(pkt6_icmp, pkt6, ntohs(pkt6->shdr.size));
569                 GNUNET_SCHEDULER_add_now(&send_icmp_response, pkt6_icmp);
570               }
571             break;
572           }
573       }
574     /* ethertype is ipv4 */
575     else if (ntohs(pkt_tun->tun.type) == 0x0800)
576       {
577         struct ip_pkt *pkt = (struct ip_pkt*) message;
578         struct ip_udp *udp = (struct ip_udp*) message;
579         GNUNET_assert(pkt->ip_hdr.version == 4);
580
581         /* Send dns-packets to the service-dns */
582         if (pkt->ip_hdr.proto == 0x11 && ntohs(udp->udp_hdr.dpt) == 53 )
583           {
584             /* 9 = 8 for the udp-header + 1 for the unsigned char data[1]; */
585             size_t len = sizeof(struct query_packet) + ntohs(udp->udp_hdr.len) - 9;
586
587             struct query_packet_list* query = GNUNET_malloc(len + 2*sizeof(struct query_packet_list*));
588             query->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_QUERY_DNS);
589             query->pkt.hdr.size = htons(len);
590             query->pkt.orig_to = pkt->ip_hdr.dadr;
591             query->pkt.orig_from = pkt->ip_hdr.sadr;
592             query->pkt.src_port = udp->udp_hdr.spt;
593             memcpy(query->pkt.data, udp->data, ntohs(udp->udp_hdr.len) - 8);
594
595             GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, query);
596
597             if (dns_connection != NULL)
598               GNUNET_CLIENT_notify_transmit_ready(dns_connection,
599                                                   len,
600                                                   GNUNET_TIME_UNIT_FOREVER_REL,
601                                                   GNUNET_YES,
602                                                   &send_query,
603                                                   NULL);
604           }
605       }
606 }
607
608 /**
609  * Connect to the service-dns
610  */
611 static void
612 connect_to_service_dns (void *cls,
613                         const struct GNUNET_SCHEDULER_TaskContext *tc) {
614     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
615       return;
616     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting to service-dns\n");
617     GNUNET_assert (dns_connection == NULL);
618     dns_connection = GNUNET_CLIENT_connect ("dns", cfg);
619     GNUNET_CLIENT_receive(dns_connection, &dns_answer_handler, NULL, GNUNET_TIME_UNIT_FOREVER_REL);
620
621     /* If a packet is already in the list, schedule to send it */
622     if (head != NULL)
623       GNUNET_CLIENT_notify_transmit_ready(dns_connection,
624                                           ntohs(head->pkt.hdr.size),
625                                           GNUNET_TIME_UNIT_FOREVER_REL,
626                                           GNUNET_YES,
627                                           &send_query,
628                                           NULL);
629     else if (restart_hijack == 1)
630       {
631         GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
632       }
633 }
634
635 /**
636  * Create a new Address from an answer-packet
637  * {{{
638  */
639 void
640 new_ip6addr(char* buf, const GNUNET_HashCode *peer, const GNUNET_HashCode *service_desc) {
641         memcpy(buf+14, (int[]){htons(0x3412)}, 2);
642         memcpy(buf+8, service_desc, 6);
643         memcpy(buf, peer, 8);
644 }
645 /*}}}*/
646
647 /**
648  * This gets scheduled with cls pointing to an answer_packet and does everything
649  * needed in order to send it to the helper.
650  *
651  * At the moment this means "inventing" and IPv6-Address for .gnunet-services and
652  * doing nothing for "real" services.
653  */
654 static void
655 process_answer(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tc) {
656     struct answer_packet* pkt = cls;
657     struct answer_packet_list* list;
658
659     /* This answer is about a .gnunet-service
660      *
661      * It contains an almost complete DNS-Response, we have to fill in the ip
662      * at the offset pkt->addroffset
663      */
664     //FIXME htons?
665     if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_SERVICE)
666       {
667         pkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
668
669         GNUNET_HashCode key;
670         memset(&key, 0, sizeof(GNUNET_HashCode));
671         new_ip6addr((char*)&key, &pkt->service_descr.peer, &pkt->service_descr.service_descriptor);
672
673         uint16_t namelen = strlen((char*)pkt->data+12)+1;
674
675         struct map_entry* value = GNUNET_malloc(sizeof(struct GNUNET_vpn_service_descriptor) + 2 + namelen);
676
677         value->namelen = namelen;
678         memcpy(value->name, pkt->data+12, namelen);
679
680         memcpy(&value->desc, &pkt->service_descr, sizeof(struct GNUNET_vpn_service_descriptor));
681
682         if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put(hashmap,
683                                                            &key,
684                                                            value,
685                                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
686           {
687             GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not store to hashmap\n");
688           }
689
690         /*
691          * Copy the newly generated backward ip-address to the packet
692          */
693         char* c = ((char*)pkt)+ntohs(pkt->addroffset);
694         char* k = (char*)&key;
695         unsigned int i;
696         for (i = 0; i < 16; i++)
697             c[15-i] = k[i];
698
699         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
700
701         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
702
703       }
704     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_REV)
705       {
706         GNUNET_HashCode key;
707         memset(&key, 0, sizeof key);
708         unsigned char* k = (unsigned char*)&key;
709         unsigned char* s = pkt->data+12;
710         int i = 0;
711         /* Whoever designed the reverse IPv6-lookup is batshit insane */
712         for (i = 0; i < 16; i++)
713           {
714             unsigned char c1 = s[(4*i)+1];
715             unsigned char c2 = s[(4*i)+3];
716             if (c1 <= '9')
717               k[i] = c1 - '0';
718             else
719               k[i] = c1 - 87; /* 87 is the difference between 'a' and 10 */
720             if (c2 <= '9')
721               k[i] += 16*(c2 - '0');
722             else
723               k[i] += 16*(c2 - 87);
724           }
725
726         struct map_entry* map_entry = GNUNET_CONTAINER_multihashmap_get(hashmap, &key);
727         unsigned short offset = ntohs(pkt->addroffset);
728
729         if (map_entry == NULL)
730           {
731             GNUNET_free(pkt);
732             return;
733           }
734
735         unsigned short namelen = htons(map_entry->namelen);
736         char* name = map_entry->name;
737
738         list = GNUNET_malloc(2*sizeof(struct answer_packet_list*) + offset + 2 + ntohs(namelen));
739
740         struct answer_packet* rpkt = &list->pkt;
741
742         memcpy(rpkt, pkt, offset);
743
744         rpkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
745         rpkt->hdr.size = ntohs(offset + 2 + ntohs(namelen));
746
747         memcpy(((char*)rpkt)+offset, &namelen, 2);
748         memcpy(((char*)rpkt)+offset+2, name, ntohs(namelen));
749
750       }
751     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_IP)
752       {
753         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
754         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
755       }
756     else
757       {
758         GNUNET_break(0);
759         GNUNET_free(pkt);
760         return;
761       }
762
763     GNUNET_free(pkt);
764
765     GNUNET_CONTAINER_DLL_insert_after(answer_proc_head, answer_proc_tail, answer_proc_tail, list);
766
767     GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, fh_to_helper, &helper_write, NULL);
768
769     return;
770 }
771
772 /**
773  * This receives packets from the service-dns and schedules process_answer to
774  * handle it
775  */
776 static void
777 dns_answer_handler(void* cls, const struct GNUNET_MessageHeader *msg) {
778     /* the service disconnected, reconnect after short wait */
779     if (msg == NULL)
780       {
781         GNUNET_CLIENT_disconnect(dns_connection, GNUNET_NO);
782         dns_connection = NULL;
783         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
784                                       &connect_to_service_dns,
785                                       NULL);
786         return;
787       }
788
789     /* the service did something strange, reconnect immediately */
790     if (msg->type != htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS))
791       {
792         GNUNET_break (0);
793         GNUNET_CLIENT_disconnect(dns_connection, GNUNET_NO);
794         dns_connection = NULL;
795         GNUNET_SCHEDULER_add_now (&connect_to_service_dns,
796                                   NULL);
797         return;
798       }
799     void *pkt = GNUNET_malloc(ntohs(msg->size));
800
801     memcpy(pkt, msg, ntohs(msg->size));
802
803     GNUNET_SCHEDULER_add_now(process_answer, pkt);
804     GNUNET_CLIENT_receive(dns_connection, &dns_answer_handler, NULL, GNUNET_TIME_UNIT_FOREVER_REL);
805 }
806
807 struct udp_state
808 {
809   struct GNUNET_PeerIdentity peer;
810   GNUNET_HashCode desc;
811   short spt;
812   short dpt;
813 };
814
815 struct send_cls
816 {
817   struct GNUNET_NETWORK_Handle *sock;
818   struct udp_state state;
819 };
820
821 static size_t
822 send_udp_service (void *cls, size_t size, void *buf)
823 {
824   struct GNUNET_MessageHeader *hdr = cls;
825   GNUNET_assert(size >= ntohs(hdr->size));
826
827   memcpy(buf, cls, ntohs(hdr->size));
828   size_t ret = ntohs(hdr->size);
829   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending %d bytes back!\n", ntohs(hdr->size));
830   GNUNET_free(cls);
831   return ret;
832 }
833
834 void
835 receive_from_network (void *cls,
836                       const struct GNUNET_SCHEDULER_TaskContext *tc)
837 {
838   if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
839     {
840       GNUNET_free(cls);
841       return;
842     }
843   struct send_cls *data = cls;
844
845   char buf[1400];
846
847   ssize_t len = GNUNET_NETWORK_socket_recv (data->sock, buf, 1400);
848
849   if (len < 0) {
850     GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Problem reading from socket: %m\n");
851     goto out;
852   }
853
854   size_t len_udp = len + sizeof (struct udp_pkt);
855   size_t len_pkt = len_udp + sizeof (struct GNUNET_MessageHeader) + sizeof(GNUNET_HashCode);
856   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending data back: data: %d; udp: %d, pkt:%d\n", len, len_udp, len_pkt);
857
858   struct GNUNET_MessageHeader *hdr = GNUNET_malloc (len_pkt);
859   GNUNET_HashCode *desc = (GNUNET_HashCode *) (hdr + 1);
860   struct udp_pkt *pkt = (struct udp_pkt *) (desc + 1);
861
862   hdr->size = htons (len_pkt);
863   hdr->type = htons (GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK);
864
865   pkt->dpt = htons(data->state.spt);
866   pkt->spt = htons(data->state.dpt);
867   pkt->len = htons (len_udp);
868   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "UDP from %d to %d\n", ntohs(pkt->spt), ntohs(pkt->dpt));
869   /* The chksm can only be computed knowing the ip-addresses */
870
871   memcpy (desc, &data->state.desc, sizeof (GNUNET_HashCode));
872   memcpy (pkt + 1, buf, len);
873
874   GNUNET_CORE_notify_transmit_ready (core_handle, 42,
875                                      GNUNET_TIME_UNIT_FOREVER_REL,
876                                      &data->state.peer, len_pkt,
877                                      send_udp_service, hdr);
878
879 out:
880   GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, data->sock,
881                                  receive_from_network, cls);
882 }
883
884 void
885 send_to_network (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
886 {
887   if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
888     return;
889   struct send_cls *data = cls;
890   struct udp_pkt *pkt = (struct udp_pkt *) (data + 1);
891
892   struct sockaddr_in a4;
893   memset(&a4, 0, sizeof(struct sockaddr_in));
894   a4.sin_family = AF_INET;
895   a4.sin_port = htons(data->state.dpt);
896   memcpy(&a4.sin_addr.s_addr, (char[]){127, 0, 0, 1}, 4);
897
898   GNUNET_NETWORK_socket_sendto (data->sock, pkt + 1,
899                                 ntohs (pkt->len) - sizeof (struct udp_pkt),
900                                 (struct sockaddr*)&a4, sizeof a4);
901
902   GNUNET_free(cls);
903
904 }
905
906 static int
907 receive_udp_back (void *cls, const struct GNUNET_PeerIdentity *other,
908              const struct GNUNET_MessageHeader *message,
909              const struct GNUNET_TRANSPORT_ATS_Information *atsi)
910 {
911   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
912   struct udp_pkt *pkt = (struct udp_pkt *) (desc + 1);
913   char addr[16];
914   new_ip6addr(addr, &other->hashPubKey, desc);
915
916   size_t size = sizeof(struct ip6_udp) + ntohs(pkt->len) - 1 - sizeof(struct udp_pkt);
917
918   struct ip6_udp* pkt6 = alloca(size);
919
920   pkt6->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
921   pkt6->shdr.size = htons(size);
922
923   pkt6->tun.flags = 0;
924   pkt6->tun.type = htons(0x86dd);
925
926   pkt6->ip6_hdr.version = 6;
927   pkt6->ip6_hdr.tclass_h = 0;
928   pkt6->ip6_hdr.tclass_l = 0;
929   pkt6->ip6_hdr.flowlbl = 0;
930   pkt6->ip6_hdr.paylgth = pkt->len;
931   pkt6->ip6_hdr.nxthdr = 0x11;
932   pkt6->ip6_hdr.hoplmt = 0xff;
933
934   unsigned int i;
935   for (i = 0; i < 16; i++)
936     pkt6->ip6_hdr.sadr[15-i] = addr[i];
937
938   memcpy(pkt6->ip6_hdr.dadr, (unsigned char[]){0x12, 0x34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 16);
939
940   memcpy(&pkt6->udp_hdr, pkt, ntohs(pkt->len));
941
942   pkt6->udp_hdr.crc = 0;
943   uint32_t sum = 0;
944   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->ip6_hdr.sadr, 16);
945   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->ip6_hdr.dadr, 16);
946   uint32_t tmp = (pkt6->udp_hdr.len & 0xffff);
947   sum = calculate_checksum_update(sum, (uint16_t*)&tmp, 4);
948   tmp = htons(((pkt6->ip6_hdr.nxthdr & 0x00ff)));
949   sum = calculate_checksum_update(sum, (uint16_t*)&tmp, 4);
950
951   sum = calculate_checksum_update(sum, (uint16_t*)&pkt6->udp_hdr, ntohs(pkt->len));
952   pkt6->udp_hdr.crc = calculate_checksum_end(sum);
953
954
955   /* FIXME */ GNUNET_DISK_file_write(fh_to_helper, pkt6, size);
956
957   return GNUNET_OK;
958 }
959
960 static int
961 receive_udp_service (void *cls, const struct GNUNET_PeerIdentity *other,
962                      const struct GNUNET_MessageHeader *message,
963                      const struct GNUNET_TRANSPORT_ATS_Information *atsi)
964 {
965   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received UDP-Packet from peer %s\n",
966               GNUNET_i2s (other));
967   GNUNET_HashCode *desc = (GNUNET_HashCode *) (message + 1);
968   struct udp_pkt *pkt = (struct udp_pkt *) (desc + 1);
969
970   /* FIXME -> check acl etc */
971   GNUNET_assert (ntohs (pkt->len) ==
972                  ntohs (message->size) -
973                  sizeof (struct GNUNET_MessageHeader) -
974                  sizeof (GNUNET_HashCode));
975
976   size_t state_size = sizeof (struct udp_state);
977   size_t cls_size = sizeof (struct send_cls) + ntohs (pkt->len);
978   struct send_cls *send = GNUNET_malloc (cls_size);
979   struct udp_state *state = &send->state;
980   unsigned int new = GNUNET_NO;
981
982   memcpy (&state->peer, other, sizeof (struct GNUNET_PeerIdentity));
983   memcpy (&state->desc, desc, sizeof (GNUNET_HashCode));
984   state->spt = ntohs (pkt->spt);
985   state->dpt = ntohs (pkt->dpt);
986
987   memcpy (send + 1, pkt, ntohs (pkt->len));
988
989   GNUNET_HashCode hash;
990   GNUNET_CRYPTO_hash (state, state_size, &hash);
991
992   struct GNUNET_NETWORK_Handle *sock =
993     GNUNET_CONTAINER_multihashmap_get (udp_connections, &hash);
994
995   if (sock == NULL)
996     {
997       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Creating new Socket!\n");
998       sock = GNUNET_NETWORK_socket_create (AF_INET, SOCK_DGRAM, 0);
999       new = GNUNET_YES;
1000     }
1001
1002   send->sock = sock;
1003
1004   GNUNET_CONTAINER_multihashmap_put (udp_connections, &hash, sock,
1005                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1006
1007
1008   if (new)
1009     {
1010       struct send_cls *recv = GNUNET_malloc (sizeof (struct send_cls));
1011       memcpy (recv, send, sizeof (struct send_cls));
1012       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, sock,
1013                                      receive_from_network, recv);
1014     }
1015
1016   GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL, sock,
1017                                   send_to_network, send);
1018
1019   return GNUNET_OK;
1020 }
1021
1022 /**
1023  * Main function that will be run by the scheduler.
1024  *
1025  * @param cls closure
1026  * @param args remaining command-line arguments
1027  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
1028  * @param cfg configuration
1029  */
1030 static void
1031 run (void *cls,
1032      char *const *args,
1033      const char *cfgfile,
1034      const struct GNUNET_CONFIGURATION_Handle *cfg_) {
1035     const static struct GNUNET_CORE_MessageHandler handlers[] = {
1036           {receive_udp_service, GNUNET_MESSAGE_TYPE_SERVICE_UDP, 0},
1037           {receive_udp_back, GNUNET_MESSAGE_TYPE_SERVICE_UDP_BACK, 0},
1038           {NULL, 0, 0}
1039     };
1040     core_handle = GNUNET_CORE_connect(cfg_,
1041                                       42,
1042                                       NULL,
1043                                       NULL,
1044                                       NULL,
1045                                       NULL,
1046                                       NULL,
1047                                       NULL,
1048                                       0,
1049                                       NULL,
1050                                       0,
1051                                       handlers);
1052     mst = GNUNET_SERVER_mst_create(&message_token, NULL);
1053     cfg = cfg_;
1054     restart_hijack = 0;
1055     hashmap = GNUNET_CONTAINER_multihashmap_create(65536);
1056     udp_connections = GNUNET_CONTAINER_multihashmap_create(65536);
1057     GNUNET_SCHEDULER_add_now (connect_to_service_dns, NULL);
1058     GNUNET_SCHEDULER_add_now (start_helper_and_schedule, NULL);
1059     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls);
1060 }
1061
1062 /**
1063  * The main function to obtain template from gnunetd.
1064  *
1065  * @param argc number of arguments from the command line
1066  * @param argv command line arguments
1067  * @return 0 ok, 1 on error
1068  */
1069 int
1070 main (int argc, char *const *argv) {
1071     static const struct GNUNET_GETOPT_CommandLineOption options[] = {
1072         GNUNET_GETOPT_OPTION_END
1073     };
1074
1075     return (GNUNET_OK ==
1076             GNUNET_PROGRAM_run (argc,
1077                                 argv,
1078                                 "gnunet-daemon-vpn",
1079                                 gettext_noop ("help text"),
1080                                 options, &run, NULL)) ? ret : 1;
1081 }
1082
1083 /* end of gnunet-daemon-vpn.c */