- next test
[oweals/gnunet.git] / src / gns / gnunet-dns2gns.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012 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  * @file gnunet-dns2gns.c
22  * @brief DNS server that translates DNS requests to GNS
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include <gnunet_util_lib.h>
27 #include <gnunet_dnsparser_lib.h>
28 #include <gnunet_gns_service.h>
29 #include <gnunet_dnsstub_lib.h>
30 #include "gns.h"
31
32 /**
33  * Timeout for DNS requests.
34  */
35 #define TIMEOUT GNUNET_TIME_UNIT_MINUTES
36
37 /**
38  * Default suffix
39  */
40 #define DNS_SUFFIX ".zkey.eu"
41
42 /**
43  * FCFS suffix
44  */
45 #define FCFS_SUFFIX "fcfs.zkey.eu"
46
47 /**
48  * Data kept per request.
49  */
50 struct Request
51 {
52   /**
53    * Socket to use for sending the reply.
54    */
55   struct GNUNET_NETWORK_Handle *lsock;
56
57   /**
58    * Destination address to use.
59    */
60   const void *addr;
61
62   /**
63    * Initially, this is the DNS request, it will then be
64    * converted to the DNS response.
65    */
66   struct GNUNET_DNSPARSER_Packet *packet;
67   
68   /**
69    * Our GNS request handle.
70    */
71   struct GNUNET_GNS_LookupRequest *lookup;
72
73   /**
74    * Our DNS request handle
75    */
76   struct GNUNET_DNSSTUB_RequestSocket *dns_lookup;
77
78   /**
79    * Task run on timeout or shutdown to clean up without
80    * response.
81    */
82   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
83
84   /**
85    * Number of bytes in 'addr'.
86    */ 
87   size_t addr_len;
88
89 };
90
91
92 /**
93  * Handle to GNS resolver.
94  */
95 struct GNUNET_GNS_Handle *gns;
96
97 /**
98  * Stub resolver
99  */
100 struct GNUNET_DNSSTUB_Context *dns_stub;
101
102 /**
103  * Listen socket for IPv4.
104  */
105 static struct GNUNET_NETWORK_Handle *listen_socket4;
106
107 /**
108  * Listen socket for IPv6.
109  */
110 static struct GNUNET_NETWORK_Handle *listen_socket6;
111
112 /**
113  * Task for IPv4 socket.
114  */
115 static GNUNET_SCHEDULER_TaskIdentifier t4;
116
117 /**
118  * Task for IPv6 socket.
119  */
120 static GNUNET_SCHEDULER_TaskIdentifier t6;
121
122 /**
123  * DNS suffix
124  */
125 static char *dns_suffix;
126
127 /**
128  * FCFS suffix
129  */
130 static char *fcfs_suffix;
131
132 /**
133  * IP of DNS server
134  */
135 static char *dns_ip;
136
137 /**
138  * Task run on shutdown.  Cleans up everything.
139  *
140  * @param cls unused
141  * @param tc scheduler context
142  */
143 static void
144 do_shutdown (void *cls,
145              const struct GNUNET_SCHEDULER_TaskContext *tc)
146 {
147   if (GNUNET_SCHEDULER_NO_TASK != t4)
148     GNUNET_SCHEDULER_cancel (t4);
149   if (GNUNET_SCHEDULER_NO_TASK != t6)
150     GNUNET_SCHEDULER_cancel (t6);
151   if (NULL != listen_socket4)
152   {
153     GNUNET_NETWORK_socket_close (listen_socket4);
154     listen_socket4 = NULL;
155   }
156   if (NULL != listen_socket6)
157   {
158     GNUNET_NETWORK_socket_close (listen_socket6);
159     listen_socket6 = NULL;
160   }
161   GNUNET_GNS_disconnect (gns);
162   gns = NULL;
163   GNUNET_DNSSTUB_stop (dns_stub);
164   dns_stub = NULL;
165 }
166
167
168 /**
169  * Send the response for the given request and clean up.
170  *
171  * @param request context for the request.
172  */
173 static void
174 send_response (struct Request *request)
175 {
176   char *buf;
177   size_t size;
178   
179   if (GNUNET_SYSERR ==
180       GNUNET_DNSPARSER_pack (request->packet,
181                              UINT16_MAX /* is this not too much? */,
182                              &buf,
183                              &size))
184     {
185       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
186                   _("Failed to pack DNS response into UDP packet!\n"));
187     }
188   else
189     {
190       if (size !=
191           GNUNET_NETWORK_socket_sendto (request->lsock,
192                                         buf, size,
193                                         request->addr,
194                                         request->addr_len))
195         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "sendto");
196       GNUNET_free (buf);
197     }
198   GNUNET_SCHEDULER_cancel (request->timeout_task);
199   GNUNET_DNSPARSER_free_packet (request->packet);
200   GNUNET_free (request);
201 }
202
203
204 /**
205  * Task run on timeout.  Cleans up request.
206  *
207  * @param cls 'struct Request' of the request to clean up
208  * @param tc scheduler context
209  */
210 static void
211 do_timeout (void *cls,
212             const struct GNUNET_SCHEDULER_TaskContext *tc)
213 {
214   struct Request *request = cls;
215
216   if (NULL != request->packet)
217     GNUNET_DNSPARSER_free_packet (request->packet);
218   if (NULL != request->lookup)
219     GNUNET_GNS_cancel_lookup_request (request->lookup);
220   GNUNET_free (request);
221 }
222
223 /**
224  * Iterator called on obtained result for a DNS
225  * lookup
226  *
227  * @param cls closure
228  * @param rs the request socket
229  * @param dns the DNS udp payload
230  * @param r size of the DNS payload
231  */
232 static void
233 dns_result_processor (void *cls,
234                   struct GNUNET_DNSSTUB_RequestSocket *rs,
235                   const struct GNUNET_TUN_DnsHeader *dns,
236                   size_t r)
237 {
238   struct Request *request = cls;
239   request->packet = GNUNET_DNSPARSER_parse ((char*)dns, r);
240   send_response (request);
241 }
242
243 /**
244  * Iterator called on obtained result for a GNS
245  * lookup
246  *
247  * @param cls closure
248  * @param rd_count number of records
249  * @param rd the records in reply
250  */
251 static void
252 result_processor (void *cls,
253                   uint32_t rd_count,
254                   const struct GNUNET_NAMESTORE_RecordData *rd)
255 {
256   struct Request *request = cls;
257   struct GNUNET_DNSPARSER_Packet *packet;
258   uint32_t i;
259   struct GNUNET_DNSPARSER_Record rec;
260
261   request->lookup = NULL;
262   packet = request->packet;
263   packet->flags.query_or_response = 1;
264   packet->flags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NO_ERROR;
265   packet->flags.checking_disabled = 0;
266   packet->flags.authenticated_data = 1;
267   packet->flags.zero = 0;
268   packet->flags.recursion_available = 1;
269   packet->flags.message_truncated = 0;
270   packet->flags.authoritative_answer = 0;
271   //packet->flags.opcode = GNUNET_DNSPARSER_OPCODE_STATUS; // ???
272   for (i=0;i<rd_count;i++)
273     {
274       switch (rd[i].record_type)
275         {
276         case GNUNET_DNSPARSER_TYPE_A:
277           GNUNET_assert (sizeof (struct in_addr) == rd[i].data_size);
278           rec.name = GNUNET_strdup (packet->queries[0].name);
279           rec.class = GNUNET_DNSPARSER_CLASS_INTERNET;
280           rec.type = GNUNET_DNSPARSER_TYPE_A;
281           rec.data.raw.data = GNUNET_malloc (sizeof (struct in_addr));
282           memcpy (rec.data.raw.data,
283                   rd[i].data,
284                   rd[i].data_size);
285           rec.data.raw.data_len = sizeof (struct in_addr);
286           GNUNET_array_append (packet->answers,
287                                packet->num_answers,
288                                rec);
289           break;
290         case GNUNET_DNSPARSER_TYPE_AAAA:
291           GNUNET_assert (sizeof (struct in6_addr) == rd[i].data_size);
292           rec.name = GNUNET_strdup (packet->queries[0].name);
293           rec.data.raw.data = GNUNET_malloc (sizeof (struct in6_addr));
294           rec.class = GNUNET_DNSPARSER_CLASS_INTERNET;
295           rec.type = GNUNET_DNSPARSER_TYPE_AAAA;
296           memcpy (rec.data.raw.data,
297                   rd[i].data,
298                   rd[i].data_size);
299           rec.data.raw.data_len = sizeof (struct in6_addr);
300           GNUNET_array_append (packet->answers,
301                                packet->num_answers,
302                                rec);
303           break;
304         case GNUNET_DNSPARSER_TYPE_CNAME:
305           rec.name = GNUNET_strdup (packet->queries[0].name);
306           rec.data.hostname = strdup (rd[i].data);
307           rec.class = GNUNET_DNSPARSER_CLASS_INTERNET;
308           rec.type = GNUNET_DNSPARSER_TYPE_CNAME;
309           memcpy (rec.data.hostname,
310                   rd[i].data,
311                   rd[i].data_size);
312           GNUNET_array_append (packet->answers,
313                                packet->num_answers,
314                                rec);
315           break;
316         default:
317           /* skip */
318           break;
319         }
320     }
321   send_response (request);
322 }
323
324
325 /**
326  * Handle DNS request.
327  *
328  * @param lsock socket to use for sending the reply
329  * @param addr address to use for sending the reply
330  * @param addr_len number of bytes in addr
331  * @param udp_msg DNS request payload
332  * @param udp_msg_size number of bytes in udp_msg 
333  */
334 static void
335 handle_request (struct GNUNET_NETWORK_Handle *lsock,
336                 const void *addr,
337                 size_t addr_len,
338                 const char *udp_msg,
339                 size_t udp_msg_size)
340 {
341   struct Request *request;
342   struct GNUNET_DNSPARSER_Packet *packet;
343   char *name;
344   size_t name_len;
345   enum GNUNET_GNS_RecordType type;
346   int use_gns;
347
348   packet = GNUNET_DNSPARSER_parse (udp_msg, udp_msg_size);
349   if (NULL == packet)
350     {
351       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
352                   _("Cannot parse DNS request from %s\n"),
353                   GNUNET_a2s (addr, addr_len));
354       return;
355     }
356   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
357               "Received request with flags %u, #answers %d, #auth %d, #additional %d\n",
358               (unsigned int) packet->flags.query_or_response,
359               (int) packet->num_answers,
360               (int) packet->num_authority_records,
361               (int) packet->num_additional_records);
362   if ( (0 != packet->flags.query_or_response) || 
363        (0 != packet->num_answers) ||
364        (0 != packet->num_authority_records))
365     {
366       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
367                   _("Received malformed DNS request from %s\n"),
368                   GNUNET_a2s (addr, addr_len));
369       GNUNET_DNSPARSER_free_packet (packet);
370       return;
371     }
372   if ( (1 != packet->num_queries) )
373     {
374       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
375                   _("Received unsupported DNS request from %s\n"),
376                   GNUNET_a2s (addr, addr_len));
377       GNUNET_DNSPARSER_free_packet (packet);
378       return;
379     }
380   request = GNUNET_malloc (sizeof (struct Request) + addr_len);
381   request->lsock = lsock;
382   request->packet = packet;
383   request->addr = &request[1];
384   request->addr_len = addr_len;
385   memcpy (&request[1], addr, addr_len);
386   request->timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT,
387                                                         &do_timeout,
388                                                         request);
389   name = GNUNET_strdup (packet->queries[0].name);
390   name_len = strlen (name);
391   use_gns = GNUNET_NO;
392   if ( (name_len > strlen (dns_suffix)) &&
393        (0 == strcasecmp (dns_suffix,
394                          &name[name_len - strlen (dns_suffix)])) )
395     {
396       if ( (name_len > strlen (fcfs_suffix)) &&
397            (0 == strcasecmp (fcfs_suffix,
398                              &name[name_len - strlen (fcfs_suffix)])) )
399       {
400         name[name_len - strlen (fcfs_suffix) + 1] = '\0';
401         strcat (name, GNUNET_GNS_TLD);
402       }
403       else
404       {
405         name[name_len - strlen (dns_suffix) + 1] = '\0';
406         strcat (name, GNUNET_GNS_TLD_ZKEY);
407       }
408       name_len = strlen (name);
409     }
410   if ( (name_len > strlen ((GNUNET_GNS_TLD) + 1)) &&
411        (0 == strcasecmp (GNUNET_GNS_TLD,
412                          &name[name_len - strlen (GNUNET_GNS_TLD)])) )
413     use_gns = GNUNET_YES;
414
415   if ( (name_len > strlen (GNUNET_GNS_TLD_ZKEY)) &&
416        (0 == strcasecmp (GNUNET_GNS_TLD_ZKEY,
417                          &name[name_len - strlen (GNUNET_GNS_TLD_ZKEY)])) )
418     use_gns = GNUNET_YES;
419
420   if (GNUNET_YES == use_gns)
421   {
422       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
423                    "Calling GNS\n");
424       type = packet->queries[0].type;
425       request->lookup = GNUNET_GNS_lookup (gns,
426                                            name,
427                                            type,
428                                            GNUNET_NO,
429                                            NULL,
430                                            &result_processor,
431                                            request);
432     }
433   else
434     {
435       /* FIXME: do traditional *DNS* lookup; note that
436          gnunet-service-dns already has code to do this;
437          factor into library to share! Why not use GNUNET_RESOLVER here?*/
438       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
439                    "Calling DNS at %s\n", dns_ip);
440       GNUNET_DNSPARSER_free_packet (request->packet);
441       request->dns_lookup = GNUNET_DNSSTUB_resolve2 (dns_stub,
442                                                      udp_msg,
443                                                      udp_msg_size,
444                                                      &dns_result_processor,
445                                                      request);
446
447
448
449     }
450   GNUNET_free (name);
451 }
452
453
454 /**
455  * Task to read IPv4 DNS packets.
456  *
457  * @param cls the 'listen_socket4'
458  * @param tc scheduler context
459  */ 
460 static void
461 read_dns4 (void *cls,
462            const struct GNUNET_SCHEDULER_TaskContext *tc)
463 {
464   struct sockaddr_in v4;
465   socklen_t addrlen;
466   ssize_t size;
467
468   GNUNET_assert (listen_socket4 == cls);
469   t4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
470                                       listen_socket4,
471                                       &read_dns4,
472                                       listen_socket4);
473   if (0 == (GNUNET_SCHEDULER_REASON_READ_READY & tc->reason))
474     return; /* shutdown? */
475   size = GNUNET_NETWORK_socket_recvfrom_amount (listen_socket4);
476   if (0 > size)
477     {
478       GNUNET_break (0);
479       return; /* read error!? */
480     }
481   {
482     char buf[size];
483     
484     addrlen = sizeof (v4);
485     GNUNET_break (size == 
486                   GNUNET_NETWORK_socket_recvfrom (listen_socket4,
487                                                   buf,
488                                                   size,
489                                                   (struct sockaddr *) &v4,
490                                                   &addrlen));
491     handle_request (listen_socket4, &v4, addrlen,
492                     buf, size);
493   }
494 }
495
496
497 /**
498  * Task to read IPv6 DNS packets.
499  *
500  * @param cls the 'listen_socket6'
501  * @param tc scheduler context
502  */ 
503 static void
504 read_dns6 (void *cls,
505            const struct GNUNET_SCHEDULER_TaskContext *tc)
506 {
507   struct sockaddr_in6 v6;
508   socklen_t addrlen;
509   ssize_t size;
510
511   GNUNET_assert (listen_socket6 == cls);
512   t6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
513                                       listen_socket6,
514                                       &read_dns6,
515                                       listen_socket6);
516   if (0 == (GNUNET_SCHEDULER_REASON_READ_READY & tc->reason))
517     return; /* shutdown? */
518   size = GNUNET_NETWORK_socket_recvfrom_amount (listen_socket6);
519   if (0 > size)
520     {
521       GNUNET_break (0);
522       return; /* read error!? */
523     }
524   {
525     char buf[size];
526     
527     addrlen = sizeof (v6);
528     GNUNET_break (size == 
529                   GNUNET_NETWORK_socket_recvfrom (listen_socket6,
530                                                   buf,
531                                                   size,
532                                                   (struct sockaddr *) &v6,
533                                                   &addrlen));
534     handle_request (listen_socket6, &v6, addrlen,
535                     buf, size);
536   }
537 }
538
539
540 /**
541  * Main function that will be run.
542  *
543  * @param cls closure
544  * @param args remaining command-line arguments
545  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
546  * @param cfg configuration
547  */
548 static void
549 run (void *cls, char *const *args, const char *cfgfile,
550      const struct GNUNET_CONFIGURATION_Handle *cfg)
551 {
552   if (NULL == dns_ip)
553   {
554     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
555                 "No DNS server specified!\n");
556     return;
557   }
558
559   if (NULL == dns_suffix)
560     dns_suffix = DNS_SUFFIX;
561   if (NULL == fcfs_suffix)
562     fcfs_suffix = FCFS_SUFFIX;
563   if (NULL == (gns = GNUNET_GNS_connect (cfg)))
564     return;
565   if (NULL == (dns_stub = GNUNET_DNSSTUB_start (dns_ip)))
566     {
567       GNUNET_GNS_disconnect (gns);
568       gns = NULL;
569       return;
570     }
571   listen_socket4 = GNUNET_NETWORK_socket_create (PF_INET,
572                                                  SOCK_DGRAM, 
573                                                  IPPROTO_UDP);
574   if (NULL != listen_socket4)
575     {
576       struct sockaddr_in v4;
577
578       memset (&v4, 0, sizeof (v4));
579       v4.sin_family = AF_INET;
580 #if HAVE_SOCKADDR_IN_SIN_LEN
581       v4.sin_len = sizeof (v4);
582 #endif
583       v4.sin_port = htons (53);
584       if (GNUNET_OK !=
585           GNUNET_NETWORK_socket_bind (listen_socket4,
586                                       (struct sockaddr *) &v4,
587                                       sizeof (v4)))
588         {
589           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
590           GNUNET_NETWORK_socket_close (listen_socket4);
591           listen_socket4 = NULL;
592         }
593     }
594   listen_socket6 = GNUNET_NETWORK_socket_create (PF_INET6,
595                                                 SOCK_DGRAM, 
596                                                 IPPROTO_UDP);
597   if (NULL != listen_socket6)
598     {
599       struct sockaddr_in6 v6;
600
601       memset (&v6, 0, sizeof (v6));
602       v6.sin6_family = AF_INET6;
603 #if HAVE_SOCKADDR_IN_SIN_LEN
604       v6.sin6_len = sizeof (v6);
605 #endif
606       v6.sin6_port = htons (53);
607       if (GNUNET_OK !=
608           GNUNET_NETWORK_socket_bind (listen_socket6,
609                                       (struct sockaddr *) &v6,
610                                       sizeof (v6)))
611         {
612           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
613           GNUNET_NETWORK_socket_close (listen_socket6);
614           listen_socket6 = NULL;
615         }
616     }
617   if ( (NULL == listen_socket4) &&
618        (NULL == listen_socket6) )
619     {
620       GNUNET_GNS_disconnect (gns);
621       gns = NULL;
622       GNUNET_DNSSTUB_stop (dns_stub);
623       dns_stub = NULL;
624       return;
625     }
626   if (NULL != listen_socket4)
627     t4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
628                                         listen_socket4,
629                                         &read_dns4,
630                                         listen_socket4);
631   if (NULL != listen_socket6)
632     t6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
633                                         listen_socket6,
634                                         &read_dns6,
635                                         listen_socket6);
636
637   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
638                                 &do_shutdown, NULL);
639 }
640
641
642 /**
643  * The main function for the fcfs daemon.
644  *
645  * @param argc number of arguments from the command line
646  * @param argv command line arguments
647  * @return 0 ok, 1 on error
648  */
649 int
650 main (int argc, 
651       char *const *argv)
652 {
653   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
654     {'d', "dns", NULL,
655       gettext_noop ("IP of recursive dns resolver to use (required)"), 1,
656       &GNUNET_GETOPT_set_string, &dns_ip},
657     {'s', "suffix", NULL,
658       gettext_noop ("Authoritative DNS suffix to use (optional); default: zkey.eu"), 1,
659       &GNUNET_GETOPT_set_string, &dns_suffix},
660     {'f', "fcfs", NULL,
661       gettext_noop ("Authoritative FCFS suffix to use (optional); default: fcfs.zkey.eu"), 1,
662       &GNUNET_GETOPT_set_string, &fcfs_suffix},
663     GNUNET_GETOPT_OPTION_END
664   };
665   int ret;
666
667   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv,
668                                                  &argc, &argv))
669     return 2;
670   GNUNET_log_setup ("gnunet-dns2gns", "WARNING", NULL);
671   ret =
672       (GNUNET_OK ==
673        GNUNET_PROGRAM_run (argc, argv, "gnunet-dns2gns",
674                            _("GNUnet DNS-to-GNS proxy (a DNS server)"), 
675                            options,
676                            &run, NULL)) ? 0 : 1;
677
678   return ret;
679 }
680
681 /* end of gnunet-dns2gns.c */