Imported Upstream version 2.59.0
[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       g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_NOT_FOUND,
344                    _("Error resolving “%s”: %s"),
345                    hostname, gai_strerror (EAI_NONAME));
346       return TRUE;
347     }
348
349   return FALSE;
350 }
351
352 static GList *
353 lookup_by_name_real (GResolver                 *resolver,
354                      const gchar               *hostname,
355                      GResolverNameLookupFlags   flags,
356                      GCancellable              *cancellable,
357                      GError                    **error)
358 {
359   GList *addrs;
360   gchar *ascii_hostname = NULL;
361
362   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
363   g_return_val_if_fail (hostname != NULL, NULL);
364   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL);
365   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
366
367   /* Check if @hostname is just an IP address */
368   if (handle_ip_address (hostname, &addrs, error))
369     return addrs;
370
371   if (g_hostname_is_non_ascii (hostname))
372     hostname = ascii_hostname = g_hostname_to_ascii (hostname);
373
374   if (!hostname)
375     {
376       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
377                            _("Invalid hostname"));
378       return NULL;
379     }
380
381   g_resolver_maybe_reload (resolver);
382
383   if (flags != G_RESOLVER_NAME_LOOKUP_FLAGS_DEFAULT)
384     {
385       if (!G_RESOLVER_GET_CLASS (resolver)->lookup_by_name_with_flags)
386         {
387           g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
388                        /* Translators: The placeholder is for a function name. */
389                        _("%s not implemented"), "lookup_by_name_with_flags");
390           g_free (ascii_hostname);
391           return NULL;
392         }
393       addrs = G_RESOLVER_GET_CLASS (resolver)->
394         lookup_by_name_with_flags (resolver, hostname, flags, cancellable, error);
395     }
396   else
397     addrs = G_RESOLVER_GET_CLASS (resolver)->
398       lookup_by_name (resolver, hostname, cancellable, error);
399
400   remove_duplicates (addrs);
401
402   g_free (ascii_hostname);
403   return addrs;
404 }
405
406 /**
407  * g_resolver_lookup_by_name:
408  * @resolver: a #GResolver
409  * @hostname: the hostname to look up
410  * @cancellable: (nullable): a #GCancellable, or %NULL
411  * @error: return location for a #GError, or %NULL
412  *
413  * Synchronously resolves @hostname to determine its associated IP
414  * address(es). @hostname may be an ASCII-only or UTF-8 hostname, or
415  * the textual form of an IP address (in which case this just becomes
416  * a wrapper around g_inet_address_new_from_string()).
417  *
418  * On success, g_resolver_lookup_by_name() will return a non-empty #GList of
419  * #GInetAddress, sorted in order of preference and guaranteed to not
420  * contain duplicates. That is, if using the result to connect to
421  * @hostname, you should attempt to connect to the first address
422  * first, then the second if the first fails, etc. If you are using
423  * the result to listen on a socket, it is appropriate to add each
424  * result using e.g. g_socket_listener_add_address().
425  *
426  * If the DNS resolution fails, @error (if non-%NULL) will be set to a
427  * value from #GResolverError and %NULL will be returned.
428  *
429  * If @cancellable is non-%NULL, it can be used to cancel the
430  * operation, in which case @error (if non-%NULL) will be set to
431  * %G_IO_ERROR_CANCELLED.
432  *
433  * If you are planning to connect to a socket on the resolved IP
434  * address, it may be easier to create a #GNetworkAddress and use its
435  * #GSocketConnectable interface.
436  *
437  * Returns: (element-type GInetAddress) (transfer full): a non-empty #GList
438  * of #GInetAddress, or %NULL on error. You
439  * must unref each of the addresses and free the list when you are
440  * done with it. (You can use g_resolver_free_addresses() to do this.)
441  *
442  * Since: 2.22
443  */
444 GList *
445 g_resolver_lookup_by_name (GResolver     *resolver,
446                            const gchar   *hostname,
447                            GCancellable  *cancellable,
448                            GError       **error)
449 {
450   return lookup_by_name_real (resolver,
451                               hostname,
452                               G_RESOLVER_NAME_LOOKUP_FLAGS_DEFAULT,
453                               cancellable,
454                               error);
455 }
456
457 /**
458  * g_resolver_lookup_by_name_with_flags:
459  * @resolver: a #GResolver
460  * @hostname: the hostname to look up
461  * @flags: extra #GResolverNameLookupFlags for the lookup
462  * @cancellable: (nullable): a #GCancellable, or %NULL
463  * @error: (nullable): return location for a #GError, or %NULL
464  *
465  * This differs from g_resolver_lookup_by_name() in that you can modify
466  * the lookup behavior with @flags. For example this can be used to limit
467  * results with #G_RESOLVER_NAME_LOOKUP_FLAGS_IPV4_ONLY.
468  *
469  * Returns: (element-type GInetAddress) (transfer full): a non-empty #GList
470  * of #GInetAddress, or %NULL on error. You
471  * must unref each of the addresses and free the list when you are
472  * done with it. (You can use g_resolver_free_addresses() to do this.)
473  *
474  * Since: 2.60
475  */
476 GList *
477 g_resolver_lookup_by_name_with_flags (GResolver                 *resolver,
478                                       const gchar               *hostname,
479                                       GResolverNameLookupFlags   flags,
480                                       GCancellable              *cancellable,
481                                       GError                   **error)
482 {
483   return lookup_by_name_real (resolver,
484                               hostname,
485                               flags,
486                               cancellable,
487                               error);
488 }
489
490 static void
491 lookup_by_name_async_real (GResolver                *resolver,
492                            const gchar              *hostname,
493                            GResolverNameLookupFlags  flags,
494                            GCancellable             *cancellable,
495                            GAsyncReadyCallback       callback,
496                            gpointer                  user_data)
497 {
498   gchar *ascii_hostname = NULL;
499   GList *addrs;
500   GError *error = NULL;
501
502   g_return_if_fail (G_IS_RESOLVER (resolver));
503   g_return_if_fail (hostname != NULL);
504   g_return_if_fail (!(flags & G_RESOLVER_NAME_LOOKUP_FLAGS_IPV4_ONLY && flags & G_RESOLVER_NAME_LOOKUP_FLAGS_IPV6_ONLY));
505
506   /* Check if @hostname is just an IP address */
507   if (handle_ip_address (hostname, &addrs, &error))
508     {
509       GTask *task;
510
511       task = g_task_new (resolver, cancellable, callback, user_data);
512       g_task_set_source_tag (task, lookup_by_name_async_real);
513       if (addrs)
514         g_task_return_pointer (task, addrs, (GDestroyNotify) g_resolver_free_addresses);
515       else
516         g_task_return_error (task, error);
517       g_object_unref (task);
518       return;
519     }
520
521   if (g_hostname_is_non_ascii (hostname))
522     hostname = ascii_hostname = g_hostname_to_ascii (hostname);
523
524   if (!hostname)
525     {
526       GTask *task;
527
528       g_set_error_literal (&error, G_IO_ERROR, G_IO_ERROR_FAILED,
529                            _("Invalid hostname"));
530       task = g_task_new (resolver, cancellable, callback, user_data);
531       g_task_set_source_tag (task, lookup_by_name_async_real);
532       g_task_return_error (task, error);
533       g_object_unref (task);
534       return;
535     }
536
537   g_resolver_maybe_reload (resolver);
538
539   if (flags != G_RESOLVER_NAME_LOOKUP_FLAGS_DEFAULT)
540     {
541       if (G_RESOLVER_GET_CLASS (resolver)->lookup_by_name_with_flags_async == NULL)
542         {
543           GTask *task;
544
545           g_set_error (&error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
546                        /* Translators: The placeholder is for a function name. */
547                        _("%s not implemented"), "lookup_by_name_with_flags_async");
548           task = g_task_new (resolver, cancellable, callback, user_data);
549           g_task_set_source_tag (task, lookup_by_name_async_real);
550           g_task_return_error (task, error);
551           g_object_unref (task);
552         }
553       else
554         G_RESOLVER_GET_CLASS (resolver)->
555           lookup_by_name_with_flags_async (resolver, hostname, flags, cancellable, callback, user_data);
556     }
557   else
558     G_RESOLVER_GET_CLASS (resolver)->
559       lookup_by_name_async (resolver, hostname, cancellable, callback, user_data);
560
561   g_free (ascii_hostname);
562 }
563
564 static GList *
565 lookup_by_name_finish_real (GResolver     *resolver,
566                             GAsyncResult  *result,
567                             GError       **error,
568                             gboolean       with_flags)
569 {
570   GList *addrs;
571
572   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
573   g_return_val_if_fail (G_IS_ASYNC_RESULT (result), NULL);
574   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
575
576   if (g_async_result_legacy_propagate_error (result, error))
577     return NULL;
578   else if (g_async_result_is_tagged (result, lookup_by_name_async_real))
579     {
580       /* Handle the stringified-IP-addr case */
581       return g_task_propagate_pointer (G_TASK (result), error);
582     }
583
584   if (with_flags)
585     {
586       g_assert (G_RESOLVER_GET_CLASS (resolver)->lookup_by_name_with_flags_finish != NULL);
587       addrs = G_RESOLVER_GET_CLASS (resolver)->
588         lookup_by_name_with_flags_finish (resolver, result, error);
589     }
590   else
591     addrs = G_RESOLVER_GET_CLASS (resolver)->
592       lookup_by_name_finish (resolver, result, error);
593
594   remove_duplicates (addrs);
595
596   return addrs;
597 }
598
599 /**
600  * g_resolver_lookup_by_name_with_flags_async:
601  * @resolver: a #GResolver
602  * @hostname: the hostname to look up the address of
603  * @flags: extra #GResolverNameLookupFlags for the lookup
604  * @cancellable: (nullable): a #GCancellable, or %NULL
605  * @callback: (scope async): callback to call after resolution completes
606  * @user_data: (closure): data for @callback
607  *
608  * Begins asynchronously resolving @hostname to determine its
609  * associated IP address(es), and eventually calls @callback, which
610  * must call g_resolver_lookup_by_name_with_flags_finish() to get the result.
611  * See g_resolver_lookup_by_name() for more details.
612  *
613  * Since: 2.60
614  */
615 void
616 g_resolver_lookup_by_name_with_flags_async (GResolver                *resolver,
617                                             const gchar              *hostname,
618                                             GResolverNameLookupFlags  flags,
619                                             GCancellable             *cancellable,
620                                             GAsyncReadyCallback       callback,
621                                             gpointer                  user_data)
622 {
623   lookup_by_name_async_real (resolver,
624                              hostname,
625                              flags,
626                              cancellable,
627                              callback,
628                              user_data);
629 }
630
631 /**
632  * g_resolver_lookup_by_name_async:
633  * @resolver: a #GResolver
634  * @hostname: the hostname to look up the address of
635  * @cancellable: (nullable): a #GCancellable, or %NULL
636  * @callback: (scope async): callback to call after resolution completes
637  * @user_data: (closure): data for @callback
638  *
639  * Begins asynchronously resolving @hostname to determine its
640  * associated IP address(es), and eventually calls @callback, which
641  * must call g_resolver_lookup_by_name_finish() to get the result.
642  * See g_resolver_lookup_by_name() for more details.
643  *
644  * Since: 2.22
645  */
646 void
647 g_resolver_lookup_by_name_async (GResolver           *resolver,
648                                  const gchar         *hostname,
649                                  GCancellable        *cancellable,
650                                  GAsyncReadyCallback  callback,
651                                  gpointer             user_data)
652 {
653   lookup_by_name_async_real (resolver,
654                              hostname,
655                              0,
656                              cancellable,
657                              callback,
658                              user_data);
659 }
660
661 /**
662  * g_resolver_lookup_by_name_finish:
663  * @resolver: a #GResolver
664  * @result: the result passed to your #GAsyncReadyCallback
665  * @error: return location for a #GError, or %NULL
666  *
667  * Retrieves the result of a call to
668  * g_resolver_lookup_by_name_async().
669  *
670  * If the DNS resolution failed, @error (if non-%NULL) will be set to
671  * a value from #GResolverError. If the operation was cancelled,
672  * @error will be set to %G_IO_ERROR_CANCELLED.
673  *
674  * Returns: (element-type GInetAddress) (transfer full): a #GList
675  * of #GInetAddress, or %NULL on error. See g_resolver_lookup_by_name()
676  * for more details.
677  *
678  * Since: 2.22
679  */
680 GList *
681 g_resolver_lookup_by_name_finish (GResolver     *resolver,
682                                   GAsyncResult  *result,
683                                   GError       **error)
684 {
685   return lookup_by_name_finish_real (resolver,
686                                      result,
687                                      error,
688                                      FALSE);
689 }
690
691 /**
692  * g_resolver_lookup_by_name_with_flags_finish:
693  * @resolver: a #GResolver
694  * @result: the result passed to your #GAsyncReadyCallback
695  * @error: return location for a #GError, or %NULL
696  *
697  * Retrieves the result of a call to
698  * g_resolver_lookup_by_name_with_flags_async().
699  *
700  * If the DNS resolution failed, @error (if non-%NULL) will be set to
701  * a value from #GResolverError. If the operation was cancelled,
702  * @error will be set to %G_IO_ERROR_CANCELLED.
703  *
704  * Returns: (element-type GInetAddress) (transfer full): a #GList
705  * of #GInetAddress, or %NULL on error. See g_resolver_lookup_by_name()
706  * for more details.
707  *
708  * Since: 2.60
709  */
710 GList *
711 g_resolver_lookup_by_name_with_flags_finish (GResolver     *resolver,
712                                              GAsyncResult  *result,
713                                              GError       **error)
714 {
715   return lookup_by_name_finish_real (resolver,
716                                      result,
717                                      error,
718                                      TRUE);
719 }
720
721 /**
722  * g_resolver_free_addresses: (skip)
723  * @addresses: a #GList of #GInetAddress
724  *
725  * Frees @addresses (which should be the return value from
726  * g_resolver_lookup_by_name() or g_resolver_lookup_by_name_finish()).
727  * (This is a convenience method; you can also simply free the results
728  * by hand.)
729  *
730  * Since: 2.22
731  */
732 void
733 g_resolver_free_addresses (GList *addresses)
734 {
735   GList *a;
736
737   for (a = addresses; a; a = a->next)
738     g_object_unref (a->data);
739   g_list_free (addresses);
740 }
741
742 /**
743  * g_resolver_lookup_by_address:
744  * @resolver: a #GResolver
745  * @address: the address to reverse-resolve
746  * @cancellable: (nullable): a #GCancellable, or %NULL
747  * @error: return location for a #GError, or %NULL
748  *
749  * Synchronously reverse-resolves @address to determine its
750  * associated hostname.
751  *
752  * If the DNS resolution fails, @error (if non-%NULL) will be set to
753  * a value from #GResolverError.
754  *
755  * If @cancellable is non-%NULL, it can be used to cancel the
756  * operation, in which case @error (if non-%NULL) will be set to
757  * %G_IO_ERROR_CANCELLED.
758  *
759  * Returns: a hostname (either ASCII-only, or in ASCII-encoded
760  *     form), or %NULL on error.
761  *
762  * Since: 2.22
763  */
764 gchar *
765 g_resolver_lookup_by_address (GResolver     *resolver,
766                               GInetAddress  *address,
767                               GCancellable  *cancellable,
768                               GError       **error)
769 {
770   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
771   g_return_val_if_fail (G_IS_INET_ADDRESS (address), NULL);
772
773   g_resolver_maybe_reload (resolver);
774   return G_RESOLVER_GET_CLASS (resolver)->
775     lookup_by_address (resolver, address, cancellable, error);
776 }
777
778 /**
779  * g_resolver_lookup_by_address_async:
780  * @resolver: a #GResolver
781  * @address: the address to reverse-resolve
782  * @cancellable: (nullable): a #GCancellable, or %NULL
783  * @callback: (scope async): callback to call after resolution completes
784  * @user_data: (closure): data for @callback
785  *
786  * Begins asynchronously reverse-resolving @address to determine its
787  * associated hostname, and eventually calls @callback, which must
788  * call g_resolver_lookup_by_address_finish() to get the final result.
789  *
790  * Since: 2.22
791  */
792 void
793 g_resolver_lookup_by_address_async (GResolver           *resolver,
794                                     GInetAddress        *address,
795                                     GCancellable        *cancellable,
796                                     GAsyncReadyCallback  callback,
797                                     gpointer             user_data)
798 {
799   g_return_if_fail (G_IS_RESOLVER (resolver));
800   g_return_if_fail (G_IS_INET_ADDRESS (address));
801
802   g_resolver_maybe_reload (resolver);
803   G_RESOLVER_GET_CLASS (resolver)->
804     lookup_by_address_async (resolver, address, cancellable, callback, user_data);
805 }
806
807 /**
808  * g_resolver_lookup_by_address_finish:
809  * @resolver: a #GResolver
810  * @result: the result passed to your #GAsyncReadyCallback
811  * @error: return location for a #GError, or %NULL
812  *
813  * Retrieves the result of a previous call to
814  * g_resolver_lookup_by_address_async().
815  *
816  * If the DNS resolution failed, @error (if non-%NULL) will be set to
817  * a value from #GResolverError. If the operation was cancelled,
818  * @error will be set to %G_IO_ERROR_CANCELLED.
819  *
820  * Returns: a hostname (either ASCII-only, or in ASCII-encoded
821  * form), or %NULL on error.
822  *
823  * Since: 2.22
824  */
825 gchar *
826 g_resolver_lookup_by_address_finish (GResolver     *resolver,
827                                      GAsyncResult  *result,
828                                      GError       **error)
829 {
830   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
831
832   if (g_async_result_legacy_propagate_error (result, error))
833     return NULL;
834
835   return G_RESOLVER_GET_CLASS (resolver)->
836     lookup_by_address_finish (resolver, result, error);
837 }
838
839 static gchar *
840 g_resolver_get_service_rrname (const char *service,
841                                const char *protocol,
842                                const char *domain)
843 {
844   gchar *rrname, *ascii_domain = NULL;
845
846   if (g_hostname_is_non_ascii (domain))
847     domain = ascii_domain = g_hostname_to_ascii (domain);
848   if (!domain)
849     return NULL;
850
851   rrname = g_strdup_printf ("_%s._%s.%s", service, protocol, domain);
852
853   g_free (ascii_domain);
854   return rrname;
855 }
856
857 /**
858  * g_resolver_lookup_service:
859  * @resolver: a #GResolver
860  * @service: the service type to look up (eg, "ldap")
861  * @protocol: the networking protocol to use for @service (eg, "tcp")
862  * @domain: the DNS domain to look up the service in
863  * @cancellable: (nullable): a #GCancellable, or %NULL
864  * @error: return location for a #GError, or %NULL
865  *
866  * Synchronously performs a DNS SRV lookup for the given @service and
867  * @protocol in the given @domain and returns an array of #GSrvTarget.
868  * @domain may be an ASCII-only or UTF-8 hostname. Note also that the
869  * @service and @protocol arguments do not include the leading underscore
870  * that appears in the actual DNS entry.
871  *
872  * On success, g_resolver_lookup_service() will return a non-empty #GList of
873  * #GSrvTarget, sorted in order of preference. (That is, you should
874  * attempt to connect to the first target first, then the second if
875  * the first fails, etc.)
876  *
877  * If the DNS resolution fails, @error (if non-%NULL) will be set to
878  * a value from #GResolverError and %NULL will be returned.
879  *
880  * If @cancellable is non-%NULL, it can be used to cancel the
881  * operation, in which case @error (if non-%NULL) will be set to
882  * %G_IO_ERROR_CANCELLED.
883  *
884  * If you are planning to connect to the service, it is usually easier
885  * to create a #GNetworkService and use its #GSocketConnectable
886  * interface.
887  *
888  * Returns: (element-type GSrvTarget) (transfer full): a non-empty #GList of
889  * #GSrvTarget, or %NULL on error. You must free each of the targets and the
890  * list when you are done with it. (You can use g_resolver_free_targets() to do
891  * this.)
892  *
893  * Since: 2.22
894  */
895 GList *
896 g_resolver_lookup_service (GResolver     *resolver,
897                            const gchar   *service,
898                            const gchar   *protocol,
899                            const gchar   *domain,
900                            GCancellable  *cancellable,
901                            GError       **error)
902 {
903   GList *targets;
904   gchar *rrname;
905
906   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
907   g_return_val_if_fail (service != NULL, NULL);
908   g_return_val_if_fail (protocol != NULL, NULL);
909   g_return_val_if_fail (domain != NULL, NULL);
910
911   rrname = g_resolver_get_service_rrname (service, protocol, domain);
912   if (!rrname)
913     {
914       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
915                            _("Invalid domain"));
916       return NULL;
917     }
918
919   g_resolver_maybe_reload (resolver);
920   targets = G_RESOLVER_GET_CLASS (resolver)->
921     lookup_service (resolver, rrname, cancellable, error);
922
923   g_free (rrname);
924   return targets;
925 }
926
927 /**
928  * g_resolver_lookup_service_async:
929  * @resolver: a #GResolver
930  * @service: the service type to look up (eg, "ldap")
931  * @protocol: the networking protocol to use for @service (eg, "tcp")
932  * @domain: the DNS domain to look up the service in
933  * @cancellable: (nullable): a #GCancellable, or %NULL
934  * @callback: (scope async): callback to call after resolution completes
935  * @user_data: (closure): data for @callback
936  *
937  * Begins asynchronously performing a DNS SRV lookup for the given
938  * @service and @protocol in the given @domain, and eventually calls
939  * @callback, which must call g_resolver_lookup_service_finish() to
940  * get the final result. See g_resolver_lookup_service() for more
941  * details.
942  *
943  * Since: 2.22
944  */
945 void
946 g_resolver_lookup_service_async (GResolver           *resolver,
947                                  const gchar         *service,
948                                  const gchar         *protocol,
949                                  const gchar         *domain,
950                                  GCancellable        *cancellable,
951                                  GAsyncReadyCallback  callback,
952                                  gpointer             user_data)
953 {
954   gchar *rrname;
955
956   g_return_if_fail (G_IS_RESOLVER (resolver));
957   g_return_if_fail (service != NULL);
958   g_return_if_fail (protocol != NULL);
959   g_return_if_fail (domain != NULL);
960
961   rrname = g_resolver_get_service_rrname (service, protocol, domain);
962   if (!rrname)
963     {
964       g_task_report_new_error (resolver, callback, user_data,
965                                g_resolver_lookup_service_async,
966                                G_IO_ERROR, G_IO_ERROR_FAILED,
967                                _("Invalid domain"));
968       return;
969     }
970
971   g_resolver_maybe_reload (resolver);
972   G_RESOLVER_GET_CLASS (resolver)->
973     lookup_service_async (resolver, rrname, cancellable, callback, user_data);
974
975   g_free (rrname);
976 }
977
978 /**
979  * g_resolver_lookup_service_finish:
980  * @resolver: a #GResolver
981  * @result: the result passed to your #GAsyncReadyCallback
982  * @error: return location for a #GError, or %NULL
983  *
984  * Retrieves the result of a previous call to
985  * g_resolver_lookup_service_async().
986  *
987  * If the DNS resolution failed, @error (if non-%NULL) will be set to
988  * a value from #GResolverError. If the operation was cancelled,
989  * @error will be set to %G_IO_ERROR_CANCELLED.
990  *
991  * Returns: (element-type GSrvTarget) (transfer full): a non-empty #GList of
992  * #GSrvTarget, or %NULL on error. See g_resolver_lookup_service() for more
993  * details.
994  *
995  * Since: 2.22
996  */
997 GList *
998 g_resolver_lookup_service_finish (GResolver     *resolver,
999                                   GAsyncResult  *result,
1000                                   GError       **error)
1001 {
1002   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
1003
1004   if (g_async_result_legacy_propagate_error (result, error))
1005     return NULL;
1006
1007   return G_RESOLVER_GET_CLASS (resolver)->
1008     lookup_service_finish (resolver, result, error);
1009 }
1010
1011 /**
1012  * g_resolver_free_targets: (skip)
1013  * @targets: a #GList of #GSrvTarget
1014  *
1015  * Frees @targets (which should be the return value from
1016  * g_resolver_lookup_service() or g_resolver_lookup_service_finish()).
1017  * (This is a convenience method; you can also simply free the
1018  * results by hand.)
1019  *
1020  * Since: 2.22
1021  */
1022 void
1023 g_resolver_free_targets (GList *targets)
1024 {
1025   GList *t;
1026
1027   for (t = targets; t; t = t->next)
1028     g_srv_target_free (t->data);
1029   g_list_free (targets);
1030 }
1031
1032 /**
1033  * g_resolver_lookup_records:
1034  * @resolver: a #GResolver
1035  * @rrname: the DNS name to lookup the record for
1036  * @record_type: the type of DNS record to lookup
1037  * @cancellable: (nullable): a #GCancellable, or %NULL
1038  * @error: return location for a #GError, or %NULL
1039  *
1040  * Synchronously performs a DNS record lookup for the given @rrname and returns
1041  * a list of records as #GVariant tuples. See #GResolverRecordType for
1042  * information on what the records contain for each @record_type.
1043  *
1044  * If the DNS resolution fails, @error (if non-%NULL) will be set to
1045  * a value from #GResolverError and %NULL will be returned.
1046  *
1047  * If @cancellable is non-%NULL, it can be used to cancel the
1048  * operation, in which case @error (if non-%NULL) will be set to
1049  * %G_IO_ERROR_CANCELLED.
1050  *
1051  * Returns: (element-type GVariant) (transfer full): a non-empty #GList of
1052  * #GVariant, or %NULL on error. You must free each of the records and the list
1053  * when you are done with it. (You can use g_list_free_full() with
1054  * g_variant_unref() to do this.)
1055  *
1056  * Since: 2.34
1057  */
1058 GList *
1059 g_resolver_lookup_records (GResolver            *resolver,
1060                            const gchar          *rrname,
1061                            GResolverRecordType   record_type,
1062                            GCancellable         *cancellable,
1063                            GError              **error)
1064 {
1065   GList *records;
1066
1067   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
1068   g_return_val_if_fail (rrname != NULL, NULL);
1069
1070   g_resolver_maybe_reload (resolver);
1071   records = G_RESOLVER_GET_CLASS (resolver)->
1072     lookup_records (resolver, rrname, record_type, cancellable, error);
1073
1074   return records;
1075 }
1076
1077 /**
1078  * g_resolver_lookup_records_async:
1079  * @resolver: a #GResolver
1080  * @rrname: the DNS name to lookup the record for
1081  * @record_type: the type of DNS record to lookup
1082  * @cancellable: (nullable): a #GCancellable, or %NULL
1083  * @callback: (scope async): callback to call after resolution completes
1084  * @user_data: (closure): data for @callback
1085  *
1086  * Begins asynchronously performing a DNS lookup for the given
1087  * @rrname, and eventually calls @callback, which must call
1088  * g_resolver_lookup_records_finish() to get the final result. See
1089  * g_resolver_lookup_records() for more details.
1090  *
1091  * Since: 2.34
1092  */
1093 void
1094 g_resolver_lookup_records_async (GResolver           *resolver,
1095                                  const gchar         *rrname,
1096                                  GResolverRecordType  record_type,
1097                                  GCancellable        *cancellable,
1098                                  GAsyncReadyCallback  callback,
1099                                  gpointer             user_data)
1100 {
1101   g_return_if_fail (G_IS_RESOLVER (resolver));
1102   g_return_if_fail (rrname != NULL);
1103
1104   g_resolver_maybe_reload (resolver);
1105   G_RESOLVER_GET_CLASS (resolver)->
1106     lookup_records_async (resolver, rrname, record_type, cancellable, callback, user_data);
1107 }
1108
1109 /**
1110  * g_resolver_lookup_records_finish:
1111  * @resolver: a #GResolver
1112  * @result: the result passed to your #GAsyncReadyCallback
1113  * @error: return location for a #GError, or %NULL
1114  *
1115  * Retrieves the result of a previous call to
1116  * g_resolver_lookup_records_async(). Returns a non-empty list of records as
1117  * #GVariant tuples. See #GResolverRecordType for information on what the
1118  * records contain.
1119  *
1120  * If the DNS resolution failed, @error (if non-%NULL) will be set to
1121  * a value from #GResolverError. If the operation was cancelled,
1122  * @error will be set to %G_IO_ERROR_CANCELLED.
1123  *
1124  * Returns: (element-type GVariant) (transfer full): a non-empty #GList of
1125  * #GVariant, or %NULL on error. You must free each of the records and the list
1126  * when you are done with it. (You can use g_list_free_full() with
1127  * g_variant_unref() to do this.)
1128  *
1129  * Since: 2.34
1130  */
1131 GList *
1132 g_resolver_lookup_records_finish (GResolver     *resolver,
1133                                   GAsyncResult  *result,
1134                                   GError       **error)
1135 {
1136   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
1137   return G_RESOLVER_GET_CLASS (resolver)->
1138     lookup_records_finish (resolver, result, error);
1139 }
1140
1141 guint64
1142 g_resolver_get_serial (GResolver *resolver)
1143 {
1144   g_return_val_if_fail (G_IS_RESOLVER (resolver), 0);
1145
1146   g_resolver_maybe_reload (resolver);
1147
1148 #ifdef G_OS_UNIX
1149   return (guint64) resolver->priv->resolv_conf_timestamp;
1150 #else
1151   return 1;
1152 #endif
1153 }
1154
1155 /**
1156  * g_resolver_error_quark:
1157  *
1158  * Gets the #GResolver Error Quark.
1159  *
1160  * Returns: a #GQuark.
1161  *
1162  * Since: 2.22
1163  */
1164 G_DEFINE_QUARK (g-resolver-error-quark, g_resolver_error)