Fixes and documentation
[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 pid_t helper_pid;
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 || restart_hijack == 1)
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
169     return len;
170 }
171
172 /**
173  * Function scheduled as very last function, cleans up after us
174  */
175 static void
176 cleanup(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
177     GNUNET_assert (0 != (tskctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN));
178
179     /* stop the helper */
180     PLIBC_KILL(helper_pid, SIGTERM);
181     GNUNET_OS_process_wait(helper_pid);
182
183     /* close the connection to the service-dns */
184     if (dns_connection != NULL)
185       {
186         GNUNET_CLIENT_disconnect (dns_connection, GNUNET_NO);
187         dns_connection = NULL;
188       }
189 }
190
191 /**
192  * Start the helper-process
193  */
194 static void
195 start_helper_and_schedule(void *cls,
196                           const struct GNUNET_SCHEDULER_TaskContext *tc) {
197     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
198       return;
199
200     helper_in = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO);
201     helper_out = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
202
203     if (helper_in == NULL || helper_out == NULL) return;
204
205     helper_pid = GNUNET_OS_start_process(helper_in, helper_out, "gnunet-helper-vpn", "gnunet-helper-vpn", NULL);
206
207     fh_from_helper = GNUNET_DISK_pipe_handle (helper_out, GNUNET_DISK_PIPE_END_READ);
208     fh_to_helper = GNUNET_DISK_pipe_handle (helper_in, GNUNET_DISK_PIPE_END_WRITE);
209
210     GNUNET_DISK_pipe_close_end(helper_out, GNUNET_DISK_PIPE_END_WRITE);
211     GNUNET_DISK_pipe_close_end(helper_in, GNUNET_DISK_PIPE_END_READ);
212
213     GNUNET_SCHEDULER_add_read_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, fh_from_helper, &helper_read, NULL);
214 }
215
216 /**
217  * Restart the helper-process
218  */
219 static void
220 restart_helper(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tskctx) {
221     // Kill the helper
222     PLIBC_KILL(helper_pid, SIGKILL);
223     GNUNET_OS_process_wait(helper_pid);
224
225     /* Tell the dns-service to rehijack the dns-port
226      * The routing-table gets flushed if an interface disappears.
227      */
228     restart_hijack = 1;
229     GNUNET_CLIENT_notify_transmit_ready(dns_connection, sizeof(struct GNUNET_MessageHeader), GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_YES, &send_query, NULL);
230
231     GNUNET_DISK_pipe_close(helper_in);
232     GNUNET_DISK_pipe_close(helper_out);
233
234     /* Restart the helper */
235     GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_UNIT_SECONDS, start_helper_and_schedule, NULL);
236 }
237
238 /**
239  * Read from the helper-process
240  */
241 static void
242 helper_read(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx) {
243     /* no message can be bigger then 64k */
244     char buf[65535];
245
246     if (tsdkctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
247       return;
248
249     int t = GNUNET_DISK_file_read(fh_from_helper, &buf, 65535);
250
251     /* On read-error, restart the helper */
252     if (t<=0) {
253         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Read error for header from vpn-helper: %m\n");
254         GNUNET_SCHEDULER_add_now(sched, restart_helper, cls);
255         return;
256     }
257
258     /* FIXME */ GNUNET_SERVER_mst_receive(mst, NULL, buf, t, 0, 0);
259
260     GNUNET_SCHEDULER_add_read_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, fh_from_helper, &helper_read, NULL);
261 }
262
263 /**
264  * Calculate the checksum of an IPv4-Header
265  */
266 static uint16_t
267 calculate_ip_checksum(uint16_t* hdr, short len) {
268     uint32_t sum = 0;
269     for(; len >= 2; len -= 2)
270       sum += *(hdr++);
271     if (len == 1)
272       sum += *((unsigned char*)hdr);
273
274     sum = (sum >> 16) + (sum & 0xFFFF);
275
276     return ~sum;
277 }
278
279 /**
280  * Send an dns-answer-packet to the helper
281  */
282 static void
283 helper_write(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tsdkctx) {
284     if (tsdkctx->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
285       return;
286
287     struct answer_packet_list* ans = answer_proc_head;
288     size_t len = ntohs(ans->pkt.hdr.size);
289
290     GNUNET_assert(ans->pkt.subtype == GNUNET_DNS_ANSWER_TYPE_IP);
291
292     size_t data_len = len - sizeof(struct answer_packet) + 1;
293     size_t net_len = sizeof(struct ip_hdr) + sizeof(struct udp_dns) + data_len;
294     size_t pkt_len = sizeof(struct GNUNET_MessageHeader) + sizeof(struct pkt_tun) + net_len;
295
296     struct ip_udp_dns* pkt = alloca(pkt_len);
297     memset(pkt, 0, pkt_len);
298
299     /* set the gnunet-header */
300     pkt->shdr.size = htons(pkt_len);
301     pkt->shdr.type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
302
303     /* set the tun-header (no flags and ethertype of IPv4) */
304     pkt->tun.flags = 0;
305     pkt->tun.type = htons(0x0800);
306
307     /* set the ip-header */
308     pkt->ip_hdr.version = 4;
309     pkt->ip_hdr.hdr_lngth = 5;
310     pkt->ip_hdr.diff_serv = 0;
311     pkt->ip_hdr.tot_lngth = htons(net_len);
312     pkt->ip_hdr.ident = 0;
313     pkt->ip_hdr.flags = 0;
314     pkt->ip_hdr.frag_off = 0;
315     pkt->ip_hdr.ttl = 255;
316     pkt->ip_hdr.proto = 0x11; /* UDP */
317     pkt->ip_hdr.chks = 0; /* Will be calculated later*/
318     pkt->ip_hdr.sadr = ans->pkt.from;
319     pkt->ip_hdr.dadr = ans->pkt.to;
320
321     pkt->ip_hdr.chks = calculate_ip_checksum((uint16_t*)&pkt->ip_hdr, 5*4);
322
323     /* set the udp-header */
324     pkt->udp_dns.udp_hdr.spt = htons(53);
325     pkt->udp_dns.udp_hdr.dpt = ans->pkt.dst_port;
326     pkt->udp_dns.udp_hdr.len = htons(net_len - sizeof(struct ip_hdr));
327     pkt->udp_dns.udp_hdr.crc = 0; /* Optional for IPv4 */
328
329     memcpy(&pkt->udp_dns.data, ans->pkt.data, data_len);
330
331     GNUNET_CONTAINER_DLL_remove (answer_proc_head, answer_proc_tail, ans);
332     GNUNET_free(ans);
333
334     /* FIXME */ GNUNET_DISK_file_write(fh_to_helper, pkt, pkt_len);
335
336     /* if more packets are available, reschedule */
337     if (answer_proc_head != NULL)
338       GNUNET_SCHEDULER_add_write_file (sched,
339                                        GNUNET_TIME_UNIT_FOREVER_REL,
340                                        fh_to_helper,
341                                        &helper_write,
342                                        NULL);
343 }
344
345 /**
346  * Receive packets from the helper-process
347  */
348 static void
349 message_token(void *cls,
350               void *client,
351               const struct GNUNET_MessageHeader *message) {
352     GNUNET_assert(ntohs(message->type) == GNUNET_MESSAGE_TYPE_VPN_HELPER);
353
354     struct tun_pkt *pkt_tun = (struct tun_pkt*) message;
355
356     /* ethertype is ipv6 */
357     if (ntohs(pkt_tun->tun.type) == 0x86dd)
358       {
359         struct ip6_pkt *pkt6 = (struct ip6_pkt*) message;
360         struct ip6_tcp *pkt6_tcp;
361         struct ip6_udp *pkt6_udp;
362
363         pkt_printf(pkt6);
364         switch(pkt6->ip6_hdr.nxthdr)
365           {
366           case 0x06:
367             pkt6_tcp = (struct ip6_tcp*)pkt6;
368             pkt_printf_ip6tcp(pkt6_tcp);
369             break;
370           case 0x11:
371             pkt6_udp = (struct ip6_udp*)pkt6;
372             pkt_printf_ip6udp(pkt6_udp);
373             if (ntohs(pkt6_udp->udp_hdr.dpt) == 53) {
374                 pkt_printf_ip6dns((struct ip6_udp_dns*)pkt6_udp);
375             }
376             break;
377           }
378       }
379     /* ethertype is ipv4 */
380     else if (ntohs(pkt_tun->tun.type) == 0x0800)
381       {
382         struct ip_pkt *pkt = (struct ip_pkt*) message;
383         struct ip_udp *udp = (struct ip_udp*) message;
384         GNUNET_assert(pkt->ip_hdr.version == 4);
385
386         /* Send dns-packets to the service-dns */
387         if (pkt->ip_hdr.proto == 0x11 && ntohs(udp->udp_hdr.dpt) == 53 )
388           {
389             /* 9 = 8 for the udp-header + 1 for the unsigned char data[1]; */
390             size_t len = sizeof(struct query_packet) + ntohs(udp->udp_hdr.len) - 9;
391
392             struct query_packet_list* query = GNUNET_malloc(len + 2*sizeof(struct query_packet_list*));
393             query->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_QUERY_DNS);
394             query->pkt.hdr.size = htons(len);
395             query->pkt.orig_to = pkt->ip_hdr.dadr;
396             query->pkt.orig_from = pkt->ip_hdr.sadr;
397             query->pkt.src_port = udp->udp_hdr.spt;
398             memcpy(query->pkt.data, udp->data, ntohs(udp->udp_hdr.len) - 8);
399
400             GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, query);
401
402             if (dns_connection != NULL)
403               GNUNET_CLIENT_notify_transmit_ready(dns_connection,
404                                                   len,
405                                                   GNUNET_TIME_UNIT_FOREVER_REL,
406                                                   GNUNET_YES,
407                                                   &send_query,
408                                                   NULL);
409           }
410       }
411 }
412
413 /**
414  * Connect to the service-dns
415  */
416 static void
417 connect_to_service_dns (void *cls,
418                         const struct GNUNET_SCHEDULER_TaskContext *tc) {
419     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
420       return;
421     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Connecting to service-dns\n");
422     GNUNET_assert (dns_connection == NULL);
423     dns_connection = GNUNET_CLIENT_connect (sched, "dns", cfg);
424     GNUNET_CLIENT_receive(dns_connection, &dns_answer_handler, NULL, GNUNET_TIME_UNIT_FOREVER_REL);
425
426     /* If a packet is already in the list, schedule to send it */
427     if (head != NULL)
428       GNUNET_CLIENT_notify_transmit_ready(dns_connection,
429                                           ntohs(head->pkt.hdr.size),
430                                           GNUNET_TIME_UNIT_FOREVER_REL,
431                                           GNUNET_YES,
432                                           &send_query,
433                                           NULL);
434 }
435
436 /**
437  * This gets scheduled with cls pointing to an answer_packet and does everything
438  * needed in order to send it to the helper.
439  *
440  * At the moment this means "inventing" and IPv6-Address for .gnunet-services and
441  * doing nothing for "real" services.
442  */
443 static void
444 process_answer(void* cls, const struct GNUNET_SCHEDULER_TaskContext* tc) {
445     struct answer_packet* pkt = cls;
446
447     /* This answer is about a .gnunet-service
448      *
449      * It contains an almost complete DNS-Response, we have to fill in the ip
450      * at the offset pkt->addroffset
451      */
452     if (pkt->subtype == GNUNET_DNS_ANSWER_TYPE_SERVICE)
453       {
454         unsigned char ip6addr[16];
455
456         pkt->subtype = GNUNET_DNS_ANSWER_TYPE_IP;
457         memcpy(ip6addr, (int[]){htons(0x1234)}, 2);
458         memcpy(ip6addr+2, &pkt->peer, 7);
459         memcpy(ip6addr+9, &pkt->service_descriptor, 7);
460
461         memcpy(((char*)pkt)+ntohs(pkt->addroffset), ip6addr, 16);
462
463           /*FIXME:
464            * -save DNS_Record into hashmap, pointed to by ip
465            * -regularily walk through hashmap, deleting old entries
466            *  when is an entry old?
467            *  have a last-used field
468            *  don't remove if last-used "recent", ask dht again if record expired
469            */
470       }
471
472     struct answer_packet_list* list = GNUNET_malloc(htons(pkt->hdr.size) + 2*sizeof(struct answer_packet_list*));
473
474     memcpy(&list->pkt, pkt, htons(pkt->hdr.size));
475
476     GNUNET_CONTAINER_DLL_insert_after(answer_proc_head, answer_proc_tail, answer_proc_tail, list);
477
478     GNUNET_SCHEDULER_add_write_file (sched, GNUNET_TIME_UNIT_FOREVER_REL, fh_to_helper, &helper_write, NULL);
479
480     return;
481 }
482
483 /**
484  * This receives packets from the service-dns and schedules process_answer to
485  * handle it
486  */
487 static void
488 dns_answer_handler(void* cls, const struct GNUNET_MessageHeader *msg) {
489     /* the service disconnected, reconnect after short wait */
490     if (msg == NULL)
491       {
492         GNUNET_CLIENT_disconnect(dns_connection, GNUNET_NO);
493         dns_connection = NULL;
494         GNUNET_SCHEDULER_add_delayed (sched,
495                                       GNUNET_TIME_UNIT_SECONDS,
496                                       &connect_to_service_dns,
497                                       NULL);
498         return;
499       }
500
501     /* the service did something strange, reconnect immediately */
502     if (msg->type != htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS))
503       {
504         GNUNET_break (0);
505         GNUNET_CLIENT_disconnect(dns_connection, GNUNET_NO);
506         dns_connection = NULL;
507         GNUNET_SCHEDULER_add_now (sched,
508                                   &connect_to_service_dns,
509                                   NULL);
510         return;
511       }
512     void *pkt = GNUNET_malloc(ntohs(msg->size));
513
514     memcpy(pkt, msg, ntohs(msg->size));
515
516     GNUNET_SCHEDULER_add_now(sched, process_answer, pkt);
517     GNUNET_CLIENT_receive(dns_connection, &dns_answer_handler, NULL, GNUNET_TIME_UNIT_FOREVER_REL);
518 }
519
520 /**
521  * Main function that will be run by the scheduler.
522  *
523  * @param cls closure
524  * @param sched the scheduler to use
525  * @param args remaining command-line arguments
526  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
527  * @param cfg configuration
528  */
529 static void
530 run (void *cls,
531      struct GNUNET_SCHEDULER_Handle *sched_,
532      char *const *args,
533      const char *cfgfile,
534      const struct GNUNET_CONFIGURATION_Handle *cfg_) {
535     sched = sched_;
536     mst = GNUNET_SERVER_mst_create(&message_token, NULL);
537     cfg = cfg_;
538     restart_hijack = 0;
539     GNUNET_SCHEDULER_add_now (sched, connect_to_service_dns, NULL);
540     GNUNET_SCHEDULER_add_now (sched, start_helper_and_schedule, NULL);
541     GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_UNIT_FOREVER_REL, &cleanup, cls); 
542 }
543
544 /**
545  * The main function to obtain template from gnunetd.
546  *
547  * @param argc number of arguments from the command line
548  * @param argv command line arguments
549  * @return 0 ok, 1 on error
550  */
551 int
552 main (int argc, char *const *argv) {
553     static const struct GNUNET_GETOPT_CommandLineOption options[] = {
554         GNUNET_GETOPT_OPTION_END
555     };
556
557     return (GNUNET_OK ==
558             GNUNET_PROGRAM_run (argc,
559                                 argv,
560                                 "gnunet-daemon-vpn",
561                                 gettext_noop ("help text"),
562                                 options, &run, NULL)) ? ret : 1;
563 }
564
565 /* end of gnunet-daemon-vpn.c */