regex profiler cleanup
[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   memcpy (&rs->addr,
283           sa,
284           sa_len);
285   rs->addrlen = sa_len;
286   rs->rc = rc;
287   rs->rc_cls = rc_cls;
288   if (GNUNET_SYSERR == 
289       GNUNET_NETWORK_socket_sendto (ret,
290                                     request,
291                                     request_len,
292                                     sa,
293                                     sa_len))
294     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
295                 _("Failed to send DNS request to %s\n"),
296                 GNUNET_a2s (sa, sa_len));
297   else
298     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
299                 _("Sent DNS request to %s\n"),
300                 GNUNET_a2s (sa, sa_len));
301   return rs;
302 }
303
304
305 /**
306  * Perform DNS resolution using our default IP from init.
307  *
308  * @param ctx stub resolver to use
309  * @param request DNS request to transmit
310  * @param request_len number of bytes in msg
311  * @param rc function to call with result
312  * @param rc_cls closure for 'rc'
313  * @return socket used for the request, NULL on error
314  */
315 struct GNUNET_DNSSTUB_RequestSocket *
316 GNUNET_DNSSTUB_resolve2 (struct GNUNET_DNSSTUB_Context *ctx,
317                          const void *request,
318                          size_t request_len,
319                          GNUNET_DNSSTUB_ResultCallback rc,
320                          void *rc_cls)
321 {
322   int af;
323   struct sockaddr_in v4;
324   struct sockaddr_in6 v6;
325   struct sockaddr *sa;
326   socklen_t salen;
327   struct GNUNET_NETWORK_Handle *dnsout;
328   struct GNUNET_DNSSTUB_RequestSocket *rs;
329
330   memset (&v4, 0, sizeof (v4));
331   memset (&v6, 0, sizeof (v6));
332   if (1 == inet_pton (AF_INET, ctx->dns_exit, &v4.sin_addr))
333   {
334     salen = sizeof (v4);
335     v4.sin_family = AF_INET;
336     v4.sin_port = htons (53);
337 #if HAVE_SOCKADDR_IN_SIN_LEN
338     v4.sin_len = (u_char) salen;
339 #endif
340     sa = (struct sockaddr *) &v4;
341     af = AF_INET;
342   }
343   else if (1 == inet_pton (AF_INET6, ctx->dns_exit, &v6.sin6_addr))
344   {
345     salen = sizeof (v6);
346     v6.sin6_family = AF_INET6;
347     v6.sin6_port = htons (53);
348 #if HAVE_SOCKADDR_IN_SIN_LEN
349     v6.sin6_len = (u_char) salen;
350 #endif
351     sa = (struct sockaddr *) &v6;
352     af = AF_INET6;
353   }  
354   else
355   {
356     GNUNET_break (0);
357     return NULL;
358   }
359   if (NULL == (rs = get_request_socket (ctx, af)))
360     return NULL;
361   if (NULL != rs->dnsout4)
362     dnsout = rs->dnsout4;
363   else
364     dnsout = rs->dnsout6;
365   if (NULL == dnsout)
366   {
367     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
368                 _("Configured DNS exit `%s' is not working / valid.\n"),
369                 ctx->dns_exit);
370     return NULL;
371   }
372   memcpy (&rs->addr,
373           sa,
374           salen);
375   rs->addrlen = salen;
376   rs->rc = rc;
377   rs->rc_cls = rc_cls;
378   if (GNUNET_SYSERR ==
379       GNUNET_NETWORK_socket_sendto (dnsout,
380                                     request,
381                                     request_len, sa, salen))
382     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
383                 _("Failed to send DNS request to %s\n"),
384                 GNUNET_a2s (sa, salen));
385   rs->timeout = GNUNET_TIME_relative_to_absolute (REQUEST_TIMEOUT);
386   
387   return rs;
388
389 }
390
391
392 /**
393  * Actually do the reading of a DNS packet from our UDP socket and see
394  * if we have a valid, matching, pending request.
395  *
396  * @param rs request socket with callback details
397  * @param dnsout socket to read from
398  * @return GNUNET_OK on success, GNUNET_NO on drop, GNUNET_SYSERR on IO-errors (closed socket)
399  */
400 static int
401 do_dns_read (struct GNUNET_DNSSTUB_RequestSocket *rs,
402              struct GNUNET_NETWORK_Handle *dnsout)
403 {
404   struct sockaddr_storage addr;
405   socklen_t addrlen;
406   struct GNUNET_TUN_DnsHeader *dns;
407   ssize_t r;
408   int len;
409
410 #ifndef MINGW
411   if (0 != ioctl (GNUNET_NETWORK_get_fd (dnsout), FIONREAD, &len))
412   {
413     /* conservative choice: */
414     len = UINT16_MAX;
415   }
416 #else
417   /* port the code above? */
418   len = UINT16_MAX;
419 #endif
420   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
421               "Receiving %d byte DNS reply\n",
422               len); 
423   {
424     unsigned char buf[len] GNUNET_ALIGN;
425
426     addrlen = sizeof (addr);
427     memset (&addr, 0, sizeof (addr));  
428     r = GNUNET_NETWORK_socket_recvfrom (dnsout, 
429                                         buf, sizeof (buf),
430                                         (struct sockaddr*) &addr, &addrlen);
431     if (-1 == r)
432     {
433       GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "recvfrom");
434       GNUNET_NETWORK_socket_close (dnsout);
435       return GNUNET_SYSERR;
436     }
437     if (sizeof (struct GNUNET_TUN_DnsHeader) > r)
438     {
439       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
440                   _("Received DNS response that is too small (%u bytes)"),
441                   r);
442       return GNUNET_NO;
443     }
444     dns = (struct GNUNET_TUN_DnsHeader *) buf;
445     if ( (addrlen != rs->addrlen) ||
446          (0 != memcmp (&rs->addr,
447                        &addr,
448                        addrlen)) ||      
449        (0 == GNUNET_TIME_absolute_get_remaining (rs->timeout).rel_value) )
450     {
451       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
452                   "Request timeout or invalid sender address; ignoring reply\n"); 
453       return GNUNET_NO;
454     }
455     if (NULL != rs->rc)
456       rs->rc (rs->rc_cls,
457               rs,
458               dns,
459               r);
460   }  
461   return GNUNET_OK;
462 }
463
464
465 /**
466  * Read a DNS response from the (unhindered) UDP-Socket
467  *
468  * @param cls socket to read from
469  * @param tc scheduler context (must be shutdown or read ready)
470  */
471 static void
472 read_response (void *cls,
473                const struct GNUNET_SCHEDULER_TaskContext *tc)
474 {
475   struct GNUNET_DNSSTUB_RequestSocket *rs = cls;
476   struct GNUNET_NETWORK_FDSet *rset;
477
478   rs->read_task = GNUNET_SCHEDULER_NO_TASK;
479   if (0 == (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY))
480   {
481     /* timeout or shutdown */
482     cleanup_rs (rs);
483     return;
484   }
485   /* read and process ready sockets */
486   if ((NULL != rs->dnsout4) &&
487       (GNUNET_NETWORK_fdset_isset (tc->read_ready, rs->dnsout4)) &&
488       (GNUNET_SYSERR == do_dns_read (rs, rs->dnsout4)))
489     rs->dnsout4 = NULL;
490   if ((NULL != rs->dnsout6) &&
491       (GNUNET_NETWORK_fdset_isset (tc->read_ready, rs->dnsout6)) &&
492       (GNUNET_SYSERR == do_dns_read (rs, rs->dnsout6)))
493     rs->dnsout6 = NULL;
494
495   /* re-schedule read task */
496   rset = GNUNET_NETWORK_fdset_create ();
497   if (NULL != rs->dnsout4)
498     GNUNET_NETWORK_fdset_set (rset, rs->dnsout4);
499   if (NULL != rs->dnsout6)
500     GNUNET_NETWORK_fdset_set (rset, rs->dnsout6);
501   rs->read_task = GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
502                                                GNUNET_TIME_absolute_get_remaining (rs->timeout),
503                                                rset,
504                                                NULL,
505                                                &read_response, rs);
506   GNUNET_NETWORK_fdset_destroy (rset);
507 }
508
509
510 /**
511  * Cancel DNS resolution.
512  *
513  * @param rs resolution to cancel
514  */
515 void
516 GNUNET_DNSSTUB_resolve_cancel (struct GNUNET_DNSSTUB_RequestSocket *rs)
517 {
518   rs->rc = NULL;
519 }
520
521
522 /**
523  * Start a DNS stub resolver.
524  *
525  * @param dns_ip target IP address to use
526  * @return NULL on error
527  */
528 struct GNUNET_DNSSTUB_Context *
529 GNUNET_DNSSTUB_start (const char *dns_ip)
530 {
531   struct GNUNET_DNSSTUB_Context *ctx;
532   
533   ctx = GNUNET_malloc (sizeof (struct GNUNET_DNSSTUB_Context));
534   if (NULL != dns_ip)
535     ctx->dns_exit = GNUNET_strdup (dns_ip);
536   return ctx;
537 }
538
539
540 /**
541  * Cleanup DNSSTUB resolver.
542  *
543  * @param ctx stub resolver to clean up
544  */
545 void
546 GNUNET_DNSSTUB_stop (struct GNUNET_DNSSTUB_Context *ctx)
547 {
548   unsigned int i;
549
550   for (i=0;i<DNS_SOCKET_MAX;i++)
551     cleanup_rs (&ctx->sockets[i]);
552   if (NULL != ctx->dns_exit)
553   {
554     GNUNET_free (ctx->dns_exit);
555     ctx->dns_exit = NULL;
556   }
557   GNUNET_free (ctx);
558 }
559
560
561 /* end of dnsstub.c */