Imported Upstream version 2.61.1
[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  * Copyright (C) 2018 Igalia S.L.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General
19  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include "config.h"
23 #include <glib.h>
24 #include "glibintl.h"
25
26 #include "gresolver.h"
27 #include "gnetworkingprivate.h"
28 #include "gasyncresult.h"
29 #include "ginetaddress.h"
30 #include "gtask.h"
31 #include "gsrvtarget.h"
32 #include "gthreadedresolver.h"
33 #include "gioerror.h"
34 #include "gcancellable.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  * This is an abstract type; subclasses of it implement different resolvers for
80  * different platforms and situations.
81  */
82 G_DEFINE_ABSTRACT_TYPE_WITH_CODE (GResolver, g_resolver, G_TYPE_OBJECT,
83                                   G_ADD_PRIVATE (GResolver)
84                                   g_networking_init ();)
85
86 static GList *
87 srv_records_to_targets (GList *records)
88 {
89   const gchar *hostname;
90   guint16 port, priority, weight;
91   GSrvTarget *target;
92   GList *l;
93
94   for (l = records; l != NULL; l = g_list_next (l))
95     {
96       g_variant_get (l->data, "(qqq&s)", &priority, &weight, &port, &hostname);
97       target = g_srv_target_new (hostname, port, priority, weight);
98       g_variant_unref (l->data);
99       l->data = target;
100     }
101
102   return g_srv_target_list_sort (records);
103 }
104
105 static GList *
106 g_resolver_real_lookup_service (GResolver            *resolver,
107                                 const gchar          *rrname,
108                                 GCancellable         *cancellable,
109                                 GError              **error)
110 {
111   GList *records;
112
113   records = G_RESOLVER_GET_CLASS (resolver)->lookup_records (resolver,
114                                                              rrname,
115                                                              G_RESOLVER_RECORD_SRV,
116                                                              cancellable,
117                                                              error);
118
119   return srv_records_to_targets (records);
120 }
121
122 static void
123 g_resolver_real_lookup_service_async (GResolver            *resolver,
124                                       const gchar          *rrname,
125                                       GCancellable         *cancellable,
126                                       GAsyncReadyCallback   callback,
127                                       gpointer              user_data)
128 {
129   G_RESOLVER_GET_CLASS (resolver)->lookup_records_async (resolver,
130                                                          rrname,
131                                                          G_RESOLVER_RECORD_SRV,
132                                                          cancellable,
133                                                          callback,
134                                                          user_data);
135 }
136
137 static GList *
138 g_resolver_real_lookup_service_finish (GResolver            *resolver,
139                                        GAsyncResult         *result,
140                                        GError              **error)
141 {
142   GList *records;
143
144   records = G_RESOLVER_GET_CLASS (resolver)->lookup_records_finish (resolver,
145                                                                     result,
146                                                                     error);
147
148   return srv_records_to_targets (records);
149 }
150
151 static void
152 g_resolver_class_init (GResolverClass *resolver_class)
153 {
154   /* Automatically pass these over to the lookup_records methods */
155   resolver_class->lookup_service = g_resolver_real_lookup_service;
156   resolver_class->lookup_service_async = g_resolver_real_lookup_service_async;
157   resolver_class->lookup_service_finish = g_resolver_real_lookup_service_finish;
158
159   /**
160    * GResolver::reload:
161    * @resolver: a #GResolver
162    *
163    * Emitted when the resolver notices that the system resolver
164    * configuration has changed.
165    **/
166   signals[RELOAD] =
167     g_signal_new (I_("reload"),
168                   G_TYPE_RESOLVER,
169                   G_SIGNAL_RUN_LAST,
170                   G_STRUCT_OFFSET (GResolverClass, reload),
171                   NULL, NULL,
172                   g_cclosure_marshal_VOID__VOID,
173                   G_TYPE_NONE, 0);
174 }
175
176 static void
177 g_resolver_init (GResolver *resolver)
178 {
179 #ifdef G_OS_UNIX
180   struct stat st;
181 #endif
182
183   resolver->priv = g_resolver_get_instance_private (resolver);
184
185 #ifdef G_OS_UNIX
186   if (stat (_PATH_RESCONF, &st) == 0)
187     resolver->priv->resolv_conf_timestamp = st.st_mtime;
188 #endif
189 }
190
191 G_LOCK_DEFINE_STATIC (default_resolver);
192 static GResolver *default_resolver;
193
194 /**
195  * g_resolver_get_default:
196  *
197  * Gets the default #GResolver. You should unref it when you are done
198  * with it. #GResolver may use its reference count as a hint about how
199  * many threads it should allocate for concurrent DNS resolutions.
200  *
201  * Returns: (transfer full): the default #GResolver.
202  *
203  * Since: 2.22
204  */
205 GResolver *
206 g_resolver_get_default (void)
207 {
208   GResolver *ret;
209
210   G_LOCK (default_resolver);
211   if (!default_resolver)
212     default_resolver = g_object_new (G_TYPE_THREADED_RESOLVER, NULL);
213   ret = g_object_ref (default_resolver);
214   G_UNLOCK (default_resolver);
215
216   return ret;
217 }
218
219 /**
220  * g_resolver_set_default:
221  * @resolver: the new default #GResolver
222  *
223  * Sets @resolver to be the application's default resolver (reffing
224  * @resolver, and unreffing the previous default resolver, if any).
225  * Future calls to g_resolver_get_default() will return this resolver.
226  *
227  * This can be used if an application wants to perform any sort of DNS
228  * caching or "pinning"; it can implement its own #GResolver that
229  * calls the original default resolver for DNS operations, and
230  * implements its own cache policies on top of that, and then set
231  * itself as the default resolver for all later code to use.
232  *
233  * Since: 2.22
234  */
235 void
236 g_resolver_set_default (GResolver *resolver)
237 {
238   G_LOCK (default_resolver);
239   if (default_resolver)
240     g_object_unref (default_resolver);
241   default_resolver = g_object_ref (resolver);
242   G_UNLOCK (default_resolver);
243 }
244
245 /* Bionic has res_init() but it's not in any header */
246 #ifdef __BIONIC__
247 int res_init (void);
248 #endif
249
250 static void
251 g_resolver_maybe_reload (GResolver *resolver)
252 {
253 #ifdef G_OS_UNIX
254   struct stat st;
255
256   if (stat (_PATH_RESCONF, &st) == 0)
257     {
258       if (st.st_mtime != resolver->priv->resolv_conf_timestamp)
259         {
260           resolver->priv->resolv_conf_timestamp = st.st_mtime;
261 #ifdef HAVE_RES_INIT
262           res_init ();
263 #endif
264           g_signal_emit (resolver, signals[RELOAD], 0);
265         }
266     }
267 #endif
268 }
269
270 /* filter out duplicates, cf. https://bugzilla.gnome.org/show_bug.cgi?id=631379 */
271 static void
272 remove_duplicates (GList *addrs)
273 {
274   GList *l;
275   GList *ll;
276   GList *lll;
277
278   /* TODO: if this is too slow (it's O(n^2) but n is typically really
279    * small), we can do something more clever but note that we must not
280    * change the order of elements...
281    */
282   for (l = addrs; l != NULL; l = l->next)
283     {
284       GInetAddress *address = G_INET_ADDRESS (l->data);
285       for (ll = l->next; ll != NULL; ll = lll)
286         {
287           GInetAddress *other_address = G_INET_ADDRESS (ll->data);
288           lll = ll->next;
289           if (g_inet_address_equal (address, other_address))
290             {
291               g_object_unref (other_address);
292               /* we never return the first element */
293               g_warn_if_fail (g_list_delete_link (addrs, ll) == addrs);
294             }
295         }
296     }
297 }
298
299 /* Note that this does not follow the "FALSE means @error is set"
300  * convention. The return value tells the caller whether it should
301  * return @addrs and @error to the caller right away, or if it should
302  * continue and trying to resolve the name as a hostname.
303  */
304 static gboolean
305 handle_ip_address (const char  *hostname,
306                    GList      **addrs,
307                    GError     **error)
308 {
309   GInetAddress *addr;
310
311 #ifndef G_OS_WIN32
312   struct in_addr ip4addr;
313 #endif
314
315   addr = g_inet_address_new_from_string (hostname);
316   if (addr)
317     {
318       *addrs = g_list_append (NULL, addr);
319       return TRUE;
320     }
321
322   *addrs = NULL;
323
324 #ifdef G_OS_WIN32
325
326   /* Reject IPv6 addresses that have brackets ('[' or ']') and/or port numbers,
327    * as no valid addresses should contain these at this point.
328    * Non-standard IPv4 addresses would be rejected during the call to
329    * getaddrinfo() later.
330    */
331   if (strrchr (hostname, '[') != NULL ||
332       strrchr (hostname, ']') != NULL)
333 #else
334
335   /* Reject non-standard IPv4 numbers-and-dots addresses.
336    * g_inet_address_new_from_string() will have accepted any "real" IP
337    * address, so if inet_aton() succeeds, then it's an address we want
338    * to reject.
339    */
340   if (inet_aton (hostname, &ip4addr))
341 #endif
342     {
343 #ifdef G_OS_WIN32
344       gchar *error_message = g_win32_error_message (WSAHOST_NOT_FOUND);
345 #else
346       gchar *error_message = g_locale_to_utf8 (gai_strerror (EAI_NONAME), -1, NULL, NULL, NULL);
347       if (error_message == NULL)
348         error_message = g_strdup ("[Invalid UTF-8]");
349 #endif
350       g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_NOT_FOUND,
351                    _("Error resolving “%s”: %s"),
352                    hostname, error_message);
353       g_free (error_message);
354
355       return TRUE;
356     }
357
358   return FALSE;
359 }
360
361 static GList *
362 lookup_by_name_real (GResolver                 *resolver,
363                      const gchar               *hostname,
364                      GResolverNameLookupFlags   flags,
365                      GCancellable              *cancellable,
366                      GError                    **error)
367 {
368   GList *addrs;
369   gchar *ascii_hostname = NULL;
370
371   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
372   g_return_val_if_fail (hostname != NULL, NULL);
373   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL);
374   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
375
376   /* Check if @hostname is just an IP address */
377   if (handle_ip_address (hostname, &addrs, error))
378     return addrs;
379
380   if (g_hostname_is_non_ascii (hostname))
381     hostname = ascii_hostname = g_hostname_to_ascii (hostname);
382
383   if (!hostname)
384     {
385       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
386                            _("Invalid hostname"));
387       return NULL;
388     }
389
390   g_resolver_maybe_reload (resolver);
391
392   if (flags != G_RESOLVER_NAME_LOOKUP_FLAGS_DEFAULT)
393     {
394       if (!G_RESOLVER_GET_CLASS (resolver)->lookup_by_name_with_flags)
395         {
396           g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
397                        /* Translators: The placeholder is for a function name. */
398                        _("%s not implemented"), "lookup_by_name_with_flags");
399           g_free (ascii_hostname);
400           return NULL;
401         }
402       addrs = G_RESOLVER_GET_CLASS (resolver)->
403         lookup_by_name_with_flags (resolver, hostname, flags, cancellable, error);
404     }
405   else
406     addrs = G_RESOLVER_GET_CLASS (resolver)->
407       lookup_by_name (resolver, hostname, cancellable, error);
408
409   remove_duplicates (addrs);
410
411   g_free (ascii_hostname);
412   return addrs;
413 }
414
415 /**
416  * g_resolver_lookup_by_name:
417  * @resolver: a #GResolver
418  * @hostname: the hostname to look up
419  * @cancellable: (nullable): a #GCancellable, or %NULL
420  * @error: return location for a #GError, or %NULL
421  *
422  * Synchronously resolves @hostname to determine its associated IP
423  * address(es). @hostname may be an ASCII-only or UTF-8 hostname, or
424  * the textual form of an IP address (in which case this just becomes
425  * a wrapper around g_inet_address_new_from_string()).
426  *
427  * On success, g_resolver_lookup_by_name() will return a non-empty #GList of
428  * #GInetAddress, sorted in order of preference and guaranteed to not
429  * contain duplicates. That is, if using the result to connect to
430  * @hostname, you should attempt to connect to the first address
431  * first, then the second if the first fails, etc. If you are using
432  * the result to listen on a socket, it is appropriate to add each
433  * result using e.g. g_socket_listener_add_address().
434  *
435  * If the DNS resolution fails, @error (if non-%NULL) will be set to a
436  * value from #GResolverError and %NULL will be returned.
437  *
438  * If @cancellable is non-%NULL, it can be used to cancel the
439  * operation, in which case @error (if non-%NULL) will be set to
440  * %G_IO_ERROR_CANCELLED.
441  *
442  * If you are planning to connect to a socket on the resolved IP
443  * address, it may be easier to create a #GNetworkAddress and use its
444  * #GSocketConnectable interface.
445  *
446  * Returns: (element-type GInetAddress) (transfer full): a non-empty #GList
447  * of #GInetAddress, or %NULL on error. You
448  * must unref each of the addresses and free the list when you are
449  * done with it. (You can use g_resolver_free_addresses() to do this.)
450  *
451  * Since: 2.22
452  */
453 GList *
454 g_resolver_lookup_by_name (GResolver     *resolver,
455                            const gchar   *hostname,
456                            GCancellable  *cancellable,
457                            GError       **error)
458 {
459   return lookup_by_name_real (resolver,
460                               hostname,
461                               G_RESOLVER_NAME_LOOKUP_FLAGS_DEFAULT,
462                               cancellable,
463                               error);
464 }
465
466 /**
467  * g_resolver_lookup_by_name_with_flags:
468  * @resolver: a #GResolver
469  * @hostname: the hostname to look up
470  * @flags: extra #GResolverNameLookupFlags for the lookup
471  * @cancellable: (nullable): a #GCancellable, or %NULL
472  * @error: (nullable): return location for a #GError, or %NULL
473  *
474  * This differs from g_resolver_lookup_by_name() in that you can modify
475  * the lookup behavior with @flags. For example this can be used to limit
476  * results with #G_RESOLVER_NAME_LOOKUP_FLAGS_IPV4_ONLY.
477  *
478  * Returns: (element-type GInetAddress) (transfer full): a non-empty #GList
479  * of #GInetAddress, or %NULL on error. You
480  * must unref each of the addresses and free the list when you are
481  * done with it. (You can use g_resolver_free_addresses() to do this.)
482  *
483  * Since: 2.60
484  */
485 GList *
486 g_resolver_lookup_by_name_with_flags (GResolver                 *resolver,
487                                       const gchar               *hostname,
488                                       GResolverNameLookupFlags   flags,
489                                       GCancellable              *cancellable,
490                                       GError                   **error)
491 {
492   return lookup_by_name_real (resolver,
493                               hostname,
494                               flags,
495                               cancellable,
496                               error);
497 }
498
499 static void
500 lookup_by_name_async_real (GResolver                *resolver,
501                            const gchar              *hostname,
502                            GResolverNameLookupFlags  flags,
503                            GCancellable             *cancellable,
504                            GAsyncReadyCallback       callback,
505                            gpointer                  user_data)
506 {
507   gchar *ascii_hostname = NULL;
508   GList *addrs;
509   GError *error = NULL;
510
511   g_return_if_fail (G_IS_RESOLVER (resolver));
512   g_return_if_fail (hostname != NULL);
513   g_return_if_fail (!(flags & G_RESOLVER_NAME_LOOKUP_FLAGS_IPV4_ONLY && flags & G_RESOLVER_NAME_LOOKUP_FLAGS_IPV6_ONLY));
514
515   /* Check if @hostname is just an IP address */
516   if (handle_ip_address (hostname, &addrs, &error))
517     {
518       GTask *task;
519
520       task = g_task_new (resolver, cancellable, callback, user_data);
521       g_task_set_source_tag (task, lookup_by_name_async_real);
522       if (addrs)
523         g_task_return_pointer (task, addrs, (GDestroyNotify) g_resolver_free_addresses);
524       else
525         g_task_return_error (task, error);
526       g_object_unref (task);
527       return;
528     }
529
530   if (g_hostname_is_non_ascii (hostname))
531     hostname = ascii_hostname = g_hostname_to_ascii (hostname);
532
533   if (!hostname)
534     {
535       GTask *task;
536
537       g_set_error_literal (&error, G_IO_ERROR, G_IO_ERROR_FAILED,
538                            _("Invalid hostname"));
539       task = g_task_new (resolver, cancellable, callback, user_data);
540       g_task_set_source_tag (task, lookup_by_name_async_real);
541       g_task_return_error (task, error);
542       g_object_unref (task);
543       return;
544     }
545
546   g_resolver_maybe_reload (resolver);
547
548   if (flags != G_RESOLVER_NAME_LOOKUP_FLAGS_DEFAULT)
549     {
550       if (G_RESOLVER_GET_CLASS (resolver)->lookup_by_name_with_flags_async == NULL)
551         {
552           GTask *task;
553
554           g_set_error (&error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
555                        /* Translators: The placeholder is for a function name. */
556                        _("%s not implemented"), "lookup_by_name_with_flags_async");
557           task = g_task_new (resolver, cancellable, callback, user_data);
558           g_task_set_source_tag (task, lookup_by_name_async_real);
559           g_task_return_error (task, error);
560           g_object_unref (task);
561         }
562       else
563         G_RESOLVER_GET_CLASS (resolver)->
564           lookup_by_name_with_flags_async (resolver, hostname, flags, cancellable, callback, user_data);
565     }
566   else
567     G_RESOLVER_GET_CLASS (resolver)->
568       lookup_by_name_async (resolver, hostname, cancellable, callback, user_data);
569
570   g_free (ascii_hostname);
571 }
572
573 static GList *
574 lookup_by_name_finish_real (GResolver     *resolver,
575                             GAsyncResult  *result,
576                             GError       **error,
577                             gboolean       with_flags)
578 {
579   GList *addrs;
580
581   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
582   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), NULL);
583   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
584
585   if (g_async_result_legacy_propagate_error (result, error))
586     return NULL;
587   else if (g_async_result_is_tagged (result, lookup_by_name_async_real))
588     {
589       /* Handle the stringified-IP-addr case */
590       return g_task_propagate_pointer (G_TASK (result), error);
591     }
592
593   if (with_flags)
594     {
595       g_assert (G_RESOLVER_GET_CLASS (resolver)->lookup_by_name_with_flags_finish != NULL);
596       addrs = G_RESOLVER_GET_CLASS (resolver)->
597         lookup_by_name_with_flags_finish (resolver, result, error);
598     }
599   else
600     addrs = G_RESOLVER_GET_CLASS (resolver)->
601       lookup_by_name_finish (resolver, result, error);
602
603   remove_duplicates (addrs);
604
605   return addrs;
606 }
607
608 /**
609  * g_resolver_lookup_by_name_with_flags_async:
610  * @resolver: a #GResolver
611  * @hostname: the hostname to look up the address of
612  * @flags: extra #GResolverNameLookupFlags for the lookup
613  * @cancellable: (nullable): a #GCancellable, or %NULL
614  * @callback: (scope async): callback to call after resolution completes
615  * @user_data: (closure): data for @callback
616  *
617  * Begins asynchronously resolving @hostname to determine its
618  * associated IP address(es), and eventually calls @callback, which
619  * must call g_resolver_lookup_by_name_with_flags_finish() to get the result.
620  * See g_resolver_lookup_by_name() for more details.
621  *
622  * Since: 2.60
623  */
624 void
625 g_resolver_lookup_by_name_with_flags_async (GResolver                *resolver,
626                                             const gchar              *hostname,
627                                             GResolverNameLookupFlags  flags,
628                                             GCancellable             *cancellable,
629                                             GAsyncReadyCallback       callback,
630                                             gpointer                  user_data)
631 {
632   lookup_by_name_async_real (resolver,
633                              hostname,
634                              flags,
635                              cancellable,
636                              callback,
637                              user_data);
638 }
639
640 /**
641  * g_resolver_lookup_by_name_async:
642  * @resolver: a #GResolver
643  * @hostname: the hostname to look up the address of
644  * @cancellable: (nullable): a #GCancellable, or %NULL
645  * @callback: (scope async): callback to call after resolution completes
646  * @user_data: (closure): data for @callback
647  *
648  * Begins asynchronously resolving @hostname to determine its
649  * associated IP address(es), and eventually calls @callback, which
650  * must call g_resolver_lookup_by_name_finish() to get the result.
651  * See g_resolver_lookup_by_name() for more details.
652  *
653  * Since: 2.22
654  */
655 void
656 g_resolver_lookup_by_name_async (GResolver           *resolver,
657                                  const gchar         *hostname,
658                                  GCancellable        *cancellable,
659                                  GAsyncReadyCallback  callback,
660                                  gpointer             user_data)
661 {
662   lookup_by_name_async_real (resolver,
663                              hostname,
664                              0,
665                              cancellable,
666                              callback,
667                              user_data);
668 }
669
670 /**
671  * g_resolver_lookup_by_name_finish:
672  * @resolver: a #GResolver
673  * @result: the result passed to your #GAsyncReadyCallback
674  * @error: return location for a #GError, or %NULL
675  *
676  * Retrieves the result of a call to
677  * g_resolver_lookup_by_name_async().
678  *
679  * If the DNS resolution failed, @error (if non-%NULL) will be set to
680  * a value from #GResolverError. If the operation was cancelled,
681  * @error will be set to %G_IO_ERROR_CANCELLED.
682  *
683  * Returns: (element-type GInetAddress) (transfer full): a #GList
684  * of #GInetAddress, or %NULL on error. See g_resolver_lookup_by_name()
685  * for more details.
686  *
687  * Since: 2.22
688  */
689 GList *
690 g_resolver_lookup_by_name_finish (GResolver     *resolver,
691                                   GAsyncResult  *result,
692                                   GError       **error)
693 {
694   return lookup_by_name_finish_real (resolver,
695                                      result,
696                                      error,
697                                      FALSE);
698 }
699
700 /**
701  * g_resolver_lookup_by_name_with_flags_finish:
702  * @resolver: a #GResolver
703  * @result: the result passed to your #GAsyncReadyCallback
704  * @error: return location for a #GError, or %NULL
705  *
706  * Retrieves the result of a call to
707  * g_resolver_lookup_by_name_with_flags_async().
708  *
709  * If the DNS resolution failed, @error (if non-%NULL) will be set to
710  * a value from #GResolverError. If the operation was cancelled,
711  * @error will be set to %G_IO_ERROR_CANCELLED.
712  *
713  * Returns: (element-type GInetAddress) (transfer full): a #GList
714  * of #GInetAddress, or %NULL on error. See g_resolver_lookup_by_name()
715  * for more details.
716  *
717  * Since: 2.60
718  */
719 GList *
720 g_resolver_lookup_by_name_with_flags_finish (GResolver     *resolver,
721                                              GAsyncResult  *result,
722                                              GError       **error)
723 {
724   return lookup_by_name_finish_real (resolver,
725                                      result,
726                                      error,
727                                      TRUE);
728 }
729
730 /**
731  * g_resolver_free_addresses: (skip)
732  * @addresses: a #GList of #GInetAddress
733  *
734  * Frees @addresses (which should be the return value from
735  * g_resolver_lookup_by_name() or g_resolver_lookup_by_name_finish()).
736  * (This is a convenience method; you can also simply free the results
737  * by hand.)
738  *
739  * Since: 2.22
740  */
741 void
742 g_resolver_free_addresses (GList *addresses)
743 {
744   GList *a;
745
746   for (a = addresses; a; a = a->next)
747     g_object_unref (a->data);
748   g_list_free (addresses);
749 }
750
751 /**
752  * g_resolver_lookup_by_address:
753  * @resolver: a #GResolver
754  * @address: the address to reverse-resolve
755  * @cancellable: (nullable): a #GCancellable, or %NULL
756  * @error: return location for a #GError, or %NULL
757  *
758  * Synchronously reverse-resolves @address to determine its
759  * associated hostname.
760  *
761  * If the DNS resolution fails, @error (if non-%NULL) will be set to
762  * a value from #GResolverError.
763  *
764  * If @cancellable is non-%NULL, it can be used to cancel the
765  * operation, in which case @error (if non-%NULL) will be set to
766  * %G_IO_ERROR_CANCELLED.
767  *
768  * Returns: a hostname (either ASCII-only, or in ASCII-encoded
769  *     form), or %NULL on error.
770  *
771  * Since: 2.22
772  */
773 gchar *
774 g_resolver_lookup_by_address (GResolver     *resolver,
775                               GInetAddress  *address,
776                               GCancellable  *cancellable,
777                               GError       **error)
778 {
779   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
780   g_return_val_if_fail (G_IS_INET_ADDRESS (address), NULL);
781
782   g_resolver_maybe_reload (resolver);
783   return G_RESOLVER_GET_CLASS (resolver)->
784     lookup_by_address (resolver, address, cancellable, error);
785 }
786
787 /**
788  * g_resolver_lookup_by_address_async:
789  * @resolver: a #GResolver
790  * @address: the address to reverse-resolve
791  * @cancellable: (nullable): a #GCancellable, or %NULL
792  * @callback: (scope async): callback to call after resolution completes
793  * @user_data: (closure): data for @callback
794  *
795  * Begins asynchronously reverse-resolving @address to determine its
796  * associated hostname, and eventually calls @callback, which must
797  * call g_resolver_lookup_by_address_finish() to get the final result.
798  *
799  * Since: 2.22
800  */
801 void
802 g_resolver_lookup_by_address_async (GResolver           *resolver,
803                                     GInetAddress        *address,
804                                     GCancellable        *cancellable,
805                                     GAsyncReadyCallback  callback,
806                                     gpointer             user_data)
807 {
808   g_return_if_fail (G_IS_RESOLVER (resolver));
809   g_return_if_fail (G_IS_INET_ADDRESS (address));
810
811   g_resolver_maybe_reload (resolver);
812   G_RESOLVER_GET_CLASS (resolver)->
813     lookup_by_address_async (resolver, address, cancellable, callback, user_data);
814 }
815
816 /**
817  * g_resolver_lookup_by_address_finish:
818  * @resolver: a #GResolver
819  * @result: the result passed to your #GAsyncReadyCallback
820  * @error: return location for a #GError, or %NULL
821  *
822  * Retrieves the result of a previous call to
823  * g_resolver_lookup_by_address_async().
824  *
825  * If the DNS resolution failed, @error (if non-%NULL) will be set to
826  * a value from #GResolverError. If the operation was cancelled,
827  * @error will be set to %G_IO_ERROR_CANCELLED.
828  *
829  * Returns: a hostname (either ASCII-only, or in ASCII-encoded
830  * form), or %NULL on error.
831  *
832  * Since: 2.22
833  */
834 gchar *
835 g_resolver_lookup_by_address_finish (GResolver     *resolver,
836                                      GAsyncResult  *result,
837                                      GError       **error)
838 {
839   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
840
841   if (g_async_result_legacy_propagate_error (result, error))
842     return NULL;
843
844   return G_RESOLVER_GET_CLASS (resolver)->
845     lookup_by_address_finish (resolver, result, error);
846 }
847
848 static gchar *
849 g_resolver_get_service_rrname (const char *service,
850                                const char *protocol,
851                                const char *domain)
852 {
853   gchar *rrname, *ascii_domain = NULL;
854
855   if (g_hostname_is_non_ascii (domain))
856     domain = ascii_domain = g_hostname_to_ascii (domain);
857   if (!domain)
858     return NULL;
859
860   rrname = g_strdup_printf ("_%s._%s.%s", service, protocol, domain);
861
862   g_free (ascii_domain);
863   return rrname;
864 }
865
866 /**
867  * g_resolver_lookup_service:
868  * @resolver: a #GResolver
869  * @service: the service type to look up (eg, "ldap")
870  * @protocol: the networking protocol to use for @service (eg, "tcp")
871  * @domain: the DNS domain to look up the service in
872  * @cancellable: (nullable): a #GCancellable, or %NULL
873  * @error: return location for a #GError, or %NULL
874  *
875  * Synchronously performs a DNS SRV lookup for the given @service and
876  * @protocol in the given @domain and returns an array of #GSrvTarget.
877  * @domain may be an ASCII-only or UTF-8 hostname. Note also that the
878  * @service and @protocol arguments do not include the leading underscore
879  * that appears in the actual DNS entry.
880  *
881  * On success, g_resolver_lookup_service() will return a non-empty #GList of
882  * #GSrvTarget, sorted in order of preference. (That is, you should
883  * attempt to connect to the first target first, then the second if
884  * the first fails, etc.)
885  *
886  * If the DNS resolution fails, @error (if non-%NULL) will be set to
887  * a value from #GResolverError and %NULL will be returned.
888  *
889  * If @cancellable is non-%NULL, it can be used to cancel the
890  * operation, in which case @error (if non-%NULL) will be set to
891  * %G_IO_ERROR_CANCELLED.
892  *
893  * If you are planning to connect to the service, it is usually easier
894  * to create a #GNetworkService and use its #GSocketConnectable
895  * interface.
896  *
897  * Returns: (element-type GSrvTarget) (transfer full): a non-empty #GList of
898  * #GSrvTarget, or %NULL on error. You must free each of the targets and the
899  * list when you are done with it. (You can use g_resolver_free_targets() to do
900  * this.)
901  *
902  * Since: 2.22
903  */
904 GList *
905 g_resolver_lookup_service (GResolver     *resolver,
906                            const gchar   *service,
907                            const gchar   *protocol,
908                            const gchar   *domain,
909                            GCancellable  *cancellable,
910                            GError       **error)
911 {
912   GList *targets;
913   gchar *rrname;
914
915   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
916   g_return_val_if_fail (service != NULL, NULL);
917   g_return_val_if_fail (protocol != NULL, NULL);
918   g_return_val_if_fail (domain != NULL, NULL);
919
920   rrname = g_resolver_get_service_rrname (service, protocol, domain);
921   if (!rrname)
922     {
923       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
924                            _("Invalid domain"));
925       return NULL;
926     }
927
928   g_resolver_maybe_reload (resolver);
929   targets = G_RESOLVER_GET_CLASS (resolver)->
930     lookup_service (resolver, rrname, cancellable, error);
931
932   g_free (rrname);
933   return targets;
934 }
935
936 /**
937  * g_resolver_lookup_service_async:
938  * @resolver: a #GResolver
939  * @service: the service type to look up (eg, "ldap")
940  * @protocol: the networking protocol to use for @service (eg, "tcp")
941  * @domain: the DNS domain to look up the service in
942  * @cancellable: (nullable): a #GCancellable, or %NULL
943  * @callback: (scope async): callback to call after resolution completes
944  * @user_data: (closure): data for @callback
945  *
946  * Begins asynchronously performing a DNS SRV lookup for the given
947  * @service and @protocol in the given @domain, and eventually calls
948  * @callback, which must call g_resolver_lookup_service_finish() to
949  * get the final result. See g_resolver_lookup_service() for more
950  * details.
951  *
952  * Since: 2.22
953  */
954 void
955 g_resolver_lookup_service_async (GResolver           *resolver,
956                                  const gchar         *service,
957                                  const gchar         *protocol,
958                                  const gchar         *domain,
959                                  GCancellable        *cancellable,
960                                  GAsyncReadyCallback  callback,
961                                  gpointer             user_data)
962 {
963   gchar *rrname;
964
965   g_return_if_fail (G_IS_RESOLVER (resolver));
966   g_return_if_fail (service != NULL);
967   g_return_if_fail (protocol != NULL);
968   g_return_if_fail (domain != NULL);
969
970   rrname = g_resolver_get_service_rrname (service, protocol, domain);
971   if (!rrname)
972     {
973       g_task_report_new_error (resolver, callback, user_data,
974                                g_resolver_lookup_service_async,
975                                G_IO_ERROR, G_IO_ERROR_FAILED,
976                                _("Invalid domain"));
977       return;
978     }
979
980   g_resolver_maybe_reload (resolver);
981   G_RESOLVER_GET_CLASS (resolver)->
982     lookup_service_async (resolver, rrname, cancellable, callback, user_data);
983
984   g_free (rrname);
985 }
986
987 /**
988  * g_resolver_lookup_service_finish:
989  * @resolver: a #GResolver
990  * @result: the result passed to your #GAsyncReadyCallback
991  * @error: return location for a #GError, or %NULL
992  *
993  * Retrieves the result of a previous call to
994  * g_resolver_lookup_service_async().
995  *
996  * If the DNS resolution failed, @error (if non-%NULL) will be set to
997  * a value from #GResolverError. If the operation was cancelled,
998  * @error will be set to %G_IO_ERROR_CANCELLED.
999  *
1000  * Returns: (element-type GSrvTarget) (transfer full): a non-empty #GList of
1001  * #GSrvTarget, or %NULL on error. See g_resolver_lookup_service() for more
1002  * details.
1003  *
1004  * Since: 2.22
1005  */
1006 GList *
1007 g_resolver_lookup_service_finish (GResolver     *resolver,
1008                                   GAsyncResult  *result,
1009                                   GError       **error)
1010 {
1011   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
1012
1013   if (g_async_result_legacy_propagate_error (result, error))
1014     return NULL;
1015
1016   return G_RESOLVER_GET_CLASS (resolver)->
1017     lookup_service_finish (resolver, result, error);
1018 }
1019
1020 /**
1021  * g_resolver_free_targets: (skip)
1022  * @targets: a #GList of #GSrvTarget
1023  *
1024  * Frees @targets (which should be the return value from
1025  * g_resolver_lookup_service() or g_resolver_lookup_service_finish()).
1026  * (This is a convenience method; you can also simply free the
1027  * results by hand.)
1028  *
1029  * Since: 2.22
1030  */
1031 void
1032 g_resolver_free_targets (GList *targets)
1033 {
1034   GList *t;
1035
1036   for (t = targets; t; t = t->next)
1037     g_srv_target_free (t->data);
1038   g_list_free (targets);
1039 }
1040
1041 /**
1042  * g_resolver_lookup_records:
1043  * @resolver: a #GResolver
1044  * @rrname: the DNS name to look up the record for
1045  * @record_type: the type of DNS record to look up
1046  * @cancellable: (nullable): a #GCancellable, or %NULL
1047  * @error: return location for a #GError, or %NULL
1048  *
1049  * Synchronously performs a DNS record lookup for the given @rrname and returns
1050  * a list of records as #GVariant tuples. See #GResolverRecordType for
1051  * information on what the records contain for each @record_type.
1052  *
1053  * If the DNS resolution fails, @error (if non-%NULL) will be set to
1054  * a value from #GResolverError and %NULL will be returned.
1055  *
1056  * If @cancellable is non-%NULL, it can be used to cancel the
1057  * operation, in which case @error (if non-%NULL) will be set to
1058  * %G_IO_ERROR_CANCELLED.
1059  *
1060  * Returns: (element-type GVariant) (transfer full): a non-empty #GList of
1061  * #GVariant, or %NULL on error. You must free each of the records and the list
1062  * when you are done with it. (You can use g_list_free_full() with
1063  * g_variant_unref() to do this.)
1064  *
1065  * Since: 2.34
1066  */
1067 GList *
1068 g_resolver_lookup_records (GResolver            *resolver,
1069                            const gchar          *rrname,
1070                            GResolverRecordType   record_type,
1071                            GCancellable         *cancellable,
1072                            GError              **error)
1073 {
1074   GList *records;
1075
1076   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
1077   g_return_val_if_fail (rrname != NULL, NULL);
1078
1079   g_resolver_maybe_reload (resolver);
1080   records = G_RESOLVER_GET_CLASS (resolver)->
1081     lookup_records (resolver, rrname, record_type, cancellable, error);
1082
1083   return records;
1084 }
1085
1086 /**
1087  * g_resolver_lookup_records_async:
1088  * @resolver: a #GResolver
1089  * @rrname: the DNS name to look up the record for
1090  * @record_type: the type of DNS record to look up
1091  * @cancellable: (nullable): a #GCancellable, or %NULL
1092  * @callback: (scope async): callback to call after resolution completes
1093  * @user_data: (closure): data for @callback
1094  *
1095  * Begins asynchronously performing a DNS lookup for the given
1096  * @rrname, and eventually calls @callback, which must call
1097  * g_resolver_lookup_records_finish() to get the final result. See
1098  * g_resolver_lookup_records() for more details.
1099  *
1100  * Since: 2.34
1101  */
1102 void
1103 g_resolver_lookup_records_async (GResolver           *resolver,
1104                                  const gchar         *rrname,
1105                                  GResolverRecordType  record_type,
1106                                  GCancellable        *cancellable,
1107                                  GAsyncReadyCallback  callback,
1108                                  gpointer             user_data)
1109 {
1110   g_return_if_fail (G_IS_RESOLVER (resolver));
1111   g_return_if_fail (rrname != NULL);
1112
1113   g_resolver_maybe_reload (resolver);
1114   G_RESOLVER_GET_CLASS (resolver)->
1115     lookup_records_async (resolver, rrname, record_type, cancellable, callback, user_data);
1116 }
1117
1118 /**
1119  * g_resolver_lookup_records_finish:
1120  * @resolver: a #GResolver
1121  * @result: the result passed to your #GAsyncReadyCallback
1122  * @error: return location for a #GError, or %NULL
1123  *
1124  * Retrieves the result of a previous call to
1125  * g_resolver_lookup_records_async(). Returns a non-empty list of records as
1126  * #GVariant tuples. See #GResolverRecordType for information on what the
1127  * records contain.
1128  *
1129  * If the DNS resolution failed, @error (if non-%NULL) will be set to
1130  * a value from #GResolverError. If the operation was cancelled,
1131  * @error will be set to %G_IO_ERROR_CANCELLED.
1132  *
1133  * Returns: (element-type GVariant) (transfer full): a non-empty #GList of
1134  * #GVariant, or %NULL on error. You must free each of the records and the list
1135  * when you are done with it. (You can use g_list_free_full() with
1136  * g_variant_unref() to do this.)
1137  *
1138  * Since: 2.34
1139  */
1140 GList *
1141 g_resolver_lookup_records_finish (GResolver     *resolver,
1142                                   GAsyncResult  *result,
1143                                   GError       **error)
1144 {
1145   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
1146   return G_RESOLVER_GET_CLASS (resolver)->
1147     lookup_records_finish (resolver, result, error);
1148 }
1149
1150 guint64
1151 g_resolver_get_serial (GResolver *resolver)
1152 {
1153   g_return_val_if_fail (G_IS_RESOLVER (resolver), 0);
1154
1155   g_resolver_maybe_reload (resolver);
1156
1157 #ifdef G_OS_UNIX
1158   return (guint64) resolver->priv->resolv_conf_timestamp;
1159 #else
1160   return 1;
1161 #endif
1162 }
1163
1164 /**
1165  * g_resolver_error_quark:
1166  *
1167  * Gets the #GResolver Error Quark.
1168  *
1169  * Returns: a #GQuark.
1170  *
1171  * Since: 2.22
1172  */
1173 G_DEFINE_QUARK (g-resolver-error-quark, g_resolver_error)