Clean up includes
[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 void
82 g_resolver_class_init (GResolverClass *resolver_class)
83 {
84   volatile GType type;
85
86   g_type_class_add_private (resolver_class, sizeof (GResolverPrivate));
87
88   /* Make sure _g_networking_init() has been called */
89   type = g_inet_address_get_type ();
90   (type); /* To avoid -Wunused-but-set-variable */
91
92   /* Initialize _g_resolver_addrinfo_hints */
93 #ifdef AI_ADDRCONFIG
94   _g_resolver_addrinfo_hints.ai_flags |= AI_ADDRCONFIG;
95 #endif
96   /* These two don't actually matter, they just get copied into the
97    * returned addrinfo structures (and then we ignore them). But if
98    * we leave them unset, we'll get back duplicate answers.
99    */
100   _g_resolver_addrinfo_hints.ai_socktype = SOCK_STREAM;
101   _g_resolver_addrinfo_hints.ai_protocol = IPPROTO_TCP;
102
103   /**
104    * GResolver::reload:
105    * @resolver: a #GResolver
106    *
107    * Emitted when the resolver notices that the system resolver
108    * configuration has changed.
109    **/
110   signals[RELOAD] =
111     g_signal_new (I_("reload"),
112                   G_TYPE_RESOLVER,
113                   G_SIGNAL_RUN_LAST,
114                   G_STRUCT_OFFSET (GResolverClass, reload),
115                   NULL, NULL,
116                   g_cclosure_marshal_VOID__VOID,
117                   G_TYPE_NONE, 0);
118 }
119
120 static void
121 g_resolver_init (GResolver *resolver)
122 {
123 #ifdef G_OS_UNIX
124   struct stat st;
125 #endif
126
127   resolver->priv = G_TYPE_INSTANCE_GET_PRIVATE (resolver, G_TYPE_RESOLVER, GResolverPrivate);
128
129 #ifdef G_OS_UNIX
130   if (stat (_PATH_RESCONF, &st) == 0)
131     resolver->priv->resolv_conf_timestamp = st.st_mtime;
132 #endif
133 }
134
135 static GResolver *default_resolver;
136
137 /**
138  * g_resolver_get_default:
139  *
140  * Gets the default #GResolver. You should unref it when you are done
141  * with it. #GResolver may use its reference count as a hint about how
142  * many threads/processes, etc it should allocate for concurrent DNS
143  * resolutions.
144  *
145  * Return value: (transfer full): the default #GResolver.
146  *
147  * Since: 2.22
148  */
149 GResolver *
150 g_resolver_get_default (void)
151 {
152   if (!default_resolver)
153     default_resolver = g_object_new (G_TYPE_THREADED_RESOLVER, NULL);
154
155   return g_object_ref (default_resolver);
156 }
157
158 /**
159  * g_resolver_set_default:
160  * @resolver: the new default #GResolver
161  *
162  * Sets @resolver to be the application's default resolver (reffing
163  * @resolver, and unreffing the previous default resolver, if any).
164  * Future calls to g_resolver_get_default() will return this resolver.
165  *
166  * This can be used if an application wants to perform any sort of DNS
167  * caching or "pinning"; it can implement its own #GResolver that
168  * calls the original default resolver for DNS operations, and
169  * implements its own cache policies on top of that, and then set
170  * itself as the default resolver for all later code to use.
171  *
172  * Since: 2.22
173  */
174 void
175 g_resolver_set_default (GResolver *resolver)
176 {
177   if (default_resolver)
178     g_object_unref (default_resolver);
179   default_resolver = g_object_ref (resolver);
180 }
181
182
183 static void
184 g_resolver_maybe_reload (GResolver *resolver)
185 {
186 #ifdef G_OS_UNIX
187   struct stat st;
188
189   if (stat (_PATH_RESCONF, &st) == 0)
190     {
191       if (st.st_mtime != resolver->priv->resolv_conf_timestamp)
192         {
193           resolver->priv->resolv_conf_timestamp = st.st_mtime;
194           res_init ();
195           g_signal_emit (resolver, signals[RELOAD], 0);
196         }
197     }
198 #endif
199 }
200
201 /* filter out duplicates, cf. https://bugzilla.gnome.org/show_bug.cgi?id=631379 */
202 static void
203 remove_duplicates (GList *addrs)
204 {
205   GList *l;
206   GList *ll;
207   GList *lll;
208
209   /* TODO: if this is too slow (it's O(n^2) but n is typically really
210    * small), we can do something more clever but note that we must not
211    * change the order of elements...
212    */
213   for (l = addrs; l != NULL; l = l->next)
214     {
215       GInetAddress *address = G_INET_ADDRESS (l->data);
216       for (ll = l->next; ll != NULL; ll = lll)
217         {
218           GInetAddress *other_address = G_INET_ADDRESS (ll->data);
219           lll = ll->next;
220           if (g_inet_address_equal (address, other_address))
221             {
222               g_object_unref (other_address);
223               /* we never return the first element */
224               g_warn_if_fail (g_list_delete_link (addrs, ll) == addrs);
225             }
226         }
227     }
228 }
229
230
231 /**
232  * g_resolver_lookup_by_name:
233  * @resolver: a #GResolver
234  * @hostname: the hostname to look up
235  * @cancellable: (allow-none): a #GCancellable, or %NULL
236  * @error: return location for a #GError, or %NULL
237  *
238  * Synchronously resolves @hostname to determine its associated IP
239  * address(es). @hostname may be an ASCII-only or UTF-8 hostname, or
240  * the textual form of an IP address (in which case this just becomes
241  * a wrapper around g_inet_address_new_from_string()).
242  *
243  * On success, g_resolver_lookup_by_name() will return a #GList of
244  * #GInetAddress, sorted in order of preference and guaranteed to not
245  * contain duplicates. That is, if using the result to connect to
246  * @hostname, you should attempt to connect to the first address
247  * first, then the second if the first fails, etc. If you are using
248  * the result to listen on a socket, it is appropriate to add each
249  * result using e.g. g_socket_listener_add_address().
250  *
251  * If the DNS resolution fails, @error (if non-%NULL) will be set to a
252  * value from #GResolverError.
253  *
254  * If @cancellable is non-%NULL, it can be used to cancel the
255  * operation, in which case @error (if non-%NULL) will be set to
256  * %G_IO_ERROR_CANCELLED.
257  *
258  * If you are planning to connect to a socket on the resolved IP
259  * address, it may be easier to create a #GNetworkAddress and use its
260  * #GSocketConnectable interface.
261  *
262  * Return value: (element-type GInetAddress) (transfer full): a #GList
263  * of #GInetAddress, or %NULL on error. You
264  * must unref each of the addresses and free the list when you are
265  * done with it. (You can use g_resolver_free_addresses() to do this.)
266  *
267  * Since: 2.22
268  */
269 GList *
270 g_resolver_lookup_by_name (GResolver     *resolver,
271                            const gchar   *hostname,
272                            GCancellable  *cancellable,
273                            GError       **error)
274 {
275   GInetAddress *addr;
276   GList *addrs;
277   gchar *ascii_hostname = NULL;
278
279   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
280   g_return_val_if_fail (hostname != NULL, NULL);
281
282   /* Check if @hostname is just an IP address */
283   addr = g_inet_address_new_from_string (hostname);
284   if (addr)
285     return g_list_append (NULL, addr);
286
287   if (g_hostname_is_non_ascii (hostname))
288     hostname = ascii_hostname = g_hostname_to_ascii (hostname);
289
290   g_resolver_maybe_reload (resolver);
291   addrs = G_RESOLVER_GET_CLASS (resolver)->
292     lookup_by_name (resolver, hostname, cancellable, error);
293
294   remove_duplicates (addrs);
295
296   g_free (ascii_hostname);
297   return addrs;
298 }
299
300 /**
301  * g_resolver_lookup_by_name_async:
302  * @resolver: a #GResolver
303  * @hostname: the hostname to look up the address of
304  * @cancellable: (allow-none): a #GCancellable, or %NULL
305  * @callback: (scope async): callback to call after resolution completes
306  * @user_data: (closure): data for @callback
307  *
308  * Begins asynchronously resolving @hostname to determine its
309  * associated IP address(es), and eventually calls @callback, which
310  * must call g_resolver_lookup_by_name_finish() to get the result.
311  * See g_resolver_lookup_by_name() for more details.
312  *
313  * Since: 2.22
314  */
315 void
316 g_resolver_lookup_by_name_async (GResolver           *resolver,
317                                  const gchar         *hostname,
318                                  GCancellable        *cancellable,
319                                  GAsyncReadyCallback  callback,
320                                  gpointer             user_data)
321 {
322   GInetAddress *addr;
323   gchar *ascii_hostname = NULL;
324
325   g_return_if_fail (G_IS_RESOLVER (resolver));
326   g_return_if_fail (hostname != NULL);
327
328   /* Check if @hostname is just an IP address */
329   addr = g_inet_address_new_from_string (hostname);
330   if (addr)
331     {
332       GSimpleAsyncResult *simple;
333
334       simple = g_simple_async_result_new (G_OBJECT (resolver),
335                                           callback, user_data,
336                                           g_resolver_lookup_by_name_async);
337
338       g_simple_async_result_set_op_res_gpointer (simple, addr, g_object_unref);
339       g_simple_async_result_complete_in_idle (simple);
340       g_object_unref (simple);
341       return;
342     }
343
344   if (g_hostname_is_non_ascii (hostname))
345     hostname = ascii_hostname = g_hostname_to_ascii (hostname);
346
347   g_resolver_maybe_reload (resolver);
348   G_RESOLVER_GET_CLASS (resolver)->
349     lookup_by_name_async (resolver, hostname, cancellable, callback, user_data);
350
351   g_free (ascii_hostname);
352 }
353
354 /**
355  * g_resolver_lookup_by_name_finish:
356  * @resolver: a #GResolver
357  * @result: the result passed to your #GAsyncReadyCallback
358  * @error: return location for a #GError, or %NULL
359  *
360  * Retrieves the result of a call to
361  * g_resolver_lookup_by_name_async().
362  *
363  * If the DNS resolution failed, @error (if non-%NULL) will be set to
364  * a value from #GResolverError. If the operation was cancelled,
365  * @error will be set to %G_IO_ERROR_CANCELLED.
366  *
367  * Return value: (element-type GInetAddress) (transfer full): a #GList
368  * of #GInetAddress, or %NULL on error. See g_resolver_lookup_by_name()
369  * for more details.
370  *
371  * Since: 2.22
372  */
373 GList *
374 g_resolver_lookup_by_name_finish (GResolver     *resolver,
375                                   GAsyncResult  *result,
376                                   GError       **error)
377 {
378   GList *addrs;
379
380   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
381
382   if (G_IS_SIMPLE_ASYNC_RESULT (result))
383     {
384       GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
385
386       if (g_simple_async_result_propagate_error (simple, error))
387         return NULL;
388
389       /* Handle the stringified-IP-addr case */
390       if (g_simple_async_result_get_source_tag (simple) == g_resolver_lookup_by_name_async)
391         {
392           GInetAddress *addr;
393
394           addr = g_simple_async_result_get_op_res_gpointer (simple);
395           return g_list_append (NULL, g_object_ref (addr));
396         }
397     }
398
399   addrs = G_RESOLVER_GET_CLASS (resolver)->
400     lookup_by_name_finish (resolver, result, error);
401
402   remove_duplicates (addrs);
403
404   return addrs;
405 }
406
407 /**
408  * g_resolver_free_addresses: (skip)
409  * @addresses: a #GList of #GInetAddress
410  *
411  * Frees @addresses (which should be the return value from
412  * g_resolver_lookup_by_name() or g_resolver_lookup_by_name_finish()).
413  * (This is a convenience method; you can also simply free the results
414  * by hand.)
415  *
416  * Since: 2.22
417  */
418 void
419 g_resolver_free_addresses (GList *addresses)
420 {
421   GList *a;
422
423   for (a = addresses; a; a = a->next)
424     g_object_unref (a->data);
425   g_list_free (addresses);
426 }
427
428 /**
429  * g_resolver_lookup_by_address:
430  * @resolver: a #GResolver
431  * @address: the address to reverse-resolve
432  * @cancellable: (allow-none): a #GCancellable, or %NULL
433  * @error: return location for a #GError, or %NULL
434  *
435  * Synchronously reverse-resolves @address to determine its
436  * associated hostname.
437  *
438  * If the DNS resolution fails, @error (if non-%NULL) will be set to
439  * a value from #GResolverError.
440  *
441  * If @cancellable is non-%NULL, it can be used to cancel the
442  * operation, in which case @error (if non-%NULL) will be set to
443  * %G_IO_ERROR_CANCELLED.
444  *
445  * Return value: a hostname (either ASCII-only, or in ASCII-encoded
446  *     form), or %NULL on error.
447  *
448  * Since: 2.22
449  */
450 gchar *
451 g_resolver_lookup_by_address (GResolver     *resolver,
452                               GInetAddress  *address,
453                               GCancellable  *cancellable,
454                               GError       **error)
455 {
456   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
457   g_return_val_if_fail (G_IS_INET_ADDRESS (address), NULL);
458
459   g_resolver_maybe_reload (resolver);
460   return G_RESOLVER_GET_CLASS (resolver)->
461     lookup_by_address (resolver, address, cancellable, error);
462 }
463
464 /**
465  * g_resolver_lookup_by_address_async:
466  * @resolver: a #GResolver
467  * @address: the address to reverse-resolve
468  * @cancellable: (allow-none): a #GCancellable, or %NULL
469  * @callback: (scope async): callback to call after resolution completes
470  * @user_data: (closure): data for @callback
471  *
472  * Begins asynchronously reverse-resolving @address to determine its
473  * associated hostname, and eventually calls @callback, which must
474  * call g_resolver_lookup_by_address_finish() to get the final result.
475  *
476  * Since: 2.22
477  */
478 void
479 g_resolver_lookup_by_address_async (GResolver           *resolver,
480                                     GInetAddress        *address,
481                                     GCancellable        *cancellable,
482                                     GAsyncReadyCallback  callback,
483                                     gpointer             user_data)
484 {
485   g_return_if_fail (G_IS_RESOLVER (resolver));
486   g_return_if_fail (G_IS_INET_ADDRESS (address));
487
488   g_resolver_maybe_reload (resolver);
489   G_RESOLVER_GET_CLASS (resolver)->
490     lookup_by_address_async (resolver, address, cancellable, callback, user_data);
491 }
492
493 /**
494  * g_resolver_lookup_by_address_finish:
495  * @resolver: a #GResolver
496  * @result: the result passed to your #GAsyncReadyCallback
497  * @error: return location for a #GError, or %NULL
498  *
499  * Retrieves the result of a previous call to
500  * g_resolver_lookup_by_address_async().
501  *
502  * If the DNS resolution failed, @error (if non-%NULL) will be set to
503  * a value from #GResolverError. If the operation was cancelled,
504  * @error will be set to %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_finish (GResolver     *resolver,
513                                      GAsyncResult  *result,
514                                      GError       **error)
515 {
516   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
517
518   if (G_IS_SIMPLE_ASYNC_RESULT (result))
519     {
520       GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
521
522       if (g_simple_async_result_propagate_error (simple, error))
523         return NULL;
524     }
525
526   return G_RESOLVER_GET_CLASS (resolver)->
527     lookup_by_address_finish (resolver, result, error);
528 }
529
530 static gchar *
531 g_resolver_get_service_rrname (const char *service,
532                                const char *protocol,
533                                const char *domain)
534 {
535   gchar *rrname, *ascii_domain = NULL;
536
537   if (g_hostname_is_non_ascii (domain))
538     domain = ascii_domain = g_hostname_to_ascii (domain);
539
540   rrname = g_strdup_printf ("_%s._%s.%s", service, protocol, domain);
541
542   g_free (ascii_domain);
543   return rrname;
544 }
545
546 /**
547  * g_resolver_lookup_service:
548  * @resolver: a #GResolver
549  * @service: the service type to look up (eg, "ldap")
550  * @protocol: the networking protocol to use for @service (eg, "tcp")
551  * @domain: the DNS domain to look up the service in
552  * @cancellable: (allow-none): a #GCancellable, or %NULL
553  * @error: return location for a #GError, or %NULL
554  *
555  * Synchronously performs a DNS SRV lookup for the given @service and
556  * @protocol in the given @domain and returns an array of #GSrvTarget.
557  * @domain may be an ASCII-only or UTF-8 hostname. Note also that the
558  * @service and @protocol arguments <emphasis>do not</emphasis>
559  * include the leading underscore that appears in the actual DNS
560  * entry.
561  *
562  * On success, g_resolver_lookup_service() will return a #GList of
563  * #GSrvTarget, sorted in order of preference. (That is, you should
564  * attempt to connect to the first target first, then the second if
565  * the first fails, etc.)
566  *
567  * If the DNS resolution fails, @error (if non-%NULL) will be set to
568  * a value from #GResolverError.
569  *
570  * If @cancellable is non-%NULL, it can be used to cancel the
571  * operation, in which case @error (if non-%NULL) will be set to
572  * %G_IO_ERROR_CANCELLED.
573  *
574  * If you are planning to connect to the service, it is usually easier
575  * to create a #GNetworkService and use its #GSocketConnectable
576  * interface.
577  *
578  * Return value: (element-type GSrvTarget) (transfer full): a #GList of #GSrvTarget,
579  * or %NULL on error. You must free each of the targets and the list when you are
580  * done with it. (You can use g_resolver_free_targets() to do this.)
581  *
582  * Since: 2.22
583  */
584 GList *
585 g_resolver_lookup_service (GResolver     *resolver,
586                            const gchar   *service,
587                            const gchar   *protocol,
588                            const gchar   *domain,
589                            GCancellable  *cancellable,
590                            GError       **error)
591 {
592   GList *targets;
593   gchar *rrname;
594
595   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
596   g_return_val_if_fail (service != NULL, NULL);
597   g_return_val_if_fail (protocol != NULL, NULL);
598   g_return_val_if_fail (domain != NULL, NULL);
599
600   rrname = g_resolver_get_service_rrname (service, protocol, domain);
601
602   g_resolver_maybe_reload (resolver);
603   targets = G_RESOLVER_GET_CLASS (resolver)->
604     lookup_service (resolver, rrname, cancellable, error);
605
606   g_free (rrname);
607   return targets;
608 }
609
610 /**
611  * g_resolver_lookup_service_async:
612  * @resolver: a #GResolver
613  * @service: the service type to look up (eg, "ldap")
614  * @protocol: the networking protocol to use for @service (eg, "tcp")
615  * @domain: the DNS domain to look up the service in
616  * @cancellable: (allow-none): a #GCancellable, or %NULL
617  * @callback: (scope async): callback to call after resolution completes
618  * @user_data: (closure): data for @callback
619  *
620  * Begins asynchronously performing a DNS SRV lookup for the given
621  * @service and @protocol in the given @domain, and eventually calls
622  * @callback, which must call g_resolver_lookup_service_finish() to
623  * get the final result. See g_resolver_lookup_service() for more
624  * details.
625  *
626  * Since: 2.22
627  */
628 void
629 g_resolver_lookup_service_async (GResolver           *resolver,
630                                  const gchar         *service,
631                                  const gchar         *protocol,
632                                  const gchar         *domain,
633                                  GCancellable        *cancellable,
634                                  GAsyncReadyCallback  callback,
635                                  gpointer             user_data)
636 {
637   gchar *rrname;
638
639   g_return_if_fail (G_IS_RESOLVER (resolver));
640   g_return_if_fail (service != NULL);
641   g_return_if_fail (protocol != NULL);
642   g_return_if_fail (domain != NULL);
643
644   rrname = g_resolver_get_service_rrname (service, protocol, domain);
645
646   g_resolver_maybe_reload (resolver);
647   G_RESOLVER_GET_CLASS (resolver)->
648     lookup_service_async (resolver, rrname, cancellable, callback, user_data);
649
650   g_free (rrname);
651 }
652
653 /**
654  * g_resolver_lookup_service_finish:
655  * @resolver: a #GResolver
656  * @result: the result passed to your #GAsyncReadyCallback
657  * @error: return location for a #GError, or %NULL
658  *
659  * Retrieves the result of a previous call to
660  * g_resolver_lookup_service_async().
661  *
662  * If the DNS resolution failed, @error (if non-%NULL) will be set to
663  * a value from #GResolverError. If the operation was cancelled,
664  * @error will be set to %G_IO_ERROR_CANCELLED.
665  *
666  * Return value: (element-type GSrvTarget) (transfer full): a #GList of #GSrvTarget,
667  * or %NULL on error. See g_resolver_lookup_service() for more details.
668  *
669  * Since: 2.22
670  */
671 GList *
672 g_resolver_lookup_service_finish (GResolver     *resolver,
673                                   GAsyncResult  *result,
674                                   GError       **error)
675 {
676   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
677
678   if (G_IS_SIMPLE_ASYNC_RESULT (result))
679     {
680       GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
681
682       if (g_simple_async_result_propagate_error (simple, error))
683         return NULL;
684     }
685
686   return G_RESOLVER_GET_CLASS (resolver)->
687     lookup_service_finish (resolver, result, error);
688 }
689
690 /**
691  * g_resolver_free_targets: (skip)
692  * @targets: a #GList of #GSrvTarget
693  *
694  * Frees @targets (which should be the return value from
695  * g_resolver_lookup_service() or g_resolver_lookup_service_finish()).
696  * (This is a convenience method; you can also simply free the
697  * results by hand.)
698  *
699  * Since: 2.22
700  */
701 void
702 g_resolver_free_targets (GList *targets)
703 {
704   GList *t;
705
706   for (t = targets; t; t = t->next)
707     g_srv_target_free (t->data);
708   g_list_free (targets);
709 }
710
711 /**
712  * g_resolver_error_quark:
713  *
714  * Gets the #GResolver Error Quark.
715  *
716  * Return value: a #GQuark.
717  *
718  * Since: 2.22
719  */
720 GQuark
721 g_resolver_error_quark (void)
722 {
723   return g_quark_from_static_string ("g-resolver-error-quark");
724 }
725
726
727 static GResolverError
728 g_resolver_error_from_addrinfo_error (gint err)
729 {
730   switch (err)
731     {
732     case EAI_FAIL:
733 #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
734     case EAI_NODATA:
735 #endif
736     case EAI_NONAME:
737       return G_RESOLVER_ERROR_NOT_FOUND;
738
739     case EAI_AGAIN:
740       return G_RESOLVER_ERROR_TEMPORARY_FAILURE;
741
742     default:
743       return G_RESOLVER_ERROR_INTERNAL;
744     }
745 }
746
747 struct addrinfo _g_resolver_addrinfo_hints;
748
749 /* Private method to process a getaddrinfo() response. */
750 GList *
751 _g_resolver_addresses_from_addrinfo (const char       *hostname,
752                                      struct addrinfo  *res,
753                                      gint              gai_retval,
754                                      GError          **error)
755 {
756   struct addrinfo *ai;
757   GSocketAddress *sockaddr;
758   GInetAddress *addr;
759   GList *addrs;
760
761   if (gai_retval != 0)
762     {
763       g_set_error (error, G_RESOLVER_ERROR,
764                    g_resolver_error_from_addrinfo_error (gai_retval),
765                    _("Error resolving '%s': %s"),
766                    hostname, gai_strerror (gai_retval));
767       return NULL;
768     }
769
770   g_return_val_if_fail (res != NULL, NULL);
771
772   addrs = NULL;
773   for (ai = res; ai; ai = ai->ai_next)
774     {
775       sockaddr = g_socket_address_new_from_native (ai->ai_addr, ai->ai_addrlen);
776       if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
777         continue;
778
779       addr = g_object_ref (g_inet_socket_address_get_address ((GInetSocketAddress *)sockaddr));
780       addrs = g_list_prepend (addrs, addr);
781       g_object_unref (sockaddr);
782     }
783
784   return g_list_reverse (addrs);
785 }
786
787 /* Private method to set up a getnameinfo() request */
788 void
789 _g_resolver_address_to_sockaddr (GInetAddress            *address,
790                                  struct sockaddr_storage *sa,
791                                  gsize                   *len)
792 {
793   GSocketAddress *sockaddr;
794
795   sockaddr = g_inet_socket_address_new (address, 0);
796   g_socket_address_to_native (sockaddr, (struct sockaddr *)sa, sizeof (*sa), NULL);
797   *len = g_socket_address_get_native_size (sockaddr);
798   g_object_unref (sockaddr);
799 }
800
801 /* Private method to process a getnameinfo() response. */
802 char *
803 _g_resolver_name_from_nameinfo (GInetAddress  *address,
804                                 const gchar   *name,
805                                 gint           gni_retval,
806                                 GError       **error)
807 {
808   if (gni_retval != 0)
809     {
810       gchar *phys;
811
812       phys = g_inet_address_to_string (address);
813       g_set_error (error, G_RESOLVER_ERROR,
814                    g_resolver_error_from_addrinfo_error (gni_retval),
815                    _("Error reverse-resolving '%s': %s"),
816                    phys ? phys : "(unknown)", gai_strerror (gni_retval));
817       g_free (phys);
818       return NULL;
819     }
820
821   return g_strdup (name);
822 }
823
824 #if defined(G_OS_UNIX)
825 /* Private method to process a res_query response into GSrvTargets */
826 GList *
827 _g_resolver_targets_from_res_query (const gchar      *rrname,
828                                     guchar           *answer,
829                                     gint              len,
830                                     gint              herr,
831                                     GError          **error)
832 {
833   gint count;
834   gchar namebuf[1024];
835   guchar *end, *p;
836   guint16 type, qclass, rdlength, priority, weight, port;
837   guint32 ttl;
838   HEADER *header;
839   GSrvTarget *target;
840   GList *targets;
841
842   if (len <= 0)
843     {
844       GResolverError errnum;
845       const gchar *format;
846
847       if (len == 0 || herr == HOST_NOT_FOUND || herr == NO_DATA)
848         {
849           errnum = G_RESOLVER_ERROR_NOT_FOUND;
850           format = _("No service record for '%s'");
851         }
852       else if (herr == TRY_AGAIN)
853         {
854           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
855           format = _("Temporarily unable to resolve '%s'");
856         }
857       else
858         {
859           errnum = G_RESOLVER_ERROR_INTERNAL;
860           format = _("Error resolving '%s'");
861         }
862
863       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
864       return NULL;
865     }
866
867   targets = NULL;
868
869   header = (HEADER *)answer;
870   p = answer + sizeof (HEADER);
871   end = answer + len;
872
873   /* Skip query */
874   count = ntohs (header->qdcount);
875   while (count-- && p < end)
876     {
877       p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
878       p += 4;
879     }
880
881   /* Read answers */
882   count = ntohs (header->ancount);
883   while (count-- && p < end)
884     {
885       p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
886       GETSHORT (type, p);
887       GETSHORT (qclass, p);
888       GETLONG  (ttl, p);
889       ttl = ttl; /* To avoid -Wunused-but-set-variable */
890       GETSHORT (rdlength, p);
891
892       if (type != T_SRV || qclass != C_IN)
893         {
894           p += rdlength;
895           continue;
896         }
897
898       GETSHORT (priority, p);
899       GETSHORT (weight, p);
900       GETSHORT (port, p);
901       p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
902
903       target = g_srv_target_new (namebuf, port, priority, weight);
904       targets = g_list_prepend (targets, target);
905     }
906
907   return g_srv_target_list_sort (targets);
908 }
909 #elif defined(G_OS_WIN32)
910 /* Private method to process a DnsQuery response into GSrvTargets */
911 GList *
912 _g_resolver_targets_from_DnsQuery (const gchar  *rrname,
913                                    DNS_STATUS    status,
914                                    DNS_RECORD   *results,
915                                    GError      **error)
916 {
917   DNS_RECORD *rec;
918   GSrvTarget *target;
919   GList *targets;
920
921   if (status != ERROR_SUCCESS)
922     {
923       GResolverError errnum;
924       const gchar *format;
925
926       if (status == DNS_ERROR_RCODE_NAME_ERROR)
927         {
928           errnum = G_RESOLVER_ERROR_NOT_FOUND;
929           format = _("No service record for '%s'");
930         }
931       else if (status == DNS_ERROR_RCODE_SERVER_FAILURE)
932         {
933           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
934           format = _("Temporarily unable to resolve '%s'");
935         }
936       else
937         {
938           errnum = G_RESOLVER_ERROR_INTERNAL;
939           format = _("Error resolving '%s'");
940         }
941
942       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
943       return NULL;
944     }
945
946   targets = NULL;
947   for (rec = results; rec; rec = rec->pNext)
948     {
949       if (rec->wType != DNS_TYPE_SRV)
950         continue;
951
952       target = g_srv_target_new (rec->Data.SRV.pNameTarget,
953                                  rec->Data.SRV.wPort,
954                                  rec->Data.SRV.wPriority,
955                                  rec->Data.SRV.wWeight);
956       targets = g_list_prepend (targets, target);
957     }
958
959   return g_srv_target_list_sort (targets);
960 }
961
962 #endif