1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
3 /* GIO - GLib Input, Output and Streaming Library
5 * Copyright (C) 2008 Red Hat, Inc.
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.
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.
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.
30 #include "gthreadedresolver.h"
31 #include "gnetworkingprivate.h"
33 #include "gcancellable.h"
34 #include "ginetaddress.h"
35 #include "ginetsocketaddress.h"
37 #include "gsocketaddress.h"
38 #include "gsrvtarget.h"
41 G_DEFINE_TYPE (GThreadedResolver, g_threaded_resolver, G_TYPE_RESOLVER)
44 g_threaded_resolver_init (GThreadedResolver *gtr)
49 g_resolver_error_from_addrinfo_error (gint err)
54 #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
58 return G_RESOLVER_ERROR_NOT_FOUND;
61 return G_RESOLVER_ERROR_TEMPORARY_FAILURE;
64 return G_RESOLVER_ERROR_INTERNAL;
68 static struct addrinfo addrinfo_hints;
71 do_lookup_by_name (GTask *task,
72 gpointer source_object,
74 GCancellable *cancellable)
76 const char *hostname = task_data;
77 struct addrinfo *res = NULL;
81 retval = getaddrinfo (hostname, NULL, &addrinfo_hints, &res);
86 GSocketAddress *sockaddr;
90 for (ai = res; ai; ai = ai->ai_next)
92 sockaddr = g_socket_address_new_from_native (ai->ai_addr, ai->ai_addrlen);
93 if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
96 addr = g_object_ref (g_inet_socket_address_get_address ((GInetSocketAddress *)sockaddr));
97 addresses = g_list_prepend (addresses, addr);
98 g_object_unref (sockaddr);
101 addresses = g_list_reverse (addresses);
102 g_task_return_pointer (task, addresses,
103 (GDestroyNotify)g_resolver_free_addresses);
107 g_task_return_new_error (task,
109 g_resolver_error_from_addrinfo_error (retval),
110 _("Error resolving '%s': %s"),
111 hostname, gai_strerror (retval));
119 lookup_by_name (GResolver *resolver,
120 const gchar *hostname,
121 GCancellable *cancellable,
127 task = g_task_new (resolver, cancellable, NULL, NULL);
128 g_task_set_task_data (task, g_strdup (hostname), g_free);
129 g_task_set_return_on_cancel (task, TRUE);
130 g_task_run_in_thread_sync (task, do_lookup_by_name);
131 addresses = g_task_propagate_pointer (task, error);
132 g_object_unref (task);
138 lookup_by_name_async (GResolver *resolver,
139 const gchar *hostname,
140 GCancellable *cancellable,
141 GAsyncReadyCallback callback,
146 task = g_task_new (resolver, cancellable, callback, user_data);
147 g_task_set_task_data (task, g_strdup (hostname), g_free);
148 g_task_set_return_on_cancel (task, TRUE);
149 g_task_run_in_thread (task, do_lookup_by_name);
150 g_object_unref (task);
154 lookup_by_name_finish (GResolver *resolver,
155 GAsyncResult *result,
158 g_return_val_if_fail (g_task_is_valid (result, resolver), NULL);
160 return g_task_propagate_pointer (G_TASK (result), error);
165 do_lookup_by_address (GTask *task,
166 gpointer source_object,
168 GCancellable *cancellable)
170 GInetAddress *address = task_data;
171 struct sockaddr_storage sockaddr;
173 GSocketAddress *gsockaddr;
174 gchar name[NI_MAXHOST];
177 gsockaddr = g_inet_socket_address_new (address, 0);
178 g_socket_address_to_native (gsockaddr, (struct sockaddr *)&sockaddr,
179 sizeof (sockaddr), NULL);
180 sockaddr_size = g_socket_address_get_native_size (gsockaddr);
181 g_object_unref (gsockaddr);
183 retval = getnameinfo ((struct sockaddr *)&sockaddr, sockaddr_size,
184 name, sizeof (name), NULL, 0, NI_NAMEREQD);
186 g_task_return_pointer (task, g_strdup (name), g_free);
191 phys = g_inet_address_to_string (address);
192 g_task_return_new_error (task,
194 g_resolver_error_from_addrinfo_error (retval),
195 _("Error reverse-resolving '%s': %s"),
196 phys ? phys : "(unknown)",
197 gai_strerror (retval));
203 lookup_by_address (GResolver *resolver,
204 GInetAddress *address,
205 GCancellable *cancellable,
211 task = g_task_new (resolver, cancellable, NULL, NULL);
212 g_task_set_task_data (task, g_object_ref (address), g_object_unref);
213 g_task_set_return_on_cancel (task, TRUE);
214 g_task_run_in_thread_sync (task, do_lookup_by_address);
215 name = g_task_propagate_pointer (task, error);
216 g_object_unref (task);
222 lookup_by_address_async (GResolver *resolver,
223 GInetAddress *address,
224 GCancellable *cancellable,
225 GAsyncReadyCallback callback,
230 task = g_task_new (resolver, cancellable, callback, user_data);
231 g_task_set_task_data (task, g_object_ref (address), g_object_unref);
232 g_task_set_return_on_cancel (task, TRUE);
233 g_task_run_in_thread (task, do_lookup_by_address);
234 g_object_unref (task);
238 lookup_by_address_finish (GResolver *resolver,
239 GAsyncResult *result,
242 g_return_val_if_fail (g_task_is_valid (result, resolver), NULL);
244 return g_task_propagate_pointer (G_TASK (result), error);
248 #if defined(G_OS_UNIX)
251 /* Copy from bionic/libc/private/arpa_nameser_compat.h
252 * and bionic/libc/private/arpa_nameser.h */
254 unsigned id :16; /* query identification number */
255 #if BYTE_ORDER == BIG_ENDIAN
256 /* fields in third byte */
257 unsigned qr: 1; /* response flag */
258 unsigned opcode: 4; /* purpose of message */
259 unsigned aa: 1; /* authoritive answer */
260 unsigned tc: 1; /* truncated message */
261 unsigned rd: 1; /* recursion desired */
262 /* fields in fourth byte */
263 unsigned ra: 1; /* recursion available */
264 unsigned unused :1; /* unused bits (MBZ as of 4.9.3a3) */
265 unsigned ad: 1; /* authentic data from named */
266 unsigned cd: 1; /* checking disabled by resolver */
267 unsigned rcode :4; /* response code */
269 #if BYTE_ORDER == LITTLE_ENDIAN || BYTE_ORDER == PDP_ENDIAN
270 /* fields in third byte */
271 unsigned rd :1; /* recursion desired */
272 unsigned tc :1; /* truncated message */
273 unsigned aa :1; /* authoritive answer */
274 unsigned opcode :4; /* purpose of message */
275 unsigned qr :1; /* response flag */
276 /* fields in fourth byte */
277 unsigned rcode :4; /* response code */
278 unsigned cd: 1; /* checking disabled by resolver */
279 unsigned ad: 1; /* authentic data from named */
280 unsigned unused :1; /* unused bits (MBZ as of 4.9.3a3) */
281 unsigned ra :1; /* recursion available */
283 /* remaining bytes */
284 unsigned qdcount :16; /* number of question entries */
285 unsigned ancount :16; /* number of answer entries */
286 unsigned nscount :16; /* number of authority entries */
287 unsigned arcount :16; /* number of resource entries */
290 #define NS_INT32SZ 4 /* #/bytes of data in a uint32_t */
291 #define NS_INT16SZ 2 /* #/bytes of data in a uint16_t */
293 #define NS_GET16(s, cp) do { \
294 const u_char *t_cp = (const u_char *)(cp); \
295 (s) = ((uint16_t)t_cp[0] << 8) \
296 | ((uint16_t)t_cp[1]) \
298 (cp) += NS_INT16SZ; \
299 } while (/*CONSTCOND*/0)
301 #define NS_GET32(l, cp) do { \
302 const u_char *t_cp = (const u_char *)(cp); \
303 (l) = ((uint32_t)t_cp[0] << 24) \
304 | ((uint32_t)t_cp[1] << 16) \
305 | ((uint32_t)t_cp[2] << 8) \
306 | ((uint32_t)t_cp[3]) \
308 (cp) += NS_INT32SZ; \
309 } while (/*CONSTCOND*/0)
311 #define GETSHORT NS_GET16
312 #define GETLONG NS_GET32
316 /* From bionic/libc/private/resolv_private.h */
317 int dn_expand(const u_char *, const u_char *, const u_char *, char *, int);
318 #define dn_skipname __dn_skipname
319 int dn_skipname(const u_char *, const u_char *);
321 /* From bionic/libc/private/arpa_nameser_compat.h */
323 #define T_TXT ns_t_txt
324 #define T_SOA ns_t_soa
327 /* From bionic/libc/private/arpa_nameser.h */
328 typedef enum __ns_type {
329 ns_t_invalid = 0, /* Cookie. */
330 ns_t_a = 1, /* Host address. */
331 ns_t_ns = 2, /* Authoritative server. */
332 ns_t_md = 3, /* Mail destination. */
333 ns_t_mf = 4, /* Mail forwarder. */
334 ns_t_cname = 5, /* Canonical name. */
335 ns_t_soa = 6, /* Start of authority zone. */
336 ns_t_mb = 7, /* Mailbox domain name. */
337 ns_t_mg = 8, /* Mail group member. */
338 ns_t_mr = 9, /* Mail rename name. */
339 ns_t_null = 10, /* Null resource record. */
340 ns_t_wks = 11, /* Well known service. */
341 ns_t_ptr = 12, /* Domain name pointer. */
342 ns_t_hinfo = 13, /* Host information. */
343 ns_t_minfo = 14, /* Mailbox information. */
344 ns_t_mx = 15, /* Mail routing information. */
345 ns_t_txt = 16, /* Text strings. */
346 ns_t_rp = 17, /* Responsible person. */
347 ns_t_afsdb = 18, /* AFS cell database. */
348 ns_t_x25 = 19, /* X_25 calling address. */
349 ns_t_isdn = 20, /* ISDN calling address. */
350 ns_t_rt = 21, /* Router. */
351 ns_t_nsap = 22, /* NSAP address. */
352 ns_t_nsap_ptr = 23, /* Reverse NSAP lookup (deprecated). */
353 ns_t_sig = 24, /* Security signature. */
354 ns_t_key = 25, /* Security key. */
355 ns_t_px = 26, /* X.400 mail mapping. */
356 ns_t_gpos = 27, /* Geographical position (withdrawn). */
357 ns_t_aaaa = 28, /* Ip6 Address. */
358 ns_t_loc = 29, /* Location Information. */
359 ns_t_nxt = 30, /* Next domain (security). */
360 ns_t_eid = 31, /* Endpoint identifier. */
361 ns_t_nimloc = 32, /* Nimrod Locator. */
362 ns_t_srv = 33, /* Server Selection. */
363 ns_t_atma = 34, /* ATM Address */
364 ns_t_naptr = 35, /* Naming Authority PoinTeR */
365 ns_t_kx = 36, /* Key Exchange */
366 ns_t_cert = 37, /* Certification record */
367 ns_t_a6 = 38, /* IPv6 address (deprecates AAAA) */
368 ns_t_dname = 39, /* Non-terminal DNAME (for IPv6) */
369 ns_t_sink = 40, /* Kitchen sink (experimentatl) */
370 ns_t_opt = 41, /* EDNS0 option (meta-RR) */
371 ns_t_apl = 42, /* Address prefix list (RFC 3123) */
372 ns_t_tkey = 249, /* Transaction key */
373 ns_t_tsig = 250, /* Transaction signature. */
374 ns_t_ixfr = 251, /* Incremental zone transfer. */
375 ns_t_axfr = 252, /* Transfer zone of authority. */
376 ns_t_mailb = 253, /* Transfer mailbox records. */
377 ns_t_maila = 254, /* Transfer mail agent records. */
378 ns_t_any = 255, /* Wildcard match. */
379 ns_t_zxfr = 256, /* BIND-specific, nonstandard. */
383 #endif /* __BIONIC__ */
386 parse_res_srv (guchar *answer,
391 guint16 priority, weight, port;
393 GETSHORT (priority, *p);
394 GETSHORT (weight, *p);
396 *p += dn_expand (answer, end, *p, namebuf, sizeof (namebuf));
398 return g_variant_new ("(qqqs)",
406 parse_res_soa (guchar *answer,
410 gchar mnamebuf[1024];
411 gchar rnamebuf[1024];
412 guint32 serial, refresh, retry, expire, ttl;
414 *p += dn_expand (answer, end, *p, mnamebuf, sizeof (mnamebuf));
415 *p += dn_expand (answer, end, *p, rnamebuf, sizeof (rnamebuf));
417 GETLONG (serial, *p);
418 GETLONG (refresh, *p);
420 GETLONG (expire, *p);
423 return g_variant_new ("(ssuuuuu)",
434 parse_res_ns (guchar *answer,
440 *p += dn_expand (answer, end, *p, namebuf, sizeof (namebuf));
442 return g_variant_new ("(s)", namebuf);
446 parse_res_mx (guchar *answer,
453 GETSHORT (preference, *p);
455 *p += dn_expand (answer, end, *p, namebuf, sizeof (namebuf));
457 return g_variant_new ("(qs)",
463 parse_res_txt (guchar *answer,
472 array = g_ptr_array_new_with_free_func (g_free);
478 g_ptr_array_add (array, g_strndup ((gchar *)at, len));
483 record = g_variant_new ("(@as)",
484 g_variant_new_strv ((const gchar **)array->pdata, array->len));
485 g_ptr_array_free (array, TRUE);
490 g_resolver_record_type_to_rrtype (GResolverRecordType type)
494 case G_RESOLVER_RECORD_SRV:
496 case G_RESOLVER_RECORD_TXT:
498 case G_RESOLVER_RECORD_SOA:
500 case G_RESOLVER_RECORD_NS:
502 case G_RESOLVER_RECORD_MX:
505 g_return_val_if_reached (-1);
508 #pragma GCC diagnostic push
509 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
512 g_resolver_records_from_res_query (const gchar *rrname,
522 guint16 type, qclass, rdlength;
530 GResolverError errnum;
533 if (len == 0 || herr == HOST_NOT_FOUND || herr == NO_DATA)
535 errnum = G_RESOLVER_ERROR_NOT_FOUND;
536 format = _("No DNS record of the requested type for '%s'");
538 else if (herr == TRY_AGAIN)
540 errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
541 format = _("Temporarily unable to resolve '%s'");
545 errnum = G_RESOLVER_ERROR_INTERNAL;
546 format = _("Error resolving '%s'");
549 g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
555 header = (HEADER *)answer;
556 p = answer + sizeof (HEADER);
560 count = ntohs (header->qdcount);
561 while (count-- && p < end)
563 p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
566 /* To silence gcc warnings */
567 namebuf[0] = namebuf[1];
571 count = ntohs (header->ancount);
572 while (count-- && p < end)
574 p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
576 GETSHORT (qclass, p);
578 ttl = ttl; /* To avoid -Wunused-but-set-variable */
579 GETSHORT (rdlength, p);
581 if (type != rrtype || qclass != C_IN)
590 record = parse_res_srv (answer, end, &p);
593 record = parse_res_mx (answer, end, &p);
596 record = parse_res_soa (answer, end, &p);
599 record = parse_res_ns (answer, end, &p);
602 record = parse_res_txt (answer, p + rdlength, &p);
605 g_warn_if_reached ();
611 records = g_list_prepend (records, record);
616 g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_NOT_FOUND,
617 _("No DNS record of the requested type for '%s'"), rrname);
625 #pragma GCC diagnostic pop
627 #elif defined(G_OS_WIN32)
630 parse_dns_srv (DNS_RECORD *rec)
632 return g_variant_new ("(qqqs)",
633 (guint16)rec->Data.SRV.wPriority,
634 (guint16)rec->Data.SRV.wWeight,
635 (guint16)rec->Data.SRV.wPort,
636 rec->Data.SRV.pNameTarget);
640 parse_dns_soa (DNS_RECORD *rec)
642 return g_variant_new ("(ssuuuuu)",
643 rec->Data.SOA.pNamePrimaryServer,
644 rec->Data.SOA.pNameAdministrator,
645 (guint32)rec->Data.SOA.dwSerialNo,
646 (guint32)rec->Data.SOA.dwRefresh,
647 (guint32)rec->Data.SOA.dwRetry,
648 (guint32)rec->Data.SOA.dwExpire,
649 (guint32)rec->Data.SOA.dwDefaultTtl);
653 parse_dns_ns (DNS_RECORD *rec)
655 return g_variant_new ("(s)", rec->Data.NS.pNameHost);
659 parse_dns_mx (DNS_RECORD *rec)
661 return g_variant_new ("(qs)",
662 (guint16)rec->Data.MX.wPreference,
663 rec->Data.MX.pNameExchange);
667 parse_dns_txt (DNS_RECORD *rec)
673 array = g_ptr_array_new ();
674 for (i = 0; i < rec->Data.TXT.dwStringCount; i++)
675 g_ptr_array_add (array, rec->Data.TXT.pStringArray[i]);
676 record = g_variant_new ("(@as)",
677 g_variant_new_strv ((const gchar **)array->pdata, array->len));
678 g_ptr_array_free (array, TRUE);
683 g_resolver_record_type_to_dnstype (GResolverRecordType type)
687 case G_RESOLVER_RECORD_SRV:
689 case G_RESOLVER_RECORD_TXT:
690 return DNS_TYPE_TEXT;
691 case G_RESOLVER_RECORD_SOA:
693 case G_RESOLVER_RECORD_NS:
695 case G_RESOLVER_RECORD_MX:
698 g_return_val_if_reached (-1);
702 g_resolver_records_from_DnsQuery (const gchar *rrname,
712 if (status != ERROR_SUCCESS)
714 GResolverError errnum;
717 if (status == DNS_ERROR_RCODE_NAME_ERROR)
719 errnum = G_RESOLVER_ERROR_NOT_FOUND;
720 format = _("No DNS record of the requested type for '%s'");
722 else if (status == DNS_ERROR_RCODE_SERVER_FAILURE)
724 errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
725 format = _("Temporarily unable to resolve '%s'");
729 errnum = G_RESOLVER_ERROR_INTERNAL;
730 format = _("Error resolving '%s'");
733 g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
738 for (rec = results; rec; rec = rec->pNext)
740 if (rec->wType != dnstype)
745 record = parse_dns_srv (rec);
748 record = parse_dns_soa (rec);
751 record = parse_dns_ns (rec);
754 record = parse_dns_mx (rec);
757 record = parse_dns_txt (rec);
760 g_warn_if_reached ();
765 records = g_list_prepend (records, g_variant_ref_sink (record));
770 g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_NOT_FOUND,
771 _("No DNS record of the requested type for '%s'"), rrname);
783 GResolverRecordType record_type;
787 free_lookup_records_data (LookupRecordsData *lrd)
789 g_free (lrd->rrname);
790 g_slice_free (LookupRecordsData, lrd);
794 free_records (GList *records)
796 g_list_free_full (records, (GDestroyNotify) g_variant_unref);
799 #if defined(G_OS_UNIX)
802 int res_query(const char *, int, int, u_char *, int);
807 do_lookup_records (GTask *task,
808 gpointer source_object,
810 GCancellable *cancellable)
812 LookupRecordsData *lrd = task_data;
814 GError *error = NULL;
816 #if defined(G_OS_UNIX)
822 rrtype = g_resolver_record_type_to_rrtype (lrd->record_type);
823 answer = g_byte_array_new ();
826 g_byte_array_set_size (answer, len * 2);
827 len = res_query (lrd->rrname, C_IN, rrtype, answer->data, answer->len);
829 /* If answer fit in the buffer then we're done */
830 if (len < 0 || len < (gint)answer->len)
834 * On overflow some res_query's return the length needed, others
835 * return the full length entered. This code works in either case.
840 records = g_resolver_records_from_res_query (lrd->rrname, rrtype, answer->data, len, herr, &error);
841 g_byte_array_free (answer, TRUE);
846 DNS_RECORD *results = NULL;
849 dnstype = g_resolver_record_type_to_dnstype (lrd->record_type);
850 status = DnsQuery_A (lrd->rrname, dnstype, DNS_QUERY_STANDARD, NULL, &results, NULL);
851 records = g_resolver_records_from_DnsQuery (lrd->rrname, dnstype, status, results, &error);
853 DnsRecordListFree (results, DnsFreeRecordList);
858 g_task_return_pointer (task, records, (GDestroyNotify) free_records);
860 g_task_return_error (task, error);
864 lookup_records (GResolver *resolver,
866 GResolverRecordType record_type,
867 GCancellable *cancellable,
872 LookupRecordsData *lrd;
874 task = g_task_new (resolver, cancellable, NULL, NULL);
876 lrd = g_slice_new (LookupRecordsData);
877 lrd->rrname = g_strdup (rrname);
878 lrd->record_type = record_type;
879 g_task_set_task_data (task, lrd, (GDestroyNotify) free_lookup_records_data);
881 g_task_set_return_on_cancel (task, TRUE);
882 g_task_run_in_thread_sync (task, do_lookup_records);
883 records = g_task_propagate_pointer (task, error);
884 g_object_unref (task);
890 lookup_records_async (GResolver *resolver,
892 GResolverRecordType record_type,
893 GCancellable *cancellable,
894 GAsyncReadyCallback callback,
898 LookupRecordsData *lrd;
900 task = g_task_new (resolver, cancellable, callback, user_data);
902 lrd = g_slice_new (LookupRecordsData);
903 lrd->rrname = g_strdup (rrname);
904 lrd->record_type = record_type;
905 g_task_set_task_data (task, lrd, (GDestroyNotify) free_lookup_records_data);
907 g_task_set_return_on_cancel (task, TRUE);
908 g_task_run_in_thread (task, do_lookup_records);
909 g_object_unref (task);
913 lookup_records_finish (GResolver *resolver,
914 GAsyncResult *result,
917 g_return_val_if_fail (g_task_is_valid (result, resolver), NULL);
919 return g_task_propagate_pointer (G_TASK (result), error);
924 g_threaded_resolver_class_init (GThreadedResolverClass *threaded_class)
926 GResolverClass *resolver_class = G_RESOLVER_CLASS (threaded_class);
928 resolver_class->lookup_by_name = lookup_by_name;
929 resolver_class->lookup_by_name_async = lookup_by_name_async;
930 resolver_class->lookup_by_name_finish = lookup_by_name_finish;
931 resolver_class->lookup_by_address = lookup_by_address;
932 resolver_class->lookup_by_address_async = lookup_by_address_async;
933 resolver_class->lookup_by_address_finish = lookup_by_address_finish;
934 resolver_class->lookup_records = lookup_records;
935 resolver_class->lookup_records_async = lookup_records_async;
936 resolver_class->lookup_records_finish = lookup_records_finish;
938 /* Initialize _g_resolver_addrinfo_hints */
940 addrinfo_hints.ai_flags |= AI_ADDRCONFIG;
942 /* These two don't actually matter, they just get copied into the
943 * returned addrinfo structures (and then we ignore them). But if
944 * we leave them unset, we'll get back duplicate answers.
946 addrinfo_hints.ai_socktype = SOCK_STREAM;
947 addrinfo_hints.ai_protocol = IPPROTO_TCP;