1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
3 /* GIO - GLib Input, Output and Streaming Library
5 * Copyright (C) 2008 Red Hat, Inc.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20 * Boston, MA 02111-1307, USA.
27 #include "gresolver.h"
28 #include "gnetworkingprivate.h"
29 #include "gasyncresult.h"
30 #include "ginetaddress.h"
31 #include "ginetsocketaddress.h"
32 #include "gsimpleasyncresult.h"
33 #include "gsrvtarget.h"
36 #include "gunixresolver.h"
39 #include "gwin32resolver.h"
48 * @short_description: Asynchronous and cancellable DNS resolver
51 * #GResolver provides cancellable synchronous and asynchronous DNS
52 * resolution, for hostnames (g_resolver_lookup_by_address(),
53 * g_resolver_lookup_by_name() and their async variants) and SRV
54 * (service) records (g_resolver_lookup_service()).
56 * #GNetworkAddress and #GNetworkService provide wrappers around
57 * #GResolver functionality that also implement #GSocketConnectable,
58 * making it easy to connect to a remote host/service.
64 * The object that handles DNS resolution. Use g_resolver_get_default()
65 * to get the default resolver.
67 G_DEFINE_TYPE (GResolver, g_resolver, G_TYPE_OBJECT)
70 g_resolver_class_init (GResolverClass *resolver_class)
74 /* Make sure _g_networking_init() has been called */
75 type = g_inet_address_get_type ();
77 /* Initialize _g_resolver_addrinfo_hints */
79 _g_resolver_addrinfo_hints.ai_flags |= AI_ADDRCONFIG;
81 /* These two don't actually matter, they just get copied into the
82 * returned addrinfo structures (and then we ignore them). But if
83 * we leave them unset, we'll get back duplicate answers.
85 _g_resolver_addrinfo_hints.ai_socktype = SOCK_STREAM;
86 _g_resolver_addrinfo_hints.ai_protocol = IPPROTO_TCP;
90 g_resolver_init (GResolver *resolver)
94 static GResolver *default_resolver;
97 * g_resolver_get_default:
99 * Gets the default #GResolver. You should unref it when you are done
100 * with it. #GResolver may use its reference count as a hint about how
101 * many threads/processes, etc it should allocate for concurrent DNS
104 * Return value: the default #GResolver.
109 g_resolver_get_default (void)
111 if (!default_resolver)
113 if (g_thread_supported ())
114 default_resolver = g_object_new (G_TYPE_THREADED_RESOLVER, NULL);
117 #if defined(G_OS_UNIX)
118 default_resolver = g_object_new (G_TYPE_UNIX_RESOLVER, NULL);
119 #elif defined(G_OS_WIN32)
120 default_resolver = g_object_new (G_TYPE_WIN32_RESOLVER, NULL);
125 return g_object_ref (default_resolver);
129 * g_resolver_set_default:
130 * @resolver: the new default #GResolver
132 * Sets @resolver to be the application's default resolver (reffing
133 * @resolver, and unreffing the previous default resolver, if any).
134 * Future calls to g_resolver_get_default() will return this resolver.
136 * This can be used if an application wants to perform any sort of DNS
137 * caching or "pinning"; it can implement its own #GResolver that
138 * calls the original default resolver for DNS operations, and
139 * implements its own cache policies on top of that, and then set
140 * itself as the default resolver for all later code to use.
145 g_resolver_set_default (GResolver *resolver)
147 if (default_resolver)
148 g_object_unref (default_resolver);
149 default_resolver = g_object_ref (resolver);
154 * g_resolver_lookup_by_name:
155 * @resolver: a #GResolver
156 * @hostname: the hostname to look up
157 * @cancellable: a #GCancellable, or %NULL
158 * @error: return location for a #GError, or %NULL
160 * Synchronously resolves @hostname to determine its associated IP
161 * address(es). @hostname may be an ASCII-only or UTF-8 hostname, or
162 * the textual form of an IP address (in which case this just becomes
163 * a wrapper around g_inet_address_new_from_string()).
165 * On success, g_resolver_lookup_by_name() will return a #GList of
166 * #GInetAddress, sorted in order of preference. (That is, you should
167 * attempt to connect to the first address first, then the second if
168 * the first fails, etc.)
170 * If the DNS resolution fails, @error (if non-%NULL) will be set to a
171 * value from #GResolverError.
173 * If @cancellable is non-%NULL, it can be used to cancel the
174 * operation, in which case @error (if non-%NULL) will be set to
175 * %G_IO_ERROR_CANCELLED.
177 * If you are planning to connect to a socket on the resolved IP
178 * address, it may be easier to create a #GNetworkAddress and use its
179 * #GSocketConnectable interface.
181 * Return value: a #GList of #GInetAddress, or %NULL on error. You
182 * must unref each of the addresses and free the list when you are
183 * done with it. (You can use g_resolver_free_addresses() to do this.)
188 g_resolver_lookup_by_name (GResolver *resolver,
189 const gchar *hostname,
190 GCancellable *cancellable,
195 gchar *ascii_hostname = NULL;
197 g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
198 g_return_val_if_fail (hostname != NULL, NULL);
200 /* Check if @hostname is just an IP address */
201 addr = g_inet_address_new_from_string (hostname);
203 return g_list_append (NULL, addr);
205 if (g_hostname_is_non_ascii (hostname))
206 hostname = ascii_hostname = g_hostname_to_ascii (hostname);
208 addrs = G_RESOLVER_GET_CLASS (resolver)->
209 lookup_by_name (resolver, hostname, cancellable, error);
211 g_free (ascii_hostname);
216 * g_resolver_lookup_by_name_async:
217 * @resolver: a #GResolver
218 * @hostname: the hostname to look up the address of
219 * @cancellable: a #GCancellable, or %NULL
220 * @callback: callback to call after resolution completes
221 * @user_data: data for @callback
223 * Begins asynchronously resolving @hostname to determine its
224 * associated IP address(es), and eventually calls @callback, which
225 * must call g_resolver_lookup_by_name_finish() to get the result.
226 * See g_resolver_lookup_by_name() for more details.
231 g_resolver_lookup_by_name_async (GResolver *resolver,
232 const gchar *hostname,
233 GCancellable *cancellable,
234 GAsyncReadyCallback callback,
238 gchar *ascii_hostname = NULL;
240 g_return_if_fail (G_IS_RESOLVER (resolver));
241 g_return_if_fail (hostname != NULL);
243 /* Check if @hostname is just an IP address */
244 addr = g_inet_address_new_from_string (hostname);
247 GSimpleAsyncResult *simple;
250 simple = g_simple_async_result_new (G_OBJECT (resolver),
252 g_resolver_lookup_by_name_async);
254 addrs = g_list_append (NULL, addr);
255 g_simple_async_result_set_op_res_gpointer (simple, addrs, (GDestroyNotify)g_resolver_free_addresses);
256 g_simple_async_result_complete_in_idle (simple);
257 g_object_unref (simple);
261 if (g_hostname_is_non_ascii (hostname))
262 hostname = ascii_hostname = g_hostname_to_ascii (hostname);
264 G_RESOLVER_GET_CLASS (resolver)->
265 lookup_by_name_async (resolver, hostname, cancellable, callback, user_data);
267 g_free (ascii_hostname);
271 * g_resolver_lookup_by_name_finish:
272 * @resolver: a #GResolver
273 * @result: the result passed to your #GAsyncReadyCallback
274 * @error: return location for a #GError, or %NULL
276 * Retrieves the result of a call to
277 * g_resolver_lookup_by_name_async().
279 * If the DNS resolution failed, @error (if non-%NULL) will be set to
280 * a value from #GResolverError. If the operation was cancelled,
281 * @error will be set to %G_IO_ERROR_CANCELLED.
283 * Return value: a #GList of #GInetAddress, or %NULL on error. See
284 * g_resolver_lookup_by_name() for more details.
289 g_resolver_lookup_by_name_finish (GResolver *resolver,
290 GAsyncResult *result,
293 g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
295 if (G_IS_SIMPLE_ASYNC_RESULT (result))
297 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
299 if (g_simple_async_result_propagate_error (simple, error))
302 /* Handle the stringified-IP-addr case */
303 if (g_simple_async_result_get_source_tag (simple) == g_resolver_lookup_by_name_async)
307 addrs = g_simple_async_result_get_op_res_gpointer (simple);
308 g_simple_async_result_set_op_res_gpointer (simple, NULL, NULL);
313 return G_RESOLVER_GET_CLASS (resolver)->
314 lookup_by_name_finish (resolver, result, error);
318 * g_resolver_free_addresses:
319 * @addresses: a #GList of #GInetAddress
321 * Frees @addresses (which should be the return value from
322 * g_resolver_lookup_by_name() or g_resolver_lookup_by_name_finish()).
323 * (This is a convenience method; you can also simply free the results
329 g_resolver_free_addresses (GList *addresses)
333 for (a = addresses; a; a = a->next)
334 g_object_unref (a->data);
335 g_list_free (addresses);
339 * g_resolver_lookup_by_address:
340 * @resolver: a #GResolver
341 * @address: the address to reverse-resolve
342 * @cancellable: a #GCancellable, or %NULL
343 * @error: return location for a #GError, or %NULL
345 * Synchronously reverse-resolves @address to determine its
346 * associated hostname.
348 * If the DNS resolution fails, @error (if non-%NULL) will be set to
349 * a value from #GResolverError.
351 * If @cancellable is non-%NULL, it can be used to cancel the
352 * operation, in which case @error (if non-%NULL) will be set to
353 * %G_IO_ERROR_CANCELLED.
355 * Return value: a hostname (either ASCII-only, or in ASCII-encoded
356 * form), or %NULL on error.
361 g_resolver_lookup_by_address (GResolver *resolver,
362 GInetAddress *address,
363 GCancellable *cancellable,
366 g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
367 g_return_val_if_fail (G_IS_INET_ADDRESS (address), NULL);
369 return G_RESOLVER_GET_CLASS (resolver)->
370 lookup_by_address (resolver, address, cancellable, error);
374 * g_resolver_lookup_by_address_async:
375 * @resolver: a #GResolver
376 * @address: the address to reverse-resolve
377 * @cancellable: a #GCancellable, or %NULL
378 * @callback: callback to call after resolution completes
379 * @user_data: data for @callback
381 * Begins asynchronously reverse-resolving @address to determine its
382 * associated hostname, and eventually calls @callback, which must
383 * call g_resolver_lookup_by_address_finish() to get the final result.
388 g_resolver_lookup_by_address_async (GResolver *resolver,
389 GInetAddress *address,
390 GCancellable *cancellable,
391 GAsyncReadyCallback callback,
394 g_return_if_fail (G_IS_RESOLVER (resolver));
395 g_return_if_fail (G_IS_INET_ADDRESS (address));
397 G_RESOLVER_GET_CLASS (resolver)->
398 lookup_by_address_async (resolver, address, cancellable, callback, user_data);
402 * g_resolver_lookup_by_address_finish:
403 * @resolver: a #GResolver
404 * @result: the result passed to your #GAsyncReadyCallback
405 * @error: return location for a #GError, or %NULL
407 * Retrieves the result of a previous call to
408 * g_resolver_lookup_by_address_async().
410 * If the DNS resolution failed, @error (if non-%NULL) will be set to
411 * a value from #GResolverError. If the operation was cancelled,
412 * @error will be set to %G_IO_ERROR_CANCELLED.
414 * Return value: a hostname (either ASCII-only, or in ASCII-encoded
415 * form), or %NULL on error.
420 g_resolver_lookup_by_address_finish (GResolver *resolver,
421 GAsyncResult *result,
424 g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
426 if (G_IS_SIMPLE_ASYNC_RESULT (result))
428 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
430 if (g_simple_async_result_propagate_error (simple, error))
434 return G_RESOLVER_GET_CLASS (resolver)->
435 lookup_by_address_finish (resolver, result, error);
439 g_resolver_get_service_rrname (const char *service,
440 const char *protocol,
443 gchar *rrname, *ascii_domain = NULL;
445 if (g_hostname_is_non_ascii (domain))
446 domain = ascii_domain = g_hostname_to_ascii (domain);
448 rrname = g_strdup_printf ("_%s._%s.%s", service, protocol, domain);
450 g_free (ascii_domain);
455 * g_resolver_lookup_service:
456 * @resolver: a #GResolver
457 * @service: the service type to look up (eg, "ldap")
458 * @protocol: the networking protocol to use for @service (eg, "tcp")
459 * @domain: the DNS domain to look up the service in
460 * @cancellable: a #GCancellable, or %NULL
461 * @error: return location for a #GError, or %NULL
463 * Synchronously performs a DNS SRV lookup for the given @service and
464 * @protocol in the given @domain and returns an array of #GSrvTarget.
465 * @domain may be an ASCII-only or UTF-8 hostname. Note also that the
466 * @service and @protocol arguments <emphasis>do not</emphasis>
467 * include the leading underscore that appears in the actual DNS
470 * On success, g_resolver_lookup_service() will return a #GList of
471 * #GSrvTarget, sorted in order of preference. (That is, you should
472 * attempt to connect to the first target first, then the second if
473 * the first fails, etc.)
475 * If the DNS resolution fails, @error (if non-%NULL) will be set to
476 * a value from #GResolverError.
478 * If @cancellable is non-%NULL, it can be used to cancel the
479 * operation, in which case @error (if non-%NULL) will be set to
480 * %G_IO_ERROR_CANCELLED.
482 * If you are planning to connect to the service, it is usually easier
483 * to create a #GNetworkService and use its #GSocketConnectable
486 * Return value: a #GList of #GSrvTarget, or %NULL on error. You must
487 * free each of the targets and the list when you are done with it.
488 * (You can use g_resolver_free_targets() to do this.)
493 g_resolver_lookup_service (GResolver *resolver,
494 const gchar *service,
495 const gchar *protocol,
497 GCancellable *cancellable,
503 g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
504 g_return_val_if_fail (service != NULL, NULL);
505 g_return_val_if_fail (protocol != NULL, NULL);
506 g_return_val_if_fail (domain != NULL, NULL);
508 rrname = g_resolver_get_service_rrname (service, protocol, domain);
510 targets = G_RESOLVER_GET_CLASS (resolver)->
511 lookup_service (resolver, rrname, cancellable, error);
518 * g_resolver_lookup_service_async:
519 * @resolver: a #GResolver
520 * @service: the service type to look up (eg, "ldap")
521 * @protocol: the networking protocol to use for @service (eg, "tcp")
522 * @domain: the DNS domain to look up the service in
523 * @cancellable: a #GCancellable, or %NULL
524 * @callback: callback to call after resolution completes
525 * @user_data: data for @callback
527 * Begins asynchronously performing a DNS SRV lookup for the given
528 * @service and @protocol in the given @domain, and eventually calls
529 * @callback, which must call g_resolver_lookup_service_finish() to
530 * get the final result. See g_resolver_lookup_service() for more
536 g_resolver_lookup_service_async (GResolver *resolver,
537 const gchar *service,
538 const gchar *protocol,
540 GCancellable *cancellable,
541 GAsyncReadyCallback callback,
546 g_return_if_fail (G_IS_RESOLVER (resolver));
547 g_return_if_fail (service != NULL);
548 g_return_if_fail (protocol != NULL);
549 g_return_if_fail (domain != NULL);
551 rrname = g_resolver_get_service_rrname (service, protocol, domain);
553 G_RESOLVER_GET_CLASS (resolver)->
554 lookup_service_async (resolver, rrname, cancellable, callback, user_data);
560 * g_resolver_lookup_service_finish:
561 * @resolver: a #GResolver
562 * @result: the result passed to your #GAsyncReadyCallback
563 * @error: return location for a #GError, or %NULL
565 * Retrieves the result of a previous call to
566 * g_resolver_lookup_service_async().
568 * If the DNS resolution failed, @error (if non-%NULL) will be set to
569 * a value from #GResolverError. If the operation was cancelled,
570 * @error will be set to %G_IO_ERROR_CANCELLED.
572 * Return value: a #GList of #GSrvTarget, or %NULL on error. See
573 * g_resolver_lookup_service() for more details.
578 g_resolver_lookup_service_finish (GResolver *resolver,
579 GAsyncResult *result,
582 g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
584 if (G_IS_SIMPLE_ASYNC_RESULT (result))
586 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
588 if (g_simple_async_result_propagate_error (simple, error))
592 return G_RESOLVER_GET_CLASS (resolver)->
593 lookup_service_finish (resolver, result, error);
597 * g_resolver_free_targets:
598 * @targets: a #GList of #GSrvTarget
600 * Frees @targets (which should be the return value from
601 * g_resolver_lookup_service() or g_resolver_lookup_service_finish()).
602 * (This is a convenience method; you can also simply free the
608 g_resolver_free_targets (GList *targets)
612 for (t = targets; t; t = t->next)
613 g_srv_target_free (t->data);
614 g_list_free (targets);
618 * g_resolver_error_quark:
620 * Gets the #GResolver Error Quark.
622 * Return value: a #GQuark.
627 g_resolver_error_quark (void)
629 return g_quark_from_static_string ("g-resolver-error-quark");
633 static GResolverError
634 g_resolver_error_from_addrinfo_error (gint err)
639 #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
643 return G_RESOLVER_ERROR_NOT_FOUND;
646 return G_RESOLVER_ERROR_TEMPORARY_FAILURE;
649 return G_RESOLVER_ERROR_INTERNAL;
653 struct addrinfo _g_resolver_addrinfo_hints;
655 /* Private method to process a getaddrinfo() response. */
657 _g_resolver_addresses_from_addrinfo (const char *hostname,
658 struct addrinfo *res,
663 GSocketAddress *sockaddr;
669 g_set_error (error, G_RESOLVER_ERROR,
670 g_resolver_error_from_addrinfo_error (gai_retval),
671 _("Error resolving '%s': %s"),
672 hostname, gai_strerror (gai_retval));
676 g_return_val_if_fail (res != NULL, NULL);
679 for (ai = res; ai; ai = ai->ai_next)
681 sockaddr = g_socket_address_new_from_native (ai->ai_addr, ai->ai_addrlen);
682 if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
685 addr = g_object_ref (g_inet_socket_address_get_address ((GInetSocketAddress *)sockaddr));
686 addrs = g_list_prepend (addrs, addr);
687 g_object_unref (sockaddr);
690 return g_list_reverse (addrs);
693 /* Private method to set up a getnameinfo() request */
695 _g_resolver_address_to_sockaddr (GInetAddress *address,
696 struct sockaddr_storage *sa,
699 GSocketAddress *sockaddr;
701 sockaddr = g_inet_socket_address_new (address, 0);
702 g_socket_address_to_native (sockaddr, (struct sockaddr *)sa, sizeof (*sa), NULL);
703 *sa_len = g_socket_address_get_native_size (sockaddr);
704 g_object_unref (sockaddr);
707 /* Private method to process a getnameinfo() response. */
709 _g_resolver_name_from_nameinfo (GInetAddress *address,
718 phys = g_inet_address_to_string (address);
719 g_set_error (error, G_RESOLVER_ERROR,
720 g_resolver_error_from_addrinfo_error (gni_retval),
721 _("Error reverse-resolving '%s': %s"),
722 phys ? phys : "(unknown)", gai_strerror (gni_retval));
727 return g_strdup (name);
730 #if defined(G_OS_UNIX)
731 /* Private method to process a res_query response into GSrvTargets */
733 _g_resolver_targets_from_res_query (const gchar *rrname,
742 guint16 type, qclass, rdlength, priority, weight, port;
750 GResolverError errnum;
753 if (len == 0 || herr == HOST_NOT_FOUND || herr == NO_DATA)
755 errnum = G_RESOLVER_ERROR_NOT_FOUND;
756 format = _("No service record for '%s'");
758 else if (herr == TRY_AGAIN)
760 errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
761 format = _("Temporarily unable to resolve '%s'");
765 errnum = G_RESOLVER_ERROR_INTERNAL;
766 format = _("Error resolving '%s'");
769 g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
775 header = (HEADER *)answer;
776 p = answer + sizeof (HEADER);
780 count = ntohs (header->qdcount);
781 while (count-- && p < end)
783 p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
788 count = ntohs (header->ancount);
789 while (count-- && p < end)
791 p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
793 GETSHORT (qclass, p);
795 GETSHORT (rdlength, p);
797 if (type != T_SRV || qclass != C_IN)
803 GETSHORT (priority, p);
804 GETSHORT (weight, p);
806 p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
808 target = g_srv_target_new (namebuf, port, priority, weight);
809 targets = g_list_prepend (targets, target);
812 return g_srv_target_list_sort (targets);
814 #elif defined(G_OS_WIN32)
815 /* Private method to process a DnsQuery response into GSrvTargets */
817 _g_resolver_targets_from_DnsQuery (const gchar *rrname,
826 if (status != ERROR_SUCCESS)
828 GResolverError errnum;
831 if (status == DNS_ERROR_RCODE_NAME_ERROR)
833 errnum = G_RESOLVER_ERROR_NOT_FOUND;
834 format = _("No service record for '%s'");
836 else if (status == DNS_ERROR_RCODE_SERVER_FAILURE)
838 errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
839 format = _("Temporarily unable to resolve '%s'");
843 errnum = G_RESOLVER_ERROR_INTERNAL;
844 format = _("Error resolving '%s'");
847 g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
852 for (rec = results; rec; rec = rec->pNext)
854 if (rec->wType != DNS_TYPE_SRV)
857 target = g_srv_target_new (rec->Data.SRV.pNameTarget,
859 rec->Data.SRV.wPriority,
860 rec->Data.SRV.wWeight);
861 targets = g_list_prepend (targets, target);
864 return g_srv_target_list_sort (targets);
869 #define __G_RESOLVER_C__
870 #include "gioaliasdef.c"