gio: Add g_async_result_legacy_propagate_error()
[platform/upstream/glib.git] / gio / gresolver.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2
3 /* GIO - GLib Input, Output and Streaming Library
4  *
5  * Copyright (C) 2008 Red Hat, Inc.
6  *
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.
11  *
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.
16  *
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.
21  */
22
23 #include "config.h"
24 #include <glib.h>
25 #include "glibintl.h"
26
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"
34 #include "gthreadedresolver.h"
35
36 #ifdef G_OS_UNIX
37 #include <sys/stat.h>
38 #endif
39
40 #include <stdlib.h>
41
42
43 /**
44  * SECTION:gresolver
45  * @short_description: Asynchronous and cancellable DNS resolver
46  * @include: gio/gio.h
47  *
48  * #GResolver provides cancellable synchronous and asynchronous DNS
49  * resolution, for hostnames (g_resolver_lookup_by_address(),
50  * g_resolver_lookup_by_name() and their async variants) and SRV
51  * (service) records (g_resolver_lookup_service()).
52  *
53  * #GNetworkAddress and #GNetworkService provide wrappers around
54  * #GResolver functionality that also implement #GSocketConnectable,
55  * making it easy to connect to a remote host/service.
56  */
57
58 enum {
59   RELOAD,
60   LAST_SIGNAL
61 };
62
63 static guint signals[LAST_SIGNAL] = { 0 };
64
65 struct _GResolverPrivate {
66 #ifdef G_OS_UNIX
67   time_t resolv_conf_timestamp;
68 #else
69   int dummy;
70 #endif
71 };
72
73 /**
74  * GResolver:
75  *
76  * The object that handles DNS resolution. Use g_resolver_get_default()
77  * to get the default resolver.
78  */
79 G_DEFINE_TYPE (GResolver, g_resolver, G_TYPE_OBJECT)
80
81 static GList *
82 srv_records_to_targets (GList *records)
83 {
84   const gchar *hostname;
85   guint16 port, priority, weight;
86   GSrvTarget *target;
87   GList *l;
88
89   for (l = records; l != NULL; l = g_list_next (l))
90     {
91       g_variant_get (l->data, "(qqq&s)", &priority, &weight, &port, &hostname);
92       target = g_srv_target_new (hostname, port, priority, weight);
93       g_variant_unref (l->data);
94       l->data = target;
95     }
96
97   return g_srv_target_list_sort (records);
98 }
99
100 static GList *
101 g_resolver_real_lookup_service (GResolver            *resolver,
102                                 const gchar          *rrname,
103                                 GCancellable         *cancellable,
104                                 GError              **error)
105 {
106   GList *records;
107
108   records = G_RESOLVER_GET_CLASS (resolver)->lookup_records (resolver,
109                                                              rrname,
110                                                              G_RESOLVER_RECORD_SRV,
111                                                              cancellable,
112                                                              error);
113
114   return srv_records_to_targets (records);
115 }
116
117 static void
118 g_resolver_real_lookup_service_async (GResolver            *resolver,
119                                       const gchar          *rrname,
120                                       GCancellable         *cancellable,
121                                       GAsyncReadyCallback   callback,
122                                       gpointer              user_data)
123 {
124   G_RESOLVER_GET_CLASS (resolver)->lookup_records_async (resolver,
125                                                          rrname,
126                                                          G_RESOLVER_RECORD_SRV,
127                                                          cancellable,
128                                                          callback,
129                                                          user_data);
130 }
131
132 static GList *
133 g_resolver_real_lookup_service_finish (GResolver            *resolver,
134                                        GAsyncResult         *result,
135                                        GError              **error)
136 {
137   GList *records;
138
139   records = G_RESOLVER_GET_CLASS (resolver)->lookup_records_finish (resolver,
140                                                                     result,
141                                                                     error);
142
143   return srv_records_to_targets (records);
144 }
145
146 static void
147 g_resolver_class_init (GResolverClass *resolver_class)
148 {
149   /* Automatically pass these over to the lookup_records methods */
150   resolver_class->lookup_service = g_resolver_real_lookup_service;
151   resolver_class->lookup_service_async = g_resolver_real_lookup_service_async;
152   resolver_class->lookup_service_finish = g_resolver_real_lookup_service_finish;
153
154   g_type_class_add_private (resolver_class, sizeof (GResolverPrivate));
155
156   /* Make sure _g_networking_init() has been called */
157   g_type_ensure (G_TYPE_INET_ADDRESS);
158
159   /* Initialize _g_resolver_addrinfo_hints */
160 #ifdef AI_ADDRCONFIG
161   _g_resolver_addrinfo_hints.ai_flags |= AI_ADDRCONFIG;
162 #endif
163   /* These two don't actually matter, they just get copied into the
164    * returned addrinfo structures (and then we ignore them). But if
165    * we leave them unset, we'll get back duplicate answers.
166    */
167   _g_resolver_addrinfo_hints.ai_socktype = SOCK_STREAM;
168   _g_resolver_addrinfo_hints.ai_protocol = IPPROTO_TCP;
169
170   /**
171    * GResolver::reload:
172    * @resolver: a #GResolver
173    *
174    * Emitted when the resolver notices that the system resolver
175    * configuration has changed.
176    **/
177   signals[RELOAD] =
178     g_signal_new (I_("reload"),
179                   G_TYPE_RESOLVER,
180                   G_SIGNAL_RUN_LAST,
181                   G_STRUCT_OFFSET (GResolverClass, reload),
182                   NULL, NULL,
183                   g_cclosure_marshal_VOID__VOID,
184                   G_TYPE_NONE, 0);
185 }
186
187 static void
188 g_resolver_init (GResolver *resolver)
189 {
190 #ifdef G_OS_UNIX
191   struct stat st;
192 #endif
193
194   resolver->priv = G_TYPE_INSTANCE_GET_PRIVATE (resolver, G_TYPE_RESOLVER, GResolverPrivate);
195
196 #ifdef G_OS_UNIX
197   if (stat (_PATH_RESCONF, &st) == 0)
198     resolver->priv->resolv_conf_timestamp = st.st_mtime;
199 #endif
200 }
201
202 static GResolver *default_resolver;
203
204 /**
205  * g_resolver_get_default:
206  *
207  * Gets the default #GResolver. You should unref it when you are done
208  * with it. #GResolver may use its reference count as a hint about how
209  * many threads it should allocate for concurrent DNS resolutions.
210  *
211  * Return value: (transfer full): the default #GResolver.
212  *
213  * Since: 2.22
214  */
215 GResolver *
216 g_resolver_get_default (void)
217 {
218   if (!default_resolver)
219     default_resolver = g_object_new (G_TYPE_THREADED_RESOLVER, NULL);
220
221   return g_object_ref (default_resolver);
222 }
223
224 /**
225  * g_resolver_set_default:
226  * @resolver: the new default #GResolver
227  *
228  * Sets @resolver to be the application's default resolver (reffing
229  * @resolver, and unreffing the previous default resolver, if any).
230  * Future calls to g_resolver_get_default() will return this resolver.
231  *
232  * This can be used if an application wants to perform any sort of DNS
233  * caching or "pinning"; it can implement its own #GResolver that
234  * calls the original default resolver for DNS operations, and
235  * implements its own cache policies on top of that, and then set
236  * itself as the default resolver for all later code to use.
237  *
238  * Since: 2.22
239  */
240 void
241 g_resolver_set_default (GResolver *resolver)
242 {
243   if (default_resolver)
244     g_object_unref (default_resolver);
245   default_resolver = g_object_ref (resolver);
246 }
247
248
249 static void
250 g_resolver_maybe_reload (GResolver *resolver)
251 {
252 #ifdef G_OS_UNIX
253   struct stat st;
254
255   if (stat (_PATH_RESCONF, &st) == 0)
256     {
257       if (st.st_mtime != resolver->priv->resolv_conf_timestamp)
258         {
259           resolver->priv->resolv_conf_timestamp = st.st_mtime;
260           res_init ();
261           g_signal_emit (resolver, signals[RELOAD], 0);
262         }
263     }
264 #endif
265 }
266
267 /* filter out duplicates, cf. https://bugzilla.gnome.org/show_bug.cgi?id=631379 */
268 static void
269 remove_duplicates (GList *addrs)
270 {
271   GList *l;
272   GList *ll;
273   GList *lll;
274
275   /* TODO: if this is too slow (it's O(n^2) but n is typically really
276    * small), we can do something more clever but note that we must not
277    * change the order of elements...
278    */
279   for (l = addrs; l != NULL; l = l->next)
280     {
281       GInetAddress *address = G_INET_ADDRESS (l->data);
282       for (ll = l->next; ll != NULL; ll = lll)
283         {
284           GInetAddress *other_address = G_INET_ADDRESS (ll->data);
285           lll = ll->next;
286           if (g_inet_address_equal (address, other_address))
287             {
288               g_object_unref (other_address);
289               /* we never return the first element */
290               g_warn_if_fail (g_list_delete_link (addrs, ll) == addrs);
291             }
292         }
293     }
294 }
295
296
297 /**
298  * g_resolver_lookup_by_name:
299  * @resolver: a #GResolver
300  * @hostname: the hostname to look up
301  * @cancellable: (allow-none): a #GCancellable, or %NULL
302  * @error: return location for a #GError, or %NULL
303  *
304  * Synchronously resolves @hostname to determine its associated IP
305  * address(es). @hostname may be an ASCII-only or UTF-8 hostname, or
306  * the textual form of an IP address (in which case this just becomes
307  * a wrapper around g_inet_address_new_from_string()).
308  *
309  * On success, g_resolver_lookup_by_name() will return a #GList of
310  * #GInetAddress, sorted in order of preference and guaranteed to not
311  * contain duplicates. That is, if using the result to connect to
312  * @hostname, you should attempt to connect to the first address
313  * first, then the second if the first fails, etc. If you are using
314  * the result to listen on a socket, it is appropriate to add each
315  * result using e.g. g_socket_listener_add_address().
316  *
317  * If the DNS resolution fails, @error (if non-%NULL) will be set to a
318  * value from #GResolverError.
319  *
320  * If @cancellable is non-%NULL, it can be used to cancel the
321  * operation, in which case @error (if non-%NULL) will be set to
322  * %G_IO_ERROR_CANCELLED.
323  *
324  * If you are planning to connect to a socket on the resolved IP
325  * address, it may be easier to create a #GNetworkAddress and use its
326  * #GSocketConnectable interface.
327  *
328  * Return value: (element-type GInetAddress) (transfer full): a #GList
329  * of #GInetAddress, or %NULL on error. You
330  * must unref each of the addresses and free the list when you are
331  * done with it. (You can use g_resolver_free_addresses() to do this.)
332  *
333  * Since: 2.22
334  */
335 GList *
336 g_resolver_lookup_by_name (GResolver     *resolver,
337                            const gchar   *hostname,
338                            GCancellable  *cancellable,
339                            GError       **error)
340 {
341   GInetAddress *addr;
342   GList *addrs;
343   gchar *ascii_hostname = NULL;
344
345   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
346   g_return_val_if_fail (hostname != NULL, NULL);
347
348   /* Check if @hostname is just an IP address */
349   addr = g_inet_address_new_from_string (hostname);
350   if (addr)
351     return g_list_append (NULL, addr);
352
353   if (g_hostname_is_non_ascii (hostname))
354     hostname = ascii_hostname = g_hostname_to_ascii (hostname);
355
356   g_resolver_maybe_reload (resolver);
357   addrs = G_RESOLVER_GET_CLASS (resolver)->
358     lookup_by_name (resolver, hostname, cancellable, error);
359
360   remove_duplicates (addrs);
361
362   g_free (ascii_hostname);
363   return addrs;
364 }
365
366 /**
367  * g_resolver_lookup_by_name_async:
368  * @resolver: a #GResolver
369  * @hostname: the hostname to look up the address of
370  * @cancellable: (allow-none): a #GCancellable, or %NULL
371  * @callback: (scope async): callback to call after resolution completes
372  * @user_data: (closure): data for @callback
373  *
374  * Begins asynchronously resolving @hostname to determine its
375  * associated IP address(es), and eventually calls @callback, which
376  * must call g_resolver_lookup_by_name_finish() to get the result.
377  * See g_resolver_lookup_by_name() for more details.
378  *
379  * Since: 2.22
380  */
381 void
382 g_resolver_lookup_by_name_async (GResolver           *resolver,
383                                  const gchar         *hostname,
384                                  GCancellable        *cancellable,
385                                  GAsyncReadyCallback  callback,
386                                  gpointer             user_data)
387 {
388   GInetAddress *addr;
389   gchar *ascii_hostname = NULL;
390
391   g_return_if_fail (G_IS_RESOLVER (resolver));
392   g_return_if_fail (hostname != NULL);
393
394   /* Check if @hostname is just an IP address */
395   addr = g_inet_address_new_from_string (hostname);
396   if (addr)
397     {
398       GSimpleAsyncResult *simple;
399
400       simple = g_simple_async_result_new (G_OBJECT (resolver),
401                                           callback, user_data,
402                                           g_resolver_lookup_by_name_async);
403
404       g_simple_async_result_set_op_res_gpointer (simple, addr, g_object_unref);
405       g_simple_async_result_complete_in_idle (simple);
406       g_object_unref (simple);
407       return;
408     }
409
410   if (g_hostname_is_non_ascii (hostname))
411     hostname = ascii_hostname = g_hostname_to_ascii (hostname);
412
413   g_resolver_maybe_reload (resolver);
414   G_RESOLVER_GET_CLASS (resolver)->
415     lookup_by_name_async (resolver, hostname, cancellable, callback, user_data);
416
417   g_free (ascii_hostname);
418 }
419
420 /**
421  * g_resolver_lookup_by_name_finish:
422  * @resolver: a #GResolver
423  * @result: the result passed to your #GAsyncReadyCallback
424  * @error: return location for a #GError, or %NULL
425  *
426  * Retrieves the result of a call to
427  * g_resolver_lookup_by_name_async().
428  *
429  * If the DNS resolution failed, @error (if non-%NULL) will be set to
430  * a value from #GResolverError. If the operation was cancelled,
431  * @error will be set to %G_IO_ERROR_CANCELLED.
432  *
433  * Return value: (element-type GInetAddress) (transfer full): a #GList
434  * of #GInetAddress, or %NULL on error. See g_resolver_lookup_by_name()
435  * for more details.
436  *
437  * Since: 2.22
438  */
439 GList *
440 g_resolver_lookup_by_name_finish (GResolver     *resolver,
441                                   GAsyncResult  *result,
442                                   GError       **error)
443 {
444   GList *addrs;
445
446   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
447
448   if (g_async_result_legacy_propagate_error (result, error))
449     return NULL;
450
451   if (G_IS_SIMPLE_ASYNC_RESULT (result))
452     {
453       GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
454
455       /* Handle the stringified-IP-addr case */
456       if (g_simple_async_result_get_source_tag (simple) == g_resolver_lookup_by_name_async)
457         {
458           GInetAddress *addr;
459
460           addr = g_simple_async_result_get_op_res_gpointer (simple);
461           return g_list_append (NULL, g_object_ref (addr));
462         }
463     }
464
465   addrs = G_RESOLVER_GET_CLASS (resolver)->
466     lookup_by_name_finish (resolver, result, error);
467
468   remove_duplicates (addrs);
469
470   return addrs;
471 }
472
473 /**
474  * g_resolver_free_addresses: (skip)
475  * @addresses: a #GList of #GInetAddress
476  *
477  * Frees @addresses (which should be the return value from
478  * g_resolver_lookup_by_name() or g_resolver_lookup_by_name_finish()).
479  * (This is a convenience method; you can also simply free the results
480  * by hand.)
481  *
482  * Since: 2.22
483  */
484 void
485 g_resolver_free_addresses (GList *addresses)
486 {
487   GList *a;
488
489   for (a = addresses; a; a = a->next)
490     g_object_unref (a->data);
491   g_list_free (addresses);
492 }
493
494 /**
495  * g_resolver_lookup_by_address:
496  * @resolver: a #GResolver
497  * @address: the address to reverse-resolve
498  * @cancellable: (allow-none): a #GCancellable, or %NULL
499  * @error: return location for a #GError, or %NULL
500  *
501  * Synchronously reverse-resolves @address to determine its
502  * associated hostname.
503  *
504  * If the DNS resolution fails, @error (if non-%NULL) will be set to
505  * a value from #GResolverError.
506  *
507  * If @cancellable is non-%NULL, it can be used to cancel the
508  * operation, in which case @error (if non-%NULL) will be set to
509  * %G_IO_ERROR_CANCELLED.
510  *
511  * Return value: a hostname (either ASCII-only, or in ASCII-encoded
512  *     form), or %NULL on error.
513  *
514  * Since: 2.22
515  */
516 gchar *
517 g_resolver_lookup_by_address (GResolver     *resolver,
518                               GInetAddress  *address,
519                               GCancellable  *cancellable,
520                               GError       **error)
521 {
522   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
523   g_return_val_if_fail (G_IS_INET_ADDRESS (address), NULL);
524
525   g_resolver_maybe_reload (resolver);
526   return G_RESOLVER_GET_CLASS (resolver)->
527     lookup_by_address (resolver, address, cancellable, error);
528 }
529
530 /**
531  * g_resolver_lookup_by_address_async:
532  * @resolver: a #GResolver
533  * @address: the address to reverse-resolve
534  * @cancellable: (allow-none): a #GCancellable, or %NULL
535  * @callback: (scope async): callback to call after resolution completes
536  * @user_data: (closure): data for @callback
537  *
538  * Begins asynchronously reverse-resolving @address to determine its
539  * associated hostname, and eventually calls @callback, which must
540  * call g_resolver_lookup_by_address_finish() to get the final result.
541  *
542  * Since: 2.22
543  */
544 void
545 g_resolver_lookup_by_address_async (GResolver           *resolver,
546                                     GInetAddress        *address,
547                                     GCancellable        *cancellable,
548                                     GAsyncReadyCallback  callback,
549                                     gpointer             user_data)
550 {
551   g_return_if_fail (G_IS_RESOLVER (resolver));
552   g_return_if_fail (G_IS_INET_ADDRESS (address));
553
554   g_resolver_maybe_reload (resolver);
555   G_RESOLVER_GET_CLASS (resolver)->
556     lookup_by_address_async (resolver, address, cancellable, callback, user_data);
557 }
558
559 /**
560  * g_resolver_lookup_by_address_finish:
561  * @resolver: a #GResolver
562  * @result: the result passed to your #GAsyncReadyCallback
563  * @error: return location for a #GError, or %NULL
564  *
565  * Retrieves the result of a previous call to
566  * g_resolver_lookup_by_address_async().
567  *
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.
571  *
572  * Return value: a hostname (either ASCII-only, or in ASCII-encoded
573  * form), or %NULL on error.
574  *
575  * Since: 2.22
576  */
577 gchar *
578 g_resolver_lookup_by_address_finish (GResolver     *resolver,
579                                      GAsyncResult  *result,
580                                      GError       **error)
581 {
582   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
583
584   if (g_async_result_legacy_propagate_error (result, error))
585     return NULL;
586
587   return G_RESOLVER_GET_CLASS (resolver)->
588     lookup_by_address_finish (resolver, result, error);
589 }
590
591 static gchar *
592 g_resolver_get_service_rrname (const char *service,
593                                const char *protocol,
594                                const char *domain)
595 {
596   gchar *rrname, *ascii_domain = NULL;
597
598   if (g_hostname_is_non_ascii (domain))
599     domain = ascii_domain = g_hostname_to_ascii (domain);
600
601   rrname = g_strdup_printf ("_%s._%s.%s", service, protocol, domain);
602
603   g_free (ascii_domain);
604   return rrname;
605 }
606
607 /**
608  * g_resolver_lookup_service:
609  * @resolver: a #GResolver
610  * @service: the service type to look up (eg, "ldap")
611  * @protocol: the networking protocol to use for @service (eg, "tcp")
612  * @domain: the DNS domain to look up the service in
613  * @cancellable: (allow-none): a #GCancellable, or %NULL
614  * @error: return location for a #GError, or %NULL
615  *
616  * Synchronously performs a DNS SRV lookup for the given @service and
617  * @protocol in the given @domain and returns an array of #GSrvTarget.
618  * @domain may be an ASCII-only or UTF-8 hostname. Note also that the
619  * @service and @protocol arguments <emphasis>do not</emphasis>
620  * include the leading underscore that appears in the actual DNS
621  * entry.
622  *
623  * On success, g_resolver_lookup_service() will return a #GList of
624  * #GSrvTarget, sorted in order of preference. (That is, you should
625  * attempt to connect to the first target first, then the second if
626  * the first fails, etc.)
627  *
628  * If the DNS resolution fails, @error (if non-%NULL) will be set to
629  * a value from #GResolverError.
630  *
631  * If @cancellable is non-%NULL, it can be used to cancel the
632  * operation, in which case @error (if non-%NULL) will be set to
633  * %G_IO_ERROR_CANCELLED.
634  *
635  * If you are planning to connect to the service, it is usually easier
636  * to create a #GNetworkService and use its #GSocketConnectable
637  * interface.
638  *
639  * Return value: (element-type GSrvTarget) (transfer full): a #GList of #GSrvTarget,
640  * or %NULL on error. You must free each of the targets and the list when you are
641  * done with it. (You can use g_resolver_free_targets() to do this.)
642  *
643  * Since: 2.22
644  */
645 GList *
646 g_resolver_lookup_service (GResolver     *resolver,
647                            const gchar   *service,
648                            const gchar   *protocol,
649                            const gchar   *domain,
650                            GCancellable  *cancellable,
651                            GError       **error)
652 {
653   GList *targets;
654   gchar *rrname;
655
656   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
657   g_return_val_if_fail (service != NULL, NULL);
658   g_return_val_if_fail (protocol != NULL, NULL);
659   g_return_val_if_fail (domain != NULL, NULL);
660
661   rrname = g_resolver_get_service_rrname (service, protocol, domain);
662
663   g_resolver_maybe_reload (resolver);
664   targets = G_RESOLVER_GET_CLASS (resolver)->
665     lookup_service (resolver, rrname, cancellable, error);
666
667   g_free (rrname);
668   return targets;
669 }
670
671 /**
672  * g_resolver_lookup_service_async:
673  * @resolver: a #GResolver
674  * @service: the service type to look up (eg, "ldap")
675  * @protocol: the networking protocol to use for @service (eg, "tcp")
676  * @domain: the DNS domain to look up the service in
677  * @cancellable: (allow-none): a #GCancellable, or %NULL
678  * @callback: (scope async): callback to call after resolution completes
679  * @user_data: (closure): data for @callback
680  *
681  * Begins asynchronously performing a DNS SRV lookup for the given
682  * @service and @protocol in the given @domain, and eventually calls
683  * @callback, which must call g_resolver_lookup_service_finish() to
684  * get the final result. See g_resolver_lookup_service() for more
685  * details.
686  *
687  * Since: 2.22
688  */
689 void
690 g_resolver_lookup_service_async (GResolver           *resolver,
691                                  const gchar         *service,
692                                  const gchar         *protocol,
693                                  const gchar         *domain,
694                                  GCancellable        *cancellable,
695                                  GAsyncReadyCallback  callback,
696                                  gpointer             user_data)
697 {
698   gchar *rrname;
699
700   g_return_if_fail (G_IS_RESOLVER (resolver));
701   g_return_if_fail (service != NULL);
702   g_return_if_fail (protocol != NULL);
703   g_return_if_fail (domain != NULL);
704
705   rrname = g_resolver_get_service_rrname (service, protocol, domain);
706
707   g_resolver_maybe_reload (resolver);
708   G_RESOLVER_GET_CLASS (resolver)->
709     lookup_service_async (resolver, rrname, cancellable, callback, user_data);
710
711   g_free (rrname);
712 }
713
714 /**
715  * g_resolver_lookup_service_finish:
716  * @resolver: a #GResolver
717  * @result: the result passed to your #GAsyncReadyCallback
718  * @error: return location for a #GError, or %NULL
719  *
720  * Retrieves the result of a previous call to
721  * g_resolver_lookup_service_async().
722  *
723  * If the DNS resolution failed, @error (if non-%NULL) will be set to
724  * a value from #GResolverError. If the operation was cancelled,
725  * @error will be set to %G_IO_ERROR_CANCELLED.
726  *
727  * Return value: (element-type GSrvTarget) (transfer full): a #GList of #GSrvTarget,
728  * or %NULL on error. See g_resolver_lookup_service() for more details.
729  *
730  * Since: 2.22
731  */
732 GList *
733 g_resolver_lookup_service_finish (GResolver     *resolver,
734                                   GAsyncResult  *result,
735                                   GError       **error)
736 {
737   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
738
739   if (g_async_result_legacy_propagate_error (result, error))
740     return NULL;
741
742   return G_RESOLVER_GET_CLASS (resolver)->
743     lookup_service_finish (resolver, result, error);
744 }
745
746 /**
747  * g_resolver_free_targets: (skip)
748  * @targets: a #GList of #GSrvTarget
749  *
750  * Frees @targets (which should be the return value from
751  * g_resolver_lookup_service() or g_resolver_lookup_service_finish()).
752  * (This is a convenience method; you can also simply free the
753  * results by hand.)
754  *
755  * Since: 2.22
756  */
757 void
758 g_resolver_free_targets (GList *targets)
759 {
760   GList *t;
761
762   for (t = targets; t; t = t->next)
763     g_srv_target_free (t->data);
764   g_list_free (targets);
765 }
766
767 /**
768  * g_resolver_lookup_records:
769  * @resolver: a #GResolver
770  * @rrname: the DNS name to lookup the record for
771  * @record_type: the type of DNS record to lookup
772  * @cancellable: (allow-none): a #GCancellable, or %NULL
773  * @error: return location for a #GError, or %NULL
774  *
775  * Synchronously performs a DNS record lookup for the given @rrname and returns
776  * a list of records as #GVariant tuples. See #GResolverRecordType for
777  * information on what the records contain for each @record_type.
778  *
779  * If the DNS resolution fails, @error (if non-%NULL) will be set to
780  * a value from #GResolverError.
781  *
782  * If @cancellable is non-%NULL, it can be used to cancel the
783  * operation, in which case @error (if non-%NULL) will be set to
784  * %G_IO_ERROR_CANCELLED.
785  *
786  * Return value: (element-type GVariant) (transfer full): a #GList of #GVariant,
787  * or %NULL on error. You must free each of the records and the list when you are
788  * done with it. (You can use g_list_free_full() with g_variant_unref() to do this.)
789  *
790  * Since: 2.34
791  */
792 GList *
793 g_resolver_lookup_records (GResolver            *resolver,
794                            const gchar          *rrname,
795                            GResolverRecordType   record_type,
796                            GCancellable         *cancellable,
797                            GError              **error)
798 {
799   GList *records;
800
801   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
802   g_return_val_if_fail (rrname != NULL, NULL);
803
804   g_resolver_maybe_reload (resolver);
805   records = G_RESOLVER_GET_CLASS (resolver)->
806     lookup_records (resolver, rrname, record_type, cancellable, error);
807
808   return records;
809 }
810
811 /**
812  * g_resolver_lookup_records_async:
813  * @resolver: a #GResolver
814  * @rrname: the DNS name to lookup the record for
815  * @record_type: the type of DNS record to lookup
816  * @cancellable: (allow-none): a #GCancellable, or %NULL
817  * @callback: (scope async): callback to call after resolution completes
818  * @user_data: (closure): data for @callback
819  *
820  * Begins asynchronously performing a DNS lookup for the given
821  * @rrname, and eventually calls @callback, which must call
822  * g_resolver_lookup_records_finish() to get the final result. See
823  * g_resolver_lookup_records() for more details.
824  *
825  * Since: 2.34
826  */
827 void
828 g_resolver_lookup_records_async (GResolver           *resolver,
829                                  const gchar         *rrname,
830                                  GResolverRecordType  record_type,
831                                  GCancellable        *cancellable,
832                                  GAsyncReadyCallback  callback,
833                                  gpointer             user_data)
834 {
835   g_return_if_fail (G_IS_RESOLVER (resolver));
836   g_return_if_fail (rrname != NULL);
837
838   g_resolver_maybe_reload (resolver);
839   G_RESOLVER_GET_CLASS (resolver)->
840     lookup_records_async (resolver, rrname, record_type, cancellable, callback, user_data);
841 }
842
843 /**
844  * g_resolver_lookup_records_finish:
845  * @resolver: a #GResolver
846  * @result: the result passed to your #GAsyncReadyCallback
847  * @error: return location for a #GError, or %NULL
848  *
849  * Retrieves the result of a previous call to
850  * g_resolver_lookup_records_async(). Returns a list of records as #GVariant
851  * tuples. See #GResolverRecordType for information on what the records contain.
852  *
853  * If the DNS resolution failed, @error (if non-%NULL) will be set to
854  * a value from #GResolverError. If the operation was cancelled,
855  * @error will be set to %G_IO_ERROR_CANCELLED.
856  *
857  * Return value: (element-type GVariant) (transfer full): a #GList of #GVariant,
858  * or %NULL on error. You must free each of the records and the list when you are
859  * done with it. (You can use g_list_free_full() with g_variant_unref() to do this.)
860  *
861  * Since: 2.34
862  */
863 GList *
864 g_resolver_lookup_records_finish (GResolver     *resolver,
865                                   GAsyncResult  *result,
866                                   GError       **error)
867 {
868   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
869   return G_RESOLVER_GET_CLASS (resolver)->
870     lookup_records_finish (resolver, result, error);
871 }
872
873 /**
874  * g_resolver_error_quark:
875  *
876  * Gets the #GResolver Error Quark.
877  *
878  * Return value: a #GQuark.
879  *
880  * Since: 2.22
881  */
882 GQuark
883 g_resolver_error_quark (void)
884 {
885   return g_quark_from_static_string ("g-resolver-error-quark");
886 }
887
888
889 static GResolverError
890 g_resolver_error_from_addrinfo_error (gint err)
891 {
892   switch (err)
893     {
894     case EAI_FAIL:
895 #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
896     case EAI_NODATA:
897 #endif
898     case EAI_NONAME:
899       return G_RESOLVER_ERROR_NOT_FOUND;
900
901     case EAI_AGAIN:
902       return G_RESOLVER_ERROR_TEMPORARY_FAILURE;
903
904     default:
905       return G_RESOLVER_ERROR_INTERNAL;
906     }
907 }
908
909 struct addrinfo _g_resolver_addrinfo_hints;
910
911 /* Private method to process a getaddrinfo() response. */
912 GList *
913 _g_resolver_addresses_from_addrinfo (const char       *hostname,
914                                      struct addrinfo  *res,
915                                      gint              gai_retval,
916                                      GError          **error)
917 {
918   struct addrinfo *ai;
919   GSocketAddress *sockaddr;
920   GInetAddress *addr;
921   GList *addrs;
922
923   if (gai_retval != 0)
924     {
925       g_set_error (error, G_RESOLVER_ERROR,
926                    g_resolver_error_from_addrinfo_error (gai_retval),
927                    _("Error resolving '%s': %s"),
928                    hostname, gai_strerror (gai_retval));
929       return NULL;
930     }
931
932   g_return_val_if_fail (res != NULL, NULL);
933
934   addrs = NULL;
935   for (ai = res; ai; ai = ai->ai_next)
936     {
937       sockaddr = g_socket_address_new_from_native (ai->ai_addr, ai->ai_addrlen);
938       if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
939         continue;
940
941       addr = g_object_ref (g_inet_socket_address_get_address ((GInetSocketAddress *)sockaddr));
942       addrs = g_list_prepend (addrs, addr);
943       g_object_unref (sockaddr);
944     }
945
946   return g_list_reverse (addrs);
947 }
948
949 /* Private method to set up a getnameinfo() request */
950 void
951 _g_resolver_address_to_sockaddr (GInetAddress            *address,
952                                  struct sockaddr_storage *sa,
953                                  gsize                   *len)
954 {
955   GSocketAddress *sockaddr;
956
957   sockaddr = g_inet_socket_address_new (address, 0);
958   g_socket_address_to_native (sockaddr, (struct sockaddr *)sa, sizeof (*sa), NULL);
959   *len = g_socket_address_get_native_size (sockaddr);
960   g_object_unref (sockaddr);
961 }
962
963 /* Private method to process a getnameinfo() response. */
964 char *
965 _g_resolver_name_from_nameinfo (GInetAddress  *address,
966                                 const gchar   *name,
967                                 gint           gni_retval,
968                                 GError       **error)
969 {
970   if (gni_retval != 0)
971     {
972       gchar *phys;
973
974       phys = g_inet_address_to_string (address);
975       g_set_error (error, G_RESOLVER_ERROR,
976                    g_resolver_error_from_addrinfo_error (gni_retval),
977                    _("Error reverse-resolving '%s': %s"),
978                    phys ? phys : "(unknown)", gai_strerror (gni_retval));
979       g_free (phys);
980       return NULL;
981     }
982
983   return g_strdup (name);
984 }
985
986 #if defined(G_OS_UNIX)
987
988 static gboolean
989 parse_short (guchar  **p,
990              guchar   *end,
991              guint16  *value)
992 {
993   if (*p + 2 > end)
994     return FALSE;
995   GETSHORT (*value, *p);
996   return TRUE;
997 }
998
999 static gboolean
1000 parse_long (guchar  **p,
1001             guchar   *end,
1002             guint32  *value)
1003 {
1004   if (*p + 4 > end)
1005     return FALSE;
1006   GETLONG (*value, *p);
1007   return TRUE;
1008 }
1009
1010 static GVariant *
1011 parse_res_srv (guchar  *answer,
1012                guchar  *end,
1013                guchar  *p)
1014 {
1015   gchar namebuf[1024];
1016   guint16 priority, weight, port;
1017   gint n;
1018
1019   if (!parse_short (&p, end, &priority) ||
1020       !parse_short (&p, end, &weight) ||
1021       !parse_short (&p, end, &port))
1022     return NULL;
1023
1024   n = dn_expand (answer, end, p, namebuf, sizeof (namebuf));
1025   if (n < 0)
1026     return NULL;
1027   *p += n;
1028
1029   return g_variant_new ("(qqqs)",
1030                         priority,
1031                         weight,
1032                         port,
1033                         namebuf);
1034 }
1035
1036 static GVariant *
1037 parse_res_soa (guchar  *answer,
1038                guchar  *end,
1039                guchar  *p)
1040 {
1041   gchar mnamebuf[1024];
1042   gchar rnamebuf[1024];
1043   guint32 serial, refresh, retry, expire, ttl;
1044   gint n;
1045
1046   n = dn_expand (answer, end, p, mnamebuf, sizeof (mnamebuf));
1047   if (n < 0)
1048     return NULL;
1049   p += n;
1050
1051   n = dn_expand (answer, end, p, rnamebuf, sizeof (rnamebuf));
1052   if (n < 0)
1053     return NULL;
1054   p += n;
1055
1056   if (!parse_long (&p, end, &serial) ||
1057       !parse_long (&p, end, &refresh) ||
1058       !parse_long (&p, end, &retry) ||
1059       !parse_long (&p, end, &expire) ||
1060       !parse_long (&p, end, &ttl))
1061     return NULL;
1062
1063   return g_variant_new ("(ssuuuuu)",
1064                         mnamebuf,
1065                         rnamebuf,
1066                         serial,
1067                         refresh,
1068                         retry,
1069                         expire,
1070                         ttl);
1071 }
1072
1073 static GVariant *
1074 parse_res_ns (guchar  *answer,
1075               guchar  *end,
1076               guchar  *p)
1077 {
1078   gchar namebuf[1024];
1079   gint n;
1080
1081   n = dn_expand (answer, end, p, namebuf, sizeof (namebuf));
1082   if (n < 0)
1083     return NULL;
1084
1085   return g_variant_new ("(s)", namebuf);
1086 }
1087
1088 static GVariant *
1089 parse_res_mx (guchar  *answer,
1090               guchar  *end,
1091               guchar  *p)
1092 {
1093   gchar namebuf[1024];
1094   guint16 preference;
1095   gint n;
1096
1097   if (!parse_short (&p, end, &preference))
1098     return NULL;
1099
1100   n = dn_expand (answer, end, p, namebuf, sizeof (namebuf));
1101   if (n < 0)
1102     return NULL;
1103   p += n;
1104
1105   return g_variant_new ("(qs)",
1106                         preference,
1107                         namebuf);
1108 }
1109
1110 static GVariant *
1111 parse_res_txt (guchar  *answer,
1112                guchar  *end,
1113                guchar  *p)
1114 {
1115   GVariant *record;
1116   GPtrArray *array;
1117   gsize len;
1118
1119   array = g_ptr_array_new_with_free_func (g_free);
1120   while (p < end)
1121     {
1122       len = *(p++);
1123       if (len > p - end)
1124         break;
1125       g_ptr_array_add (array, g_strndup ((gchar *)p, len));
1126       p += len;
1127     }
1128
1129   record = g_variant_new ("(@as)",
1130                           g_variant_new_strv ((const gchar **)array->pdata, array->len));
1131   g_ptr_array_free (array, TRUE);
1132   return record;
1133 }
1134
1135 gint
1136 _g_resolver_record_type_to_rrtype (GResolverRecordType type)
1137 {
1138   switch (type)
1139   {
1140     case G_RESOLVER_RECORD_SRV:
1141       return T_SRV;
1142     case G_RESOLVER_RECORD_TXT:
1143       return T_TXT;
1144     case G_RESOLVER_RECORD_SOA:
1145       return T_SOA;
1146     case G_RESOLVER_RECORD_NS:
1147       return T_NS;
1148     case G_RESOLVER_RECORD_MX:
1149       return T_MX;
1150   }
1151   g_return_val_if_reached (-1);
1152 }
1153
1154 /* Private method to process a res_query response into GSrvTargets */
1155 GList *
1156 _g_resolver_records_from_res_query (const gchar      *rrname,
1157                                     gint              rrtype,
1158                                     guchar           *answer,
1159                                     gint              len,
1160                                     gint              herr,
1161                                     GError          **error)
1162 {
1163   gint count;
1164   guchar *end, *p;
1165   guint16 type, qclass, rdlength;
1166   guint32 ttl;
1167   HEADER *header;
1168   GList *records;
1169   GVariant *record;
1170   gint n, i;
1171
1172   if (len <= 0)
1173     {
1174       GResolverError errnum;
1175       const gchar *format;
1176
1177       if (len == 0 || herr == HOST_NOT_FOUND || herr == NO_DATA)
1178         {
1179           errnum = G_RESOLVER_ERROR_NOT_FOUND;
1180           format = _("No DNS record of the requested type for '%s'");
1181         }
1182       else if (herr == TRY_AGAIN)
1183         {
1184           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
1185           format = _("Temporarily unable to resolve '%s'");
1186         }
1187       else
1188         {
1189           errnum = G_RESOLVER_ERROR_INTERNAL;
1190           format = _("Error resolving '%s'");
1191         }
1192
1193       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
1194       return NULL;
1195     }
1196
1197   records = NULL;
1198
1199   header = (HEADER *)answer;
1200   p = answer + sizeof (HEADER);
1201   end = answer + len;
1202
1203   /* Skip query */
1204   count = ntohs (header->qdcount);
1205   for (i = 0; i < count && p < end; i++)
1206     {
1207       n = dn_skipname (p, end);
1208       if (n < 0)
1209         break;
1210       p += n;
1211       p += 4;
1212     }
1213
1214   /* Incomplete response */
1215   if (i < count)
1216     {
1217       g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_TEMPORARY_FAILURE,
1218                    _("Incomplete data received for '%s'"), rrname);
1219       return NULL;
1220     }
1221
1222   /* Read answers */
1223   count = ntohs (header->ancount);
1224   for (i = 0; i < count && p < end; i++)
1225     {
1226       n = dn_skipname (p, end);
1227       if (n < 0)
1228         break;
1229       p += n;
1230
1231       if (!parse_short (&p, end, &type) ||
1232           !parse_short (&p, end, &qclass) ||
1233           !parse_long (&p, end, &ttl) ||
1234           !parse_short (&p, end, &rdlength))
1235         break;
1236
1237       ttl = ttl; /* To avoid -Wunused-but-set-variable */
1238
1239       if (p + rdlength > end)
1240         break;
1241
1242       if (type == rrtype && qclass == C_IN)
1243         {
1244           switch (rrtype)
1245             {
1246             case T_SRV:
1247               record = parse_res_srv (answer, end, p);
1248               break;
1249             case T_MX:
1250               record = parse_res_mx (answer, end, p);
1251               break;
1252             case T_SOA:
1253               record = parse_res_soa (answer, end, p);
1254               break;
1255             case T_NS:
1256               record = parse_res_ns (answer, end, p);
1257               break;
1258             case T_TXT:
1259               record = parse_res_txt (answer, p + rdlength, p);
1260               break;
1261             default:
1262               g_warn_if_reached ();
1263               record = NULL;
1264               break;
1265             }
1266
1267           if (record != NULL)
1268             records = g_list_prepend (records, record);
1269         }
1270
1271       p += rdlength;
1272     }
1273
1274   /* Somehow got a truncated response */
1275   if (i < count)
1276     {
1277       g_list_free_full (records, (GDestroyNotify)g_variant_unref);
1278       g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_TEMPORARY_FAILURE,
1279                    _("Incomplete data received for '%s'"), rrname);
1280       return NULL;
1281     }
1282
1283   return records;
1284 }
1285
1286 #elif defined(G_OS_WIN32)
1287 static GVariant *
1288 parse_dns_srv (DNS_RECORD *rec)
1289 {
1290   return g_variant_new ("(qqqs)",
1291                         (guint16)rec->Data.SRV.wPriority,
1292                         (guint16)rec->Data.SRV.wWeight,
1293                         (guint16)rec->Data.SRV.wPort,
1294                         rec->Data.SRV.pNameTarget);
1295 }
1296
1297 static GVariant *
1298 parse_dns_soa (DNS_RECORD *rec)
1299 {
1300   return g_variant_new ("(ssuuuuu)",
1301                         rec->Data.SOA.pNamePrimaryServer,
1302                         rec->Data.SOA.pNameAdministrator,
1303                         (guint32)rec->Data.SOA.dwSerialNo,
1304                         (guint32)rec->Data.SOA.dwRefresh,
1305                         (guint32)rec->Data.SOA.dwRetry,
1306                         (guint32)rec->Data.SOA.dwExpire,
1307                         (guint32)rec->Data.SOA.dwDefaultTtl);
1308 }
1309
1310 static GVariant *
1311 parse_dns_ns (DNS_RECORD *rec)
1312 {
1313   return g_variant_new ("(s)", rec->Data.NS.pNameHost);
1314 }
1315
1316 static GVariant *
1317 parse_dns_mx (DNS_RECORD *rec)
1318 {
1319   return g_variant_new ("(qs)",
1320                         (guint16)rec->Data.MX.wPreference,
1321                         rec->Data.MX.pNameExchange);
1322 }
1323
1324 static GVariant *
1325 parse_dns_txt (DNS_RECORD *rec)
1326 {
1327   GVariant *record;
1328   GPtrArray *array;
1329   DWORD i;
1330
1331   array = g_ptr_array_new ();
1332   for (i = 0; i < rec->Data.TXT.dwStringCount; i++)
1333     g_ptr_array_add (array, rec->Data.TXT.pStringArray[i]);
1334   record = g_variant_new ("(@as)",
1335                           g_variant_new_strv ((const gchar **)array->pdata, array->len));
1336   g_ptr_array_free (array, TRUE);
1337   return record;
1338 }
1339
1340 WORD
1341 _g_resolver_record_type_to_dnstype (GResolverRecordType type)
1342 {
1343   switch (type)
1344   {
1345     case G_RESOLVER_RECORD_SRV:
1346       return DNS_TYPE_SRV;
1347     case G_RESOLVER_RECORD_TXT:
1348       return DNS_TYPE_TEXT;
1349     case G_RESOLVER_RECORD_SOA:
1350       return DNS_TYPE_SOA;
1351     case G_RESOLVER_RECORD_NS:
1352       return DNS_TYPE_NS;
1353     case G_RESOLVER_RECORD_MX:
1354       return DNS_TYPE_MX;
1355   }
1356   g_return_val_if_reached (-1);
1357 }
1358
1359 /* Private method to process a DnsQuery response into GVariants */
1360 GList *
1361 _g_resolver_records_from_DnsQuery (const gchar  *rrname,
1362                                    WORD          dnstype,
1363                                    DNS_STATUS    status,
1364                                    DNS_RECORD   *results,
1365                                    GError      **error)
1366 {
1367   DNS_RECORD *rec;
1368   gpointer record;
1369   GList *records;
1370
1371   if (status != ERROR_SUCCESS)
1372     {
1373       GResolverError errnum;
1374       const gchar *format;
1375
1376       if (status == DNS_ERROR_RCODE_NAME_ERROR)
1377         {
1378           errnum = G_RESOLVER_ERROR_NOT_FOUND;
1379           format = _("No DNS record of the requested type for '%s'");
1380         }
1381       else if (status == DNS_ERROR_RCODE_SERVER_FAILURE)
1382         {
1383           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
1384           format = _("Temporarily unable to resolve '%s'");
1385         }
1386       else
1387         {
1388           errnum = G_RESOLVER_ERROR_INTERNAL;
1389           format = _("Error resolving '%s'");
1390         }
1391
1392       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
1393       return NULL;
1394     }
1395
1396   records = NULL;
1397   for (rec = results; rec; rec = rec->pNext)
1398     {
1399       if (rec->wType != dnstype)
1400         continue;
1401       switch (dnstype)
1402         {
1403         case DNS_TYPE_SRV:
1404           record = parse_dns_srv (rec);
1405           break;
1406         case DNS_TYPE_SOA:
1407           record = parse_dns_soa (rec);
1408           break;
1409         case DNS_TYPE_NS:
1410           record = parse_dns_ns (rec);
1411           break;
1412         case DNS_TYPE_MX:
1413           record = parse_dns_mx (rec);
1414           break;
1415         case DNS_TYPE_TEXT:
1416           record = parse_dns_txt (rec);
1417           break;
1418         default:
1419           g_warn_if_reached ();
1420           record = NULL;
1421           break;
1422         }
1423       if (record != NULL)
1424         records = g_list_prepend (records, g_variant_ref_sink (record));
1425     }
1426
1427   return records;
1428 }
1429
1430 #endif