-fixes
[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       rec.expiration_time.abs_value = rd[i].expiration_time;
275       switch (rd[i].record_type)
276         {
277         case GNUNET_DNSPARSER_TYPE_A:
278           GNUNET_assert (sizeof (struct in_addr) == rd[i].data_size);
279           rec.name = GNUNET_strdup (packet->queries[0].name);
280           rec.class = GNUNET_DNSPARSER_CLASS_INTERNET;
281           rec.type = GNUNET_DNSPARSER_TYPE_A;
282           rec.data.raw.data = GNUNET_malloc (sizeof (struct in_addr));
283           memcpy (rec.data.raw.data,
284                   rd[i].data,
285                   rd[i].data_size);
286           rec.data.raw.data_len = sizeof (struct in_addr);
287           GNUNET_array_append (packet->answers,
288                                packet->num_answers,
289                                rec);
290           break;
291         case GNUNET_DNSPARSER_TYPE_AAAA:
292           GNUNET_assert (sizeof (struct in6_addr) == rd[i].data_size);
293           rec.name = GNUNET_strdup (packet->queries[0].name);
294           rec.data.raw.data = GNUNET_malloc (sizeof (struct in6_addr));
295           rec.class = GNUNET_DNSPARSER_CLASS_INTERNET;
296           rec.type = GNUNET_DNSPARSER_TYPE_AAAA;
297           memcpy (rec.data.raw.data,
298                   rd[i].data,
299                   rd[i].data_size);
300           rec.data.raw.data_len = sizeof (struct in6_addr);
301           GNUNET_array_append (packet->answers,
302                                packet->num_answers,
303                                rec);
304           break;
305         case GNUNET_DNSPARSER_TYPE_CNAME:
306           rec.name = GNUNET_strdup (packet->queries[0].name);
307           rec.data.hostname = strdup (rd[i].data);
308           rec.class = GNUNET_DNSPARSER_CLASS_INTERNET;
309           rec.type = GNUNET_DNSPARSER_TYPE_CNAME;
310           memcpy (rec.data.hostname,
311                   rd[i].data,
312                   rd[i].data_size);
313           GNUNET_array_append (packet->answers,
314                                packet->num_answers,
315                                rec);
316           break;
317         default:
318           /* skip */
319           break;
320         }
321     }
322   send_response (request);
323 }
324
325
326 /**
327  * Handle DNS request.
328  *
329  * @param lsock socket to use for sending the reply
330  * @param addr address to use for sending the reply
331  * @param addr_len number of bytes in addr
332  * @param udp_msg DNS request payload
333  * @param udp_msg_size number of bytes in udp_msg 
334  */
335 static void
336 handle_request (struct GNUNET_NETWORK_Handle *lsock,
337                 const void *addr,
338                 size_t addr_len,
339                 const char *udp_msg,
340                 size_t udp_msg_size)
341 {
342   struct Request *request;
343   struct GNUNET_DNSPARSER_Packet *packet;
344   char *name;
345   size_t name_len;
346   enum GNUNET_GNS_RecordType type;
347   int use_gns;
348
349   packet = GNUNET_DNSPARSER_parse (udp_msg, udp_msg_size);
350   if (NULL == packet)
351     {
352       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
353                   _("Cannot parse DNS request from %s\n"),
354                   GNUNET_a2s (addr, addr_len));
355       return;
356     }
357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
358               "Received request with flags %u, #answers %d, #auth %d, #additional %d\n",
359               (unsigned int) packet->flags.query_or_response,
360               (int) packet->num_answers,
361               (int) packet->num_authority_records,
362               (int) packet->num_additional_records);
363   if ( (0 != packet->flags.query_or_response) || 
364        (0 != packet->num_answers) ||
365        (0 != packet->num_authority_records))
366     {
367       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
368                   _("Received malformed DNS request from %s\n"),
369                   GNUNET_a2s (addr, addr_len));
370       GNUNET_DNSPARSER_free_packet (packet);
371       return;
372     }
373   if ( (1 != packet->num_queries) )
374     {
375       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
376                   _("Received unsupported DNS request from %s\n"),
377                   GNUNET_a2s (addr, addr_len));
378       GNUNET_DNSPARSER_free_packet (packet);
379       return;
380     }
381   request = GNUNET_malloc (sizeof (struct Request) + addr_len);
382   request->lsock = lsock;
383   request->packet = packet;
384   request->addr = &request[1];
385   request->addr_len = addr_len;
386   memcpy (&request[1], addr, addr_len);
387   request->timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT,
388                                                         &do_timeout,
389                                                         request);
390   name = GNUNET_strdup (packet->queries[0].name);
391   name_len = strlen (name);
392   use_gns = GNUNET_NO;
393   if ( (name_len > strlen (dns_suffix)) &&
394        (0 == strcasecmp (dns_suffix,
395                          &name[name_len - strlen (dns_suffix)])) )
396     {
397       if ( (name_len > strlen (fcfs_suffix)) &&
398            (0 == strcasecmp (fcfs_suffix,
399                              &name[name_len - strlen (fcfs_suffix)])) )
400       {
401         name[name_len - strlen (fcfs_suffix) + 1] = '\0';
402         strcat (name, GNUNET_GNS_TLD);
403       }
404       else
405       {
406         name[name_len - strlen (dns_suffix) + 1] = '\0';
407         strcat (name, GNUNET_GNS_TLD_ZKEY);
408       }
409       name_len = strlen (name);
410     }
411   if ( (name_len > strlen ((GNUNET_GNS_TLD) + 1)) &&
412        (0 == strcasecmp (GNUNET_GNS_TLD,
413                          &name[name_len - strlen (GNUNET_GNS_TLD)])) )
414     use_gns = GNUNET_YES;
415
416   if ( (name_len > strlen (GNUNET_GNS_TLD_ZKEY)) &&
417        (0 == strcasecmp (GNUNET_GNS_TLD_ZKEY,
418                          &name[name_len - strlen (GNUNET_GNS_TLD_ZKEY)])) )
419     use_gns = GNUNET_YES;
420
421   if (GNUNET_YES == use_gns)
422   {
423       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
424                    "Calling GNS\n");
425       type = packet->queries[0].type;
426       request->lookup = GNUNET_GNS_lookup (gns,
427                                            name,
428                                            type,
429                                            GNUNET_NO,
430                                            NULL,
431                                            &result_processor,
432                                            request);
433     }
434   else
435     {
436       /* FIXME: do traditional *DNS* lookup; note that
437          gnunet-service-dns already has code to do this;
438          factor into library to share! Why not use GNUNET_RESOLVER here?*/
439       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
440                    "Calling DNS at %s\n", dns_ip);
441       GNUNET_DNSPARSER_free_packet (request->packet);
442       request->dns_lookup = GNUNET_DNSSTUB_resolve2 (dns_stub,
443                                                      udp_msg,
444                                                      udp_msg_size,
445                                                      &dns_result_processor,
446                                                      request);
447
448
449
450     }
451   GNUNET_free (name);
452 }
453
454
455 /**
456  * Task to read IPv4 DNS packets.
457  *
458  * @param cls the 'listen_socket4'
459  * @param tc scheduler context
460  */ 
461 static void
462 read_dns4 (void *cls,
463            const struct GNUNET_SCHEDULER_TaskContext *tc)
464 {
465   struct sockaddr_in v4;
466   socklen_t addrlen;
467   ssize_t size;
468
469   GNUNET_assert (listen_socket4 == cls);
470   t4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
471                                       listen_socket4,
472                                       &read_dns4,
473                                       listen_socket4);
474   if (0 == (GNUNET_SCHEDULER_REASON_READ_READY & tc->reason))
475     return; /* shutdown? */
476   size = GNUNET_NETWORK_socket_recvfrom_amount (listen_socket4);
477   if (0 > size)
478     {
479       GNUNET_break (0);
480       return; /* read error!? */
481     }
482   {
483     char buf[size];
484     
485     addrlen = sizeof (v4);
486     GNUNET_break (size == 
487                   GNUNET_NETWORK_socket_recvfrom (listen_socket4,
488                                                   buf,
489                                                   size,
490                                                   (struct sockaddr *) &v4,
491                                                   &addrlen));
492     handle_request (listen_socket4, &v4, addrlen,
493                     buf, size);
494   }
495 }
496
497
498 /**
499  * Task to read IPv6 DNS packets.
500  *
501  * @param cls the 'listen_socket6'
502  * @param tc scheduler context
503  */ 
504 static void
505 read_dns6 (void *cls,
506            const struct GNUNET_SCHEDULER_TaskContext *tc)
507 {
508   struct sockaddr_in6 v6;
509   socklen_t addrlen;
510   ssize_t size;
511
512   GNUNET_assert (listen_socket6 == cls);
513   t6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
514                                       listen_socket6,
515                                       &read_dns6,
516                                       listen_socket6);
517   if (0 == (GNUNET_SCHEDULER_REASON_READ_READY & tc->reason))
518     return; /* shutdown? */
519   size = GNUNET_NETWORK_socket_recvfrom_amount (listen_socket6);
520   if (0 > size)
521     {
522       GNUNET_break (0);
523       return; /* read error!? */
524     }
525   {
526     char buf[size];
527     
528     addrlen = sizeof (v6);
529     GNUNET_break (size == 
530                   GNUNET_NETWORK_socket_recvfrom (listen_socket6,
531                                                   buf,
532                                                   size,
533                                                   (struct sockaddr *) &v6,
534                                                   &addrlen));
535     handle_request (listen_socket6, &v6, addrlen,
536                     buf, size);
537   }
538 }
539
540
541 /**
542  * Main function that will be run.
543  *
544  * @param cls closure
545  * @param args remaining command-line arguments
546  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
547  * @param cfg configuration
548  */
549 static void
550 run (void *cls, char *const *args, const char *cfgfile,
551      const struct GNUNET_CONFIGURATION_Handle *cfg)
552 {
553   if (NULL == dns_ip)
554   {
555     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
556                 "No DNS server specified!\n");
557     return;
558   }
559
560   if (NULL == dns_suffix)
561     dns_suffix = DNS_SUFFIX;
562   if (NULL == fcfs_suffix)
563     fcfs_suffix = FCFS_SUFFIX;
564   if (NULL == (gns = GNUNET_GNS_connect (cfg)))
565     return;
566   if (NULL == (dns_stub = GNUNET_DNSSTUB_start (dns_ip)))
567     {
568       GNUNET_GNS_disconnect (gns);
569       gns = NULL;
570       return;
571     }
572   listen_socket4 = GNUNET_NETWORK_socket_create (PF_INET,
573                                                  SOCK_DGRAM, 
574                                                  IPPROTO_UDP);
575   if (NULL != listen_socket4)
576     {
577       struct sockaddr_in v4;
578
579       memset (&v4, 0, sizeof (v4));
580       v4.sin_family = AF_INET;
581 #if HAVE_SOCKADDR_IN_SIN_LEN
582       v4.sin_len = sizeof (v4);
583 #endif
584       v4.sin_port = htons (53);
585       if (GNUNET_OK !=
586           GNUNET_NETWORK_socket_bind (listen_socket4,
587                                       (struct sockaddr *) &v4,
588                                       sizeof (v4)))
589         {
590           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
591           GNUNET_NETWORK_socket_close (listen_socket4);
592           listen_socket4 = NULL;
593         }
594     }
595   listen_socket6 = GNUNET_NETWORK_socket_create (PF_INET6,
596                                                 SOCK_DGRAM, 
597                                                 IPPROTO_UDP);
598   if (NULL != listen_socket6)
599     {
600       struct sockaddr_in6 v6;
601
602       memset (&v6, 0, sizeof (v6));
603       v6.sin6_family = AF_INET6;
604 #if HAVE_SOCKADDR_IN_SIN_LEN
605       v6.sin6_len = sizeof (v6);
606 #endif
607       v6.sin6_port = htons (53);
608       if (GNUNET_OK !=
609           GNUNET_NETWORK_socket_bind (listen_socket6,
610                                       (struct sockaddr *) &v6,
611                                       sizeof (v6)))
612         {
613           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
614           GNUNET_NETWORK_socket_close (listen_socket6);
615           listen_socket6 = NULL;
616         }
617     }
618   if ( (NULL == listen_socket4) &&
619        (NULL == listen_socket6) )
620     {
621       GNUNET_GNS_disconnect (gns);
622       gns = NULL;
623       GNUNET_DNSSTUB_stop (dns_stub);
624       dns_stub = NULL;
625       return;
626     }
627   if (NULL != listen_socket4)
628     t4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
629                                         listen_socket4,
630                                         &read_dns4,
631                                         listen_socket4);
632   if (NULL != listen_socket6)
633     t6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
634                                         listen_socket6,
635                                         &read_dns6,
636                                         listen_socket6);
637
638   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
639                                 &do_shutdown, NULL);
640 }
641
642
643 /**
644  * The main function for the fcfs daemon.
645  *
646  * @param argc number of arguments from the command line
647  * @param argv command line arguments
648  * @return 0 ok, 1 on error
649  */
650 int
651 main (int argc, 
652       char *const *argv)
653 {
654   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
655     {'d', "dns", NULL,
656       gettext_noop ("IP of recursive dns resolver to use (required)"), 1,
657       &GNUNET_GETOPT_set_string, &dns_ip},
658     {'s', "suffix", NULL,
659       gettext_noop ("Authoritative DNS suffix to use (optional); default: zkey.eu"), 1,
660       &GNUNET_GETOPT_set_string, &dns_suffix},
661     {'f', "fcfs", NULL,
662       gettext_noop ("Authoritative FCFS suffix to use (optional); default: fcfs.zkey.eu"), 1,
663       &GNUNET_GETOPT_set_string, &fcfs_suffix},
664     GNUNET_GETOPT_OPTION_END
665   };
666   int ret;
667
668   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv,
669                                                  &argc, &argv))
670     return 2;
671   GNUNET_log_setup ("gnunet-dns2gns", "WARNING", NULL);
672   ret =
673       (GNUNET_OK ==
674        GNUNET_PROGRAM_run (argc, argv, "gnunet-dns2gns",
675                            _("GNUnet DNS-to-GNS proxy (a DNS server)"), 
676                            options,
677                            &run, NULL)) ? 0 : 1;
678
679   return ret;
680 }
681
682 /* end of gnunet-dns2gns.c */