Answer PTR-Requests (mock-version)
[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 Tölke
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_client_lib.h"
38 #include "gnunet_container_lib.h"
39 #include "block_dns.h"
40
41 /**
42  * Final status code.
43  */
44 static int ret;
45
46 /**
47  * The scheduler to use throughout the daemon
48  */
49 static struct GNUNET_SCHEDULER_Handle *sched;
50
51 /**
52  * The configuration to use
53  */
54 static const struct GNUNET_CONFIGURATION_Handle *cfg;
55
56 /**
57  * PipeHandle to receive data from the helper
58  */
59 static struct GNUNET_DISK_PipeHandle* helper_in;
60
61 /**
62  * PipeHandle to send data to the helper
63  */
64 static struct GNUNET_DISK_PipeHandle* helper_out;
65
66 /**
67  * FileHandle to receive data from the helper
68  */
69 static const struct GNUNET_DISK_FileHandle* fh_from_helper;
70
71 /**
72  * FileHandle to send data to the helper
73  */
74 static const struct GNUNET_DISK_FileHandle* fh_to_helper;
75
76 /**
77  * The Message-Tokenizer that tokenizes the messages comming from the helper
78  */
79 static struct GNUNET_SERVER_MessageStreamTokenizer* mst;
80
81 /**
82  * The connection to the service-dns
83  */
84 static struct GNUNET_CLIENT_Connection *dns_connection;
85
86 /**
87  * A flag to show that the service-dns has to rehijack the outbound dns-packets
88  *
89  * This gets set when the helper restarts as the routing-tables are flushed when
90  * the interface vanishes.
91  */
92 static unsigned char restart_hijack;
93
94 /**
95  * The process id of the helper
96  */
97 static struct GNUNET_OS_Process *helper_proc;
98
99 /**
100  * a list of outgoing dns-query-packets
101  */
102 static struct query_packet_list *head;
103
104 /**
105  * The last element of the list of outgoing dns-query-packets
106  */
107 static struct query_packet_list *tail;
108
109 /**
110  * A list of processed dns-responses.
111  *
112  * "processed" means that the packet is complete and can be sent out via udp
113  * directly
114  */
115 static struct answer_packet_list *answer_proc_head;
116
117 /**
118  * The last element of the list of processed dns-responses.
119  */
120 static struct answer_packet_list *answer_proc_tail;
121
122 static void helper_read(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx);
123 static void dns_answer_handler(void* cls, const struct GNUNET_MessageHeader *msg);
124
125 /**
126  * Callback called by notify_transmit_ready; sends dns-queries or rehijack-messages
127  * to the service-dns
128  */
129 static size_t
130 send_query(void* cls, size_t size, void* buf) {
131     size_t len;
132     /*
133      * Send the rehijack-message
134      */
135     if (restart_hijack == 1)
136       {
137         restart_hijack = 0;
138         /*
139          * The message is just a header
140          */
141         GNUNET_assert(sizeof(struct GNUNET_MessageHeader) <= size);
142         struct GNUNET_MessageHeader* hdr = buf;
143         len = sizeof(struct GNUNET_MessageHeader);
144         hdr->size = htons(len);
145         hdr->type = htons(GNUNET_MESSAGE_TYPE_REHIJACK);
146       }
147     else
148       {
149         struct query_packet_list* query = head;
150         len = ntohs(query->pkt.hdr.size);
151
152         GNUNET_assert(len <= size);
153
154         memcpy(buf, &query->pkt.hdr, len);
155
156         GNUNET_CONTAINER_DLL_remove (head, tail, query);
157
158         GNUNET_free(query);
159       }
160
161     /*
162      * Check whether more data is to be sent
163      */
164     if (head != NULL)
165       {
166         GNUNET_CLIENT_notify_transmit_ready(dns_connection, ntohs(head->pkt.hdr.size), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
167       }
168     else if (restart_hijack == 1)
169       {
170         GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
171       }
172
173     return len;
174 }
175
176 /**
177  * Function scheduled as very last function, cleans up after us
178  */
179 static void
180 cleanup(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
181     GNUNET_assert (0 != (tskctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN));
182
183     /* stop the helper */
184     GNUNET_OS_process_kill (helper_proc, SIGTERM);
185     GNUNET_OS_process_wait (helper_proc);
186     GNUNET_OS_process_close (helper_proc);
187     helper_proc = NULL;
188
189     /* close the connection to the service-dns */
190     if (dns_connection != NULL)
191       {
192         GNUNET_CLIENT_disconnect (dns_connection, GNUNET_NO);
193         dns_connection = NULL;
194       }
195 }
196
197 /**
198  * Start the helper-process
199  */
200 static void
201 start_helper_and_schedule(void *cls,
202                           const struct GNUNET_SCHEDULER_TaskContext *tc) {
203     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
204       return;
205
206     helper_in = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO);
207     helper_out = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
208
209     if (helper_in == NULL || helper_out == NULL) return;
210
211     helper_proc = GNUNET_OS_start_process(helper_in, helper_out, "gnunet-helper-vpn", "gnunet-helper-vpn", NULL);
212
213     fh_from_helper = GNUNET_DISK_pipe_handle (helper_out, GNUNET_DISK_PIPE_END_READ);
214     fh_to_helper = GNUNET_DISK_pipe_handle (helper_in, GNUNET_DISK_PIPE_END_WRITE);
215
216     GNUNET_DISK_pipe_close_end(helper_out, GNUNET_DISK_PIPE_END_WRITE);
217     GNUNET_DISK_pipe_close_end(helper_in, GNUNET_DISK_PIPE_END_READ);
218
219     /* Tell the dns-service to rehijack the dns-port
220      * The routing-table gets flushed if an interface disappears.
221      */
222     restart_hijack = 1;
223     GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
224
225     GNUNET_SCHEDULER_add_read_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, fh_from_helper, &helper_read, NULL);
226 }
227
228 /**
229  * Restart the helper-process
230  */
231 static void
232 restart_helper(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
233     // Kill the helper
234     GNUNET_OS_process_kill (helper_proc, SIGKILL);
235     GNUNET_OS_process_wait (helper_proc);
236     GNUNET_OS_process_close (helper_proc);
237     helper_proc = NULL;
238
239     GNUNET_DISK_pipe_close(helper_in);
240     GNUNET_DISK_pipe_close(helper_out);
241
242     /* Restart the helper */
243     GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_UNIT_SECONDS, start_helper_and_schedule, NULL);
244 }
245
246 /**
247  * Read from the helper-process
248  */
249 static void
250 helper_read(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx) {
251     /* no message can be bigger then 64k */
252     char buf[65535];
253
254     if (tsdkctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
255       return;
256
257     int t = GNUNET_DISK_file_read(fh_from_helper, &buf, 65535);
258
259     /* On read-error, restart the helper */
260     if (t<=0) {
261         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Read error for header from vpn-helper: %m\n");
262         GNUNET_SCHEDULER_add_now(sched, restart_helper, cls);
263         return;
264     }
265
266     /* FIXME */ GNUNET_SERVER_mst_receive(mst, NULL, buf, t, 0, 0);
267
268     GNUNET_SCHEDULER_add_read_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, fh_from_helper, &helper_read, NULL);
269 }
270
271 /**
272  * Calculate the checksum of an IPv4-Header
273  */
274 static uint16_t
275 calculate_ip_checksum(uint16_t* hdr, short len) {
276     uint32_t sum = 0;
277     for(; len >= 2; len -= 2)
278       sum += *(hdr++);
279     if (len == 1)
280       sum += *((unsigned char*)hdr);
281
282     sum = (sum >> 16) + (sum & 0xFFFF);
283
284     return ~sum;
285 }
286
287 /**
288  * Send an dns-answer-packet to the helper
289  */
290 static void
291 helper_write(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx) {
292     if (tsdkctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
293       return;
294
295     struct answer_packet_list* ans = answer_proc_head;
296     size_t len = ntohs(ans->pkt.hdr.size);
297
298     GNUNET_assert(ans->pkt.subtype == GNUNET_DNS_ANSWER_TYPE_IP);
299
300     size_t data_len = len - sizeof(struct answer_packet) + 1;
301     size_t net_len = sizeof(struct ip_hdr) + sizeof(struct udp_dns) + data_len;
302     size_t pkt_len = sizeof(struct GNUNET_MessageHeader) + sizeof(struct pkt_tun) + net_len;
303
304     struct ip_udp_dns* pkt = alloca(pkt_len);
305     memset(pkt, 0, pkt_len);
306
307     /* set the gnunet-header */
308     pkt->shdr.size = htons(pkt_len);
309     pkt->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
310
311     /* set the tun-header (no flags and ethertype of IPv4) */
312     pkt->tun.flags = 0;
313     pkt->tun.type = htons(0x0800);
314
315     /* set the ip-header */
316     pkt->ip_hdr.version = 4;
317     pkt->ip_hdr.hdr_lngth = 5;
318     pkt->ip_hdr.diff_serv = 0;
319     pkt->ip_hdr.tot_lngth = htons(net_len);
320     pkt->ip_hdr.ident = 0;
321     pkt->ip_hdr.flags = 0;
322     pkt->ip_hdr.frag_off = 0;
323     pkt->ip_hdr.ttl = 255;
324     pkt->ip_hdr.proto = 0x11; /* UDP */
325     pkt->ip_hdr.chks = 0; /* Will be calculated later*/
326     pkt->ip_hdr.sadr = ans->pkt.from;
327     pkt->ip_hdr.dadr = ans->pkt.to;
328
329     pkt->ip_hdr.chks = calculate_ip_checksum((uint16_t*)&pkt->ip_hdr, 5*4);
330
331     /* set the udp-header */
332     pkt->udp_dns.udp_hdr.spt = htons(53);
333     pkt->udp_dns.udp_hdr.dpt = ans->pkt.dst_port;
334     pkt->udp_dns.udp_hdr.len = htons(net_len - sizeof(struct ip_hdr));
335     pkt->udp_dns.udp_hdr.crc = 0; /* Optional for IPv4 */
336
337     memcpy(&pkt->udp_dns.data, ans->pkt.data, data_len);
338
339     GNUNET_CONTAINER_DLL_remove (answer_proc_head, answer_proc_tail, ans);
340     GNUNET_free(ans);
341
342     /* FIXME */ GNUNET_DISK_file_write(fh_to_helper, pkt, pkt_len);
343
344     /* if more packets are available, reschedule */
345     if (answer_proc_head != NULL)
346       GNUNET_SCHEDULER_add_write_file (sched,
347                                        GNUNET_TIME_UNIT_FOREVER_REL,
348                                        fh_to_helper,
349                                        &helper_write,
350                                        NULL);
351 }
352
353 /**
354  * Receive packets from the helper-process
355  */
356 static void
357 message_token(void *cls,
358               void *client,
359               const struct GNUNET_MessageHeader *message) {
360     GNUNET_assert(ntohs(message->type) == GNUNET_MESSAGE_TYPE_VPN_HELPER);
361
362     struct tun_pkt *pkt_tun = (struct tun_pkt*) message;
363
364     /* ethertype is ipv6 */
365     if (ntohs(pkt_tun->tun.type) == 0x86dd)
366       {
367         struct ip6_pkt *pkt6 = (struct ip6_pkt*) message;
368         struct ip6_tcp *pkt6_tcp;
369         struct ip6_udp *pkt6_udp;
370
371         pkt_printf(pkt6);
372         switch(pkt6->ip6_hdr.nxthdr)
373           {
374           case 0x06:
375             pkt6_tcp = (struct ip6_tcp*)pkt6;
376             pkt_printf_ip6tcp(pkt6_tcp);
377             break;
378           case 0x11:
379             pkt6_udp = (struct ip6_udp*)pkt6;
380             pkt_printf_ip6udp(pkt6_udp);
381             if (ntohs(pkt6_udp->udp_hdr.dpt) == 53) {
382                 pkt_printf_ip6dns((struct ip6_udp_dns*)pkt6_udp);
383             }
384             break;
385           }
386       }
387     /* ethertype is ipv4 */
388     else if (ntohs(pkt_tun->tun.type) == 0x0800)
389       {
390         struct ip_pkt *pkt = (struct ip_pkt*) message;
391         struct ip_udp *udp = (struct ip_udp*) message;
392         GNUNET_assert(pkt->ip_hdr.version == 4);
393
394         /* Send dns-packets to the service-dns */
395         if (pkt->ip_hdr.proto == 0x11 && ntohs(udp->udp_hdr.dpt) == 53 )
396           {
397             /* 9 = 8 for the udp-header + 1 for the unsigned char data[1]; */
398             size_t len = sizeof(struct query_packet) + ntohs(udp->udp_hdr.len) - 9;
399
400             struct query_packet_list* query = GNUNET_malloc(len + 2*sizeof(struct query_packet_list*));
401             query->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_QUERY_DNS);
402             query->pkt.hdr.size = htons(len);
403             query->pkt.orig_to = pkt->ip_hdr.dadr;
404             query->pkt.orig_from = pkt->ip_hdr.sadr;
405             query->pkt.src_port = udp->udp_hdr.spt;
406             memcpy(query->pkt.data, udp->data, ntohs(udp->udp_hdr.len) - 8);
407
408             GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, query);
409
410             if (dns_connection != NULL)
411               GNUNET_CLIENT_notify_transmit_ready(dns_connection,
412                                                   len,
413                                                   GNUNET_TIME_UNIT_FOREVER_REL,
414                                                   GNUNET_YES,
415                                                   &send_query,
416                                                   NULL);
417           }
418       }
419 }
420
421 /**
422  * Connect to the service-dns
423  */
424 static void
425 connect_to_service_dns (void *cls,
426                         const struct GNUNET_SCHEDULER_TaskContext *tc) {
427     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
428       return;
429     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting to service-dns\n");
430     GNUNET_assert (dns_connection == NULL);
431     dns_connection = GNUNET_CLIENT_connect (sched, "dns", cfg);
432     GNUNET_CLIENT_receive(dns_connection, &dns_answer_handler, NULL, GNUNET_TIME_UNIT_FOREVER_REL);
433
434     /* If a packet is already in the list, schedule to send it */
435     if (head != NULL)
436       GNUNET_CLIENT_notify_transmit_ready(dns_connection,
437                                           ntohs(head->pkt.hdr.size),
438                                           GNUNET_TIME_UNIT_FOREVER_REL,
439                                           GNUNET_YES,
440                                           &send_query,
441                                           NULL);
442     else if (restart_hijack == 1)
443       {
444         GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
445       }
446 }
447
448 /**
449  * This gets scheduled with cls pointing to an answer_packet and does everything
450  * needed in order to send it to the helper.
451  *
452  * At the moment this means "inventing" and IPv6-Address for .gnunet-services and
453  * doing nothing for "real" services.
454  */
455 static void
456 process_answer(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tc) {
457     struct answer_packet* pkt = cls;
458     struct answer_packet_list* list;
459
460     /* This answer is about a .gnunet-service
461      *
462      * It contains an almost complete DNS-Response, we have to fill in the ip
463      * at the offset pkt->addroffset
464      */
465     //FIXME htons?
466     if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_SERVICE)
467       {
468         unsigned char ip6addr[16];
469
470         pkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
471         memcpy(ip6addr, (int[]){htons(0x1234)}, 2);
472         memcpy(ip6addr+2, &pkt->peer, 7);
473         memcpy(ip6addr+9, &pkt->service_descriptor, 7);
474
475         memcpy(((char*)pkt)+ntohs(pkt->addroffset), ip6addr, 16);
476
477           /*FIXME:
478            * -save DNS_Record into hashmap, pointed to by ip
479            * -regularily walk through hashmap, deleting old entries
480            *  when is an entry old?
481            *  have a last-used field
482            *  don't remove if last-used "recent", ask dht again if record expired
483            */
484
485         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
486
487         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
488       }
489     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_REV)
490       {
491         unsigned short offset = ntohs(pkt->addroffset);
492
493         unsigned short namelen = htons(22); /* calculate the length of the answer */
494         char name[22] = {13, 'p', 'h', 'i', 'l', 'i', 'p', 'p', 't', 'o', 'e', 'l', 'k', 'e', 6, 'g', 'n', 'u', 'n', 'e', 't', 0};
495
496         list = GNUNET_malloc(2*sizeof(struct answer_packet_list*) + offset + 2 + ntohs(namelen));
497
498         struct answer_packet* rpkt = &list->pkt;
499
500         memcpy(rpkt, pkt, offset);
501
502         rpkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
503         rpkt->hdr.size = ntohs(offset + 2 + ntohs(namelen));
504
505         memcpy(((char*)rpkt)+offset, &namelen, 2);
506         memcpy(((char*)rpkt)+offset+2, name, ntohs(namelen));
507
508       }
509     else if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_IP)
510       {
511         list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
512         memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
513       }
514
515     GNUNET_CONTAINER_DLL_insert_after(answer_proc_head, answer_proc_tail, answer_proc_tail, list);
516
517     GNUNET_SCHEDULER_add_write_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, fh_to_helper, &helper_write, NULL);
518
519     return;
520 }
521
522 /**
523  * This receives packets from the service-dns and schedules process_answer to
524  * handle it
525  */
526 static void
527 dns_answer_handler(void* cls, const struct GNUNET_MessageHeader *msg) {
528     /* the service disconnected, reconnect after short wait */
529     if (msg == NULL)
530       {
531         GNUNET_CLIENT_disconnect(dns_connection, GNUNET_NO);
532         dns_connection = NULL;
533         GNUNET_SCHEDULER_add_delayed (sched,
534                                       GNUNET_TIME_UNIT_SECONDS,
535                                       &connect_to_service_dns,
536                                       NULL);
537         return;
538       }
539
540     /* the service did something strange, reconnect immediately */
541     if (msg->type != htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS))
542       {
543         GNUNET_break (0);
544         GNUNET_CLIENT_disconnect(dns_connection, GNUNET_NO);
545         dns_connection = NULL;
546         GNUNET_SCHEDULER_add_now (sched,
547                                   &connect_to_service_dns,
548                                   NULL);
549         return;
550       }
551     void *pkt = GNUNET_malloc(ntohs(msg->size));
552
553     memcpy(pkt, msg, ntohs(msg->size));
554
555     GNUNET_SCHEDULER_add_now(sched, process_answer, pkt);
556     GNUNET_CLIENT_receive(dns_connection, &dns_answer_handler, NULL, GNUNET_TIME_UNIT_FOREVER_REL);
557 }
558
559 /**
560  * Main function that will be run by the scheduler.
561  *
562  * @param cls closure
563  * @param sched the scheduler to use
564  * @param args remaining command-line arguments
565  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
566  * @param cfg configuration
567  */
568 static void
569 run (void *cls,
570      struct GNUNET_SCHEDULER_Handle *sched_,
571      char *const *args,
572      const char *cfgfile,
573      const struct GNUNET_CONFIGURATION_Handle *cfg_) {
574     sched = sched_;
575     mst = GNUNET_SERVER_mst_create(&message_token, NULL);
576     cfg = cfg_;
577     restart_hijack = 0;
578     GNUNET_SCHEDULER_add_now (sched, connect_to_service_dns, NULL);
579     GNUNET_SCHEDULER_add_now (sched, start_helper_and_schedule, NULL);
580     GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls); 
581 }
582
583 /**
584  * The main function to obtain template from gnunetd.
585  *
586  * @param argc number of arguments from the command line
587  * @param argv command line arguments
588  * @return 0 ok, 1 on error
589  */
590 int
591 main (int argc, char *const *argv) {
592     static const struct GNUNET_GETOPT_CommandLineOption options[] = {
593         GNUNET_GETOPT_OPTION_END
594     };
595
596     return (GNUNET_OK ==
597             GNUNET_PROGRAM_run (argc,
598                                 argv,
599                                 "gnunet-daemon-vpn",
600                                 gettext_noop ("help text"),
601                                 options, &run, NULL)) ? ret : 1;
602 }
603
604 /* end of gnunet-daemon-vpn.c */