-API comments
[oweals/gnunet.git] / src / dns / dnsstub.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 dns/dnsstub.c
22  * @brief DNS stub resolver which sends DNS requests to an actual resolver
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.h"
27 #include "gnunet_dnsstub_lib.h"
28
29 /**
30  * Timeout for an external (Internet-DNS) DNS resolution
31  */
32 #define REQUEST_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
33
34 /**
35  * How many DNS sockets do we open at most at the same time?
36  * (technical socket maximum is this number x2 for IPv4+IPv6)
37  */
38 #define DNS_SOCKET_MAX 128
39
40
41 /**
42  * UDP socket we are using for sending DNS requests to the Internet.
43  */
44 struct GNUNET_DNSSTUB_RequestSocket
45 {
46   
47   /**
48    * UDP socket we use for this request for IPv4
49    */
50   struct GNUNET_NETWORK_Handle *dnsout4;
51
52   /**
53    * UDP socket we use for this request for IPv6
54    */
55   struct GNUNET_NETWORK_Handle *dnsout6;
56
57   /**
58    * Function to call with result.
59    */
60   GNUNET_DNSSTUB_ResultCallback rc;
61
62   /**
63    * Closure for 'rc'.
64    */
65   void *rc_cls;
66
67   /**
68    * Task for reading from dnsout4 and dnsout6.
69    */
70   GNUNET_SCHEDULER_TaskIdentifier read_task;
71
72   /**
73    * When should this request time out?
74    */
75   struct GNUNET_TIME_Absolute timeout;
76
77   /**
78    * Address we sent the DNS request to.
79    */
80   struct sockaddr_storage addr;
81
82   /**
83    * Number of bytes in 'addr'.
84    */
85   socklen_t addrlen;
86
87 };
88
89
90 /**
91  * Handle to the stub resolver.
92  */ 
93 struct GNUNET_DNSSTUB_Context
94 {
95
96   /**
97    * Array of all open sockets for DNS requests. 
98    */
99   struct GNUNET_DNSSTUB_RequestSocket sockets[DNS_SOCKET_MAX];
100
101   /**
102    * IP address to use for the DNS server if we are a DNS exit service
103    * (for VPN via mesh); otherwise NULL.
104    */
105   char *dns_exit;
106 };
107
108
109
110 /**
111  * We're done with a GNUNET_DNSSTUB_RequestSocket, close it for now.
112  *
113  * @param rs request socket to clean up
114  */
115 static void
116 cleanup_rs (struct GNUNET_DNSSTUB_RequestSocket *rs)
117 {
118   if (NULL != rs->dnsout4)
119   {
120     GNUNET_NETWORK_socket_close (rs->dnsout4);
121     rs->dnsout4 = NULL;
122   }
123   if (NULL != rs->dnsout6)
124   {
125     GNUNET_NETWORK_socket_close (rs->dnsout6);
126     rs->dnsout6 = NULL;
127   }
128   if (GNUNET_SCHEDULER_NO_TASK != rs->read_task)
129   {
130     GNUNET_SCHEDULER_cancel (rs->read_task);
131     rs->read_task = GNUNET_SCHEDULER_NO_TASK;
132   }
133 }
134
135
136 /**
137  * Open source port for sending DNS requests
138  *
139  * @param af AF_INET or AF_INET6
140  * @return GNUNET_OK on success
141  */ 
142 static struct GNUNET_NETWORK_Handle *
143 open_socket (int af)
144 {
145   struct sockaddr_in a4;
146   struct sockaddr_in6 a6;
147   struct sockaddr *sa;
148   socklen_t alen;
149   struct GNUNET_NETWORK_Handle *ret;
150
151   ret = GNUNET_NETWORK_socket_create (af, SOCK_DGRAM, 0);
152   if (NULL == ret)
153     return NULL;
154   switch (af)
155   {
156   case AF_INET:
157     memset (&a4, 0, alen = sizeof (struct sockaddr_in));
158     sa = (struct sockaddr *) &a4;
159     break;
160   case AF_INET6:
161     memset (&a6, 0, alen = sizeof (struct sockaddr_in6));
162     sa = (struct sockaddr *) &a6;
163     break;
164   default:
165     GNUNET_break (0);
166     GNUNET_NETWORK_socket_close (ret);
167     return NULL;
168   }
169   sa->sa_family = af;
170   if (GNUNET_OK != GNUNET_NETWORK_socket_bind (ret,
171                                                sa, 
172                                                alen))
173   {
174     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
175                 _("Could not bind to any port: %s\n"),
176                 STRERROR (errno));
177     GNUNET_NETWORK_socket_close (ret);
178     return NULL;
179   }
180   return ret;
181 }
182
183
184 /**
185  * Read a DNS response from the (unhindered) UDP-Socket
186  *
187  * @param cls socket to read from
188  * @param tc scheduler context (must be shutdown or read ready)
189  */
190 static void
191 read_response (void *cls,
192                const struct GNUNET_SCHEDULER_TaskContext *tc);
193
194
195 /**
196  * Get a socket of the specified address family to send out a
197  * UDP DNS request to the Internet.  
198  *
199  * @param ctx the DNSSTUB context
200  * @param af desired address family
201  * @return NULL on error (given AF not "supported")
202  */
203 static struct GNUNET_DNSSTUB_RequestSocket *
204 get_request_socket (struct GNUNET_DNSSTUB_Context *ctx,
205                     int af)
206 {
207   struct GNUNET_DNSSTUB_RequestSocket *rs;
208   struct GNUNET_NETWORK_FDSet *rset;
209
210   rs = &ctx->sockets[GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, 
211                                                DNS_SOCKET_MAX)];
212   rs->timeout = GNUNET_TIME_relative_to_absolute (REQUEST_TIMEOUT);
213   switch (af)
214   {
215   case AF_INET:
216     if (NULL == rs->dnsout4)
217       rs->dnsout4 = open_socket (AF_INET);
218     break;
219   case AF_INET6:
220     if (NULL == rs->dnsout6)
221       rs->dnsout6 = open_socket (AF_INET6);
222     break;
223   default:
224     return NULL;
225   }  
226   if (GNUNET_SCHEDULER_NO_TASK != rs->read_task)
227   {
228     GNUNET_SCHEDULER_cancel (rs->read_task);
229     rs->read_task = GNUNET_SCHEDULER_NO_TASK;
230   }
231   if ( (NULL == rs->dnsout4) &&
232        (NULL == rs->dnsout6) )
233     return NULL;
234   rset = GNUNET_NETWORK_fdset_create ();
235   if (NULL != rs->dnsout4)
236     GNUNET_NETWORK_fdset_set (rset, rs->dnsout4);
237   if (NULL != rs->dnsout6)
238     GNUNET_NETWORK_fdset_set (rset, rs->dnsout6);
239   rs->read_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
240                                                REQUEST_TIMEOUT,
241                                                rset,
242                                                NULL,
243                                                &read_response, rs);
244   GNUNET_NETWORK_fdset_destroy (rset);
245   return rs;
246 }
247
248
249 /**
250  * Perform DNS resolution.
251  *
252  * @param ctx stub resolver to use
253  * @param sa the socket address
254  * @param sa_len the socket length
255  * @param request DNS request to transmit
256  * @param request_len number of bytes in msg
257  * @param rc function to call with result
258  * @param rc_cls closure for 'rc'
259  * @return socket used for the request, NULL on error
260  */
261 struct GNUNET_DNSSTUB_RequestSocket *
262 GNUNET_DNSSTUB_resolve (struct GNUNET_DNSSTUB_Context *ctx,
263                         const struct sockaddr *sa,
264                         socklen_t sa_len,
265                         const void *request,
266                         size_t request_len,
267                         GNUNET_DNSSTUB_ResultCallback rc,
268                         void *rc_cls)
269 {
270   struct GNUNET_DNSSTUB_RequestSocket *rs;
271   struct GNUNET_NETWORK_Handle *ret;
272   int af;
273
274   af = sa->sa_family;
275   if (NULL == (rs = get_request_socket (ctx, af)))
276     return NULL;
277   if (NULL != rs->dnsout4)
278     ret = rs->dnsout4;
279   else
280     ret = rs->dnsout6;
281   GNUNET_assert (NULL != ret);
282   rs->rc = rc;
283   rs->rc_cls = rc_cls;
284   if (GNUNET_SYSERR == 
285       GNUNET_NETWORK_socket_sendto (ret,
286                                     request,
287                                     request_len,
288                                     sa,
289                                     sa_len))
290     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
291                 _("Failed to send DNS request to %s\n"),
292                 GNUNET_a2s (sa, sa_len));
293   return rs;
294 }
295
296
297 /**
298  * Perform DNS resolution using our default IP from init.
299  *
300  * @param ctx stub resolver to use
301  * @param request DNS request to transmit
302  * @param request_len number of bytes in msg
303  * @param rc function to call with result
304  * @param rc_cls closure for 'rc'
305  * @return socket used for the request, NULL on error
306  */
307 struct GNUNET_DNSSTUB_RequestSocket *
308 GNUNET_DNSSTUB_resolve2 (struct GNUNET_DNSSTUB_Context *ctx,
309                          const void *request,
310                          size_t request_len,
311                          GNUNET_DNSSTUB_ResultCallback rc,
312                          void *rc_cls)
313 {
314   int af;
315   struct sockaddr_in v4;
316   struct sockaddr_in6 v6;
317   struct sockaddr *sa;
318   socklen_t salen;
319   struct GNUNET_NETWORK_Handle *dnsout;
320   struct GNUNET_DNSSTUB_RequestSocket *rs;
321
322   memset (&v4, 0, sizeof (v4));
323   memset (&v6, 0, sizeof (v6));
324   if (1 == inet_pton (AF_INET, ctx->dns_exit, &v4.sin_addr))
325   {
326     salen = sizeof (v4);
327     v4.sin_family = AF_INET;
328     v4.sin_port = htons (53);
329 #if HAVE_SOCKADDR_IN_SIN_LEN
330     v4.sin_len = (u_char) salen;
331 #endif
332     sa = (struct sockaddr *) &v4;
333     af = AF_INET;
334   }
335   else if (1 == inet_pton (AF_INET6, ctx->dns_exit, &v6.sin6_addr))
336   {
337     salen = sizeof (v6);
338     v6.sin6_family = AF_INET6;
339     v6.sin6_port = htons (53);
340 #if HAVE_SOCKADDR_IN_SIN_LEN
341     v6.sin6_len = (u_char) salen;
342 #endif
343     sa = (struct sockaddr *) &v6;
344     af = AF_INET6;
345   }  
346   else
347   {
348     GNUNET_break (0);
349     return NULL;
350   }
351   if (NULL == (rs = get_request_socket (ctx, af)))
352     return NULL;
353   if (NULL != rs->dnsout4)
354     dnsout = rs->dnsout4;
355   else
356     dnsout = rs->dnsout6;
357   if (NULL == dnsout)
358   {
359     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
360                 _("Configured DNS exit `%s' is not working / valid.\n"),
361                 ctx->dns_exit);
362     return NULL;
363   }
364   memcpy (&rs->addr,
365           sa,
366           salen);
367   rs->addrlen = salen;
368   rs->rc = rc;
369   rs->rc_cls = rc_cls;
370   if (GNUNET_SYSERR ==
371       GNUNET_NETWORK_socket_sendto (dnsout,
372                                     request,
373                                     request_len, sa, salen))
374     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
375                 _("Failed to send DNS request to %s\n"),
376                 GNUNET_a2s (sa, salen));
377   rs->timeout = GNUNET_TIME_relative_to_absolute (REQUEST_TIMEOUT);
378   
379   return rs;
380
381 }
382
383
384 /**
385  * Actually do the reading of a DNS packet from our UDP socket and see
386  * if we have a valid, matching, pending request.
387  *
388  * @param rs request socket with callback details
389  * @param dnsout socket to read from
390  * @return GNUNET_OK on success, GNUNET_NO on drop, GNUNET_SYSERR on IO-errors (closed socket)
391  */
392 static int
393 do_dns_read (struct GNUNET_DNSSTUB_RequestSocket *rs,
394              struct GNUNET_NETWORK_Handle *dnsout)
395 {
396   struct sockaddr_storage addr;
397   socklen_t addrlen;
398   struct GNUNET_TUN_DnsHeader *dns;
399   ssize_t r;
400   int len;
401
402 #ifndef MINGW
403   if (0 != ioctl (GNUNET_NETWORK_get_fd (dnsout), FIONREAD, &len))
404   {
405     /* conservative choice: */
406     len = UINT16_MAX;
407   }
408 #else
409   /* port the code above? */
410   len = UINT16_MAX;
411 #endif
412
413   {
414     unsigned char buf[len] GNUNET_ALIGN;
415
416     addrlen = sizeof (addr);
417     memset (&addr, 0, sizeof (addr));  
418     r = GNUNET_NETWORK_socket_recvfrom (dnsout, 
419                                         buf, sizeof (buf),
420                                         (struct sockaddr*) &addr, &addrlen);
421     if (-1 == r)
422     {
423       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "recvfrom");
424       GNUNET_NETWORK_socket_close (dnsout);
425       return GNUNET_SYSERR;
426     }
427     if (sizeof (struct GNUNET_TUN_DnsHeader) > r)
428     {
429       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
430                   _("Received DNS response that is too small (%u bytes)"),
431                   r);
432       return GNUNET_NO;
433     }
434     dns = (struct GNUNET_TUN_DnsHeader *) buf;
435     if ( (addrlen != rs->addrlen) ||
436          (0 != memcmp (&rs->addr,
437                        &addr,
438                        addrlen)) ||      
439        (0 == GNUNET_TIME_absolute_get_remaining (rs->timeout).rel_value) )
440       return GNUNET_NO;
441     rs->rc (rs->rc_cls,
442             rs,
443             dns,
444             r);
445   }  
446   return GNUNET_OK;
447 }
448
449
450 /**
451  * Read a DNS response from the (unhindered) UDP-Socket
452  *
453  * @param cls socket to read from
454  * @param tc scheduler context (must be shutdown or read ready)
455  */
456 static void
457 read_response (void *cls,
458                const struct GNUNET_SCHEDULER_TaskContext *tc)
459 {
460   struct GNUNET_DNSSTUB_RequestSocket *rs = cls;
461   struct GNUNET_NETWORK_FDSet *rset;
462
463   rs->read_task = GNUNET_SCHEDULER_NO_TASK;
464   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
465   {
466     /* timeout or shutdown */
467     cleanup_rs (rs);
468     return;
469   }
470   /* read and process ready sockets */
471   if ((NULL != rs->dnsout4) &&
472       (GNUNET_NETWORK_fdset_isset (tc->read_ready, rs->dnsout4)) &&
473       (GNUNET_SYSERR == do_dns_read (rs, rs->dnsout4)))
474     rs->dnsout4 = NULL;
475   if ((NULL != rs->dnsout6) &&
476       (GNUNET_NETWORK_fdset_isset (tc->read_ready, rs->dnsout6)) &&
477       (GNUNET_SYSERR == do_dns_read (rs, rs->dnsout6)))
478     rs->dnsout6 = NULL;
479
480   /* re-schedule read task */
481   rset = GNUNET_NETWORK_fdset_create ();
482   if (NULL != rs->dnsout4)
483     GNUNET_NETWORK_fdset_set (rset, rs->dnsout4);
484   if (NULL != rs->dnsout6)
485     GNUNET_NETWORK_fdset_set (rset, rs->dnsout6);
486   rs->read_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
487                                                GNUNET_TIME_absolute_get_remaining (rs->timeout),
488                                                rset,
489                                                NULL,
490                                                &read_response, rs);
491   GNUNET_NETWORK_fdset_destroy (rset);
492 }
493
494
495
496 /**
497  * Start a DNS stub resolver.
498  *
499  * @param dns_ip target IP address to use
500  * @return NULL on error
501  */
502 struct GNUNET_DNSSTUB_Context *
503 GNUNET_DNSSTUB_start (const char *dns_ip)
504 {
505   struct GNUNET_DNSSTUB_Context *ctx;
506   
507   ctx = GNUNET_malloc (sizeof (struct GNUNET_DNSSTUB_Context));
508   if (NULL != dns_ip)
509     ctx->dns_exit = GNUNET_strdup (dns_ip);
510   return ctx;
511 }
512
513
514 /**
515  * Cleanup DNSSTUB resolver.
516  *
517  * @param ctx stub resolver to clean up
518  */
519 void
520 GNUNET_DNSSTUB_stop (struct GNUNET_DNSSTUB_Context *ctx)
521 {
522   unsigned int i;
523
524   for (i=0;i<DNS_SOCKET_MAX;i++)
525     cleanup_rs (&ctx->sockets[i]);
526   if (NULL != ctx->dns_exit)
527   {
528     GNUNET_free (ctx->dns_exit);
529     ctx->dns_exit = NULL;
530   }
531   GNUNET_free (ctx);
532 }
533
534
535 /* end of dnsstub.c */