gio: don't quote quark names for G_DEFINE_QUARK
[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 G_DEFINE_QUARK (g-resolver-error-quark, g_resolver_error)
878
879 static GResolverError
880 g_resolver_error_from_addrinfo_error (gint err)
881 {
882   switch (err)
883     {
884     case EAI_FAIL:
885 #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
886     case EAI_NODATA:
887 #endif
888     case EAI_NONAME:
889       return G_RESOLVER_ERROR_NOT_FOUND;
890
891     case EAI_AGAIN:
892       return G_RESOLVER_ERROR_TEMPORARY_FAILURE;
893
894     default:
895       return G_RESOLVER_ERROR_INTERNAL;
896     }
897 }
898
899 struct addrinfo _g_resolver_addrinfo_hints;
900
901 /* Private method to process a getaddrinfo() response. */
902 GList *
903 _g_resolver_addresses_from_addrinfo (const char       *hostname,
904                                      struct addrinfo  *res,
905                                      gint              gai_retval,
906                                      GError          **error)
907 {
908   struct addrinfo *ai;
909   GSocketAddress *sockaddr;
910   GInetAddress *addr;
911   GList *addrs;
912
913   if (gai_retval != 0)
914     {
915       g_set_error (error, G_RESOLVER_ERROR,
916                    g_resolver_error_from_addrinfo_error (gai_retval),
917                    _("Error resolving '%s': %s"),
918                    hostname, gai_strerror (gai_retval));
919       return NULL;
920     }
921
922   g_return_val_if_fail (res != NULL, NULL);
923
924   addrs = NULL;
925   for (ai = res; ai; ai = ai->ai_next)
926     {
927       sockaddr = g_socket_address_new_from_native (ai->ai_addr, ai->ai_addrlen);
928       if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
929         continue;
930
931       addr = g_object_ref (g_inet_socket_address_get_address ((GInetSocketAddress *)sockaddr));
932       addrs = g_list_prepend (addrs, addr);
933       g_object_unref (sockaddr);
934     }
935
936   return g_list_reverse (addrs);
937 }
938
939 /* Private method to set up a getnameinfo() request */
940 void
941 _g_resolver_address_to_sockaddr (GInetAddress            *address,
942                                  struct sockaddr_storage *sa,
943                                  gsize                   *len)
944 {
945   GSocketAddress *sockaddr;
946
947   sockaddr = g_inet_socket_address_new (address, 0);
948   g_socket_address_to_native (sockaddr, (struct sockaddr *)sa, sizeof (*sa), NULL);
949   *len = g_socket_address_get_native_size (sockaddr);
950   g_object_unref (sockaddr);
951 }
952
953 /* Private method to process a getnameinfo() response. */
954 char *
955 _g_resolver_name_from_nameinfo (GInetAddress  *address,
956                                 const gchar   *name,
957                                 gint           gni_retval,
958                                 GError       **error)
959 {
960   if (gni_retval != 0)
961     {
962       gchar *phys;
963
964       phys = g_inet_address_to_string (address);
965       g_set_error (error, G_RESOLVER_ERROR,
966                    g_resolver_error_from_addrinfo_error (gni_retval),
967                    _("Error reverse-resolving '%s': %s"),
968                    phys ? phys : "(unknown)", gai_strerror (gni_retval));
969       g_free (phys);
970       return NULL;
971     }
972
973   return g_strdup (name);
974 }
975
976 #if defined(G_OS_UNIX)
977
978 static gboolean
979 parse_short (guchar  **p,
980              guchar   *end,
981              guint16  *value)
982 {
983   if (*p + 2 > end)
984     return FALSE;
985   GETSHORT (*value, *p);
986   return TRUE;
987 }
988
989 static gboolean
990 parse_long (guchar  **p,
991             guchar   *end,
992             guint32  *value)
993 {
994   if (*p + 4 > end)
995     return FALSE;
996   GETLONG (*value, *p);
997   return TRUE;
998 }
999
1000 static GVariant *
1001 parse_res_srv (guchar  *answer,
1002                guchar  *end,
1003                guchar  *p)
1004 {
1005   gchar namebuf[1024];
1006   guint16 priority, weight, port;
1007   gint n;
1008
1009   if (!parse_short (&p, end, &priority) ||
1010       !parse_short (&p, end, &weight) ||
1011       !parse_short (&p, end, &port))
1012     return NULL;
1013
1014   n = dn_expand (answer, end, p, namebuf, sizeof (namebuf));
1015   if (n < 0)
1016     return NULL;
1017   *p += n;
1018
1019   return g_variant_new ("(qqqs)",
1020                         priority,
1021                         weight,
1022                         port,
1023                         namebuf);
1024 }
1025
1026 static GVariant *
1027 parse_res_soa (guchar  *answer,
1028                guchar  *end,
1029                guchar  *p)
1030 {
1031   gchar mnamebuf[1024];
1032   gchar rnamebuf[1024];
1033   guint32 serial, refresh, retry, expire, ttl;
1034   gint n;
1035
1036   n = dn_expand (answer, end, p, mnamebuf, sizeof (mnamebuf));
1037   if (n < 0)
1038     return NULL;
1039   p += n;
1040
1041   n = dn_expand (answer, end, p, rnamebuf, sizeof (rnamebuf));
1042   if (n < 0)
1043     return NULL;
1044   p += n;
1045
1046   if (!parse_long (&p, end, &serial) ||
1047       !parse_long (&p, end, &refresh) ||
1048       !parse_long (&p, end, &retry) ||
1049       !parse_long (&p, end, &expire) ||
1050       !parse_long (&p, end, &ttl))
1051     return NULL;
1052
1053   return g_variant_new ("(ssuuuuu)",
1054                         mnamebuf,
1055                         rnamebuf,
1056                         serial,
1057                         refresh,
1058                         retry,
1059                         expire,
1060                         ttl);
1061 }
1062
1063 static GVariant *
1064 parse_res_ns (guchar  *answer,
1065               guchar  *end,
1066               guchar  *p)
1067 {
1068   gchar namebuf[1024];
1069   gint n;
1070
1071   n = dn_expand (answer, end, p, namebuf, sizeof (namebuf));
1072   if (n < 0)
1073     return NULL;
1074
1075   return g_variant_new ("(s)", namebuf);
1076 }
1077
1078 static GVariant *
1079 parse_res_mx (guchar  *answer,
1080               guchar  *end,
1081               guchar  *p)
1082 {
1083   gchar namebuf[1024];
1084   guint16 preference;
1085   gint n;
1086
1087   if (!parse_short (&p, end, &preference))
1088     return NULL;
1089
1090   n = dn_expand (answer, end, p, namebuf, sizeof (namebuf));
1091   if (n < 0)
1092     return NULL;
1093   p += n;
1094
1095   return g_variant_new ("(qs)",
1096                         preference,
1097                         namebuf);
1098 }
1099
1100 static GVariant *
1101 parse_res_txt (guchar  *answer,
1102                guchar  *end,
1103                guchar  *p)
1104 {
1105   GVariant *record;
1106   GPtrArray *array;
1107   gsize len;
1108
1109   array = g_ptr_array_new_with_free_func (g_free);
1110   while (p < end)
1111     {
1112       len = *(p++);
1113       if (len > p - end)
1114         break;
1115       g_ptr_array_add (array, g_strndup ((gchar *)p, len));
1116       p += len;
1117     }
1118
1119   record = g_variant_new ("(@as)",
1120                           g_variant_new_strv ((const gchar **)array->pdata, array->len));
1121   g_ptr_array_free (array, TRUE);
1122   return record;
1123 }
1124
1125 gint
1126 _g_resolver_record_type_to_rrtype (GResolverRecordType type)
1127 {
1128   switch (type)
1129   {
1130     case G_RESOLVER_RECORD_SRV:
1131       return T_SRV;
1132     case G_RESOLVER_RECORD_TXT:
1133       return T_TXT;
1134     case G_RESOLVER_RECORD_SOA:
1135       return T_SOA;
1136     case G_RESOLVER_RECORD_NS:
1137       return T_NS;
1138     case G_RESOLVER_RECORD_MX:
1139       return T_MX;
1140   }
1141   g_return_val_if_reached (-1);
1142 }
1143
1144 /* Private method to process a res_query response into GSrvTargets */
1145 GList *
1146 _g_resolver_records_from_res_query (const gchar      *rrname,
1147                                     gint              rrtype,
1148                                     guchar           *answer,
1149                                     gint              len,
1150                                     gint              herr,
1151                                     GError          **error)
1152 {
1153   gint count;
1154   guchar *end, *p;
1155   guint16 type, qclass, rdlength;
1156   guint32 ttl;
1157   HEADER *header;
1158   GList *records;
1159   GVariant *record;
1160   gint n, i;
1161
1162   if (len <= 0)
1163     {
1164       GResolverError errnum;
1165       const gchar *format;
1166
1167       if (len == 0 || herr == HOST_NOT_FOUND || herr == NO_DATA)
1168         {
1169           errnum = G_RESOLVER_ERROR_NOT_FOUND;
1170           format = _("No DNS record of the requested type for '%s'");
1171         }
1172       else if (herr == TRY_AGAIN)
1173         {
1174           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
1175           format = _("Temporarily unable to resolve '%s'");
1176         }
1177       else
1178         {
1179           errnum = G_RESOLVER_ERROR_INTERNAL;
1180           format = _("Error resolving '%s'");
1181         }
1182
1183       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
1184       return NULL;
1185     }
1186
1187   records = NULL;
1188
1189   header = (HEADER *)answer;
1190   p = answer + sizeof (HEADER);
1191   end = answer + len;
1192
1193   /* Skip query */
1194   count = ntohs (header->qdcount);
1195   for (i = 0; i < count && p < end; i++)
1196     {
1197       n = dn_skipname (p, end);
1198       if (n < 0)
1199         break;
1200       p += n;
1201       p += 4;
1202     }
1203
1204   /* Incomplete response */
1205   if (i < count)
1206     {
1207       g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_TEMPORARY_FAILURE,
1208                    _("Incomplete data received for '%s'"), rrname);
1209       return NULL;
1210     }
1211
1212   /* Read answers */
1213   count = ntohs (header->ancount);
1214   for (i = 0; i < count && p < end; i++)
1215     {
1216       n = dn_skipname (p, end);
1217       if (n < 0)
1218         break;
1219       p += n;
1220
1221       if (!parse_short (&p, end, &type) ||
1222           !parse_short (&p, end, &qclass) ||
1223           !parse_long (&p, end, &ttl) ||
1224           !parse_short (&p, end, &rdlength))
1225         break;
1226
1227       ttl = ttl; /* To avoid -Wunused-but-set-variable */
1228
1229       if (p + rdlength > end)
1230         break;
1231
1232       if (type == rrtype && qclass == C_IN)
1233         {
1234           switch (rrtype)
1235             {
1236             case T_SRV:
1237               record = parse_res_srv (answer, end, p);
1238               break;
1239             case T_MX:
1240               record = parse_res_mx (answer, end, p);
1241               break;
1242             case T_SOA:
1243               record = parse_res_soa (answer, end, p);
1244               break;
1245             case T_NS:
1246               record = parse_res_ns (answer, end, p);
1247               break;
1248             case T_TXT:
1249               record = parse_res_txt (answer, p + rdlength, p);
1250               break;
1251             default:
1252               g_warn_if_reached ();
1253               record = NULL;
1254               break;
1255             }
1256
1257           if (record != NULL)
1258             records = g_list_prepend (records, record);
1259         }
1260
1261       p += rdlength;
1262     }
1263
1264   /* Somehow got a truncated response */
1265   if (i < count)
1266     {
1267       g_list_free_full (records, (GDestroyNotify)g_variant_unref);
1268       g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_TEMPORARY_FAILURE,
1269                    _("Incomplete data received for '%s'"), rrname);
1270       return NULL;
1271     }
1272
1273   return records;
1274 }
1275
1276 #elif defined(G_OS_WIN32)
1277 static GVariant *
1278 parse_dns_srv (DNS_RECORD *rec)
1279 {
1280   return g_variant_new ("(qqqs)",
1281                         (guint16)rec->Data.SRV.wPriority,
1282                         (guint16)rec->Data.SRV.wWeight,
1283                         (guint16)rec->Data.SRV.wPort,
1284                         rec->Data.SRV.pNameTarget);
1285 }
1286
1287 static GVariant *
1288 parse_dns_soa (DNS_RECORD *rec)
1289 {
1290   return g_variant_new ("(ssuuuuu)",
1291                         rec->Data.SOA.pNamePrimaryServer,
1292                         rec->Data.SOA.pNameAdministrator,
1293                         (guint32)rec->Data.SOA.dwSerialNo,
1294                         (guint32)rec->Data.SOA.dwRefresh,
1295                         (guint32)rec->Data.SOA.dwRetry,
1296                         (guint32)rec->Data.SOA.dwExpire,
1297                         (guint32)rec->Data.SOA.dwDefaultTtl);
1298 }
1299
1300 static GVariant *
1301 parse_dns_ns (DNS_RECORD *rec)
1302 {
1303   return g_variant_new ("(s)", rec->Data.NS.pNameHost);
1304 }
1305
1306 static GVariant *
1307 parse_dns_mx (DNS_RECORD *rec)
1308 {
1309   return g_variant_new ("(qs)",
1310                         (guint16)rec->Data.MX.wPreference,
1311                         rec->Data.MX.pNameExchange);
1312 }
1313
1314 static GVariant *
1315 parse_dns_txt (DNS_RECORD *rec)
1316 {
1317   GVariant *record;
1318   GPtrArray *array;
1319   DWORD i;
1320
1321   array = g_ptr_array_new ();
1322   for (i = 0; i < rec->Data.TXT.dwStringCount; i++)
1323     g_ptr_array_add (array, rec->Data.TXT.pStringArray[i]);
1324   record = g_variant_new ("(@as)",
1325                           g_variant_new_strv ((const gchar **)array->pdata, array->len));
1326   g_ptr_array_free (array, TRUE);
1327   return record;
1328 }
1329
1330 WORD
1331 _g_resolver_record_type_to_dnstype (GResolverRecordType type)
1332 {
1333   switch (type)
1334   {
1335     case G_RESOLVER_RECORD_SRV:
1336       return DNS_TYPE_SRV;
1337     case G_RESOLVER_RECORD_TXT:
1338       return DNS_TYPE_TEXT;
1339     case G_RESOLVER_RECORD_SOA:
1340       return DNS_TYPE_SOA;
1341     case G_RESOLVER_RECORD_NS:
1342       return DNS_TYPE_NS;
1343     case G_RESOLVER_RECORD_MX:
1344       return DNS_TYPE_MX;
1345   }
1346   g_return_val_if_reached (-1);
1347 }
1348
1349 /* Private method to process a DnsQuery response into GVariants */
1350 GList *
1351 _g_resolver_records_from_DnsQuery (const gchar  *rrname,
1352                                    WORD          dnstype,
1353                                    DNS_STATUS    status,
1354                                    DNS_RECORD   *results,
1355                                    GError      **error)
1356 {
1357   DNS_RECORD *rec;
1358   gpointer record;
1359   GList *records;
1360
1361   if (status != ERROR_SUCCESS)
1362     {
1363       GResolverError errnum;
1364       const gchar *format;
1365
1366       if (status == DNS_ERROR_RCODE_NAME_ERROR)
1367         {
1368           errnum = G_RESOLVER_ERROR_NOT_FOUND;
1369           format = _("No DNS record of the requested type for '%s'");
1370         }
1371       else if (status == DNS_ERROR_RCODE_SERVER_FAILURE)
1372         {
1373           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
1374           format = _("Temporarily unable to resolve '%s'");
1375         }
1376       else
1377         {
1378           errnum = G_RESOLVER_ERROR_INTERNAL;
1379           format = _("Error resolving '%s'");
1380         }
1381
1382       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
1383       return NULL;
1384     }
1385
1386   records = NULL;
1387   for (rec = results; rec; rec = rec->pNext)
1388     {
1389       if (rec->wType != dnstype)
1390         continue;
1391       switch (dnstype)
1392         {
1393         case DNS_TYPE_SRV:
1394           record = parse_dns_srv (rec);
1395           break;
1396         case DNS_TYPE_SOA:
1397           record = parse_dns_soa (rec);
1398           break;
1399         case DNS_TYPE_NS:
1400           record = parse_dns_ns (rec);
1401           break;
1402         case DNS_TYPE_MX:
1403           record = parse_dns_mx (rec);
1404           break;
1405         case DNS_TYPE_TEXT:
1406           record = parse_dns_txt (rec);
1407           break;
1408         default:
1409           g_warn_if_reached ();
1410           record = NULL;
1411           break;
1412         }
1413       if (record != NULL)
1414         records = g_list_prepend (records, g_variant_ref_sink (record));
1415     }
1416
1417   return records;
1418 }
1419
1420 #endif