big scheduler refactoring, expect some issues
[oweals/gnunet.git] / src / vpn / gnunet-service-dns.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009 Christian Grothoff (and other contributing authors)
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-service-dns.c
23  * @author Philipp Toelke
24  */
25 #include "platform.h"
26 #include "gnunet_getopt_lib.h"
27 #include "gnunet_service_lib.h"
28 #include "gnunet_network_lib.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet-service-dns-p.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet-vpn-packet.h"
33 #include "gnunet-vpn-pretty-print.h"
34 #include "gnunet_container_lib.h"
35 #include "gnunet-dns-parser.h"
36 #include "gnunet_dht_service.h"
37 #include "gnunet_block_lib.h"
38 #include "block_dns.h"
39 #include "gnunet_crypto_lib.h"
40 #include "gnunet_signatures.h"
41
42
43 /**
44  * The UDP-Socket through which DNS-Resolves will be sent if they are not to be
45  * sent through gnunet. The port of this socket will not be hijacked.
46  */
47 static struct GNUNET_NETWORK_Handle *dnsout;
48
49 /**
50  * The port bound to the socket dnsout
51  */
52 static unsigned short dnsoutport;
53
54 /**
55  * A handle to the DHT-Service
56  */
57 static struct GNUNET_DHT_Handle *dht;
58
59 /**
60  * The configuration to use
61  */
62 static const struct GNUNET_CONFIGURATION_Handle *cfg;
63
64 /**
65  * A list of DNS-Responses that have to be sent to the requesting client
66  */
67 static struct answer_packet_list *head;
68
69 /**
70  * The tail of the list of DNS-responses
71  */
72 static struct answer_packet_list *tail;
73
74 /**
75  * A structure containing a mapping from network-byte-ordered DNS-id to
76  * some information needed to handle this query
77  *
78  * It currently allocates at least
79  * (1 + machine-width + 32 + 32 + 16 + machine-width + 8) * 65536 bit
80  * = 1.7 MiB on 64 bit.
81  * = 1.2 MiB on 32 bit.
82  */
83 static struct {
84     unsigned valid:1;
85     struct GNUNET_SERVER_Client* client;
86     unsigned local_ip:32;
87     unsigned remote_ip:32;
88     unsigned local_port:16;
89     char* name;
90     unsigned namelen:8;
91 } query_states[65536];
92
93 /**
94  * A struct used to give more than one value as
95  * closure to receive_dht
96  */
97 struct receive_dht_cls {
98     unsigned short id;
99     struct GNUNET_DHT_GetHandle* handle;
100 };
101
102 /**
103  * Hijack all outgoing DNS-Traffic but for traffic leaving "our" port.
104  */
105 static void
106 hijack(unsigned short port) {
107     char port_s[6];
108
109     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Hijacking, port is %d\n", port);
110     snprintf(port_s, 6, "%d", port);
111     GNUNET_OS_start_process(NULL,
112                             NULL,
113                             "gnunet-helper-hijack-dns",
114                             "gnunet-hijack-dns",
115                             port_s,
116                             NULL);
117 }
118
119 /**
120  * Delete the hijacking-routes
121  */
122 static void
123 unhijack(unsigned short port) {
124     char port_s[6];
125
126     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "unHijacking, port is %d\n", port);
127     snprintf(port_s, 6, "%d", port);
128     GNUNET_OS_start_process(NULL,
129                             NULL,
130                             "gnunet-helper-hijack-dns",
131                             "gnunet-hijack-dns",
132                             "-d",
133                             port_s,
134                             NULL);
135 }
136
137 /**
138  * Send the DNS-Response to the client. Gets called via the notify_transmit_ready-
139  * system.
140  */
141 static size_t
142 send_answer(void* cls, size_t size, void* buf) {
143     struct answer_packet_list* query = head;
144     size_t len = ntohs(query->pkt.hdr.size);
145
146     GNUNET_assert(len <= size);
147
148     memcpy(buf, &query->pkt.hdr, len);
149
150     GNUNET_CONTAINER_DLL_remove (head, tail, query);
151
152     GNUNET_free(query);
153
154     /* When more data is to be sent, reschedule */
155     if (head != NULL)
156       GNUNET_SERVER_notify_transmit_ready(cls,
157                                           ntohs(head->pkt.hdr.size),
158                                           GNUNET_TIME_UNIT_FOREVER_REL,
159                                           &send_answer,
160                                           cls);
161
162     return len;
163 }
164
165 /**
166  * Receive a block from the dht.
167  */
168 static void
169 receive_dht(void *cls,
170             struct GNUNET_TIME_Absolute exp,
171             const GNUNET_HashCode *key,
172             const struct GNUNET_PeerIdentity *const *get_path,
173             const struct GNUNET_PeerIdentity *const *put_path,
174             enum GNUNET_BLOCK_Type type,
175             size_t size,
176             const void *data) {
177
178     unsigned short id = ((struct receive_dht_cls*)cls)->id;
179     struct GNUNET_DHT_GetHandle* handle = ((struct receive_dht_cls*)cls)->handle;
180     GNUNET_free(cls);
181
182     GNUNET_assert(type == GNUNET_BLOCK_TYPE_DNS);
183
184     /* If no query with this id is pending, ignore the block */
185     if (query_states[id].valid != GNUNET_YES) return;
186     query_states[id].valid = GNUNET_NO;
187
188     const struct GNUNET_DNS_Record* rec = data;
189     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
190                "Got block of size %d, peer: %08x, desc: %08x\n",
191                size,
192                *((unsigned int*)&rec->peer),
193                *((unsigned int*)&rec->service_descriptor));
194
195     size_t len = sizeof(struct answer_packet) - 1 \
196                  + sizeof(struct dns_static) \
197                  + query_states[id].namelen \
198                  + sizeof(struct dns_query_line) \
199                  + 2 /* To hold the pointer (as defined in RFC1035) to the name */ \
200                  + sizeof(struct dns_record_line) - 1 \
201                  + 16; /* To hold the IPv6-Address */
202
203     struct answer_packet_list* answer = GNUNET_malloc(len + 2*sizeof(struct answer_packet_list*));
204     memset(answer, 0, len + 2*sizeof(struct answer_packet_list*));
205
206     answer->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS);
207     answer->pkt.hdr.size = htons(len);
208     answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_SERVICE;
209
210     GNUNET_CRYPTO_hash(&rec->peer,
211                        sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
212                        &answer->pkt.peer);
213
214     memcpy(&answer->pkt.service_descriptor,
215            &rec->service_descriptor,
216            sizeof(GNUNET_HashCode));
217     memcpy(&answer->pkt.service_type,
218            &rec->service_type,
219            sizeof(answer->pkt.service_type));
220     memcpy(&answer->pkt.ports, &rec->ports, sizeof(answer->pkt.ports));
221
222     answer->pkt.from = query_states[id].remote_ip;
223
224     answer->pkt.to = query_states[id].local_ip;
225     answer->pkt.dst_port = query_states[id].local_port;
226
227     struct dns_pkt *dpkt = (struct dns_pkt*)answer->pkt.data;
228
229     dpkt->s.id = id;
230     dpkt->s.aa = 1;
231     dpkt->s.qr = 1;
232     dpkt->s.ra = 1;
233     dpkt->s.qdcount = htons(1);
234     dpkt->s.ancount = htons(1);
235
236     memcpy(dpkt->data, query_states[id].name, query_states[id].namelen);
237     GNUNET_free(query_states[id].name);
238
239
240     struct dns_query_line* dque = (struct dns_query_line*)(dpkt->data+(query_states[id].namelen));
241     dque->type = htons(28); /* AAAA */
242     dque->class = htons(1); /* IN */
243
244     char* anname = (char*)(dpkt->data+(query_states[id].namelen)+sizeof(struct dns_query_line));
245     memcpy(anname, (char[]){0xc0, 0x0c}, 2);
246
247     struct dns_record_line *drec_data = (struct dns_record_line*)(dpkt->data+(query_states[id].namelen)+sizeof(struct dns_query_line)+2);
248     drec_data->type = htons(28); /* AAAA */
249     drec_data->class = htons(1); /* IN */
250     drec_data->ttl = htonl(3600); /* FIXME: read from block */
251     drec_data->data_len = htons(16);
252
253     /* Calculate at which offset in the packet the IPv6-Address belongs, it is
254      * filled in by the daemon-vpn */
255     answer->pkt.addroffset = htons((unsigned short)((unsigned long)(&drec_data->data)-(unsigned long)(&answer->pkt)));
256
257     GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, answer);
258
259     GNUNET_SERVER_notify_transmit_ready(query_states[id].client,
260                                         len,
261                                         GNUNET_TIME_UNIT_FOREVER_REL,
262                                         &send_answer,
263                                         query_states[id].client);
264
265     GNUNET_DHT_get_stop(handle);
266 }
267
268 /**
269  * This receives a GNUNET_MESSAGE_TYPE_REHIJACK and rehijacks the DNS
270  */
271 static void
272 rehijack(void *cls,
273          struct GNUNET_SERVER_Client *client,
274          const struct GNUNET_MessageHeader *message) {
275     unhijack(dnsoutport);
276     hijack(dnsoutport);
277 }
278
279 /**
280  * This receives the dns-payload from the daemon-vpn and sends it on over the udp-socket
281  */
282 static void
283 receive_query(void *cls,
284               struct GNUNET_SERVER_Client *client,
285               const struct GNUNET_MessageHeader *message) {
286     struct query_packet* pkt = (struct query_packet*)message;
287     struct dns_pkt* dns = (struct dns_pkt*)pkt->data;
288     struct dns_pkt_parsed* pdns = parse_dns_packet(dns);
289
290     query_states[dns->s.id].valid = GNUNET_YES;
291     query_states[dns->s.id].client = client;
292     query_states[dns->s.id].local_ip = pkt->orig_from;
293     query_states[dns->s.id].local_port = pkt->src_port;
294     query_states[dns->s.id].remote_ip = pkt->orig_to;
295     query_states[dns->s.id].namelen = strlen((char*)dns->data) + 1;
296     query_states[dns->s.id].name = GNUNET_malloc(query_states[dns->s.id].namelen);
297     memcpy(query_states[dns->s.id].name, dns->data, query_states[dns->s.id].namelen);
298
299     if (pdns->queries[0]->namelen > 9 &&
300         0 == strncmp(pdns->queries[0]->name+(pdns->queries[0]->namelen - 9), ".gnunet.", 9))
301       {
302         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Query for .gnunet!\n");
303         GNUNET_HashCode key;
304         GNUNET_CRYPTO_hash(pdns->queries[0]->name, pdns->queries[0]->namelen, &key);
305
306         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
307                    "Getting with key %08x, len is %d\n",
308                    *((unsigned int*)&key),
309                    pdns->queries[0]->namelen);
310
311         struct receive_dht_cls* cls = GNUNET_malloc(sizeof(struct receive_dht_cls));
312         cls->id = dns->s.id;
313
314         cls->handle = GNUNET_DHT_get_start(dht,
315                                            GNUNET_TIME_UNIT_MINUTES,
316                                            GNUNET_BLOCK_TYPE_DNS,
317                                            &key,
318                                            GNUNET_DHT_RO_NONE,
319                                            NULL,
320                                            0,
321                                            NULL,
322                                            0,
323                                            receive_dht,
324                                            cls);
325
326         goto out;
327       }
328
329     /* The query should be sent to the network */
330
331     struct sockaddr_in dest;
332     memset(&dest, 0, sizeof dest);
333     dest.sin_port = htons(53);
334     dest.sin_addr.s_addr = pkt->orig_to;
335
336     GNUNET_NETWORK_socket_sendto(dnsout,
337                                  dns,
338                                  ntohs(pkt->hdr.size) - sizeof(struct query_packet) + 1,
339                                  (struct sockaddr*) &dest,
340                                  sizeof dest);
341
342 out:
343     free_parsed_dns_packet(pdns);
344     pdns = NULL;
345     GNUNET_SERVER_receive_done(client, GNUNET_OK);
346 }
347
348 /**
349  * Read a response-packet of the UDP-Socket
350  */
351 static void
352 read_response (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc) {
353     unsigned char buf[65536];
354     struct dns_pkt* dns = (struct dns_pkt*)buf;
355
356     if (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)
357       return;
358
359     struct sockaddr_in addr;
360     memset(&addr, 0, sizeof addr);
361     socklen_t addrlen = sizeof addr;
362
363     int r;
364     r = GNUNET_NETWORK_socket_recvfrom(dnsout,
365                                        buf,
366                                        65536,
367                                        (struct sockaddr*)&addr,
368                                        &addrlen);
369
370     /* if (r < 0) FIXME */
371
372     if (query_states[dns->s.id].valid == GNUNET_YES) {
373         query_states[dns->s.id].valid = GNUNET_NO;
374
375         size_t len = sizeof(struct answer_packet) + r - 1; /* 1 for the unsigned char data[1]; */
376         struct answer_packet_list* answer = GNUNET_malloc(len + 2*sizeof(struct answer_packet_list*));
377         answer->pkt.hdr.type = htons(GNUNET_MESSAGE_TYPE_LOCAL_RESPONSE_DNS);
378         answer->pkt.hdr.size = htons(len);
379         answer->pkt.subtype = GNUNET_DNS_ANSWER_TYPE_IP;
380         answer->pkt.from = addr.sin_addr.s_addr;
381         answer->pkt.to = query_states[dns->s.id].local_ip;
382         answer->pkt.dst_port = query_states[dns->s.id].local_port;
383         memcpy(answer->pkt.data, buf, r);
384
385         GNUNET_CONTAINER_DLL_insert_after(head, tail, tail, answer);
386
387         GNUNET_SERVER_notify_transmit_ready(query_states[dns->s.id].client,
388                                             len,
389                                             GNUNET_TIME_UNIT_FOREVER_REL,
390                                             &send_answer,
391                                             query_states[dns->s.id].client);
392     }
393
394     GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
395                                   dnsout,
396                                   &read_response,
397                                   NULL);
398 }
399
400
401 /**
402  * Task run during shutdown.
403  *
404  * @param cls unused
405  * @param tc unused
406  */
407 static void
408 cleanup_task (void *cls,
409               const struct GNUNET_SCHEDULER_TaskContext *tc)
410 {
411   unhijack(dnsoutport);
412   GNUNET_DHT_disconnect(dht);
413 }
414
415 /**
416  * Publish a DNS-record in the DHT. This is up to now just for testing.
417  */
418 static void
419 publish_name (void *cls,
420               const struct GNUNET_SCHEDULER_TaskContext *tc) {
421     if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
422       return;
423
424     char* name = "philipptoelke.gnunet.";
425     size_t size = sizeof(struct GNUNET_DNS_Record);
426     struct GNUNET_DNS_Record data;
427     memset(&data, 0, size);
428
429     data.purpose.size = htonl(size - sizeof(struct GNUNET_CRYPTO_RsaSignature));
430     data.purpose.purpose = GNUNET_SIGNATURE_PURPOSE_DNS_RECORD;
431
432     GNUNET_CRYPTO_hash(name, strlen(name)+1, &data.service_descriptor);
433
434     char* keyfile;
435     if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg, "GNUNETD",
436                                                              "HOSTKEY", &keyfile))
437       {
438         GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "could not read keyfile-value\n");
439         if (keyfile != NULL) GNUNET_free(keyfile);
440         return;
441       }
442
443     struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file(keyfile);
444     GNUNET_free(keyfile);
445
446     GNUNET_CRYPTO_rsa_key_get_public(my_private_key, &data.peer);
447
448     data.expiration_time = GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS);
449
450   /* Sign the block */
451     if (GNUNET_OK != GNUNET_CRYPTO_rsa_sign(my_private_key,
452                                             &data.purpose,
453                                             &data.signature))
454       {
455         GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "could not sign DNS_Record\n");
456         return;
457       }
458     GNUNET_CRYPTO_rsa_key_free(my_private_key);
459
460     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
461                "Putting with key %08x\n",
462                *((unsigned int*)&data.service_descriptor));
463
464     GNUNET_DHT_put(dht,
465                    &data.service_descriptor,
466                    GNUNET_DHT_RO_NONE,
467                    GNUNET_BLOCK_TYPE_DNS,
468                    size,
469                    (char*)&data,
470                    GNUNET_TIME_relative_to_absolute(GNUNET_TIME_UNIT_HOURS),
471                    GNUNET_TIME_UNIT_MINUTES,
472                    NULL,
473                    NULL);
474
475     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_HOURS,
476                                   publish_name,
477                                   NULL);
478 }
479
480 /**
481  * @param cls closure
482  * @param server the initialized server
483  * @param cfg configuration to use
484  */
485 static void
486 run (void *cls,
487      struct GNUNET_SERVER_Handle *server,
488      const struct GNUNET_CONFIGURATION_Handle *cfg_)
489 {
490   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
491       /* callback, cls, type, size */
492         {&receive_query, NULL, GNUNET_MESSAGE_TYPE_LOCAL_QUERY_DNS, 0},
493         {&rehijack, NULL, GNUNET_MESSAGE_TYPE_REHIJACK, sizeof(struct GNUNET_MessageHeader)},
494         {NULL, NULL, 0, 0}
495   };
496
497   cfg = cfg_;
498
499   unsigned int i;
500   for (i = 0; i < 65536; i++) {
501       query_states[i].valid = GNUNET_NO;
502   }
503
504   dht = GNUNET_DHT_connect(cfg, 1024);
505
506   struct sockaddr_in addr;
507
508   dnsout = GNUNET_NETWORK_socket_create (AF_INET, SOCK_DGRAM, 0);
509   if (dnsout == NULL)
510     return;
511   memset(&addr, 0, sizeof(struct sockaddr_in));
512
513   int err = GNUNET_NETWORK_socket_bind (dnsout,
514                                         (struct sockaddr*)&addr,
515                                         sizeof(struct sockaddr_in));
516
517   if (err != GNUNET_YES) {
518       GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Could not bind a port, exiting\n");
519       return;
520   }
521
522   /* Read the port we bound to */
523   socklen_t addrlen = sizeof(struct sockaddr_in);
524   err = getsockname(GNUNET_NETWORK_get_fd(dnsout),
525                     (struct sockaddr*) &addr,
526                     &addrlen);
527
528   dnsoutport = htons(addr.sin_port);
529
530   hijack(htons(addr.sin_port));
531
532   GNUNET_SCHEDULER_add_now (publish_name, NULL);
533
534   GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL, dnsout, &read_response, NULL);
535
536   GNUNET_SERVER_add_handlers (server, handlers);
537   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
538                                 &cleanup_task,
539                                 cls);
540 }
541
542 /**
543  * The main function for the dns service.
544  *
545  * @param argc number of arguments from the command line
546  * @param argv command line arguments
547  * @return 0 ok, 1 on error
548  */
549 int
550 main (int argc, char *const *argv)
551 {
552   return (GNUNET_OK ==
553           GNUNET_SERVICE_run (argc,
554                               argv,
555                               "dns",
556                               GNUNET_SERVICE_OPTION_NONE,
557                               &run, NULL)) ? 0 : 1;
558 }