Merge branch '976-disable-assert-checks' into 'master'
[glib.git] / gio / gthreadedresolver.c
blob9e110cd0b1f9e1d6787bf9443371c1e0a98a1016
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.1 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, see <http://www.gnu.org/licenses/>.
21 #include "config.h"
22 #include <glib.h>
23 #include "glibintl.h"
25 #include <stdio.h>
26 #include <string.h>
28 #include "gthreadedresolver.h"
29 #include "gnetworkingprivate.h"
31 #include "gcancellable.h"
32 #include "ginetaddress.h"
33 #include "ginetsocketaddress.h"
34 #include "gtask.h"
35 #include "gsocketaddress.h"
36 #include "gsrvtarget.h"
39 G_DEFINE_TYPE (GThreadedResolver, g_threaded_resolver, G_TYPE_RESOLVER)
41 static void
42 g_threaded_resolver_init (GThreadedResolver *gtr)
46 static GResolverError
47 g_resolver_error_from_addrinfo_error (gint err)
49 switch (err)
51 case EAI_FAIL:
52 #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
53 case EAI_NODATA:
54 #endif
55 case EAI_NONAME:
56 return G_RESOLVER_ERROR_NOT_FOUND;
58 case EAI_AGAIN:
59 return G_RESOLVER_ERROR_TEMPORARY_FAILURE;
61 default:
62 return G_RESOLVER_ERROR_INTERNAL;
66 static struct addrinfo addrinfo_hints;
68 static void
69 do_lookup_by_name (GTask *task,
70 gpointer source_object,
71 gpointer task_data,
72 GCancellable *cancellable)
74 const char *hostname = task_data;
75 struct addrinfo *res = NULL;
76 GList *addresses;
77 gint retval;
79 retval = getaddrinfo (hostname, NULL, &addrinfo_hints, &res);
81 if (retval == 0)
83 struct addrinfo *ai;
84 GSocketAddress *sockaddr;
85 GInetAddress *addr;
87 addresses = NULL;
88 for (ai = res; ai; ai = ai->ai_next)
90 sockaddr = g_socket_address_new_from_native (ai->ai_addr, ai->ai_addrlen);
91 if (!sockaddr)
92 continue;
93 if (!G_IS_INET_SOCKET_ADDRESS (sockaddr))
95 g_clear_object (&sockaddr);
96 continue;
99 addr = g_object_ref (g_inet_socket_address_get_address ((GInetSocketAddress *)sockaddr));
100 addresses = g_list_prepend (addresses, addr);
101 g_object_unref (sockaddr);
104 if (addresses != NULL)
106 addresses = g_list_reverse (addresses);
107 g_task_return_pointer (task, addresses,
108 (GDestroyNotify)g_resolver_free_addresses);
110 else
112 /* All addresses failed to be converted to GSocketAddresses. */
113 g_task_return_new_error (task,
114 G_RESOLVER_ERROR,
115 G_RESOLVER_ERROR_NOT_FOUND,
116 _("Error resolving “%s”: %s"),
117 hostname,
118 _("No valid addresses were found"));
121 else
123 g_task_return_new_error (task,
124 G_RESOLVER_ERROR,
125 g_resolver_error_from_addrinfo_error (retval),
126 _("Error resolving “%s”: %s"),
127 hostname, gai_strerror (retval));
130 if (res)
131 freeaddrinfo (res);
134 static GList *
135 lookup_by_name (GResolver *resolver,
136 const gchar *hostname,
137 GCancellable *cancellable,
138 GError **error)
140 GTask *task;
141 GList *addresses;
143 task = g_task_new (resolver, cancellable, NULL, NULL);
144 g_task_set_source_tag (task, lookup_by_name);
145 g_task_set_task_data (task, g_strdup (hostname), g_free);
146 g_task_set_return_on_cancel (task, TRUE);
147 g_task_run_in_thread_sync (task, do_lookup_by_name);
148 addresses = g_task_propagate_pointer (task, error);
149 g_object_unref (task);
151 return addresses;
154 static void
155 lookup_by_name_async (GResolver *resolver,
156 const gchar *hostname,
157 GCancellable *cancellable,
158 GAsyncReadyCallback callback,
159 gpointer user_data)
161 GTask *task;
163 task = g_task_new (resolver, cancellable, callback, user_data);
164 g_task_set_source_tag (task, lookup_by_name_async);
165 g_task_set_task_data (task, g_strdup (hostname), g_free);
166 g_task_set_return_on_cancel (task, TRUE);
167 g_task_run_in_thread (task, do_lookup_by_name);
168 g_object_unref (task);
171 static GList *
172 lookup_by_name_finish (GResolver *resolver,
173 GAsyncResult *result,
174 GError **error)
176 g_return_val_if_fail (g_task_is_valid (result, resolver), NULL);
178 return g_task_propagate_pointer (G_TASK (result), error);
182 static void
183 do_lookup_by_address (GTask *task,
184 gpointer source_object,
185 gpointer task_data,
186 GCancellable *cancellable)
188 GInetAddress *address = task_data;
189 struct sockaddr_storage sockaddr;
190 gsize sockaddr_size;
191 GSocketAddress *gsockaddr;
192 gchar name[NI_MAXHOST];
193 gint retval;
195 gsockaddr = g_inet_socket_address_new (address, 0);
196 g_socket_address_to_native (gsockaddr, (struct sockaddr *)&sockaddr,
197 sizeof (sockaddr), NULL);
198 sockaddr_size = g_socket_address_get_native_size (gsockaddr);
199 g_object_unref (gsockaddr);
201 retval = getnameinfo ((struct sockaddr *)&sockaddr, sockaddr_size,
202 name, sizeof (name), NULL, 0, NI_NAMEREQD);
203 if (retval == 0)
204 g_task_return_pointer (task, g_strdup (name), g_free);
205 else
207 gchar *phys;
209 phys = g_inet_address_to_string (address);
210 g_task_return_new_error (task,
211 G_RESOLVER_ERROR,
212 g_resolver_error_from_addrinfo_error (retval),
213 _("Error reverse-resolving “%s”: %s"),
214 phys ? phys : "(unknown)",
215 gai_strerror (retval));
216 g_free (phys);
220 static gchar *
221 lookup_by_address (GResolver *resolver,
222 GInetAddress *address,
223 GCancellable *cancellable,
224 GError **error)
226 GTask *task;
227 gchar *name;
229 task = g_task_new (resolver, cancellable, NULL, NULL);
230 g_task_set_source_tag (task, lookup_by_address);
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_sync (task, do_lookup_by_address);
234 name = g_task_propagate_pointer (task, error);
235 g_object_unref (task);
237 return name;
240 static void
241 lookup_by_address_async (GResolver *resolver,
242 GInetAddress *address,
243 GCancellable *cancellable,
244 GAsyncReadyCallback callback,
245 gpointer user_data)
247 GTask *task;
249 task = g_task_new (resolver, cancellable, callback, user_data);
250 g_task_set_source_tag (task, lookup_by_address_async);
251 g_task_set_task_data (task, g_object_ref (address), g_object_unref);
252 g_task_set_return_on_cancel (task, TRUE);
253 g_task_run_in_thread (task, do_lookup_by_address);
254 g_object_unref (task);
257 static gchar *
258 lookup_by_address_finish (GResolver *resolver,
259 GAsyncResult *result,
260 GError **error)
262 g_return_val_if_fail (g_task_is_valid (result, resolver), NULL);
264 return g_task_propagate_pointer (G_TASK (result), error);
268 #if defined(G_OS_UNIX)
270 #if defined __BIONIC__ && !defined BIND_4_COMPAT
271 /* Copy from bionic/libc/private/arpa_nameser_compat.h
272 * and bionic/libc/private/arpa_nameser.h */
273 typedef struct {
274 unsigned id :16; /* query identification number */
275 #if BYTE_ORDER == BIG_ENDIAN
276 /* fields in third byte */
277 unsigned qr: 1; /* response flag */
278 unsigned opcode: 4; /* purpose of message */
279 unsigned aa: 1; /* authoritive answer */
280 unsigned tc: 1; /* truncated message */
281 unsigned rd: 1; /* recursion desired */
282 /* fields in fourth byte */
283 unsigned ra: 1; /* recursion available */
284 unsigned unused :1; /* unused bits (MBZ as of 4.9.3a3) */
285 unsigned ad: 1; /* authentic data from named */
286 unsigned cd: 1; /* checking disabled by resolver */
287 unsigned rcode :4; /* response code */
288 #endif
289 #if BYTE_ORDER == LITTLE_ENDIAN || BYTE_ORDER == PDP_ENDIAN
290 /* fields in third byte */
291 unsigned rd :1; /* recursion desired */
292 unsigned tc :1; /* truncated message */
293 unsigned aa :1; /* authoritive answer */
294 unsigned opcode :4; /* purpose of message */
295 unsigned qr :1; /* response flag */
296 /* fields in fourth byte */
297 unsigned rcode :4; /* response code */
298 unsigned cd: 1; /* checking disabled by resolver */
299 unsigned ad: 1; /* authentic data from named */
300 unsigned unused :1; /* unused bits (MBZ as of 4.9.3a3) */
301 unsigned ra :1; /* recursion available */
302 #endif
303 /* remaining bytes */
304 unsigned qdcount :16; /* number of question entries */
305 unsigned ancount :16; /* number of answer entries */
306 unsigned nscount :16; /* number of authority entries */
307 unsigned arcount :16; /* number of resource entries */
308 } HEADER;
310 #define NS_INT32SZ 4 /* #/bytes of data in a uint32_t */
311 #define NS_INT16SZ 2 /* #/bytes of data in a uint16_t */
313 #define NS_GET16(s, cp) do { \
314 const u_char *t_cp = (const u_char *)(cp); \
315 (s) = ((uint16_t)t_cp[0] << 8) \
316 | ((uint16_t)t_cp[1]) \
318 (cp) += NS_INT16SZ; \
319 } while (/*CONSTCOND*/0)
321 #define NS_GET32(l, cp) do { \
322 const u_char *t_cp = (const u_char *)(cp); \
323 (l) = ((uint32_t)t_cp[0] << 24) \
324 | ((uint32_t)t_cp[1] << 16) \
325 | ((uint32_t)t_cp[2] << 8) \
326 | ((uint32_t)t_cp[3]) \
328 (cp) += NS_INT32SZ; \
329 } while (/*CONSTCOND*/0)
331 #define GETSHORT NS_GET16
332 #define GETLONG NS_GET32
334 #define C_IN 1
336 /* From bionic/libc/private/resolv_private.h */
337 int dn_expand(const u_char *, const u_char *, const u_char *, char *, int);
338 #define dn_skipname __dn_skipname
339 int dn_skipname(const u_char *, const u_char *);
341 /* From bionic/libc/private/arpa_nameser_compat.h */
342 #define T_MX ns_t_mx
343 #define T_TXT ns_t_txt
344 #define T_SOA ns_t_soa
345 #define T_NS ns_t_ns
347 /* From bionic/libc/private/arpa_nameser.h */
348 typedef enum __ns_type {
349 ns_t_invalid = 0, /* Cookie. */
350 ns_t_a = 1, /* Host address. */
351 ns_t_ns = 2, /* Authoritative server. */
352 ns_t_md = 3, /* Mail destination. */
353 ns_t_mf = 4, /* Mail forwarder. */
354 ns_t_cname = 5, /* Canonical name. */
355 ns_t_soa = 6, /* Start of authority zone. */
356 ns_t_mb = 7, /* Mailbox domain name. */
357 ns_t_mg = 8, /* Mail group member. */
358 ns_t_mr = 9, /* Mail rename name. */
359 ns_t_null = 10, /* Null resource record. */
360 ns_t_wks = 11, /* Well known service. */
361 ns_t_ptr = 12, /* Domain name pointer. */
362 ns_t_hinfo = 13, /* Host information. */
363 ns_t_minfo = 14, /* Mailbox information. */
364 ns_t_mx = 15, /* Mail routing information. */
365 ns_t_txt = 16, /* Text strings. */
366 ns_t_rp = 17, /* Responsible person. */
367 ns_t_afsdb = 18, /* AFS cell database. */
368 ns_t_x25 = 19, /* X_25 calling address. */
369 ns_t_isdn = 20, /* ISDN calling address. */
370 ns_t_rt = 21, /* Router. */
371 ns_t_nsap = 22, /* NSAP address. */
372 ns_t_nsap_ptr = 23, /* Reverse NSAP lookup (deprecated). */
373 ns_t_sig = 24, /* Security signature. */
374 ns_t_key = 25, /* Security key. */
375 ns_t_px = 26, /* X.400 mail mapping. */
376 ns_t_gpos = 27, /* Geographical position (withdrawn). */
377 ns_t_aaaa = 28, /* Ip6 Address. */
378 ns_t_loc = 29, /* Location Information. */
379 ns_t_nxt = 30, /* Next domain (security). */
380 ns_t_eid = 31, /* Endpoint identifier. */
381 ns_t_nimloc = 32, /* Nimrod Locator. */
382 ns_t_srv = 33, /* Server Selection. */
383 ns_t_atma = 34, /* ATM Address */
384 ns_t_naptr = 35, /* Naming Authority PoinTeR */
385 ns_t_kx = 36, /* Key Exchange */
386 ns_t_cert = 37, /* Certification record */
387 ns_t_a6 = 38, /* IPv6 address (deprecates AAAA) */
388 ns_t_dname = 39, /* Non-terminal DNAME (for IPv6) */
389 ns_t_sink = 40, /* Kitchen sink (experimentatl) */
390 ns_t_opt = 41, /* EDNS0 option (meta-RR) */
391 ns_t_apl = 42, /* Address prefix list (RFC 3123) */
392 ns_t_tkey = 249, /* Transaction key */
393 ns_t_tsig = 250, /* Transaction signature. */
394 ns_t_ixfr = 251, /* Incremental zone transfer. */
395 ns_t_axfr = 252, /* Transfer zone of authority. */
396 ns_t_mailb = 253, /* Transfer mailbox records. */
397 ns_t_maila = 254, /* Transfer mail agent records. */
398 ns_t_any = 255, /* Wildcard match. */
399 ns_t_zxfr = 256, /* BIND-specific, nonstandard. */
400 ns_t_max = 65536
401 } ns_type;
403 #endif /* __BIONIC__ */
405 static GVariant *
406 parse_res_srv (guchar *answer,
407 guchar *end,
408 guchar **p)
410 gchar namebuf[1024];
411 guint16 priority, weight, port;
413 GETSHORT (priority, *p);
414 GETSHORT (weight, *p);
415 GETSHORT (port, *p);
416 *p += dn_expand (answer, end, *p, namebuf, sizeof (namebuf));
418 return g_variant_new ("(qqqs)",
419 priority,
420 weight,
421 port,
422 namebuf);
425 static GVariant *
426 parse_res_soa (guchar *answer,
427 guchar *end,
428 guchar **p)
430 gchar mnamebuf[1024];
431 gchar rnamebuf[1024];
432 guint32 serial, refresh, retry, expire, ttl;
434 *p += dn_expand (answer, end, *p, mnamebuf, sizeof (mnamebuf));
435 *p += dn_expand (answer, end, *p, rnamebuf, sizeof (rnamebuf));
437 GETLONG (serial, *p);
438 GETLONG (refresh, *p);
439 GETLONG (retry, *p);
440 GETLONG (expire, *p);
441 GETLONG (ttl, *p);
443 return g_variant_new ("(ssuuuuu)",
444 mnamebuf,
445 rnamebuf,
446 serial,
447 refresh,
448 retry,
449 expire,
450 ttl);
453 static GVariant *
454 parse_res_ns (guchar *answer,
455 guchar *end,
456 guchar **p)
458 gchar namebuf[1024];
460 *p += dn_expand (answer, end, *p, namebuf, sizeof (namebuf));
462 return g_variant_new ("(s)", namebuf);
465 static GVariant *
466 parse_res_mx (guchar *answer,
467 guchar *end,
468 guchar **p)
470 gchar namebuf[1024];
471 guint16 preference;
473 GETSHORT (preference, *p);
475 *p += dn_expand (answer, end, *p, namebuf, sizeof (namebuf));
477 return g_variant_new ("(qs)",
478 preference,
479 namebuf);
482 static GVariant *
483 parse_res_txt (guchar *answer,
484 guchar *end,
485 guchar **p)
487 GVariant *record;
488 GPtrArray *array;
489 guchar *at = *p;
490 gsize len;
492 array = g_ptr_array_new_with_free_func (g_free);
493 while (at < end)
495 len = *(at++);
496 if (len > at - end)
497 break;
498 g_ptr_array_add (array, g_strndup ((gchar *)at, len));
499 at += len;
502 *p = at;
503 record = g_variant_new ("(@as)",
504 g_variant_new_strv ((const gchar **)array->pdata, array->len));
505 g_ptr_array_free (array, TRUE);
506 return record;
509 static gint
510 g_resolver_record_type_to_rrtype (GResolverRecordType type)
512 switch (type)
514 case G_RESOLVER_RECORD_SRV:
515 return T_SRV;
516 case G_RESOLVER_RECORD_TXT:
517 return T_TXT;
518 case G_RESOLVER_RECORD_SOA:
519 return T_SOA;
520 case G_RESOLVER_RECORD_NS:
521 return T_NS;
522 case G_RESOLVER_RECORD_MX:
523 return T_MX;
525 g_return_val_if_reached (-1);
528 static GList *
529 g_resolver_records_from_res_query (const gchar *rrname,
530 gint rrtype,
531 guchar *answer,
532 gint len,
533 gint herr,
534 GError **error)
536 gint count;
537 gchar namebuf[1024];
538 guchar *end, *p;
539 guint16 type, qclass, rdlength;
540 HEADER *header;
541 GList *records;
542 GVariant *record;
544 if (len <= 0)
546 if (len == 0 || herr == HOST_NOT_FOUND || herr == NO_DATA)
548 g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_NOT_FOUND,
549 _("No DNS record of the requested type for “%s”"), rrname);
551 else if (herr == TRY_AGAIN)
553 g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_TEMPORARY_FAILURE,
554 _("Temporarily unable to resolve “%s”"), rrname);
556 else
558 g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_INTERNAL,
559 _("Error resolving “%s”"), rrname);
562 return NULL;
565 records = NULL;
567 header = (HEADER *)answer;
568 p = answer + sizeof (HEADER);
569 end = answer + len;
571 /* Skip query */
572 count = ntohs (header->qdcount);
573 while (count-- && p < end)
575 p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
576 p += 4;
578 /* To silence gcc warnings */
579 namebuf[0] = namebuf[1];
582 /* Read answers */
583 count = ntohs (header->ancount);
584 while (count-- && p < end)
586 p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
587 GETSHORT (type, p);
588 GETSHORT (qclass, p);
589 p += 4; /* ignore the ttl (type=long) value */
590 GETSHORT (rdlength, p);
592 if (type != rrtype || qclass != C_IN)
594 p += rdlength;
595 continue;
598 switch (rrtype)
600 case T_SRV:
601 record = parse_res_srv (answer, end, &p);
602 break;
603 case T_MX:
604 record = parse_res_mx (answer, end, &p);
605 break;
606 case T_SOA:
607 record = parse_res_soa (answer, end, &p);
608 break;
609 case T_NS:
610 record = parse_res_ns (answer, end, &p);
611 break;
612 case T_TXT:
613 record = parse_res_txt (answer, p + rdlength, &p);
614 break;
615 default:
616 g_warn_if_reached ();
617 record = NULL;
618 break;
621 if (record != NULL)
622 records = g_list_prepend (records, record);
625 if (records == NULL)
627 g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_NOT_FOUND,
628 _("No DNS record of the requested type for “%s”"), rrname);
630 return NULL;
632 else
633 return records;
636 #elif defined(G_OS_WIN32)
638 static GVariant *
639 parse_dns_srv (DNS_RECORD *rec)
641 return g_variant_new ("(qqqs)",
642 (guint16)rec->Data.SRV.wPriority,
643 (guint16)rec->Data.SRV.wWeight,
644 (guint16)rec->Data.SRV.wPort,
645 rec->Data.SRV.pNameTarget);
648 static GVariant *
649 parse_dns_soa (DNS_RECORD *rec)
651 return g_variant_new ("(ssuuuuu)",
652 rec->Data.SOA.pNamePrimaryServer,
653 rec->Data.SOA.pNameAdministrator,
654 (guint32)rec->Data.SOA.dwSerialNo,
655 (guint32)rec->Data.SOA.dwRefresh,
656 (guint32)rec->Data.SOA.dwRetry,
657 (guint32)rec->Data.SOA.dwExpire,
658 (guint32)rec->Data.SOA.dwDefaultTtl);
661 static GVariant *
662 parse_dns_ns (DNS_RECORD *rec)
664 return g_variant_new ("(s)", rec->Data.NS.pNameHost);
667 static GVariant *
668 parse_dns_mx (DNS_RECORD *rec)
670 return g_variant_new ("(qs)",
671 (guint16)rec->Data.MX.wPreference,
672 rec->Data.MX.pNameExchange);
675 static GVariant *
676 parse_dns_txt (DNS_RECORD *rec)
678 GVariant *record;
679 GPtrArray *array;
680 DWORD i;
682 array = g_ptr_array_new ();
683 for (i = 0; i < rec->Data.TXT.dwStringCount; i++)
684 g_ptr_array_add (array, rec->Data.TXT.pStringArray[i]);
685 record = g_variant_new ("(@as)",
686 g_variant_new_strv ((const gchar **)array->pdata, array->len));
687 g_ptr_array_free (array, TRUE);
688 return record;
691 static WORD
692 g_resolver_record_type_to_dnstype (GResolverRecordType type)
694 switch (type)
696 case G_RESOLVER_RECORD_SRV:
697 return DNS_TYPE_SRV;
698 case G_RESOLVER_RECORD_TXT:
699 return DNS_TYPE_TEXT;
700 case G_RESOLVER_RECORD_SOA:
701 return DNS_TYPE_SOA;
702 case G_RESOLVER_RECORD_NS:
703 return DNS_TYPE_NS;
704 case G_RESOLVER_RECORD_MX:
705 return DNS_TYPE_MX;
707 g_return_val_if_reached (-1);
710 static GList *
711 g_resolver_records_from_DnsQuery (const gchar *rrname,
712 WORD dnstype,
713 DNS_STATUS status,
714 DNS_RECORD *results,
715 GError **error)
717 DNS_RECORD *rec;
718 gpointer record;
719 GList *records;
721 if (status != ERROR_SUCCESS)
723 if (status == DNS_ERROR_RCODE_NAME_ERROR)
725 g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_NOT_FOUND,
726 _("No DNS record of the requested type for “%s”"), rrname);
728 else if (status == DNS_ERROR_RCODE_SERVER_FAILURE)
730 g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_TEMPORARY_FAILURE,
731 _("Temporarily unable to resolve “%s”"), rrname);
733 else
735 g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_INTERNAL,
736 _("Error resolving “%s”"), rrname);
739 return NULL;
742 records = NULL;
743 for (rec = results; rec; rec = rec->pNext)
745 if (rec->wType != dnstype)
746 continue;
747 switch (dnstype)
749 case DNS_TYPE_SRV:
750 record = parse_dns_srv (rec);
751 break;
752 case DNS_TYPE_SOA:
753 record = parse_dns_soa (rec);
754 break;
755 case DNS_TYPE_NS:
756 record = parse_dns_ns (rec);
757 break;
758 case DNS_TYPE_MX:
759 record = parse_dns_mx (rec);
760 break;
761 case DNS_TYPE_TEXT:
762 record = parse_dns_txt (rec);
763 break;
764 default:
765 g_warn_if_reached ();
766 record = NULL;
767 break;
769 if (record != NULL)
770 records = g_list_prepend (records, g_variant_ref_sink (record));
773 if (records == NULL)
775 g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_NOT_FOUND,
776 _("No DNS record of the requested type for “%s”"), rrname);
778 return NULL;
780 else
781 return records;
784 #endif
786 typedef struct {
787 char *rrname;
788 GResolverRecordType record_type;
789 } LookupRecordsData;
791 static void
792 free_lookup_records_data (LookupRecordsData *lrd)
794 g_free (lrd->rrname);
795 g_slice_free (LookupRecordsData, lrd);
798 static void
799 free_records (GList *records)
801 g_list_free_full (records, (GDestroyNotify) g_variant_unref);
804 #if defined(G_OS_UNIX)
805 #ifdef __BIONIC__
806 #ifndef C_IN
807 #define C_IN 1
808 #endif
809 int res_query(const char *, int, int, u_char *, int);
810 #endif
811 #endif
813 static void
814 do_lookup_records (GTask *task,
815 gpointer source_object,
816 gpointer task_data,
817 GCancellable *cancellable)
819 LookupRecordsData *lrd = task_data;
820 GList *records;
821 GError *error = NULL;
823 #if defined(G_OS_UNIX)
824 gint len = 512;
825 gint herr;
826 GByteArray *answer;
827 gint rrtype;
829 #ifdef HAVE_RES_NQUERY
830 /* Load the resolver state. This is done once per worker thread, and the
831 * #GResolver::reload signal is ignored (since we always reload). This could
832 * be improved by having an explicit worker thread pool, with each thread
833 * containing some state which is initialised at thread creation time and
834 * updated in response to #GResolver::reload.
836 * What we have currently is not particularly worse than using res_query() in
837 * worker threads, since it would transparently call res_init() for each new
838 * worker thread. (Although the workers would get reused by the
839 * #GThreadPool.) */
840 struct __res_state res;
841 if (res_ninit (&res) != 0)
843 g_task_return_new_error (task, G_RESOLVER_ERROR, G_RESOLVER_ERROR_INTERNAL,
844 _("Error resolving “%s”"), lrd->rrname);
845 return;
847 #endif
849 rrtype = g_resolver_record_type_to_rrtype (lrd->record_type);
850 answer = g_byte_array_new ();
851 for (;;)
853 g_byte_array_set_size (answer, len * 2);
854 #if defined(HAVE_RES_NQUERY)
855 len = res_nquery (&res, lrd->rrname, C_IN, rrtype, answer->data, answer->len);
856 #else
857 len = res_query (lrd->rrname, C_IN, rrtype, answer->data, answer->len);
858 #endif
860 /* If answer fit in the buffer then we're done */
861 if (len < 0 || len < (gint)answer->len)
862 break;
865 * On overflow some res_query's return the length needed, others
866 * return the full length entered. This code works in either case.
870 herr = h_errno;
871 records = g_resolver_records_from_res_query (lrd->rrname, rrtype, answer->data, len, herr, &error);
872 g_byte_array_free (answer, TRUE);
874 #ifdef HAVE_RES_NQUERY
876 #if defined(HAVE_RES_NDESTROY)
877 res_ndestroy (&res);
878 #elif defined(HAVE_RES_NCLOSE)
879 res_nclose (&res);
880 #elif defined(HAVE_RES_NINIT)
881 #error "Your platform has res_ninit() but not res_nclose() or res_ndestroy(). Please file a bug at https://gitlab.gnome.org/GNOME/glib/issues/new"
882 #endif
884 #endif /* HAVE_RES_NQUERY */
886 #else
888 DNS_STATUS status;
889 DNS_RECORD *results = NULL;
890 WORD dnstype;
892 dnstype = g_resolver_record_type_to_dnstype (lrd->record_type);
893 status = DnsQuery_A (lrd->rrname, dnstype, DNS_QUERY_STANDARD, NULL, &results, NULL);
894 records = g_resolver_records_from_DnsQuery (lrd->rrname, dnstype, status, results, &error);
895 if (results != NULL)
896 DnsRecordListFree (results, DnsFreeRecordList);
898 #endif
900 if (records)
901 g_task_return_pointer (task, records, (GDestroyNotify) free_records);
902 else
903 g_task_return_error (task, error);
906 static GList *
907 lookup_records (GResolver *resolver,
908 const gchar *rrname,
909 GResolverRecordType record_type,
910 GCancellable *cancellable,
911 GError **error)
913 GTask *task;
914 GList *records;
915 LookupRecordsData *lrd;
917 task = g_task_new (resolver, cancellable, NULL, NULL);
918 g_task_set_source_tag (task, lookup_records);
920 lrd = g_slice_new (LookupRecordsData);
921 lrd->rrname = g_strdup (rrname);
922 lrd->record_type = record_type;
923 g_task_set_task_data (task, lrd, (GDestroyNotify) free_lookup_records_data);
925 g_task_set_return_on_cancel (task, TRUE);
926 g_task_run_in_thread_sync (task, do_lookup_records);
927 records = g_task_propagate_pointer (task, error);
928 g_object_unref (task);
930 return records;
933 static void
934 lookup_records_async (GResolver *resolver,
935 const char *rrname,
936 GResolverRecordType record_type,
937 GCancellable *cancellable,
938 GAsyncReadyCallback callback,
939 gpointer user_data)
941 GTask *task;
942 LookupRecordsData *lrd;
944 task = g_task_new (resolver, cancellable, callback, user_data);
945 g_task_set_source_tag (task, lookup_records_async);
947 lrd = g_slice_new (LookupRecordsData);
948 lrd->rrname = g_strdup (rrname);
949 lrd->record_type = record_type;
950 g_task_set_task_data (task, lrd, (GDestroyNotify) free_lookup_records_data);
952 g_task_set_return_on_cancel (task, TRUE);
953 g_task_run_in_thread (task, do_lookup_records);
954 g_object_unref (task);
957 static GList *
958 lookup_records_finish (GResolver *resolver,
959 GAsyncResult *result,
960 GError **error)
962 g_return_val_if_fail (g_task_is_valid (result, resolver), NULL);
964 return g_task_propagate_pointer (G_TASK (result), error);
968 static void
969 g_threaded_resolver_class_init (GThreadedResolverClass *threaded_class)
971 GResolverClass *resolver_class = G_RESOLVER_CLASS (threaded_class);
973 resolver_class->lookup_by_name = lookup_by_name;
974 resolver_class->lookup_by_name_async = lookup_by_name_async;
975 resolver_class->lookup_by_name_finish = lookup_by_name_finish;
976 resolver_class->lookup_by_address = lookup_by_address;
977 resolver_class->lookup_by_address_async = lookup_by_address_async;
978 resolver_class->lookup_by_address_finish = lookup_by_address_finish;
979 resolver_class->lookup_records = lookup_records;
980 resolver_class->lookup_records_async = lookup_records_async;
981 resolver_class->lookup_records_finish = lookup_records_finish;
983 /* Initialize addrinfo_hints */
984 #ifdef AI_ADDRCONFIG
985 addrinfo_hints.ai_flags |= AI_ADDRCONFIG;
986 #endif
987 /* These two don't actually matter, they just get copied into the
988 * returned addrinfo structures (and then we ignore them). But if
989 * we leave them unset, we'll get back duplicate answers.
991 addrinfo_hints.ai_socktype = SOCK_STREAM;
992 addrinfo_hints.ai_protocol = IPPROTO_TCP;