gio/tests/file: skip the file monitor tests if using GPollFileMonitor
[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   else if (g_async_result_is_tagged (result, g_resolver_lookup_by_name_async))
451     {
452       GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
453       GInetAddress *addr;
454
455       /* Handle the stringified-IP-addr case */
456       addr = g_simple_async_result_get_op_res_gpointer (simple);
457       return g_list_append (NULL, g_object_ref (addr));
458     }
459
460   addrs = G_RESOLVER_GET_CLASS (resolver)->
461     lookup_by_name_finish (resolver, result, error);
462
463   remove_duplicates (addrs);
464
465   return addrs;
466 }
467
468 /**
469  * g_resolver_free_addresses: (skip)
470  * @addresses: a #GList of #GInetAddress
471  *
472  * Frees @addresses (which should be the return value from
473  * g_resolver_lookup_by_name() or g_resolver_lookup_by_name_finish()).
474  * (This is a convenience method; you can also simply free the results
475  * by hand.)
476  *
477  * Since: 2.22
478  */
479 void
480 g_resolver_free_addresses (GList *addresses)
481 {
482   GList *a;
483
484   for (a = addresses; a; a = a->next)
485     g_object_unref (a->data);
486   g_list_free (addresses);
487 }
488
489 /**
490  * g_resolver_lookup_by_address:
491  * @resolver: a #GResolver
492  * @address: the address to reverse-resolve
493  * @cancellable: (allow-none): a #GCancellable, or %NULL
494  * @error: return location for a #GError, or %NULL
495  *
496  * Synchronously reverse-resolves @address to determine its
497  * associated hostname.
498  *
499  * If the DNS resolution fails, @error (if non-%NULL) will be set to
500  * a value from #GResolverError.
501  *
502  * If @cancellable is non-%NULL, it can be used to cancel the
503  * operation, in which case @error (if non-%NULL) will be set to
504  * %G_IO_ERROR_CANCELLED.
505  *
506  * Return value: a hostname (either ASCII-only, or in ASCII-encoded
507  *     form), or %NULL on error.
508  *
509  * Since: 2.22
510  */
511 gchar *
512 g_resolver_lookup_by_address (GResolver     *resolver,
513                               GInetAddress  *address,
514                               GCancellable  *cancellable,
515                               GError       **error)
516 {
517   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
518   g_return_val_if_fail (G_IS_INET_ADDRESS (address), NULL);
519
520   g_resolver_maybe_reload (resolver);
521   return G_RESOLVER_GET_CLASS (resolver)->
522     lookup_by_address (resolver, address, cancellable, error);
523 }
524
525 /**
526  * g_resolver_lookup_by_address_async:
527  * @resolver: a #GResolver
528  * @address: the address to reverse-resolve
529  * @cancellable: (allow-none): a #GCancellable, or %NULL
530  * @callback: (scope async): callback to call after resolution completes
531  * @user_data: (closure): data for @callback
532  *
533  * Begins asynchronously reverse-resolving @address to determine its
534  * associated hostname, and eventually calls @callback, which must
535  * call g_resolver_lookup_by_address_finish() to get the final result.
536  *
537  * Since: 2.22
538  */
539 void
540 g_resolver_lookup_by_address_async (GResolver           *resolver,
541                                     GInetAddress        *address,
542                                     GCancellable        *cancellable,
543                                     GAsyncReadyCallback  callback,
544                                     gpointer             user_data)
545 {
546   g_return_if_fail (G_IS_RESOLVER (resolver));
547   g_return_if_fail (G_IS_INET_ADDRESS (address));
548
549   g_resolver_maybe_reload (resolver);
550   G_RESOLVER_GET_CLASS (resolver)->
551     lookup_by_address_async (resolver, address, cancellable, callback, user_data);
552 }
553
554 /**
555  * g_resolver_lookup_by_address_finish:
556  * @resolver: a #GResolver
557  * @result: the result passed to your #GAsyncReadyCallback
558  * @error: return location for a #GError, or %NULL
559  *
560  * Retrieves the result of a previous call to
561  * g_resolver_lookup_by_address_async().
562  *
563  * If the DNS resolution failed, @error (if non-%NULL) will be set to
564  * a value from #GResolverError. If the operation was cancelled,
565  * @error will be set to %G_IO_ERROR_CANCELLED.
566  *
567  * Return value: a hostname (either ASCII-only, or in ASCII-encoded
568  * form), or %NULL on error.
569  *
570  * Since: 2.22
571  */
572 gchar *
573 g_resolver_lookup_by_address_finish (GResolver     *resolver,
574                                      GAsyncResult  *result,
575                                      GError       **error)
576 {
577   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
578
579   if (g_async_result_legacy_propagate_error (result, error))
580     return NULL;
581
582   return G_RESOLVER_GET_CLASS (resolver)->
583     lookup_by_address_finish (resolver, result, error);
584 }
585
586 static gchar *
587 g_resolver_get_service_rrname (const char *service,
588                                const char *protocol,
589                                const char *domain)
590 {
591   gchar *rrname, *ascii_domain = NULL;
592
593   if (g_hostname_is_non_ascii (domain))
594     domain = ascii_domain = g_hostname_to_ascii (domain);
595
596   rrname = g_strdup_printf ("_%s._%s.%s", service, protocol, domain);
597
598   g_free (ascii_domain);
599   return rrname;
600 }
601
602 /**
603  * g_resolver_lookup_service:
604  * @resolver: a #GResolver
605  * @service: the service type to look up (eg, "ldap")
606  * @protocol: the networking protocol to use for @service (eg, "tcp")
607  * @domain: the DNS domain to look up the service in
608  * @cancellable: (allow-none): a #GCancellable, or %NULL
609  * @error: return location for a #GError, or %NULL
610  *
611  * Synchronously performs a DNS SRV lookup for the given @service and
612  * @protocol in the given @domain and returns an array of #GSrvTarget.
613  * @domain may be an ASCII-only or UTF-8 hostname. Note also that the
614  * @service and @protocol arguments <emphasis>do not</emphasis>
615  * include the leading underscore that appears in the actual DNS
616  * entry.
617  *
618  * On success, g_resolver_lookup_service() will return a #GList of
619  * #GSrvTarget, sorted in order of preference. (That is, you should
620  * attempt to connect to the first target first, then the second if
621  * the first fails, etc.)
622  *
623  * If the DNS resolution fails, @error (if non-%NULL) will be set to
624  * a value from #GResolverError.
625  *
626  * If @cancellable is non-%NULL, it can be used to cancel the
627  * operation, in which case @error (if non-%NULL) will be set to
628  * %G_IO_ERROR_CANCELLED.
629  *
630  * If you are planning to connect to the service, it is usually easier
631  * to create a #GNetworkService and use its #GSocketConnectable
632  * interface.
633  *
634  * Return value: (element-type GSrvTarget) (transfer full): a #GList of #GSrvTarget,
635  * or %NULL on error. You must free each of the targets and the list when you are
636  * done with it. (You can use g_resolver_free_targets() to do this.)
637  *
638  * Since: 2.22
639  */
640 GList *
641 g_resolver_lookup_service (GResolver     *resolver,
642                            const gchar   *service,
643                            const gchar   *protocol,
644                            const gchar   *domain,
645                            GCancellable  *cancellable,
646                            GError       **error)
647 {
648   GList *targets;
649   gchar *rrname;
650
651   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
652   g_return_val_if_fail (service != NULL, NULL);
653   g_return_val_if_fail (protocol != NULL, NULL);
654   g_return_val_if_fail (domain != NULL, NULL);
655
656   rrname = g_resolver_get_service_rrname (service, protocol, domain);
657
658   g_resolver_maybe_reload (resolver);
659   targets = G_RESOLVER_GET_CLASS (resolver)->
660     lookup_service (resolver, rrname, cancellable, error);
661
662   g_free (rrname);
663   return targets;
664 }
665
666 /**
667  * g_resolver_lookup_service_async:
668  * @resolver: a #GResolver
669  * @service: the service type to look up (eg, "ldap")
670  * @protocol: the networking protocol to use for @service (eg, "tcp")
671  * @domain: the DNS domain to look up the service in
672  * @cancellable: (allow-none): a #GCancellable, or %NULL
673  * @callback: (scope async): callback to call after resolution completes
674  * @user_data: (closure): data for @callback
675  *
676  * Begins asynchronously performing a DNS SRV lookup for the given
677  * @service and @protocol in the given @domain, and eventually calls
678  * @callback, which must call g_resolver_lookup_service_finish() to
679  * get the final result. See g_resolver_lookup_service() for more
680  * details.
681  *
682  * Since: 2.22
683  */
684 void
685 g_resolver_lookup_service_async (GResolver           *resolver,
686                                  const gchar         *service,
687                                  const gchar         *protocol,
688                                  const gchar         *domain,
689                                  GCancellable        *cancellable,
690                                  GAsyncReadyCallback  callback,
691                                  gpointer             user_data)
692 {
693   gchar *rrname;
694
695   g_return_if_fail (G_IS_RESOLVER (resolver));
696   g_return_if_fail (service != NULL);
697   g_return_if_fail (protocol != NULL);
698   g_return_if_fail (domain != NULL);
699
700   rrname = g_resolver_get_service_rrname (service, protocol, domain);
701
702   g_resolver_maybe_reload (resolver);
703   G_RESOLVER_GET_CLASS (resolver)->
704     lookup_service_async (resolver, rrname, cancellable, callback, user_data);
705
706   g_free (rrname);
707 }
708
709 /**
710  * g_resolver_lookup_service_finish:
711  * @resolver: a #GResolver
712  * @result: the result passed to your #GAsyncReadyCallback
713  * @error: return location for a #GError, or %NULL
714  *
715  * Retrieves the result of a previous call to
716  * g_resolver_lookup_service_async().
717  *
718  * If the DNS resolution failed, @error (if non-%NULL) will be set to
719  * a value from #GResolverError. If the operation was cancelled,
720  * @error will be set to %G_IO_ERROR_CANCELLED.
721  *
722  * Return value: (element-type GSrvTarget) (transfer full): a #GList of #GSrvTarget,
723  * or %NULL on error. See g_resolver_lookup_service() for more details.
724  *
725  * Since: 2.22
726  */
727 GList *
728 g_resolver_lookup_service_finish (GResolver     *resolver,
729                                   GAsyncResult  *result,
730                                   GError       **error)
731 {
732   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
733
734   if (g_async_result_legacy_propagate_error (result, error))
735     return NULL;
736
737   return G_RESOLVER_GET_CLASS (resolver)->
738     lookup_service_finish (resolver, result, error);
739 }
740
741 /**
742  * g_resolver_free_targets: (skip)
743  * @targets: a #GList of #GSrvTarget
744  *
745  * Frees @targets (which should be the return value from
746  * g_resolver_lookup_service() or g_resolver_lookup_service_finish()).
747  * (This is a convenience method; you can also simply free the
748  * results by hand.)
749  *
750  * Since: 2.22
751  */
752 void
753 g_resolver_free_targets (GList *targets)
754 {
755   GList *t;
756
757   for (t = targets; t; t = t->next)
758     g_srv_target_free (t->data);
759   g_list_free (targets);
760 }
761
762 /**
763  * g_resolver_lookup_records:
764  * @resolver: a #GResolver
765  * @rrname: the DNS name to lookup the record for
766  * @record_type: the type of DNS record to lookup
767  * @cancellable: (allow-none): a #GCancellable, or %NULL
768  * @error: return location for a #GError, or %NULL
769  *
770  * Synchronously performs a DNS record lookup for the given @rrname and returns
771  * a list of records as #GVariant tuples. See #GResolverRecordType for
772  * information on what the records contain for each @record_type.
773  *
774  * If the DNS resolution fails, @error (if non-%NULL) will be set to
775  * a value from #GResolverError.
776  *
777  * If @cancellable is non-%NULL, it can be used to cancel the
778  * operation, in which case @error (if non-%NULL) will be set to
779  * %G_IO_ERROR_CANCELLED.
780  *
781  * Return value: (element-type GVariant) (transfer full): a #GList of #GVariant,
782  * or %NULL on error. You must free each of the records and the list when you are
783  * done with it. (You can use g_list_free_full() with g_variant_unref() to do this.)
784  *
785  * Since: 2.34
786  */
787 GList *
788 g_resolver_lookup_records (GResolver            *resolver,
789                            const gchar          *rrname,
790                            GResolverRecordType   record_type,
791                            GCancellable         *cancellable,
792                            GError              **error)
793 {
794   GList *records;
795
796   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
797   g_return_val_if_fail (rrname != NULL, NULL);
798
799   g_resolver_maybe_reload (resolver);
800   records = G_RESOLVER_GET_CLASS (resolver)->
801     lookup_records (resolver, rrname, record_type, cancellable, error);
802
803   return records;
804 }
805
806 /**
807  * g_resolver_lookup_records_async:
808  * @resolver: a #GResolver
809  * @rrname: the DNS name to lookup the record for
810  * @record_type: the type of DNS record to lookup
811  * @cancellable: (allow-none): a #GCancellable, or %NULL
812  * @callback: (scope async): callback to call after resolution completes
813  * @user_data: (closure): data for @callback
814  *
815  * Begins asynchronously performing a DNS lookup for the given
816  * @rrname, and eventually calls @callback, which must call
817  * g_resolver_lookup_records_finish() to get the final result. See
818  * g_resolver_lookup_records() for more details.
819  *
820  * Since: 2.34
821  */
822 void
823 g_resolver_lookup_records_async (GResolver           *resolver,
824                                  const gchar         *rrname,
825                                  GResolverRecordType  record_type,
826                                  GCancellable        *cancellable,
827                                  GAsyncReadyCallback  callback,
828                                  gpointer             user_data)
829 {
830   g_return_if_fail (G_IS_RESOLVER (resolver));
831   g_return_if_fail (rrname != NULL);
832
833   g_resolver_maybe_reload (resolver);
834   G_RESOLVER_GET_CLASS (resolver)->
835     lookup_records_async (resolver, rrname, record_type, cancellable, callback, user_data);
836 }
837
838 /**
839  * g_resolver_lookup_records_finish:
840  * @resolver: a #GResolver
841  * @result: the result passed to your #GAsyncReadyCallback
842  * @error: return location for a #GError, or %NULL
843  *
844  * Retrieves the result of a previous call to
845  * g_resolver_lookup_records_async(). Returns a list of records as #GVariant
846  * tuples. See #GResolverRecordType for information on what the records contain.
847  *
848  * If the DNS resolution failed, @error (if non-%NULL) will be set to
849  * a value from #GResolverError. If the operation was cancelled,
850  * @error will be set to %G_IO_ERROR_CANCELLED.
851  *
852  * Return value: (element-type GVariant) (transfer full): a #GList of #GVariant,
853  * or %NULL on error. You must free each of the records and the list when you are
854  * done with it. (You can use g_list_free_full() with g_variant_unref() to do this.)
855  *
856  * Since: 2.34
857  */
858 GList *
859 g_resolver_lookup_records_finish (GResolver     *resolver,
860                                   GAsyncResult  *result,
861                                   GError       **error)
862 {
863   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
864   return G_RESOLVER_GET_CLASS (resolver)->
865     lookup_records_finish (resolver, result, error);
866 }
867
868 /**
869  * g_resolver_error_quark:
870  *
871  * Gets the #GResolver Error Quark.
872  *
873  * Return value: a #GQuark.
874  *
875  * Since: 2.22
876  */
877 GQuark
878 g_resolver_error_quark (void)
879 {
880   return g_quark_from_static_string ("g-resolver-error-quark");
881 }
882
883
884 static GResolverError
885 g_resolver_error_from_addrinfo_error (gint err)
886 {
887   switch (err)
888     {
889     case EAI_FAIL:
890 #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
891     case EAI_NODATA:
892 #endif
893     case EAI_NONAME:
894       return G_RESOLVER_ERROR_NOT_FOUND;
895
896     case EAI_AGAIN:
897       return G_RESOLVER_ERROR_TEMPORARY_FAILURE;
898
899     default:
900       return G_RESOLVER_ERROR_INTERNAL;
901     }
902 }
903
904 struct addrinfo _g_resolver_addrinfo_hints;
905
906 /* Private method to process a getaddrinfo() response. */
907 GList *
908 _g_resolver_addresses_from_addrinfo (const char       *hostname,
909                                      struct addrinfo  *res,
910                                      gint              gai_retval,
911                                      GError          **error)
912 {
913   struct addrinfo *ai;
914   GSocketAddress *sockaddr;
915   GInetAddress *addr;
916   GList *addrs;
917
918   if (gai_retval != 0)
919     {
920       g_set_error (error, G_RESOLVER_ERROR,
921                    g_resolver_error_from_addrinfo_error (gai_retval),
922                    _("Error resolving '%s': %s"),
923                    hostname, gai_strerror (gai_retval));
924       return NULL;
925     }
926
927   g_return_val_if_fail (res != NULL, NULL);
928
929   addrs = NULL;
930   for (ai = res; ai; ai = ai->ai_next)
931     {
932       sockaddr = g_socket_address_new_from_native (ai->ai_addr, ai->ai_addrlen);
933       if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
934         continue;
935
936       addr = g_object_ref (g_inet_socket_address_get_address ((GInetSocketAddress *)sockaddr));
937       addrs = g_list_prepend (addrs, addr);
938       g_object_unref (sockaddr);
939     }
940
941   return g_list_reverse (addrs);
942 }
943
944 /* Private method to set up a getnameinfo() request */
945 void
946 _g_resolver_address_to_sockaddr (GInetAddress            *address,
947                                  struct sockaddr_storage *sa,
948                                  gsize                   *len)
949 {
950   GSocketAddress *sockaddr;
951
952   sockaddr = g_inet_socket_address_new (address, 0);
953   g_socket_address_to_native (sockaddr, (struct sockaddr *)sa, sizeof (*sa), NULL);
954   *len = g_socket_address_get_native_size (sockaddr);
955   g_object_unref (sockaddr);
956 }
957
958 /* Private method to process a getnameinfo() response. */
959 char *
960 _g_resolver_name_from_nameinfo (GInetAddress  *address,
961                                 const gchar   *name,
962                                 gint           gni_retval,
963                                 GError       **error)
964 {
965   if (gni_retval != 0)
966     {
967       gchar *phys;
968
969       phys = g_inet_address_to_string (address);
970       g_set_error (error, G_RESOLVER_ERROR,
971                    g_resolver_error_from_addrinfo_error (gni_retval),
972                    _("Error reverse-resolving '%s': %s"),
973                    phys ? phys : "(unknown)", gai_strerror (gni_retval));
974       g_free (phys);
975       return NULL;
976     }
977
978   return g_strdup (name);
979 }
980
981 #if defined(G_OS_UNIX)
982
983 static gboolean
984 parse_short (guchar  **p,
985              guchar   *end,
986              guint16  *value)
987 {
988   if (*p + 2 > end)
989     return FALSE;
990   GETSHORT (*value, *p);
991   return TRUE;
992 }
993
994 static gboolean
995 parse_long (guchar  **p,
996             guchar   *end,
997             guint32  *value)
998 {
999   if (*p + 4 > end)
1000     return FALSE;
1001   GETLONG (*value, *p);
1002   return TRUE;
1003 }
1004
1005 static GVariant *
1006 parse_res_srv (guchar  *answer,
1007                guchar  *end,
1008                guchar  *p)
1009 {
1010   gchar namebuf[1024];
1011   guint16 priority, weight, port;
1012   gint n;
1013
1014   if (!parse_short (&p, end, &priority) ||
1015       !parse_short (&p, end, &weight) ||
1016       !parse_short (&p, end, &port))
1017     return NULL;
1018
1019   n = dn_expand (answer, end, p, namebuf, sizeof (namebuf));
1020   if (n < 0)
1021     return NULL;
1022   *p += n;
1023
1024   return g_variant_new ("(qqqs)",
1025                         priority,
1026                         weight,
1027                         port,
1028                         namebuf);
1029 }
1030
1031 static GVariant *
1032 parse_res_soa (guchar  *answer,
1033                guchar  *end,
1034                guchar  *p)
1035 {
1036   gchar mnamebuf[1024];
1037   gchar rnamebuf[1024];
1038   guint32 serial, refresh, retry, expire, ttl;
1039   gint n;
1040
1041   n = dn_expand (answer, end, p, mnamebuf, sizeof (mnamebuf));
1042   if (n < 0)
1043     return NULL;
1044   p += n;
1045
1046   n = dn_expand (answer, end, p, rnamebuf, sizeof (rnamebuf));
1047   if (n < 0)
1048     return NULL;
1049   p += n;
1050
1051   if (!parse_long (&p, end, &serial) ||
1052       !parse_long (&p, end, &refresh) ||
1053       !parse_long (&p, end, &retry) ||
1054       !parse_long (&p, end, &expire) ||
1055       !parse_long (&p, end, &ttl))
1056     return NULL;
1057
1058   return g_variant_new ("(ssuuuuu)",
1059                         mnamebuf,
1060                         rnamebuf,
1061                         serial,
1062                         refresh,
1063                         retry,
1064                         expire,
1065                         ttl);
1066 }
1067
1068 static GVariant *
1069 parse_res_ns (guchar  *answer,
1070               guchar  *end,
1071               guchar  *p)
1072 {
1073   gchar namebuf[1024];
1074   gint n;
1075
1076   n = dn_expand (answer, end, p, namebuf, sizeof (namebuf));
1077   if (n < 0)
1078     return NULL;
1079
1080   return g_variant_new ("(s)", namebuf);
1081 }
1082
1083 static GVariant *
1084 parse_res_mx (guchar  *answer,
1085               guchar  *end,
1086               guchar  *p)
1087 {
1088   gchar namebuf[1024];
1089   guint16 preference;
1090   gint n;
1091
1092   if (!parse_short (&p, end, &preference))
1093     return NULL;
1094
1095   n = dn_expand (answer, end, p, namebuf, sizeof (namebuf));
1096   if (n < 0)
1097     return NULL;
1098   p += n;
1099
1100   return g_variant_new ("(qs)",
1101                         preference,
1102                         namebuf);
1103 }
1104
1105 static GVariant *
1106 parse_res_txt (guchar  *answer,
1107                guchar  *end,
1108                guchar  *p)
1109 {
1110   GVariant *record;
1111   GPtrArray *array;
1112   gsize len;
1113
1114   array = g_ptr_array_new_with_free_func (g_free);
1115   while (p < end)
1116     {
1117       len = *(p++);
1118       if (len > p - end)
1119         break;
1120       g_ptr_array_add (array, g_strndup ((gchar *)p, len));
1121       p += len;
1122     }
1123
1124   record = g_variant_new ("(@as)",
1125                           g_variant_new_strv ((const gchar **)array->pdata, array->len));
1126   g_ptr_array_free (array, TRUE);
1127   return record;
1128 }
1129
1130 gint
1131 _g_resolver_record_type_to_rrtype (GResolverRecordType type)
1132 {
1133   switch (type)
1134   {
1135     case G_RESOLVER_RECORD_SRV:
1136       return T_SRV;
1137     case G_RESOLVER_RECORD_TXT:
1138       return T_TXT;
1139     case G_RESOLVER_RECORD_SOA:
1140       return T_SOA;
1141     case G_RESOLVER_RECORD_NS:
1142       return T_NS;
1143     case G_RESOLVER_RECORD_MX:
1144       return T_MX;
1145   }
1146   g_return_val_if_reached (-1);
1147 }
1148
1149 /* Private method to process a res_query response into GSrvTargets */
1150 GList *
1151 _g_resolver_records_from_res_query (const gchar      *rrname,
1152                                     gint              rrtype,
1153                                     guchar           *answer,
1154                                     gint              len,
1155                                     gint              herr,
1156                                     GError          **error)
1157 {
1158   gint count;
1159   guchar *end, *p;
1160   guint16 type, qclass, rdlength;
1161   guint32 ttl;
1162   HEADER *header;
1163   GList *records;
1164   GVariant *record;
1165   gint n, i;
1166
1167   if (len <= 0)
1168     {
1169       GResolverError errnum;
1170       const gchar *format;
1171
1172       if (len == 0 || herr == HOST_NOT_FOUND || herr == NO_DATA)
1173         {
1174           errnum = G_RESOLVER_ERROR_NOT_FOUND;
1175           format = _("No DNS record of the requested type for '%s'");
1176         }
1177       else if (herr == TRY_AGAIN)
1178         {
1179           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
1180           format = _("Temporarily unable to resolve '%s'");
1181         }
1182       else
1183         {
1184           errnum = G_RESOLVER_ERROR_INTERNAL;
1185           format = _("Error resolving '%s'");
1186         }
1187
1188       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
1189       return NULL;
1190     }
1191
1192   records = NULL;
1193
1194   header = (HEADER *)answer;
1195   p = answer + sizeof (HEADER);
1196   end = answer + len;
1197
1198   /* Skip query */
1199   count = ntohs (header->qdcount);
1200   for (i = 0; i < count && p < end; i++)
1201     {
1202       n = dn_skipname (p, end);
1203       if (n < 0)
1204         break;
1205       p += n;
1206       p += 4;
1207     }
1208
1209   /* Incomplete response */
1210   if (i < count)
1211     {
1212       g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_TEMPORARY_FAILURE,
1213                    _("Incomplete data received for '%s'"), rrname);
1214       return NULL;
1215     }
1216
1217   /* Read answers */
1218   count = ntohs (header->ancount);
1219   for (i = 0; i < count && p < end; i++)
1220     {
1221       n = dn_skipname (p, end);
1222       if (n < 0)
1223         break;
1224       p += n;
1225
1226       if (!parse_short (&p, end, &type) ||
1227           !parse_short (&p, end, &qclass) ||
1228           !parse_long (&p, end, &ttl) ||
1229           !parse_short (&p, end, &rdlength))
1230         break;
1231
1232       ttl = ttl; /* To avoid -Wunused-but-set-variable */
1233
1234       if (p + rdlength > end)
1235         break;
1236
1237       if (type == rrtype && qclass == C_IN)
1238         {
1239           switch (rrtype)
1240             {
1241             case T_SRV:
1242               record = parse_res_srv (answer, end, p);
1243               break;
1244             case T_MX:
1245               record = parse_res_mx (answer, end, p);
1246               break;
1247             case T_SOA:
1248               record = parse_res_soa (answer, end, p);
1249               break;
1250             case T_NS:
1251               record = parse_res_ns (answer, end, p);
1252               break;
1253             case T_TXT:
1254               record = parse_res_txt (answer, p + rdlength, p);
1255               break;
1256             default:
1257               g_warn_if_reached ();
1258               record = NULL;
1259               break;
1260             }
1261
1262           if (record != NULL)
1263             records = g_list_prepend (records, record);
1264         }
1265
1266       p += rdlength;
1267     }
1268
1269   /* Somehow got a truncated response */
1270   if (i < count)
1271     {
1272       g_list_free_full (records, (GDestroyNotify)g_variant_unref);
1273       g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_TEMPORARY_FAILURE,
1274                    _("Incomplete data received for '%s'"), rrname);
1275       return NULL;
1276     }
1277
1278   return records;
1279 }
1280
1281 #elif defined(G_OS_WIN32)
1282 static GVariant *
1283 parse_dns_srv (DNS_RECORD *rec)
1284 {
1285   return g_variant_new ("(qqqs)",
1286                         (guint16)rec->Data.SRV.wPriority,
1287                         (guint16)rec->Data.SRV.wWeight,
1288                         (guint16)rec->Data.SRV.wPort,
1289                         rec->Data.SRV.pNameTarget);
1290 }
1291
1292 static GVariant *
1293 parse_dns_soa (DNS_RECORD *rec)
1294 {
1295   return g_variant_new ("(ssuuuuu)",
1296                         rec->Data.SOA.pNamePrimaryServer,
1297                         rec->Data.SOA.pNameAdministrator,
1298                         (guint32)rec->Data.SOA.dwSerialNo,
1299                         (guint32)rec->Data.SOA.dwRefresh,
1300                         (guint32)rec->Data.SOA.dwRetry,
1301                         (guint32)rec->Data.SOA.dwExpire,
1302                         (guint32)rec->Data.SOA.dwDefaultTtl);
1303 }
1304
1305 static GVariant *
1306 parse_dns_ns (DNS_RECORD *rec)
1307 {
1308   return g_variant_new ("(s)", rec->Data.NS.pNameHost);
1309 }
1310
1311 static GVariant *
1312 parse_dns_mx (DNS_RECORD *rec)
1313 {
1314   return g_variant_new ("(qs)",
1315                         (guint16)rec->Data.MX.wPreference,
1316                         rec->Data.MX.pNameExchange);
1317 }
1318
1319 static GVariant *
1320 parse_dns_txt (DNS_RECORD *rec)
1321 {
1322   GVariant *record;
1323   GPtrArray *array;
1324   DWORD i;
1325
1326   array = g_ptr_array_new ();
1327   for (i = 0; i < rec->Data.TXT.dwStringCount; i++)
1328     g_ptr_array_add (array, rec->Data.TXT.pStringArray[i]);
1329   record = g_variant_new ("(@as)",
1330                           g_variant_new_strv ((const gchar **)array->pdata, array->len));
1331   g_ptr_array_free (array, TRUE);
1332   return record;
1333 }
1334
1335 WORD
1336 _g_resolver_record_type_to_dnstype (GResolverRecordType type)
1337 {
1338   switch (type)
1339   {
1340     case G_RESOLVER_RECORD_SRV:
1341       return DNS_TYPE_SRV;
1342     case G_RESOLVER_RECORD_TXT:
1343       return DNS_TYPE_TEXT;
1344     case G_RESOLVER_RECORD_SOA:
1345       return DNS_TYPE_SOA;
1346     case G_RESOLVER_RECORD_NS:
1347       return DNS_TYPE_NS;
1348     case G_RESOLVER_RECORD_MX:
1349       return DNS_TYPE_MX;
1350   }
1351   g_return_val_if_reached (-1);
1352 }
1353
1354 /* Private method to process a DnsQuery response into GVariants */
1355 GList *
1356 _g_resolver_records_from_DnsQuery (const gchar  *rrname,
1357                                    WORD          dnstype,
1358                                    DNS_STATUS    status,
1359                                    DNS_RECORD   *results,
1360                                    GError      **error)
1361 {
1362   DNS_RECORD *rec;
1363   gpointer record;
1364   GList *records;
1365
1366   if (status != ERROR_SUCCESS)
1367     {
1368       GResolverError errnum;
1369       const gchar *format;
1370
1371       if (status == DNS_ERROR_RCODE_NAME_ERROR)
1372         {
1373           errnum = G_RESOLVER_ERROR_NOT_FOUND;
1374           format = _("No DNS record of the requested type for '%s'");
1375         }
1376       else if (status == DNS_ERROR_RCODE_SERVER_FAILURE)
1377         {
1378           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
1379           format = _("Temporarily unable to resolve '%s'");
1380         }
1381       else
1382         {
1383           errnum = G_RESOLVER_ERROR_INTERNAL;
1384           format = _("Error resolving '%s'");
1385         }
1386
1387       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
1388       return NULL;
1389     }
1390
1391   records = NULL;
1392   for (rec = results; rec; rec = rec->pNext)
1393     {
1394       if (rec->wType != dnstype)
1395         continue;
1396       switch (dnstype)
1397         {
1398         case DNS_TYPE_SRV:
1399           record = parse_dns_srv (rec);
1400           break;
1401         case DNS_TYPE_SOA:
1402           record = parse_dns_soa (rec);
1403           break;
1404         case DNS_TYPE_NS:
1405           record = parse_dns_ns (rec);
1406           break;
1407         case DNS_TYPE_MX:
1408           record = parse_dns_mx (rec);
1409           break;
1410         case DNS_TYPE_TEXT:
1411           record = parse_dns_txt (rec);
1412           break;
1413         default:
1414           g_warn_if_reached ();
1415           record = NULL;
1416           break;
1417         }
1418       if (record != NULL)
1419         records = g_list_prepend (records, g_variant_ref_sink (record));
1420     }
1421
1422   return records;
1423 }
1424
1425 #endif