gio/tests/file: skip the file monitor tests if using GPollFileMonitor
[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 "gsimpleasyncresult.h"
35 #include "gsocketaddress.h"
36
37
38 G_DEFINE_TYPE (GThreadedResolver, g_threaded_resolver, G_TYPE_RESOLVER)
39
40 static void threaded_resolver_thread (gpointer thread_data, gpointer pool_data);
41
42 static void
43 g_threaded_resolver_init (GThreadedResolver *gtr)
44 {
45   gtr->thread_pool = g_thread_pool_new (threaded_resolver_thread, gtr,
46                                         -1, FALSE, NULL);
47 }
48
49 static void
50 finalize (GObject *object)
51 {
52   GThreadedResolver *gtr = G_THREADED_RESOLVER (object);
53
54   g_thread_pool_free (gtr->thread_pool, FALSE, FALSE);
55
56   G_OBJECT_CLASS (g_threaded_resolver_parent_class)->finalize (object);
57 }
58
59 /* A GThreadedResolverRequest represents a request in progress
60  * (usually, but see case 1). It is refcounted, to make sure that it
61  * doesn't get freed too soon. In particular, it can't be freed until
62  * (a) the resolver thread has finished resolving, (b) the calling
63  * thread has received an answer, and (c) no other thread could be in
64  * the process of trying to cancel it.
65  *
66  * The possibilities:
67  *
68  * 1. Synchronous non-cancellable request: in this case, the request
69  *    is simply done in the calling thread, without using
70  *    GThreadedResolverRequest at all.
71  *
72  * 2. Synchronous cancellable request: A req is created with a GCond,
73  *    and 3 refs (for the resolution thread, the calling thread, and
74  *    the cancellation signal handler).
75  *
76  *      a. If the resolution completes successfully, the thread pool
77  *         function (threaded_resolver_thread()) will call
78  *         g_threaded_resolver_request_complete(), which will detach
79  *         the "cancelled" signal handler (dropping one ref on req)
80  *         and signal the GCond, and then unref the req. The calling
81  *         thread receives the signal from the GCond, processes the
82  *         response, and unrefs the req, causing it to be freed.
83  *
84  *      b. If the resolution is cancelled before completing,
85  *         request_cancelled() will call
86  *         g_threaded_resolver_request_complete(), which will detach
87  *         the signal handler (as above, unreffing the req), set
88  *         req->error to indicate that it was cancelled, and signal
89  *         the GCond. The calling thread receives the signal from the
90  *         GCond, processes the response, and unrefs the req.
91  *         Eventually, the resolver thread finishes resolving (or
92  *         times out in the resolver) and calls
93  *         g_threaded_resolver_request_complete() again, but
94  *         _request_complete() does nothing this time since the
95  *         request is already complete. The thread pool func then
96  *         unrefs the req, causing it to be freed.
97  *
98  * 3. Asynchronous request: A req is created with a GSimpleAsyncResult
99  *    (and no GCond). The calling thread's ref on req is set up to be
100  *    automatically dropped when the async_result is freed. Two
101  *    sub-possibilities:
102  *
103  *      a. If the resolution completes, the thread pool function
104  *         (threaded_resolver_thread()) will call
105  *         g_threaded_resolver_request_complete(), which will detach
106  *         the "cancelled" signal handler (if it was present)
107  *         (unreffing the req), queue the async_result to complete in
108  *         an idle handler, unref the async_result (which is still
109  *         reffed by the idle handler though), and then unref the req.
110  *         The main thread then invokes the async_result's callback
111  *         and processes the response. When it finishes, the
112  *         async_result drops the ref that was taken by
113  *         g_simple_async_result_complete_in_idle(), which causes the
114  *         async_result to be freed, which causes req to be unreffed
115  *         and freed.
116  *
117  *      b. If the resolution is cancelled, request_cancelled() will
118  *         call g_threaded_resolver_request_complete(), which will
119  *         detach the signal handler (as above, unreffing the req) set
120  *         req->error to indicate that it was cancelled, and queue and
121  *         unref the async_result. The main thread completes the
122  *         async_request and unrefs it and the req, as above.
123  *         Eventually, the resolver thread finishes resolving (or
124  *         times out in the resolver) and calls
125  *         g_threaded_resolver_request_complete() again, but
126  *         _request_complete() does nothing this time since the
127  *         request is already complete. The thread pool func then
128  *         unrefs the req, causing it to be freed.
129  *
130  * g_threaded_resolver_request_complete() ensures that if the request
131  * completes and cancels "at the same time" that only one of the two
132  * conditions gets processed.
133  */
134
135 typedef struct _GThreadedResolverRequest GThreadedResolverRequest;
136 typedef void (*GThreadedResolverResolveFunc) (GThreadedResolverRequest *, GError **);
137 typedef void (*GThreadedResolverFreeFunc) (GThreadedResolverRequest *);
138
139 struct _GThreadedResolverRequest {
140   GThreadedResolverResolveFunc resolve_func;
141   GThreadedResolverFreeFunc free_func;
142
143   union {
144     struct {
145       gchar *hostname;
146       GList *addresses;
147     } name;
148     struct {
149       GInetAddress *address;
150       gchar *name;
151     } address;
152     struct {
153       gchar *rrname;
154       GResolverRecordType record_type;
155       GList *results;
156     } records;
157   } u;
158
159   GCancellable *cancellable;
160   GError *error;
161
162   GMutex mutex;
163   guint ref_count;
164
165   GCond cond;
166   GSimpleAsyncResult *async_result;
167   gboolean complete;
168
169 };
170
171 static void g_threaded_resolver_request_unref (GThreadedResolverRequest *req);
172 static void request_cancelled (GCancellable *cancellable, gpointer req);
173 static void request_cancelled_disconnect_notify (gpointer req, GClosure *closure);
174
175 static GThreadedResolverRequest *
176 g_threaded_resolver_request_new (GThreadedResolverResolveFunc  resolve_func,
177                                  GThreadedResolverFreeFunc     free_func,
178                                  GCancellable                 *cancellable)
179 {
180   GThreadedResolverRequest *req;
181
182   req = g_slice_new0 (GThreadedResolverRequest);
183   req->resolve_func = resolve_func;
184   req->free_func = free_func;
185
186   /* Initial refcount is 2; one for the caller and one for resolve_func */
187   req->ref_count = 2;
188
189   g_mutex_init (&req->mutex);
190   g_cond_init (&req->cond);
191   /* Initially locked; caller must unlock */
192   g_mutex_lock (&req->mutex);
193
194   if (cancellable)
195     {
196       req->ref_count++;
197       req->cancellable = g_object_ref (cancellable);
198       g_signal_connect_data (cancellable, "cancelled",
199                              G_CALLBACK (request_cancelled), req,
200                              request_cancelled_disconnect_notify, 0);
201     }
202
203   return req;
204 }
205
206 static void
207 g_threaded_resolver_request_unref (GThreadedResolverRequest *req)
208 {
209   guint ref_count;
210
211   g_mutex_lock (&req->mutex);
212   ref_count = --req->ref_count;
213   g_mutex_unlock (&req->mutex);
214   if (ref_count > 0)
215     return;
216
217   g_mutex_clear (&req->mutex);
218   g_cond_clear (&req->cond);
219
220   if (req->error)
221     g_error_free (req->error);
222
223   if (req->free_func)
224     req->free_func (req);
225
226   /* We don't have to free req->cancellable or req->async_result,
227    * since (if set), they must already have been freed by
228    * request_complete() in order to get here.
229    */
230
231   g_slice_free (GThreadedResolverRequest, req);
232 }
233
234 static void
235 g_threaded_resolver_request_complete (GThreadedResolverRequest *req,
236                                       GError                   *error)
237 {
238   g_mutex_lock (&req->mutex);
239   if (req->complete)
240     {
241       /* The req was cancelled, and now it has finished resolving as
242        * well. But we have nowhere to send the result, so just return.
243        */
244       g_mutex_unlock (&req->mutex);
245       g_clear_error (&error);
246       return;
247     }
248
249   req->complete = TRUE;
250   g_mutex_unlock (&req->mutex);
251
252   if (error)
253     g_propagate_error (&req->error, error);
254
255   if (req->cancellable)
256     {
257       /* Drop the signal handler's ref on @req */
258       g_signal_handlers_disconnect_by_func (req->cancellable, request_cancelled, req);
259       g_object_unref (req->cancellable);
260       req->cancellable = NULL;
261     }
262
263   if (req->async_result)
264     {
265       if (req->error)
266         g_simple_async_result_set_from_error (req->async_result, req->error);
267       g_simple_async_result_complete_in_idle (req->async_result);
268
269       /* Drop our ref on the async_result, which will eventually cause
270        * it to drop its ref on req.
271        */
272       g_object_unref (req->async_result);
273       req->async_result = NULL;
274     }
275
276   else
277     g_cond_signal (&req->cond);
278 }
279
280 static void
281 request_cancelled (GCancellable *cancellable,
282                    gpointer      user_data)
283 {
284   GThreadedResolverRequest *req = user_data;
285   GError *error = NULL;
286
287   g_cancellable_set_error_if_cancelled (req->cancellable, &error);
288   g_threaded_resolver_request_complete (req, error);
289
290   /* We can't actually cancel the resolver thread; it will eventually
291    * complete on its own and call request_complete() again, which will
292    * do nothing the second time.
293    */
294 }
295
296 static void
297 request_cancelled_disconnect_notify (gpointer  req,
298                                      GClosure *closure)
299 {
300   g_threaded_resolver_request_unref (req);
301 }
302
303 static void
304 threaded_resolver_thread (gpointer thread_data,
305                           gpointer pool_data)
306 {
307   GThreadedResolverRequest *req = thread_data;
308   GError *error = NULL;
309
310   req->resolve_func (req, &error);
311   g_threaded_resolver_request_complete (req, error);
312   g_threaded_resolver_request_unref (req);
313 }
314
315 static void
316 resolve_sync (GThreadedResolver         *gtr,
317               GThreadedResolverRequest  *req,
318               GError                   **error)
319 {
320   if (!req->cancellable)
321     {
322       req->resolve_func (req, error);
323       g_mutex_unlock (&req->mutex);
324
325       g_threaded_resolver_request_complete (req, FALSE);
326       g_threaded_resolver_request_unref (req);
327       return;
328     }
329
330   g_thread_pool_push (gtr->thread_pool, req, &req->error);
331   if (!req->error)
332     g_cond_wait (&req->cond, &req->mutex);
333   g_mutex_unlock (&req->mutex);
334
335   if (req->error)
336     {
337       g_propagate_error (error, req->error);
338       req->error = NULL;
339     }
340 }
341
342 static void
343 resolve_async (GThreadedResolver        *gtr,
344                GThreadedResolverRequest *req,
345                GAsyncReadyCallback       callback,
346                gpointer                  user_data,
347                gpointer                  tag)
348 {
349   req->async_result = g_simple_async_result_new (G_OBJECT (gtr),
350                                                  callback, user_data, tag);
351   g_simple_async_result_set_op_res_gpointer (req->async_result, req,
352                                              (GDestroyNotify)g_threaded_resolver_request_unref);
353   g_thread_pool_push (gtr->thread_pool, req, NULL);
354   g_mutex_unlock (&req->mutex);
355 }
356
357 static GThreadedResolverRequest *
358 resolve_finish (GResolver     *resolver,
359                 GAsyncResult  *result,
360                 gpointer       tag,
361                 GError       **error)
362 {
363   g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (resolver), tag), NULL);
364
365   return g_simple_async_result_get_op_res_gpointer (G_SIMPLE_ASYNC_RESULT (result));
366 }
367
368 static void
369 do_lookup_by_name (GThreadedResolverRequest  *req,
370                    GError                   **error)
371 {
372   struct addrinfo *res = NULL;
373   gint retval;
374
375   retval = getaddrinfo (req->u.name.hostname, NULL,
376                         &_g_resolver_addrinfo_hints, &res);
377   req->u.name.addresses =
378     _g_resolver_addresses_from_addrinfo (req->u.name.hostname, res, retval, error);
379   if (res)
380     freeaddrinfo (res);
381 }
382
383 static GList *
384 lookup_by_name (GResolver     *resolver,
385                 const gchar   *hostname,
386                 GCancellable  *cancellable,
387                 GError       **error)
388 {
389   GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
390   GThreadedResolverRequest *req;
391   GList *addresses;
392
393   req = g_threaded_resolver_request_new (do_lookup_by_name, NULL, cancellable);
394   req->u.name.hostname = (gchar *)hostname;
395   resolve_sync (gtr, req, error);
396
397   addresses = req->u.name.addresses;
398   g_threaded_resolver_request_unref (req);
399   return addresses;
400 }
401
402 static void
403 free_lookup_by_name (GThreadedResolverRequest *req)
404 {
405   g_free (req->u.name.hostname);
406   if (req->u.name.addresses)
407     g_resolver_free_addresses (req->u.name.addresses);
408 }
409
410 static void
411 lookup_by_name_async (GResolver           *resolver,
412                       const gchar         *hostname,
413                       GCancellable        *cancellable,
414                       GAsyncReadyCallback  callback,
415                       gpointer             user_data)
416 {
417   GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
418   GThreadedResolverRequest *req;
419
420   req = g_threaded_resolver_request_new (do_lookup_by_name, free_lookup_by_name,
421                                          cancellable);
422   req->u.name.hostname = g_strdup (hostname);
423   resolve_async (gtr, req, callback, user_data, lookup_by_name_async);
424 }
425
426 static GList *
427 lookup_by_name_finish (GResolver     *resolver,
428                        GAsyncResult  *result,
429                        GError       **error)
430 {
431   GThreadedResolverRequest *req;
432   GList *addresses;
433
434   req = resolve_finish (resolver, result, lookup_by_name_async, error);
435   addresses = req->u.name.addresses;
436   req->u.name.addresses = NULL;
437   return addresses;
438 }
439
440
441 static void
442 do_lookup_by_address (GThreadedResolverRequest  *req,
443                       GError                   **error)
444 {
445   struct sockaddr_storage sockaddr;
446   gsize sockaddr_size;
447   gchar name[NI_MAXHOST];
448   gint retval;
449
450   _g_resolver_address_to_sockaddr (req->u.address.address,
451                                    &sockaddr, &sockaddr_size);
452
453   retval = getnameinfo ((struct sockaddr *)&sockaddr, sockaddr_size,
454                         name, sizeof (name), NULL, 0, NI_NAMEREQD);
455   req->u.address.name = _g_resolver_name_from_nameinfo (req->u.address.address,
456                                                         name, retval, error);
457 }
458
459 static gchar *
460 lookup_by_address (GResolver        *resolver,
461                    GInetAddress     *address,
462                    GCancellable     *cancellable,
463                    GError          **error)
464 {
465   GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
466   GThreadedResolverRequest *req;
467   gchar *name;
468
469   req = g_threaded_resolver_request_new (do_lookup_by_address, NULL, cancellable);
470   req->u.address.address = address;
471   resolve_sync (gtr, req, error);
472
473   name = req->u.address.name;
474   g_threaded_resolver_request_unref (req);
475   return name;
476 }
477
478 static void
479 free_lookup_by_address (GThreadedResolverRequest *req)
480 {
481   g_object_unref (req->u.address.address);
482   if (req->u.address.name)
483     g_free (req->u.address.name);
484 }
485
486 static void
487 lookup_by_address_async (GResolver           *resolver,
488                          GInetAddress        *address,
489                          GCancellable        *cancellable,
490                          GAsyncReadyCallback  callback,
491                          gpointer             user_data)
492 {
493   GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
494   GThreadedResolverRequest *req;
495
496   req = g_threaded_resolver_request_new (do_lookup_by_address,
497                                          free_lookup_by_address,
498                                          cancellable);
499   req->u.address.address = g_object_ref (address);
500   resolve_async (gtr, req, callback, user_data, lookup_by_address_async);
501 }
502
503 static gchar *
504 lookup_by_address_finish (GResolver     *resolver,
505                           GAsyncResult  *result,
506                           GError       **error)
507 {
508   GThreadedResolverRequest *req;
509   gchar *name;
510
511   req = resolve_finish (resolver, result, lookup_by_address_async, error);
512   name = req->u.address.name;
513   req->u.address.name = NULL;
514   return name;
515 }
516
517
518 static void
519 do_lookup_records (GThreadedResolverRequest  *req,
520                    GError                   **error)
521 {
522 #if defined(G_OS_UNIX)
523   gint len = 512;
524   gint herr;
525   GByteArray *answer;
526   gint rrtype;
527
528   rrtype = _g_resolver_record_type_to_rrtype (req->u.records.record_type);
529   answer = g_byte_array_new ();
530   for (;;)
531     {
532       g_byte_array_set_size (answer, len * 2);
533       len = res_query (req->u.records.rrname, C_IN, rrtype, answer->data, answer->len);
534
535       /* If answer fit in the buffer then we're done */
536       if (len < 0 || len < (gint)answer->len)
537         break;
538
539       /*
540        * On overflow some res_query's return the length needed, others
541        * return the full length entered. This code works in either case.
542        */
543   }
544
545   herr = h_errno;
546   req->u.records.results = _g_resolver_records_from_res_query (req->u.records.rrname, rrtype, answer->data, len, herr, error);
547   g_byte_array_free (answer, TRUE);
548
549 #elif defined(G_OS_WIN32)
550   DNS_STATUS status;
551   DNS_RECORD *results = NULL;
552   WORD dnstype;
553
554   dnstype = _g_resolver_record_type_to_dnstype (req->u.records.record_type);
555   status = DnsQuery_A (req->u.records.rrname, dnstype, DNS_QUERY_STANDARD, NULL, &results, NULL);
556   req->u.records.results = _g_resolver_records_from_DnsQuery (req->u.records.rrname, dnstype, status, results, error);
557   if (results != NULL)
558     DnsRecordListFree (results, DnsFreeRecordList);
559 #endif
560 }
561
562 static GList *
563 lookup_records (GResolver              *resolver,
564                 const gchar            *rrname,
565                 GResolverRecordType    record_type,
566                 GCancellable          *cancellable,
567                 GError               **error)
568 {
569   GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
570   GThreadedResolverRequest *req;
571   GList *results;
572
573   req = g_threaded_resolver_request_new (do_lookup_records, NULL, cancellable);
574   req->u.records.rrname = (char *)rrname;
575   req->u.records.record_type = record_type;
576   resolve_sync (gtr, req, error);
577
578   results = req->u.records.results;
579   g_threaded_resolver_request_unref (req);
580   return results;
581 }
582
583 static void
584 free_lookup_records (GThreadedResolverRequest *req)
585 {
586   g_free (req->u.records.rrname);
587   g_list_free_full (req->u.records.results, (GDestroyNotify)g_variant_unref);
588 }
589
590 static void
591 lookup_records_async (GResolver           *resolver,
592                       const char          *rrname,
593                       GResolverRecordType  record_type,
594                       GCancellable        *cancellable,
595                       GAsyncReadyCallback  callback,
596                       gpointer             user_data)
597 {
598   GThreadedResolver *gtr = G_THREADED_RESOLVER (resolver);
599   GThreadedResolverRequest *req;
600
601   req = g_threaded_resolver_request_new (do_lookup_records,
602                                          free_lookup_records,
603                                          cancellable);
604   req->u.records.rrname = g_strdup (rrname);
605   req->u.records.record_type = record_type;
606   resolve_async (gtr, req, callback, user_data, lookup_records_async);
607 }
608
609 static GList *
610 lookup_records_finish (GResolver     *resolver,
611                        GAsyncResult  *result,
612                        GError       **error)
613 {
614   GThreadedResolverRequest *req;
615   GList *records;
616
617   req = resolve_finish (resolver, result, lookup_records_async, error);
618   records = req->u.records.results;
619   req->u.records.results = NULL;
620   return records;
621 }
622
623
624 static void
625 g_threaded_resolver_class_init (GThreadedResolverClass *threaded_class)
626 {
627   GResolverClass *resolver_class = G_RESOLVER_CLASS (threaded_class);
628   GObjectClass *object_class = G_OBJECT_CLASS (threaded_class);
629
630   resolver_class->lookup_by_name           = lookup_by_name;
631   resolver_class->lookup_by_name_async     = lookup_by_name_async;
632   resolver_class->lookup_by_name_finish    = lookup_by_name_finish;
633   resolver_class->lookup_by_address        = lookup_by_address;
634   resolver_class->lookup_by_address_async  = lookup_by_address_async;
635   resolver_class->lookup_by_address_finish = lookup_by_address_finish;
636   resolver_class->lookup_records           = lookup_records;
637   resolver_class->lookup_records_async     = lookup_records_async;
638   resolver_class->lookup_records_finish    = lookup_records_finish;
639
640   object_class->finalize = finalize;
641 }