c8b9567b8a11acd99889f426b804231d9e04f4d2
[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
30 /**
31  * Timeout for DNS requests.
32  */
33 #define TIMEOUT GNUNET_TIME_UNIT_MINUTES
34
35 /**
36  * Data kept per request.
37  */
38 struct Request
39 {
40   /**
41    * Socket to use for sending the reply.
42    */
43   struct GNUNET_NETWORK_Handle *lsock;
44
45   /**
46    * Destination address to use.
47    */
48   const void *addr;
49
50   /**
51    * Initially, this is the DNS request, it will then be
52    * converted to the DNS response.
53    */
54   struct GNUNET_DNSPARSER_Packet *packet;
55   
56   /**
57    * Our GNS request handle.
58    */
59   struct GNUNET_GNS_LookupRequest *lookup;
60
61   /**
62    * Task run on timeout or shutdown to clean up without
63    * response.
64    */
65   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
66
67   /**
68    * Number of bytes in 'addr'.
69    */ 
70   size_t addr_len;
71
72 };
73
74
75 /**
76  * Handle to GNS resolver.
77  */
78 struct GNUNET_GNS_Handle *gns;
79
80 /**
81  * Listen socket for IPv4.
82  */
83 static struct GNUNET_NETWORK_Handle *listen_socket4;
84
85 /**
86  * Listen socket for IPv6.
87  */
88 static struct GNUNET_NETWORK_Handle *listen_socket6;
89
90 /**
91  * Task for IPv4 socket.
92  */
93 static GNUNET_SCHEDULER_TaskIdentifier t4;
94
95 /**
96  * Task for IPv6 socket.
97  */
98 static GNUNET_SCHEDULER_TaskIdentifier t6;
99
100
101 /**
102  * Task run on shutdown.  Cleans up everything.
103  *
104  * @param cls unused
105  * @param tc scheduler context
106  */
107 static void
108 do_shutdown (void *cls,
109              const struct GNUNET_SCHEDULER_TaskContext *tc)
110 {
111   if (GNUNET_SCHEDULER_NO_TASK != t4)
112     GNUNET_SCHEDULER_cancel (t4);
113   if (GNUNET_SCHEDULER_NO_TASK != t6)
114     GNUNET_SCHEDULER_cancel (t6);
115   if (NULL != listen_socket4)
116   {
117     GNUNET_NETWORK_socket_close (listen_socket4);
118     listen_socket4 = NULL;
119   }
120   if (NULL != listen_socket6)
121   {
122     GNUNET_NETWORK_socket_close (listen_socket6);
123     listen_socket6 = NULL;
124   }
125   GNUNET_GNS_disconnect (gns);
126   gns = NULL;
127 }
128
129
130 /**
131  * Send the response for the given request and clean up.
132  *
133  * @param request context for the request.
134  */
135 static void
136 send_response (struct Request *request)
137 {
138   char *buf;
139   size_t size;
140   
141   if (GNUNET_SYSERR ==
142       GNUNET_DNSPARSER_pack (request->packet,
143                              UINT16_MAX /* is this not too much? */,
144                              &buf,
145                              &size))
146     {
147       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
148                   _("Failed to pack DNS response into UDP packet!\n"));
149     }
150   else
151     {
152       if (size !=
153           GNUNET_NETWORK_socket_sendto (request->lsock,
154                                         buf, size,
155                                         request->addr,
156                                         request->addr_len))
157         GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "sendto");
158       GNUNET_free (buf);
159     }
160   GNUNET_SCHEDULER_cancel (request->timeout_task);
161   GNUNET_DNSPARSER_free_packet (request->packet);
162   GNUNET_free (request);
163 }
164
165
166 /**
167  * Task run on timeout.  Cleans up request.
168  *
169  * @param cls 'struct Request' of the request to clean up
170  * @param tc scheduler context
171  */
172 static void
173 do_timeout (void *cls,
174             const struct GNUNET_SCHEDULER_TaskContext *tc)
175 {
176   struct Request *request = cls;
177
178   if (NULL != request->packet)
179     GNUNET_DNSPARSER_free_packet (request->packet);
180   if (NULL != request->lookup)
181     GNUNET_GNS_cancel_lookup_request (request->lookup);
182   GNUNET_free (request);
183 }
184
185
186 /**
187  * Iterator called on obtained result for a GNS
188  * lookup
189  *
190  * @param cls closure
191  * @param rd_count number of records
192  * @param rd the records in reply
193  */
194 static void
195 result_processor (void *cls,
196                   uint32_t rd_count,
197                   const struct GNUNET_NAMESTORE_RecordData *rd)
198 {
199   struct Request *request = cls;
200   struct GNUNET_DNSPARSER_Packet *packet;
201   uint32_t i;
202   struct GNUNET_DNSPARSER_Record rec;
203
204   request->lookup = NULL;
205   packet = request->packet;
206   packet->flags.query_or_response = 1;
207   packet->flags.return_code = GNUNET_DNSPARSER_RETURN_CODE_NO_ERROR;
208   packet->flags.checking_disabled = 0;
209   packet->flags.authenticated_data = 1;
210   packet->flags.zero = 0;
211   packet->flags.recursion_available = 1;
212   packet->flags.message_truncated = 0;
213   packet->flags.authoritative_answer = 0;
214   packet->flags.opcode = GNUNET_DNSPARSER_OPCODE_STATUS; // ???
215   for (i=0;i<rd_count;i++)
216     {
217       switch (rd[i].record_type)
218         {
219         case GNUNET_DNSPARSER_TYPE_A:
220           GNUNET_assert (sizeof (struct in_addr) == rd[i].data_size);
221           rec.name = GNUNET_strdup (packet->queries[0].name);
222           rec.data.raw.data = GNUNET_malloc (sizeof (struct in_addr));
223           memcpy (rec.data.raw.data,
224                   rd[i].data,
225                   rd[i].data_size);
226           rec.data.raw.data_len = sizeof (struct in_addr);
227           GNUNET_array_append (packet->answers,
228                                packet->num_answers,
229                                rec);
230           break;
231         case GNUNET_DNSPARSER_TYPE_AAAA:
232           GNUNET_assert (sizeof (struct in6_addr) == rd[i].data_size);
233           rec.name = GNUNET_strdup ("foo"); // request->name
234           rec.data.raw.data = GNUNET_malloc (sizeof (struct in6_addr));
235           memcpy (rec.data.raw.data,
236                   rd[i].data,
237                   rd[i].data_size);
238           rec.data.raw.data_len = sizeof (struct in6_addr);
239           GNUNET_array_append (packet->answers,
240                                packet->num_answers,
241                                rec);
242           break;
243         case GNUNET_DNSPARSER_TYPE_CNAME:
244           GNUNET_break (0); // FIXME: CNAME is handled by the GNS resolver! We never return this unless explicitly requested!
245           break;
246         default:
247           /* skip */
248           break;
249         }
250     }
251   send_response (request);
252 }
253
254
255 /**
256  * Handle DNS request.
257  *
258  * @param lsock socket to use for sending the reply
259  * @param addr address to use for sending the reply
260  * @param addr_len number of bytes in addr
261  * @param udp_msg DNS request payload
262  * @param udp_msg_size number of bytes in udp_msg 
263  */
264 static void
265 handle_request (struct GNUNET_NETWORK_Handle *lsock,
266                 const void *addr,
267                 size_t addr_len,
268                 const char *udp_msg,
269                 size_t udp_msg_size)
270 {
271   struct Request *request;
272   struct GNUNET_DNSPARSER_Packet *packet;
273   char *name;
274   size_t name_len;
275   enum GNUNET_GNS_RecordType type;
276
277   packet = GNUNET_DNSPARSER_parse (udp_msg, udp_msg_size);
278   if (NULL == packet)
279     {
280       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
281                   _("Received malformed DNS request from %s\n"),
282                   GNUNET_a2s (addr, addr_len));
283       return;
284     }
285   if ( (0 != packet->flags.query_or_response) || 
286        (0 != packet->num_answers) ||
287        (0 != packet->num_authority_records) ||
288        (0 != packet->num_additional_records) )
289     {
290       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
291                   _("Received malformed DNS request from %s\n"),
292                   GNUNET_a2s (addr, addr_len));
293       GNUNET_DNSPARSER_free_packet (packet);
294       return;
295     }
296   if ( (1 != packet->num_queries) )
297     {
298       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
299                   _("Received unsupported DNS request from %s\n"),
300                   GNUNET_a2s (addr, addr_len));
301       GNUNET_DNSPARSER_free_packet (packet);
302       return;
303     }
304   request = GNUNET_malloc (sizeof (struct Request) + addr_len);
305   request->lsock = lsock;
306   request->packet = packet;
307   request->addr = &request[1];
308   request->addr_len = addr_len;
309   memcpy (&request[1], addr, addr_len);
310   request->timeout_task = GNUNET_SCHEDULER_add_delayed (TIMEOUT,
311                                                         &do_timeout,
312                                                         request);
313   name = GNUNET_strdup (packet->queries[0].name);
314   name_len = strlen (name);
315   if ( (name_len > strlen (".zkey.eu")) &&
316        (0 == strcasecmp (".zkey.eu",
317                          &name[name_len - strlen (".zkey.eu")])) )
318     {
319       //FIXME here check if the top label after zkey.eu is a hash and append
320       //correct TLD appropriately
321       name[name_len - strlen (".zkey.eu")] = '\0';
322       strcat (name, ".gnunet"); /* little hack, only works because
323                                    ".zkey.eu" is longer than ".gnunet" */
324       name_len = strlen (name);
325     }
326   if ( (name_len > strlen (".gnunet")) &&
327        (0 == strcasecmp (".gnunet",
328                          &name[name_len - strlen (".gnunet")])) )
329     {
330       type = packet->queries[0].type;
331       request->lookup = GNUNET_GNS_lookup (gns,
332                                            name,
333                                            type,
334                                            GNUNET_NO,
335                                            NULL,
336                                            &result_processor,
337                                            request);
338     }
339   else
340     {
341       /* FIXME: do traditional *DNS* lookup; note that
342          gnunet-service-dns already has code to do this;
343          factor into library to share! Why not use GNUNET_RESOLVER here?*/
344       GNUNET_break (0);
345     }
346   GNUNET_free (name);
347 }
348
349
350 /**
351  * Task to read IPv4 DNS packets.
352  *
353  * @param cls the 'listen_socket4'
354  * @param tc scheduler context
355  */ 
356 static void
357 read_dns4 (void *cls,
358            const struct GNUNET_SCHEDULER_TaskContext *tc)
359 {
360   struct sockaddr_in v4;
361   socklen_t addrlen;
362   ssize_t size;
363
364   GNUNET_assert (listen_socket4 == cls);
365   t4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
366                                       listen_socket4,
367                                       &read_dns4,
368                                       listen_socket4);
369   if (0 == (GNUNET_SCHEDULER_REASON_READ_READY & tc->reason))
370     return; /* shutdown? */
371   size = GNUNET_NETWORK_socket_recvfrom_amount (listen_socket4);
372   if (0 > size)
373     {
374       GNUNET_break (0);
375       return; /* read error!? */
376     }
377   {
378     char buf[size];
379     
380     addrlen = sizeof (v4);
381     GNUNET_break (size == 
382                   GNUNET_NETWORK_socket_recvfrom (listen_socket4,
383                                                   buf,
384                                                   size,
385                                                   (struct sockaddr *) &v4,
386                                                   &addrlen));
387     handle_request (listen_socket4, &v4, addrlen,
388                     buf, size);
389   }
390 }
391
392
393 /**
394  * Task to read IPv6 DNS packets.
395  *
396  * @param cls the 'listen_socket6'
397  * @param tc scheduler context
398  */ 
399 static void
400 read_dns6 (void *cls,
401            const struct GNUNET_SCHEDULER_TaskContext *tc)
402 {
403   struct sockaddr_in6 v6;
404   socklen_t addrlen;
405   ssize_t size;
406
407   GNUNET_assert (listen_socket6 == cls);
408   t6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
409                                       listen_socket6,
410                                       &read_dns6,
411                                       listen_socket6);
412   if (0 == (GNUNET_SCHEDULER_REASON_READ_READY & tc->reason))
413     return; /* shutdown? */
414   size = GNUNET_NETWORK_socket_recvfrom_amount (listen_socket6);
415   if (0 > size)
416     {
417       GNUNET_break (0);
418       return; /* read error!? */
419     }
420   {
421     char buf[size];
422     
423     addrlen = sizeof (v6);
424     GNUNET_break (size == 
425                   GNUNET_NETWORK_socket_recvfrom (listen_socket6,
426                                                   buf,
427                                                   size,
428                                                   (struct sockaddr *) &v6,
429                                                   &addrlen));
430     handle_request (listen_socket6, &v6, addrlen,
431                     buf, size);
432   }
433 }
434
435
436 /**
437  * Main function that will be run.
438  *
439  * @param cls closure
440  * @param args remaining command-line arguments
441  * @param cfgfile name of the configuration file used (for saving, can be NULL!)
442  * @param cfg configuration
443  */
444 static void
445 run (void *cls, char *const *args, const char *cfgfile,
446      const struct GNUNET_CONFIGURATION_Handle *cfg)
447 {
448   gns = GNUNET_GNS_connect (cfg);
449   if (NULL == gns)
450     return;
451   listen_socket4 = GNUNET_NETWORK_socket_create (PF_INET,
452                                                  SOCK_DGRAM, 
453                                                  IPPROTO_UDP);
454   if (NULL != listen_socket4)
455     {
456       struct sockaddr_in v4;
457
458       memset (&v4, 0, sizeof (v4));
459       v4.sin_family = AF_INET;
460 #if HAVE_SOCKADDR_IN_SIN_LEN
461       v4.sin_len = sizeof (v4);
462 #endif
463       v4.sin_port = htons (53);
464       if (GNUNET_OK !=
465           GNUNET_NETWORK_socket_bind (listen_socket4,
466                                       (struct sockaddr *) &v4,
467                                       sizeof (v4)))
468         {
469           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
470           GNUNET_NETWORK_socket_close (listen_socket4);
471           listen_socket4 = NULL;
472         }
473     }
474   listen_socket6 = GNUNET_NETWORK_socket_create (PF_INET6,
475                                                 SOCK_DGRAM, 
476                                                 IPPROTO_UDP);
477   if (NULL != listen_socket6)
478     {
479       struct sockaddr_in6 v6;
480
481       memset (&v6, 0, sizeof (v6));
482       v6.sin6_family = AF_INET6;
483 #if HAVE_SOCKADDR_IN_SIN_LEN
484       v6.sin6_len = sizeof (v6);
485 #endif
486       v6.sin6_port = htons (53);
487       if (GNUNET_OK !=
488           GNUNET_NETWORK_socket_bind (listen_socket6,
489                                       (struct sockaddr *) &v6,
490                                       sizeof (v6)))
491         {
492           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
493           GNUNET_NETWORK_socket_close (listen_socket6);
494           listen_socket6 = NULL;
495         }
496     }
497   if ( (NULL == listen_socket4) &&
498        (NULL == listen_socket6) )
499     return;
500   if (NULL != listen_socket4)
501     t4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
502                                         listen_socket4,
503                                         &read_dns4,
504                                         listen_socket4);
505   if (NULL != listen_socket6)
506     t6 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
507                                         listen_socket6,
508                                         &read_dns6,
509                                         listen_socket6);
510
511   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
512                                 &do_shutdown, NULL);
513 }
514
515
516 /**
517  * The main function for the fcfs daemon.
518  *
519  * @param argc number of arguments from the command line
520  * @param argv command line arguments
521  * @return 0 ok, 1 on error
522  */
523 int
524 main (int argc, 
525       char *const *argv)
526 {
527   static const struct GNUNET_GETOPT_CommandLineOption options[] = {
528     GNUNET_GETOPT_OPTION_END
529   };
530   int ret;
531
532   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv,
533                                                  &argc, &argv))
534     return 2;
535   GNUNET_log_setup ("gnunet-dns2gns", "WARNING", NULL);
536   ret =
537       (GNUNET_OK ==
538        GNUNET_PROGRAM_run (argc, argv, "gnunet-dns2gns",
539                            _("GNUnet DNS-to-GNS proxy (a DNS server)"), 
540                            options,
541                            &run, NULL)) ? 0 : 1;
542
543   return ret;
544 }
545
546 /* end of gnunet-dns2gns.c */