Improve test coverage for GSubprocess
[platform/upstream/glib.git] / gio / gthreadedresolver.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 <stdio.h>
28 #include <string.h>
29
30 #include "gthreadedresolver.h"
31 #include "gnetworkingprivate.h"
32
33 #include "gcancellable.h"
34 #include "ginetaddress.h"
35 #include "ginetsocketaddress.h"
36 #include "gtask.h"
37 #include "gsocketaddress.h"
38 #include "gsrvtarget.h"
39
40
41 G_DEFINE_TYPE (GThreadedResolver, g_threaded_resolver, G_TYPE_RESOLVER)
42
43 static void
44 g_threaded_resolver_init (GThreadedResolver *gtr)
45 {
46 }
47
48 static GResolverError
49 g_resolver_error_from_addrinfo_error (gint err)
50 {
51   switch (err)
52     {
53     case EAI_FAIL:
54 #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
55     case EAI_NODATA:
56 #endif
57     case EAI_NONAME:
58       return G_RESOLVER_ERROR_NOT_FOUND;
59
60     case EAI_AGAIN:
61       return G_RESOLVER_ERROR_TEMPORARY_FAILURE;
62
63     default:
64       return G_RESOLVER_ERROR_INTERNAL;
65     }
66 }
67
68 static struct addrinfo addrinfo_hints;
69
70 static void
71 do_lookup_by_name (GTask         *task,
72                    gpointer       source_object,
73                    gpointer       task_data,
74                    GCancellable  *cancellable)
75 {
76   const char *hostname = task_data;
77   struct addrinfo *res = NULL;
78   GList *addresses;
79   gint retval;
80
81   retval = getaddrinfo (hostname, NULL, &addrinfo_hints, &res);
82
83   if (retval == 0)
84     {
85       struct addrinfo *ai;
86       GSocketAddress *sockaddr;
87       GInetAddress *addr;
88
89       addresses = NULL;
90       for (ai = res; ai; ai = ai->ai_next)
91         {
92           sockaddr = g_socket_address_new_from_native (ai->ai_addr, ai->ai_addrlen);
93           if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
94             continue;
95
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);
99         }
100
101       addresses = g_list_reverse (addresses);
102       g_task_return_pointer (task, addresses,
103                              (GDestroyNotify)g_resolver_free_addresses);
104     }
105   else
106     {
107       g_task_return_new_error (task,
108                                G_RESOLVER_ERROR,
109                                g_resolver_error_from_addrinfo_error (retval),
110                                _("Error resolving '%s': %s"),
111                                hostname, gai_strerror (retval));
112     }
113
114   if (res)
115     freeaddrinfo (res);
116 }
117
118 static GList *
119 lookup_by_name (GResolver     *resolver,
120                 const gchar   *hostname,
121                 GCancellable  *cancellable,
122                 GError       **error)
123 {
124   GTask *task;
125   GList *addresses;
126
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);
133
134   return addresses;
135 }
136
137 static void
138 lookup_by_name_async (GResolver           *resolver,
139                       const gchar         *hostname,
140                       GCancellable        *cancellable,
141                       GAsyncReadyCallback  callback,
142                       gpointer             user_data)
143 {
144   GTask *task;
145
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);
151 }
152
153 static GList *
154 lookup_by_name_finish (GResolver     *resolver,
155                        GAsyncResult  *result,
156                        GError       **error)
157 {
158   g_return_val_if_fail (g_task_is_valid (result, resolver), NULL);
159
160   return g_task_propagate_pointer (G_TASK (result), error);
161 }
162
163
164 static void
165 do_lookup_by_address (GTask         *task,
166                       gpointer       source_object,
167                       gpointer       task_data,
168                       GCancellable  *cancellable)
169 {
170   GInetAddress *address = task_data;
171   struct sockaddr_storage sockaddr;
172   gsize sockaddr_size;
173   GSocketAddress *gsockaddr;
174   gchar name[NI_MAXHOST];
175   gint retval;
176
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);
182
183   retval = getnameinfo ((struct sockaddr *)&sockaddr, sockaddr_size,
184                         name, sizeof (name), NULL, 0, NI_NAMEREQD);
185   if (retval == 0)
186     g_task_return_pointer (task, g_strdup (name), g_free);
187   else
188     {
189       gchar *phys;
190
191       phys = g_inet_address_to_string (address);
192       g_task_return_new_error (task,
193                                G_RESOLVER_ERROR,
194                                g_resolver_error_from_addrinfo_error (retval),
195                                _("Error reverse-resolving '%s': %s"),
196                                phys ? phys : "(unknown)",
197                                gai_strerror (retval));
198       g_free (phys);
199     }
200 }
201
202 static gchar *
203 lookup_by_address (GResolver        *resolver,
204                    GInetAddress     *address,
205                    GCancellable     *cancellable,
206                    GError          **error)
207 {
208   GTask *task;
209   gchar *name;
210
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);
217
218   return name;
219 }
220
221 static void
222 lookup_by_address_async (GResolver           *resolver,
223                          GInetAddress        *address,
224                          GCancellable        *cancellable,
225                          GAsyncReadyCallback  callback,
226                          gpointer             user_data)
227 {
228   GTask *task;
229
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);
235 }
236
237 static gchar *
238 lookup_by_address_finish (GResolver     *resolver,
239                           GAsyncResult  *result,
240                           GError       **error)
241 {
242   g_return_val_if_fail (g_task_is_valid (result, resolver), NULL);
243
244   return g_task_propagate_pointer (G_TASK (result), error);
245 }
246
247
248 #if defined(G_OS_UNIX)
249
250 #ifdef __BIONIC__
251 /* Copy from bionic/libc/private/arpa_nameser_compat.h
252  * and bionic/libc/private/arpa_nameser.h */
253 typedef struct {
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 */
268 #endif
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 */
282 #endif
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 */
288 } HEADER;
289
290 #define NS_INT32SZ      4       /* #/bytes of data in a uint32_t */
291 #define NS_INT16SZ      2       /* #/bytes of data in a uint16_t */
292
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]) \
297             ; \
298         (cp) += NS_INT16SZ; \
299 } while (/*CONSTCOND*/0)
300
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]) \
307             ; \
308         (cp) += NS_INT32SZ; \
309 } while (/*CONSTCOND*/0)
310
311 #define GETSHORT                NS_GET16
312 #define GETLONG                 NS_GET32
313
314 #define C_IN 1
315
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 *);
320
321 /* From bionic/libc/private/arpa_nameser_compat.h */
322 #define T_MX            ns_t_mx
323 #define T_TXT           ns_t_txt
324 #define T_SOA           ns_t_soa
325 #define T_NS            ns_t_ns
326
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. */
380         ns_t_max = 65536
381 } ns_type;
382
383 #endif /* __BIONIC__ */
384
385 static GVariant *
386 parse_res_srv (guchar  *answer,
387                guchar  *end,
388                guchar **p)
389 {
390   gchar namebuf[1024];
391   guint16 priority, weight, port;
392
393   GETSHORT (priority, *p);
394   GETSHORT (weight, *p);
395   GETSHORT (port, *p);
396   *p += dn_expand (answer, end, *p, namebuf, sizeof (namebuf));
397
398   return g_variant_new ("(qqqs)",
399                         priority,
400                         weight,
401                         port,
402                         namebuf);
403 }
404
405 static GVariant *
406 parse_res_soa (guchar  *answer,
407                guchar  *end,
408                guchar **p)
409 {
410   gchar mnamebuf[1024];
411   gchar rnamebuf[1024];
412   guint32 serial, refresh, retry, expire, ttl;
413
414   *p += dn_expand (answer, end, *p, mnamebuf, sizeof (mnamebuf));
415   *p += dn_expand (answer, end, *p, rnamebuf, sizeof (rnamebuf));
416
417   GETLONG (serial, *p);
418   GETLONG (refresh, *p);
419   GETLONG (retry, *p);
420   GETLONG (expire, *p);
421   GETLONG (ttl, *p);
422
423   return g_variant_new ("(ssuuuuu)",
424                         mnamebuf,
425                         rnamebuf,
426                         serial,
427                         refresh,
428                         retry,
429                         expire,
430                         ttl);
431 }
432
433 static GVariant *
434 parse_res_ns (guchar  *answer,
435               guchar  *end,
436               guchar **p)
437 {
438   gchar namebuf[1024];
439
440   *p += dn_expand (answer, end, *p, namebuf, sizeof (namebuf));
441
442   return g_variant_new ("(s)", namebuf);
443 }
444
445 static GVariant *
446 parse_res_mx (guchar  *answer,
447               guchar  *end,
448               guchar **p)
449 {
450   gchar namebuf[1024];
451   guint16 preference;
452
453   GETSHORT (preference, *p);
454
455   *p += dn_expand (answer, end, *p, namebuf, sizeof (namebuf));
456
457   return g_variant_new ("(qs)",
458                         preference,
459                         namebuf);
460 }
461
462 static GVariant *
463 parse_res_txt (guchar  *answer,
464                guchar  *end,
465                guchar **p)
466 {
467   GVariant *record;
468   GPtrArray *array;
469   guchar *at = *p;
470   gsize len;
471
472   array = g_ptr_array_new_with_free_func (g_free);
473   while (at < end)
474     {
475       len = *(at++);
476       if (len > at - end)
477         break;
478       g_ptr_array_add (array, g_strndup ((gchar *)at, len));
479       at += len;
480     }
481
482   *p = at;
483   record = g_variant_new ("(@as)",
484                           g_variant_new_strv ((const gchar **)array->pdata, array->len));
485   g_ptr_array_free (array, TRUE);
486   return record;
487 }
488
489 static gint
490 g_resolver_record_type_to_rrtype (GResolverRecordType type)
491 {
492   switch (type)
493   {
494     case G_RESOLVER_RECORD_SRV:
495       return T_SRV;
496     case G_RESOLVER_RECORD_TXT:
497       return T_TXT;
498     case G_RESOLVER_RECORD_SOA:
499       return T_SOA;
500     case G_RESOLVER_RECORD_NS:
501       return T_NS;
502     case G_RESOLVER_RECORD_MX:
503       return T_MX;
504   }
505   g_return_val_if_reached (-1);
506 }
507
508 #pragma GCC diagnostic push
509 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
510
511 static GList *
512 g_resolver_records_from_res_query (const gchar      *rrname,
513                                    gint              rrtype,
514                                    guchar           *answer,
515                                    gint              len,
516                                    gint              herr,
517                                    GError          **error)
518 {
519   gint count;
520   gchar namebuf[1024];
521   guchar *end, *p;
522   guint16 type, qclass, rdlength;
523   guint32 ttl;
524   HEADER *header;
525   GList *records;
526   GVariant *record;
527
528   if (len <= 0)
529     {
530       GResolverError errnum;
531       const gchar *format;
532
533       if (len == 0 || herr == HOST_NOT_FOUND || herr == NO_DATA)
534         {
535           errnum = G_RESOLVER_ERROR_NOT_FOUND;
536           format = _("No DNS record of the requested type for '%s'");
537         }
538       else if (herr == TRY_AGAIN)
539         {
540           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
541           format = _("Temporarily unable to resolve '%s'");
542         }
543       else
544         {
545           errnum = G_RESOLVER_ERROR_INTERNAL;
546           format = _("Error resolving '%s'");
547         }
548
549       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
550       return NULL;
551     }
552
553   records = NULL;
554
555   header = (HEADER *)answer;
556   p = answer + sizeof (HEADER);
557   end = answer + len;
558
559   /* Skip query */
560   count = ntohs (header->qdcount);
561   while (count-- && p < end)
562     {
563       p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
564       p += 4;
565
566       /* To silence gcc warnings */
567       namebuf[0] = namebuf[1];
568     }
569
570   /* Read answers */
571   count = ntohs (header->ancount);
572   while (count-- && p < end)
573     {
574       p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
575       GETSHORT (type, p);
576       GETSHORT (qclass, p);
577       GETLONG  (ttl, p);
578       ttl = ttl; /* To avoid -Wunused-but-set-variable */
579       GETSHORT (rdlength, p);
580
581       if (type != rrtype || qclass != C_IN)
582         {
583           p += rdlength;
584           continue;
585         }
586
587       switch (rrtype)
588         {
589         case T_SRV:
590           record = parse_res_srv (answer, end, &p);
591           break;
592         case T_MX:
593           record = parse_res_mx (answer, end, &p);
594           break;
595         case T_SOA:
596           record = parse_res_soa (answer, end, &p);
597           break;
598         case T_NS:
599           record = parse_res_ns (answer, end, &p);
600           break;
601         case T_TXT:
602           record = parse_res_txt (answer, p + rdlength, &p);
603           break;
604         default:
605           g_warn_if_reached ();
606           record = NULL;
607           break;
608         }
609
610       if (record != NULL)
611         records = g_list_prepend (records, record);
612     }
613
614   if (records == NULL)
615     {
616       g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_NOT_FOUND,
617                    _("No DNS record of the requested type for '%s'"), rrname);
618
619       return NULL;
620     }
621   else
622     return records;
623 }
624
625 #pragma GCC diagnostic pop
626
627 #elif defined(G_OS_WIN32)
628
629 static GVariant *
630 parse_dns_srv (DNS_RECORD *rec)
631 {
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);
637 }
638
639 static GVariant *
640 parse_dns_soa (DNS_RECORD *rec)
641 {
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);
650 }
651
652 static GVariant *
653 parse_dns_ns (DNS_RECORD *rec)
654 {
655   return g_variant_new ("(s)", rec->Data.NS.pNameHost);
656 }
657
658 static GVariant *
659 parse_dns_mx (DNS_RECORD *rec)
660 {
661   return g_variant_new ("(qs)",
662                         (guint16)rec->Data.MX.wPreference,
663                         rec->Data.MX.pNameExchange);
664 }
665
666 static GVariant *
667 parse_dns_txt (DNS_RECORD *rec)
668 {
669   GVariant *record;
670   GPtrArray *array;
671   DWORD i;
672
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);
679   return record;
680 }
681
682 static WORD
683 g_resolver_record_type_to_dnstype (GResolverRecordType type)
684 {
685   switch (type)
686   {
687     case G_RESOLVER_RECORD_SRV:
688       return DNS_TYPE_SRV;
689     case G_RESOLVER_RECORD_TXT:
690       return DNS_TYPE_TEXT;
691     case G_RESOLVER_RECORD_SOA:
692       return DNS_TYPE_SOA;
693     case G_RESOLVER_RECORD_NS:
694       return DNS_TYPE_NS;
695     case G_RESOLVER_RECORD_MX:
696       return DNS_TYPE_MX;
697   }
698   g_return_val_if_reached (-1);
699 }
700
701 static GList *
702 g_resolver_records_from_DnsQuery (const gchar  *rrname,
703                                   WORD          dnstype,
704                                   DNS_STATUS    status,
705                                   DNS_RECORD   *results,
706                                   GError      **error)
707 {
708   DNS_RECORD *rec;
709   gpointer record;
710   GList *records;
711
712   if (status != ERROR_SUCCESS)
713     {
714       GResolverError errnum;
715       const gchar *format;
716
717       if (status == DNS_ERROR_RCODE_NAME_ERROR)
718         {
719           errnum = G_RESOLVER_ERROR_NOT_FOUND;
720           format = _("No DNS record of the requested type for '%s'");
721         }
722       else if (status == DNS_ERROR_RCODE_SERVER_FAILURE)
723         {
724           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
725           format = _("Temporarily unable to resolve '%s'");
726         }
727       else
728         {
729           errnum = G_RESOLVER_ERROR_INTERNAL;
730           format = _("Error resolving '%s'");
731         }
732
733       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
734       return NULL;
735     }
736
737   records = NULL;
738   for (rec = results; rec; rec = rec->pNext)
739     {
740       if (rec->wType != dnstype)
741         continue;
742       switch (dnstype)
743         {
744         case DNS_TYPE_SRV:
745           record = parse_dns_srv (rec);
746           break;
747         case DNS_TYPE_SOA:
748           record = parse_dns_soa (rec);
749           break;
750         case DNS_TYPE_NS:
751           record = parse_dns_ns (rec);
752           break;
753         case DNS_TYPE_MX:
754           record = parse_dns_mx (rec);
755           break;
756         case DNS_TYPE_TEXT:
757           record = parse_dns_txt (rec);
758           break;
759         default:
760           g_warn_if_reached ();
761           record = NULL;
762           break;
763         }
764       if (record != NULL)
765         records = g_list_prepend (records, g_variant_ref_sink (record));
766     }
767
768   if (records == NULL)
769     {
770       g_set_error (error, G_RESOLVER_ERROR, G_RESOLVER_ERROR_NOT_FOUND,
771                    _("No DNS record of the requested type for '%s'"), rrname);
772
773       return NULL;
774     }
775   else
776     return records;
777 }
778
779 #endif
780
781 typedef struct {
782   char *rrname;
783   GResolverRecordType record_type;
784 } LookupRecordsData;
785
786 static void
787 free_lookup_records_data (LookupRecordsData *lrd)
788 {
789   g_free (lrd->rrname);
790   g_slice_free (LookupRecordsData, lrd);
791 }
792
793 static void
794 free_records (GList *records)
795 {
796   g_list_free_full (records, (GDestroyNotify) g_variant_unref);
797 }
798
799 #if defined(G_OS_UNIX)
800 #ifdef __BIONIC__
801 #define C_IN 1
802 int res_query(const char *, int, int, u_char *, int);
803 #endif
804 #endif
805
806 static void
807 do_lookup_records (GTask         *task,
808                    gpointer       source_object,
809                    gpointer       task_data,
810                    GCancellable  *cancellable)
811 {
812   LookupRecordsData *lrd = task_data;
813   GList *records;
814   GError *error = NULL;
815
816 #if defined(G_OS_UNIX)
817   gint len = 512;
818   gint herr;
819   GByteArray *answer;
820   gint rrtype;
821
822   rrtype = g_resolver_record_type_to_rrtype (lrd->record_type);
823   answer = g_byte_array_new ();
824   for (;;)
825     {
826       g_byte_array_set_size (answer, len * 2);
827       len = res_query (lrd->rrname, C_IN, rrtype, answer->data, answer->len);
828
829       /* If answer fit in the buffer then we're done */
830       if (len < 0 || len < (gint)answer->len)
831         break;
832
833       /*
834        * On overflow some res_query's return the length needed, others
835        * return the full length entered. This code works in either case.
836        */
837     }
838
839   herr = h_errno;
840   records = g_resolver_records_from_res_query (lrd->rrname, rrtype, answer->data, len, herr, &error);
841   g_byte_array_free (answer, TRUE);
842
843 #else
844
845   DNS_STATUS status;
846   DNS_RECORD *results = NULL;
847   WORD dnstype;
848
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);
852   if (results != NULL)
853     DnsRecordListFree (results, DnsFreeRecordList);
854
855 #endif
856
857   if (records)
858     g_task_return_pointer (task, records, (GDestroyNotify) free_records);
859   else
860     g_task_return_error (task, error);
861 }
862
863 static GList *
864 lookup_records (GResolver              *resolver,
865                 const gchar            *rrname,
866                 GResolverRecordType     record_type,
867                 GCancellable           *cancellable,
868                 GError                **error)
869 {
870   GTask *task;
871   GList *records;
872   LookupRecordsData *lrd;
873
874   task = g_task_new (resolver, cancellable, NULL, NULL);
875
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);
880
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);
885
886   return records;
887 }
888
889 static void
890 lookup_records_async (GResolver           *resolver,
891                       const char          *rrname,
892                       GResolverRecordType  record_type,
893                       GCancellable        *cancellable,
894                       GAsyncReadyCallback  callback,
895                       gpointer             user_data)
896 {
897   GTask *task;
898   LookupRecordsData *lrd;
899
900   task = g_task_new (resolver, cancellable, callback, user_data);
901
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);
906
907   g_task_set_return_on_cancel (task, TRUE);
908   g_task_run_in_thread (task, do_lookup_records);
909   g_object_unref (task);
910 }
911
912 static GList *
913 lookup_records_finish (GResolver     *resolver,
914                        GAsyncResult  *result,
915                        GError       **error)
916 {
917   g_return_val_if_fail (g_task_is_valid (result, resolver), NULL);
918
919   return g_task_propagate_pointer (G_TASK (result), error);
920 }
921
922
923 static void
924 g_threaded_resolver_class_init (GThreadedResolverClass *threaded_class)
925 {
926   GResolverClass *resolver_class = G_RESOLVER_CLASS (threaded_class);
927
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;
937
938   /* Initialize _g_resolver_addrinfo_hints */
939 #ifdef AI_ADDRCONFIG
940   addrinfo_hints.ai_flags |= AI_ADDRCONFIG;
941 #endif
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.
945    */
946   addrinfo_hints.ai_socktype = SOCK_STREAM;
947   addrinfo_hints.ai_protocol = IPPROTO_TCP;
948 }