send UDP-Packets to the peer offering the service
[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  * The handle to core
125  */
126 static struct GNUNET_CORE_Handle *core_handle;
127
128 struct map_entry {
129     struct GNUNET_vpn_service_descriptor desc;
130     uint16_t namelen;
131     /**
132      * In DNS-Format!
133      */
134     char name[1];
135 };
136
137 static void helper_read(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx);
138 static void dns_answer_handler(void* cls, const struct GNUNET_MessageHeader *msg);
139
140 /**
141  * Callback called by notify_transmit_ready; sends dns-queries or rehijack-messages
142  * to the service-dns
143  * {{{
144  */
145 static size_t
146 send_query(void* cls, size_t size, void* buf) {
147     size_t len;
148     /*
149      * Send the rehijack-message
150      */
151     if (restart_hijack == 1)
152       {
153         restart_hijack = 0;
154         /*
155          * The message is just a header
156          */
157         GNUNET_assert(sizeof(struct GNUNET_MessageHeader) <= size);
158         struct GNUNET_MessageHeader* hdr = buf;
159         len = sizeof(struct GNUNET_MessageHeader);
160         hdr->size = htons(len);
161         hdr->type = htons(GNUNET_MESSAGE_TYPE_REHIJACK);
162       }
163     else
164       {
165         struct query_packet_list* query = head;
166         len = ntohs(query->pkt.hdr.size);
167
168         GNUNET_assert(len <= size);
169
170         memcpy(buf, &query->pkt.hdr, len);
171
172         GNUNET_CONTAINER_DLL_remove (head, tail, query);
173
174         GNUNET_free(query);
175       }
176
177     /*
178      * Check whether more data is to be sent
179      */
180     if (head != NULL)
181       {
182         GNUNET_CLIENT_notify_transmit_ready(dns_connection, ntohs(head->pkt.hdr.size), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
183       }
184     else if (restart_hijack == 1)
185       {
186         GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
187       }
188
189     return len;
190 }
191 /* }}} */
192
193 /**
194  * Function scheduled as very last function, cleans up after us
195  *{{{
196  */
197 static void
198 cleanup(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
199     GNUNET_assert (0 != (tskctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN));
200
201     /* stop the helper */
202     if (helper_proc != NULL)
203       {
204         GNUNET_OS_process_kill (helper_proc, SIGTERM);
205         GNUNET_OS_process_wait (helper_proc);
206         GNUNET_OS_process_close (helper_proc);
207         helper_proc = NULL;
208       }
209
210     /* close the connection to the service-dns */
211     if (dns_connection != NULL)
212       {
213         GNUNET_CLIENT_disconnect (dns_connection, GNUNET_NO);
214         dns_connection = NULL;
215       }
216
217     if (core_handle != NULL)
218       {
219         GNUNET_CORE_disconnect(core_handle);
220         core_handle = NULL;
221       }
222 }
223 /*}}}*/
224
225 /**
226  * Start the helper-process
227  * {{{
228  */
229 static void
230 start_helper_and_schedule(void *cls,
231                           const struct GNUNET_SCHEDULER_TaskContext *tc) {
232     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
233       return;
234
235     helper_in = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO);
236     helper_out = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
237
238     if (helper_in == NULL || helper_out == NULL) return;
239
240     helper_proc = GNUNET_OS_start_process(helper_in, helper_out, "gnunet-helper-vpn", "gnunet-helper-vpn", NULL);
241
242     fh_from_helper = GNUNET_DISK_pipe_handle (helper_out, GNUNET_DISK_PIPE_END_READ);
243     fh_to_helper = GNUNET_DISK_pipe_handle (helper_in, GNUNET_DISK_PIPE_END_WRITE);
244
245     GNUNET_DISK_pipe_close_end(helper_out, GNUNET_DISK_PIPE_END_WRITE);
246     GNUNET_DISK_pipe_close_end(helper_in, GNUNET_DISK_PIPE_END_READ);
247
248     /* Tell the dns-service to rehijack the dns-port
249      * The routing-table gets flushed if an interface disappears.
250      */
251     restart_hijack = 1;
252     GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
253
254     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, fh_from_helper, &helper_read, NULL);
255 }
256 /*}}}*/
257
258 /**
259  * Restart the helper-process
260  * {{{
261  */
262 static void
263 restart_helper(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
264     // Kill the helper
265     GNUNET_OS_process_kill (helper_proc, SIGKILL);
266     GNUNET_OS_process_wait (helper_proc);
267     GNUNET_OS_process_close (helper_proc);
268     helper_proc = NULL;
269
270     GNUNET_DISK_pipe_close(helper_in);
271     GNUNET_DISK_pipe_close(helper_out);
272
273     /* Restart the helper */
274     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, start_helper_and_schedule, NULL);
275 }
276 /*}}}*/
277
278 /**
279  * Read from the helper-process
280  * {{{
281  */
282 static void
283 helper_read(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx) {
284     /* no message can be bigger then 64k */
285     char buf[65535];
286
287     if (tsdkctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
288       return;
289
290     int t = GNUNET_DISK_file_read(fh_from_helper, &buf, 65535);
291
292     /* On read-error, restart the helper */
293     if (t<=0) {
294         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Read error for header from vpn-helper: %m\n");
295         GNUNET_SCHEDULER_add_now(restart_helper, cls);
296         return;
297     }
298
299     /* FIXME */ GNUNET_SERVER_mst_receive(mst, NULL, buf, t, 0, 0);
300
301     GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, fh_from_helper, &helper_read, NULL);
302 }
303 /*}}}*/
304
305 /**
306  * Calculate the checksum of an IPv4-Header
307  */
308 static uint16_t
309 calculate_ip_checksum(uint16_t* hdr, short len) {
310     uint32_t sum = 0;
311     for(; len >= 2; len -= 2)
312       sum += *(hdr++);
313     if (len == 1)
314       sum += *((unsigned char*)hdr);
315
316     sum = (sum >> 16) + (sum & 0xFFFF);
317
318     return ~sum;
319 }
320
321 /**
322  * Send an dns-answer-packet to the helper
323  */
324 static void
325 helper_write(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx) {
326     if (tsdkctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
327       return;
328
329     struct answer_packet_list* ans = answer_proc_head;
330     size_t len = ntohs(ans->pkt.hdr.size);
331
332     GNUNET_assert(ans->pkt.subtype == GNUNET_DNS_ANSWER_TYPE_IP);
333
334     GNUNET_assert (20 == sizeof (struct ip_hdr));
335     GNUNET_assert (8 == sizeof (struct udp_pkt));
336     size_t data_len = len - sizeof(struct answer_packet) + 1;
337     size_t net_len = sizeof(struct ip_hdr) + sizeof(struct udp_dns) + data_len;
338     size_t pkt_len = sizeof(struct GNUNET_MessageHeader) + sizeof(struct pkt_tun) + net_len;
339
340     struct ip_udp_dns* pkt = alloca(pkt_len);
341     memset(pkt, 0, pkt_len);
342
343     /* set the gnunet-header */
344     pkt->shdr.size = htons(pkt_len);
345     pkt->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
346
347     /* set the tun-header (no flags and ethertype of IPv4) */
348     pkt->tun.flags = 0;
349     pkt->tun.type = htons(0x0800);
350
351     /* set the ip-header */
352     pkt->ip_hdr.version = 4;
353     pkt->ip_hdr.hdr_lngth = 5;
354     pkt->ip_hdr.diff_serv = 0;
355     pkt->ip_hdr.tot_lngth = htons(net_len);
356     pkt->ip_hdr.ident = 0;
357     pkt->ip_hdr.flags = 0;
358     pkt->ip_hdr.frag_off = 0;
359     pkt->ip_hdr.ttl = 255;
360     pkt->ip_hdr.proto = 0x11; /* UDP */
361     pkt->ip_hdr.chks = 0; /* Will be calculated later*/
362     pkt->ip_hdr.sadr = ans->pkt.from;
363     pkt->ip_hdr.dadr = ans->pkt.to;
364
365     pkt->ip_hdr.chks = calculate_ip_checksum((uint16_t*)&pkt->ip_hdr, 5*4);
366
367     /* set the udp-header */
368     pkt->udp_dns.udp_hdr.spt = htons(53);
369     pkt->udp_dns.udp_hdr.dpt = ans->pkt.dst_port;
370     pkt->udp_dns.udp_hdr.len = htons(net_len - sizeof(struct ip_hdr));
371     pkt->udp_dns.udp_hdr.crc = 0; /* Optional for IPv4 */
372
373     memcpy(&pkt->udp_dns.data, ans->pkt.data, data_len);
374
375     GNUNET_CONTAINER_DLL_remove (answer_proc_head, answer_proc_tail, ans);
376     GNUNET_free(ans);
377
378     /* FIXME */ GNUNET_DISK_file_write(fh_to_helper, pkt, pkt_len);
379
380     /* if more packets are available, reschedule */
381     if (answer_proc_head != NULL)
382       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
383                                        fh_to_helper,
384                                        &helper_write,
385                                        NULL);
386 }
387
388 /**
389  * @return the hash of the IP-Address if a mapping exists, NULL otherwise
390  */
391 static GNUNET_HashCode*
392 address_mapping_exists(unsigned char addr[]) {
393     GNUNET_HashCode* key = GNUNET_malloc(sizeof(GNUNET_HashCode));
394     unsigned char* k = (unsigned char*)key;
395     memset(key, 0, sizeof(GNUNET_HashCode));
396     unsigned int i;
397     for (i = 0; i < 16; i++)
398         k[15-i] = addr[i];
399
400     if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(hashmap, key))
401       return key;
402     else
403       {
404         GNUNET_free(key);
405         return NULL;
406       }
407 }
408
409 static void
410 send_icmp_response(void* cls, const struct GNUNET_SCHEDULER_TaskContext *tc) {
411     struct ip6_icmp* request = cls;
412
413     struct ip6_icmp* response = alloca(ntohs(request->shdr.size));
414     memset(response, 0, ntohs(request->shdr.size));
415
416     response->shdr.size = request->shdr.size;
417     response->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
418
419     response->tun.flags = 0;
420     response->tun.type = htons(0x86dd);
421
422     response->ip6_hdr.hoplmt = 255;
423     response->ip6_hdr.paylgth = request->ip6_hdr.paylgth;
424     response->ip6_hdr.nxthdr = 0x3a;
425     response->ip6_hdr.version = 6;
426     memcpy(&response->ip6_hdr.sadr, &request->ip6_hdr.dadr, 16);
427     memcpy(&response->ip6_hdr.dadr, &request->ip6_hdr.sadr, 16);
428
429     response->icmp_hdr.code = 0;
430     response->icmp_hdr.type = 0x81;
431
432     /* Magic, more Magic! */
433     response->icmp_hdr.chks = request->icmp_hdr.chks - 0x1;
434
435     /* Copy the rest of the packet */
436     memcpy(response+1, request+1, ntohs(request->shdr.size) - sizeof(struct ip6_icmp));
437
438     /* FIXME */ GNUNET_DISK_file_write(fh_to_helper, response, ntohs(response->shdr.size));
439
440     GNUNET_free(request);
441 }
442
443 /**
444  * cls is the pointer to a GNUNET_MessageHeader that is
445  * followed by the service-descriptor and the udp-packet that should be sent;
446  */
447 static size_t
448 handle_udp (void *cls, size_t size, void *buf)
449 {
450   struct GNUNET_PeerIdentity *peer = cls;
451   struct GNUNET_MessageHeader *hdr =
452     (struct GNUNET_MessageHeader *) (peer + 1);
453   GNUNET_HashCode *hc = (GNUNET_HashCode *) (hdr + 1);
454   struct udp_pkt *udp = (struct udp_pkt *) (hc + 1);
455   hdr->size = htons (sizeof (struct GNUNET_MessageHeader) +
456                      sizeof (GNUNET_HashCode) + ntohs (udp->len));
457   hdr->type = ntohs (GNUNET_MESSAGE_TYPE_SERVICE_UDP);
458   GNUNET_assert (size >= ntohs (hdr->size));
459   memcpy (buf, hdr, ntohs (hdr->size));
460   GNUNET_free (cls);
461   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sent!\n");
462   return ntohs (hdr->size);
463 }
464
465 static unsigned int
466 port_in_ports (uint64_t ports, uint16_t port)
467 {
468   uint16_t *ps = (uint16_t *) & ports;
469   return ps[0] == port || ps[1] == port || ps[2] == port || ps[3] == port;
470 }
471
472 void
473 send_udp (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
474 {
475   struct GNUNET_PeerIdentity *peer = cls;
476   struct GNUNET_MessageHeader *hdr =
477     (struct GNUNET_MessageHeader *) (peer + 1);
478   GNUNET_HashCode *hc = (GNUNET_HashCode *) (hdr + 1);
479   struct udp_pkt *udp = (struct udp_pkt *) (hc + 1);
480   GNUNET_CORE_notify_transmit_ready (core_handle,
481                                      42,
482                                      GNUNET_TIME_UNIT_FOREVER_REL,
483                                      peer,
484                                      htons (sizeof
485                                             (struct GNUNET_MessageHeader) +
486                                             sizeof (GNUNET_HashCode) +
487                                             ntohs (udp->len)), handle_udp,
488                                      cls);
489 }
490
491 /**
492  * Receive packets from the helper-process
493  */
494 static void
495 message_token(void *cls,
496               void *client,
497               const struct GNUNET_MessageHeader *message) {
498     GNUNET_assert(ntohs(message->type) == GNUNET_MESSAGE_TYPE_VPN_HELPER);
499
500     struct tun_pkt *pkt_tun = (struct tun_pkt*) message;
501
502     /* ethertype is ipv6 */
503     if (ntohs(pkt_tun->tun.type) == 0x86dd)
504       {
505         struct ip6_pkt *pkt6 = (struct ip6_pkt*) message;
506         GNUNET_assert(pkt6->ip6_hdr.version == 6);
507         struct ip6_tcp *pkt6_tcp;
508         struct ip6_udp *pkt6_udp;
509         struct ip6_icmp *pkt6_icmp;
510         GNUNET_HashCode* key;
511
512         pkt_printf(pkt6);
513         switch(pkt6->ip6_hdr.nxthdr)
514           {
515           case 0x06:
516             pkt6_tcp = (struct ip6_tcp*)pkt6;
517             pkt_printf_ip6tcp(pkt6_tcp);
518             break;
519           case 0x11:
520             pkt6_udp = (struct ip6_udp*)pkt6;
521             if ((key = address_mapping_exists(pkt6->ip6_hdr.dadr)) != NULL)
522               {
523                 struct map_entry* me = GNUNET_CONTAINER_multihashmap_get(hashmap, key);
524                 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);
525                 GNUNET_free(key);
526                 if (me->desc.service_type & htonl(GNUNET_DNS_SERVICE_TYPE_UDP) &&
527                     port_in_ports(me->desc.ports, pkt6_udp->udp_hdr.dpt))
528                   {
529                     size_t size = sizeof(struct GNUNET_PeerIdentity) + sizeof(struct GNUNET_MessageHeader) + sizeof(GNUNET_HashCode) + ntohs(pkt6_udp->udp_hdr.len);
530                     struct GNUNET_PeerIdentity *cls = GNUNET_malloc(size);
531                     struct GNUNET_MessageHeader *hdr = (struct GNUNET_MessageHeader*)(cls+1);
532                     GNUNET_HashCode* hc = (GNUNET_HashCode*)(hdr + 1);
533                     memcpy(cls, &me->desc.peer, sizeof(struct GNUNET_PeerIdentity));
534                     memcpy(hc, &me->desc.service_descriptor, sizeof(GNUNET_HashCode));
535                     memcpy(hc+1, &pkt6_udp->udp_hdr, ntohs(pkt6_udp->udp_hdr.len));
536                     GNUNET_CORE_peer_request_connect(core_handle,
537                                         GNUNET_TIME_UNIT_FOREVER_REL,
538                                         (struct GNUNET_PeerIdentity*)&me->desc.peer,
539                                         send_udp,
540                                         cls);
541                     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Queued to send to peer %x\n", *((unsigned int*)&me->desc.peer));
542                   }
543               }
544             break;
545           case 0x3a:
546             /* ICMPv6 */
547             pkt6_icmp = (struct ip6_icmp*)pkt6;
548             /* If this packet is an icmp-echo-request and a mapping exists, answer */
549             if (pkt6_icmp->icmp_hdr.type == 0x80 && (key = address_mapping_exists(pkt6->ip6_hdr.dadr)) != NULL)
550               {
551                 GNUNET_free(key);
552                 pkt6_icmp = GNUNET_malloc(ntohs(pkt6->shdr.size));
553                 memcpy(pkt6_icmp, pkt6, ntohs(pkt6->shdr.size));
554                 GNUNET_SCHEDULER_add_now(&send_icmp_response, pkt6_icmp);
555               }
556             break;
557           }
558       }
559     /* ethertype is ipv4 */
560     else if (ntohs(pkt_tun->tun.type) == 0x0800)
561       {
562         struct ip_pkt *pkt = (struct ip_pkt*) message;
563         struct ip_udp *udp = (struct ip_udp*) message;
564         GNUNET_assert(pkt->ip_hdr.version == 4);
565
566         /* Send dns-packets to the service-dns */
567         if (pkt->ip_hdr.proto == 0x11 && ntohs(udp->udp_hdr.dpt) == 53 )
568           {
569             /* 9 = 8 for the udp-header + 1 for the unsigned char data[1]; */
570             size_t len = sizeof(struct query_packet) + ntohs(udp->udp_hdr.len) - 9;
571
572             struct query_packet_list* query = GNUNET_malloc(len + 2*sizeof(struct query_packet_list*));
573             query->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_QUERY_DNS);
574             query->pkt.hdr.size = htons(len);
575             query->pkt.orig_to = pkt->ip_hdr.dadr;
576             query->pkt.orig_from = pkt->ip_hdr.sadr;
577             query->pkt.src_port = udp->udp_hdr.spt;
578             memcpy(query->pkt.data, udp->data, ntohs(udp->udp_hdr.len) - 8);
579
580             GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, query);
581
582             if (dns_connection != NULL)
583               GNUNET_CLIENT_notify_transmit_ready(dns_connection,
584                                                   len,
585                                                   GNUNET_TIME_UNIT_FOREVER_REL,
586                                                   GNUNET_YES,
587                                                   &send_query,
588                                                   NULL);
589           }
590       }
591 }
592
593 /**
594  * Connect to the service-dns
595  */
596 static void
597 connect_to_service_dns (void *cls,
598                         const struct GNUNET_SCHEDULER_TaskContext *tc) {
599     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
600       return;
601     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting to service-dns\n");
602     GNUNET_assert (dns_connection == NULL);
603     dns_connection = GNUNET_CLIENT_connect ("dns", cfg);
604     GNUNET_CLIENT_receive(dns_connection, &dns_answer_handler, NULL, GNUNET_TIME_UNIT_FOREVER_REL);
605
606     /* If a packet is already in the list, schedule to send it */
607     if (head != NULL)
608       GNUNET_CLIENT_notify_transmit_ready(dns_connection,
609                                           ntohs(head->pkt.hdr.size),
610                                           GNUNET_TIME_UNIT_FOREVER_REL,
611                                           GNUNET_YES,
612                                           &send_query,
613                                           NULL);
614     else if (restart_hijack == 1)
615       {
616         GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
617       }
618 }
619
620 /**
621  * Create a new Address from an answer-packet
622  * {{{
623  */
624 void
625 new_ip6addr(char* buf, struct answer_packet* pkt) {
626         memcpy(buf+14, (int[]){htons(0x3412)}, 2);
627         memcpy(buf+8, &pkt->service_descr.service_descriptor, 6);
628         memcpy(buf, &pkt->service_descr.peer, 8);
629 }
630 /*}}}*/
631
632 /**
633  * This gets scheduled with cls pointing to an answer_packet and does everything
634  * needed in order to send it to the helper.
635  *
636  * At the moment this means "inventing" and IPv6-Address for .gnunet-services and
637  * doing nothing for "real" services.
638  */
639 static void
640 process_answer(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tc) {
641     struct answer_packet* pkt = cls;
642     struct answer_packet_list* list;
643
644     /* This answer is about a .gnunet-service
645      *
646      * It contains an almost complete DNS-Response, we have to fill in the ip
647      * at the offset pkt->addroffset
648      */
649     //FIXME htons?
650     if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_SERVICE)
651       {
652         pkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
653
654         GNUNET_HashCode key;
655         memset(&key, 0, sizeof(GNUNET_HashCode));
656         new_ip6addr((char*)&key, pkt);
657
658         uint16_t namelen = strlen((char*)pkt->data+12)+1;
659
660         struct map_entry* value = GNUNET_malloc(sizeof(struct GNUNET_vpn_service_descriptor) + 2 + namelen);
661
662         value->namelen = namelen;
663         memcpy(value->name, pkt->data+12, namelen);
664
665         memcpy(&value->desc, &pkt->service_descr, sizeof(struct GNUNET_vpn_service_descriptor));
666
667         if (GNUNET_OK != GNUNET_CONTAINER_multihashmap_put(hashmap,
668                                                            &key,
669                                                            value,
670                                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
671           {
672             GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not store to hashmap\n");
673           }
674
675         /*
676          * Copy the newly generated backward ip-address to the packet
677          */
678         char* c = ((char*)pkt)+ntohs(pkt->addroffset);
679         char* k = (char*)&key;
680         unsigned int i;
681         for (i = 0; i < 16; i++)
682             c[15-i] = k[i];
683
684         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
685
686         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
687
688       }
689     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_REV)
690       {
691         GNUNET_HashCode key;
692         memset(&key, 0, sizeof key);
693         unsigned char* k = (unsigned char*)&key;
694         unsigned char* s = pkt->data+12;
695         int i = 0;
696         /* Whoever designed the reverse IPv6-lookup is batshit insane */
697         for (i = 0; i < 16; i++)
698           {
699             unsigned char c1 = s[(4*i)+1];
700             unsigned char c2 = s[(4*i)+3];
701             if (c1 <= '9')
702               k[i] = c1 - '0';
703             else
704               k[i] = c1 - 87; /* 87 is the difference between 'a' and 10 */
705             if (c2 <= '9')
706               k[i] += 16*(c2 - '0');
707             else
708               k[i] += 16*(c2 - 87);
709           }
710
711         struct map_entry* map_entry = GNUNET_CONTAINER_multihashmap_get(hashmap, &key);
712         unsigned short offset = ntohs(pkt->addroffset);
713
714         if (map_entry == NULL)
715           {
716             GNUNET_free(pkt);
717             return;
718           }
719
720         unsigned short namelen = htons(map_entry->namelen);
721         char* name = map_entry->name;
722
723         list = GNUNET_malloc(2*sizeof(struct answer_packet_list*) + offset + 2 + ntohs(namelen));
724
725         struct answer_packet* rpkt = &list->pkt;
726
727         memcpy(rpkt, pkt, offset);
728
729         rpkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
730         rpkt->hdr.size = ntohs(offset + 2 + ntohs(namelen));
731
732         memcpy(((char*)rpkt)+offset, &namelen, 2);
733         memcpy(((char*)rpkt)+offset+2, name, ntohs(namelen));
734
735       }
736     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_IP)
737       {
738         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
739         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
740       }
741     else
742       {
743         GNUNET_break(0);
744         GNUNET_free(pkt);
745         return;
746       }
747
748     GNUNET_free(pkt);
749
750     GNUNET_CONTAINER_DLL_insert_after(answer_proc_head, answer_proc_tail, answer_proc_tail, list);
751
752     GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, fh_to_helper, &helper_write, NULL);
753
754     return;
755 }
756
757 /**
758  * This receives packets from the service-dns and schedules process_answer to
759  * handle it
760  */
761 static void
762 dns_answer_handler(void* cls, const struct GNUNET_MessageHeader *msg) {
763     /* the service disconnected, reconnect after short wait */
764     if (msg == NULL)
765       {
766         GNUNET_CLIENT_disconnect(dns_connection, GNUNET_NO);
767         dns_connection = NULL;
768         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
769                                       &connect_to_service_dns,
770                                       NULL);
771         return;
772       }
773
774     /* the service did something strange, reconnect immediately */
775     if (msg->type != htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS))
776       {
777         GNUNET_break (0);
778         GNUNET_CLIENT_disconnect(dns_connection, GNUNET_NO);
779         dns_connection = NULL;
780         GNUNET_SCHEDULER_add_now (&connect_to_service_dns,
781                                   NULL);
782         return;
783       }
784     void *pkt = GNUNET_malloc(ntohs(msg->size));
785
786     memcpy(pkt, msg, ntohs(msg->size));
787
788     GNUNET_SCHEDULER_add_now(process_answer, pkt);
789     GNUNET_CLIENT_receive(dns_connection, &dns_answer_handler, NULL, GNUNET_TIME_UNIT_FOREVER_REL);
790 }
791
792 static int
793 receive_udp (void *cls, const struct GNUNET_PeerIdentity *other,
794              const struct GNUNET_MessageHeader *message,
795              const struct GNUNET_TRANSPORT_ATS_Information *atsi)
796 {
797   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received UDP-Packet from peer %s\n",
798               GNUNET_i2s (other));
799   struct udp_pkt *pkt = (struct udp_pkt *) (message + 1);
800   pkt_printf_udp (pkt);
801   return GNUNET_OK;
802 }
803
804 /**
805  * Main function that will be run by the scheduler.
806  *
807  * @param cls closure
808  * @param args remaining command-line arguments
809  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
810  * @param cfg configuration
811  */
812 static void
813 run (void *cls,
814      char *const *args,
815      const char *cfgfile,
816      const struct GNUNET_CONFIGURATION_Handle *cfg_) {
817     const static struct GNUNET_CORE_MessageHandler handlers[] = {
818           {receive_udp, GNUNET_MESSAGE_TYPE_SERVICE_UDP, 0},
819           {NULL, 0, 0}
820     };
821     core_handle = GNUNET_CORE_connect(cfg_,
822                                       42,
823                                       NULL,
824                                       NULL,
825                                       NULL,
826                                       NULL,
827                                       NULL,
828                                       NULL,
829                                       0,
830                                       NULL,
831                                       0,
832                                       handlers);
833     mst = GNUNET_SERVER_mst_create(&message_token, NULL);
834     cfg = cfg_;
835     restart_hijack = 0;
836     hashmap = GNUNET_CONTAINER_multihashmap_create(65536);
837     GNUNET_SCHEDULER_add_now (connect_to_service_dns, NULL);
838     GNUNET_SCHEDULER_add_now (start_helper_and_schedule, NULL);
839     GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls);
840 }
841
842 /**
843  * The main function to obtain template from gnunetd.
844  *
845  * @param argc number of arguments from the command line
846  * @param argv command line arguments
847  * @return 0 ok, 1 on error
848  */
849 int
850 main (int argc, char *const *argv) {
851     static const struct GNUNET_GETOPT_CommandLineOption options[] = {
852         GNUNET_GETOPT_OPTION_END
853     };
854
855     return (GNUNET_OK ==
856             GNUNET_PROGRAM_run (argc,
857                                 argv,
858                                 "gnunet-daemon-vpn",
859                                 gettext_noop ("help text"),
860                                 options, &run, NULL)) ? ret : 1;
861 }
862
863 /* end of gnunet-daemon-vpn.c */