Merge remote branch 'gvdb/master'
[platform/upstream/glib.git] / gio / gunixresolver.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 "gunixresolver.h"
31 #include "gnetworkingprivate.h"
32
33 #include "gcancellable.h"
34 #include "gsimpleasyncresult.h"
35 #include "gsocketaddress.h"
36
37 #include "gioalias.h"
38
39 G_DEFINE_TYPE (GUnixResolver, g_unix_resolver, G_TYPE_THREADED_RESOLVER)
40
41 static gboolean g_unix_resolver_watch (GIOChannel   *iochannel,
42                                        GIOCondition  condition,
43                                        gpointer      user_data);
44 static void g_unix_resolver_reload (GResolver *resolver);
45
46 static void
47 g_unix_resolver_init (GUnixResolver *gur)
48 {
49   g_unix_resolver_reload (G_RESOLVER (gur));
50 }
51
52 static void
53 g_unix_resolver_finalize (GObject *object)
54 {
55   GUnixResolver *gur = G_UNIX_RESOLVER (object);
56
57   if (gur->watch)
58     g_source_remove (gur->watch);
59   _g_asyncns_free (gur->asyncns);
60
61   G_OBJECT_CLASS (g_unix_resolver_parent_class)->finalize (object);
62 }
63
64 static void
65 g_unix_resolver_reload (GResolver *resolver)
66 {
67   GUnixResolver *gur = G_UNIX_RESOLVER (resolver);
68   gint fd;
69   GIOChannel *io;
70
71   if (gur->asyncns)
72     {
73       if (_g_asyncns_getnqueries (gur->asyncns) == 0)
74         {
75           g_source_remove (gur->watch);
76           _g_asyncns_free (gur->asyncns);
77         }
78       /* else, we will free it later from g_unix_resolver_watch */
79     }
80
81   /* FIXME: how many workers? */
82   gur->asyncns = _g_asyncns_new (2);
83
84   fd = _g_asyncns_fd (gur->asyncns);
85   io = g_io_channel_unix_new (fd);
86   gur->watch = g_io_add_watch (io, G_IO_IN | G_IO_HUP | G_IO_ERR,
87                                g_unix_resolver_watch, gur->asyncns);
88   g_io_channel_unref (io);
89 }
90
91 /* The various request possibilities:
92  *
93  * 1. Synchronous: handed off to the base class (GThreadedResolver);
94  *    since it's never possible to cancel a synchronous request in a
95  *    single-threaded program, the request is done in the calling
96  *    thread.
97  *
98  * 2. Asynchronous: An appropriate _g_asyncns_query_t is created, and
99  *    then a GUnixResolverRequest is created with that query and a
100  *    GSimpleAsyncResult. Two sub-possibilities:
101  *
102  *      a. The resolution completes: g_unix_resolver_watch() sees that
103  *         the request has completed, and calls
104  *         g_unix_resolver_request_complete(), which detaches the
105  *         "cancelled" signal handler (if it was present), queues the
106  *         async_result to be completed, and then unrefs it.
107  *
108  *      b. The resolution is cancelled: request_cancelled() calls
109  *         _g_asyncns_cancel() to cancel the resolution. Then it calls
110  *         g_unix_resolver_request_complete(), which detaches the
111  *         signal handler, and queues async_result to complete in an
112  *         idle handler. Because the asyncns resolution was cancelled,
113  *         g_unix_resolver_watch() will never be triggered for this
114  *         req.
115  *
116  *    Since there's only a single thread, it's not possible for the
117  *    request to both complete and be cancelled "at the same time",
118  *    and each of the two possibilities takes steps to block the other
119  *    from being able to happen later, so it's always safe to free req
120  *    after the async_result completes.
121  */
122
123 typedef struct _GUnixResolverRequest GUnixResolverRequest;
124 typedef void (*GUnixResolverFunc) (GUnixResolverRequest *);
125
126 struct _GUnixResolverRequest {
127   GUnixResolver *gur;
128   _g_asyncns_t *asyncns;
129
130   _g_asyncns_query_t *qy;
131   union {
132     struct {
133       gchar *hostname;
134       GList *addresses;
135     } name;
136
137     struct {
138       GInetAddress *address;
139       gchar *hostname;
140     } address;
141
142     struct {
143       gchar *service;
144       GList *targets;
145     } service;
146   } u;
147   GUnixResolverFunc process_func, free_func;
148
149   GCancellable *cancellable;
150   GSimpleAsyncResult *async_result;
151
152 };
153
154 static void g_unix_resolver_request_free (GUnixResolverRequest *req);
155 static void request_cancelled (GCancellable *cancellable,
156                                gpointer      user_data);
157
158 static GUnixResolverRequest *
159 g_unix_resolver_request_new (GUnixResolver         *gur,
160                              _g_asyncns_query_t    *qy,
161                              GUnixResolverFunc      process_func,
162                              GUnixResolverFunc      free_func,
163                              GCancellable          *cancellable,
164                              GSimpleAsyncResult    *async_result)
165 {
166   GUnixResolverRequest *req;
167
168   req = g_slice_new0 (GUnixResolverRequest);
169   req->gur = g_object_ref (gur);
170   req->asyncns = gur->asyncns;
171   req->qy = qy;
172   req->process_func = process_func;
173   req->free_func = free_func;
174
175   if (cancellable)
176     {
177       req->cancellable = g_object_ref (cancellable);
178       g_signal_connect (cancellable, "cancelled",
179                         G_CALLBACK (request_cancelled), req);
180     }
181
182   req->async_result = g_object_ref (async_result);
183
184   g_simple_async_result_set_op_res_gpointer (req->async_result, req, (GDestroyNotify)g_unix_resolver_request_free);
185
186   return req;
187 }
188
189 static void
190 g_unix_resolver_request_free (GUnixResolverRequest *req)
191 {
192   req->free_func (req);
193
194   /* We don't have to free req->cancellable and req->async_result,
195    * since they must already have been freed if we're here.
196    */
197
198   /* Check if this was the last request remaining on an old asyncns. */
199   if (req->asyncns != req->gur->asyncns &&
200       _g_asyncns_getnqueries (req->asyncns) == 0)
201     _g_asyncns_free (req->asyncns);
202
203   g_object_unref (req->gur);
204   g_slice_free (GUnixResolverRequest, req);
205 }
206
207 static void
208 g_unix_resolver_request_complete (GUnixResolverRequest *req)
209 {
210   if (req->cancellable)
211     {
212       g_signal_handlers_disconnect_by_func (req->cancellable, request_cancelled, req);
213       g_object_unref (req->cancellable);
214       req->cancellable = NULL;
215     }
216
217   /* We always complete_in_idle, even if we were called from
218    * g_unix_resolver_watch(), since we might have been started under a
219    * non-default g_main_context_get_thread_default().
220    */
221   g_simple_async_result_complete_in_idle (req->async_result);
222   g_object_unref (req->async_result);
223 }
224
225 static void
226 request_cancelled (GCancellable *cancellable,
227                    gpointer      user_data)
228 {
229   GUnixResolverRequest *req = user_data;
230   GError *error = NULL;
231
232   _g_asyncns_cancel (req->asyncns, req->qy);
233   req->qy = NULL;
234
235   g_cancellable_set_error_if_cancelled (cancellable, &error);
236   g_simple_async_result_set_from_error (req->async_result, error);
237   g_error_free (error);
238
239   g_unix_resolver_request_complete (req);
240 }
241
242 static gboolean
243 g_unix_resolver_watch (GIOChannel   *iochannel,
244                        GIOCondition  condition,
245                        gpointer      user_data)
246 {
247   _g_asyncns_t *asyncns = user_data;
248   _g_asyncns_query_t *qy;
249   GUnixResolverRequest *req;
250
251   if (condition & (G_IO_HUP | G_IO_ERR))
252     {
253       /* Will happen if we reload, and then eventually kill the old
254        * _g_asyncns_t when it's done processing requests.
255        */
256       return FALSE;
257     }
258
259   while (_g_asyncns_wait (asyncns, FALSE) == 0 &&
260          (qy = _g_asyncns_getnext (asyncns)) != NULL)
261     {
262       req = _g_asyncns_getuserdata (asyncns, qy);
263       req->process_func (req);
264       g_unix_resolver_request_complete (req);
265     }
266
267   return TRUE;
268 }
269
270 static GUnixResolverRequest *
271 resolve_async (GUnixResolver         *gur,
272                _g_asyncns_query_t    *qy,
273                GUnixResolverFunc      process_func,
274                GUnixResolverFunc      free_func,
275                GCancellable          *cancellable,
276                GAsyncReadyCallback    callback,
277                gpointer               user_data,
278                gpointer               tag)
279 {
280   GSimpleAsyncResult *result;
281   GUnixResolverRequest *req;
282
283   result = g_simple_async_result_new (G_OBJECT (gur), callback, user_data, tag);
284   req = g_unix_resolver_request_new (gur, qy, process_func, free_func,
285                                      cancellable, result);
286   g_object_unref (result);
287   _g_asyncns_setuserdata (gur->asyncns, qy, req);
288
289   return req;
290 }
291
292 static void
293 lookup_by_name_process (GUnixResolverRequest *req)
294 {
295   struct addrinfo *res;
296   gint retval;
297   GError *error = NULL;
298
299   retval = _g_asyncns_getaddrinfo_done (req->asyncns, req->qy, &res);
300   req->u.name.addresses =
301     _g_resolver_addresses_from_addrinfo (req->u.name.hostname,
302                                          res, retval, &error);
303   if (res)
304     freeaddrinfo (res);
305
306   if (error)
307     {
308       g_simple_async_result_set_from_error (req->async_result, error);
309       g_error_free (error);
310     }
311 }
312
313 static void
314 lookup_by_name_free (GUnixResolverRequest *req)
315 {
316   g_free (req->u.name.hostname);
317   if (req->u.name.addresses)
318     g_resolver_free_addresses (req->u.name.addresses);
319 }
320
321 static void
322 lookup_by_name_async (GResolver           *resolver,
323                       const gchar         *hostname,
324                       GCancellable        *cancellable,
325                       GAsyncReadyCallback  callback,
326                       gpointer             user_data)
327 {
328   GUnixResolver *gur = G_UNIX_RESOLVER (resolver);
329   GUnixResolverRequest *req;
330   _g_asyncns_query_t *qy;
331
332   qy = _g_asyncns_getaddrinfo (gur->asyncns, hostname, NULL,
333                                &_g_resolver_addrinfo_hints);
334   req = resolve_async (gur, qy, lookup_by_name_process, lookup_by_name_free,
335                        cancellable, callback, user_data, lookup_by_name_async);
336   req->u.name.hostname = g_strdup (hostname);
337 }
338
339 static GList *
340 lookup_by_name_finish (GResolver     *resolver,
341                        GAsyncResult  *result,
342                        GError       **error)
343 {
344   GSimpleAsyncResult *simple;
345   GUnixResolverRequest *req;
346   GList *addresses;
347
348   g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (resolver), lookup_by_name_async), FALSE);
349   simple = G_SIMPLE_ASYNC_RESULT (result);
350
351   if (g_simple_async_result_propagate_error (simple, error))
352     return NULL;
353
354   req = g_simple_async_result_get_op_res_gpointer (simple);
355   addresses = req->u.name.addresses;
356   req->u.name.addresses = NULL;
357
358   return addresses;
359 }
360
361
362 static void
363 lookup_by_address_process (GUnixResolverRequest *req)
364 {
365   gchar host[NI_MAXHOST];
366   gint retval;
367   GError *error = NULL;
368
369   retval = _g_asyncns_getnameinfo_done (req->asyncns, req->qy,
370                                         host, sizeof (host), NULL, 0);
371   req->u.address.hostname =
372     _g_resolver_name_from_nameinfo (req->u.address.address,
373                                     host, retval, &error);
374
375   if (error)
376     {
377       g_simple_async_result_set_from_error (req->async_result, error);
378       g_error_free (error);
379     }
380 }
381
382 static void
383 lookup_by_address_free (GUnixResolverRequest *req)
384 {
385   g_object_unref (req->u.address.address);
386   if (req->u.address.hostname)
387     g_free (req->u.address.hostname);
388 }
389
390 static void
391 lookup_by_address_async (GResolver           *resolver,
392                          GInetAddress        *address,
393                          GCancellable        *cancellable,
394                          GAsyncReadyCallback  callback,
395                          gpointer             user_data)
396 {
397   GUnixResolver *gur = G_UNIX_RESOLVER (resolver);
398   GUnixResolverRequest *req;
399   _g_asyncns_query_t *qy;
400   struct sockaddr_storage sockaddr;
401   gsize sockaddr_size;
402
403   _g_resolver_address_to_sockaddr (address, &sockaddr, &sockaddr_size);
404   qy = _g_asyncns_getnameinfo (gur->asyncns,
405                                (struct sockaddr *)&sockaddr, sockaddr_size,
406                                NI_NAMEREQD, TRUE, FALSE);
407   req = resolve_async (gur, qy, lookup_by_address_process,
408                        lookup_by_address_free, cancellable,
409                        callback, user_data, lookup_by_address_async);
410   req->u.address.address = g_object_ref (address);
411 }
412
413 static gchar *
414 lookup_by_address_finish (GResolver     *resolver,
415                           GAsyncResult  *result,
416                           GError       **error)
417 {
418   GSimpleAsyncResult *simple;
419   GUnixResolverRequest *req;
420   gchar *name;
421
422   g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (resolver), lookup_by_address_async), FALSE);
423   simple = G_SIMPLE_ASYNC_RESULT (result);
424
425   if (g_simple_async_result_propagate_error (simple, error))
426     return NULL;
427
428   req = g_simple_async_result_get_op_res_gpointer (simple);
429   name = req->u.address.hostname;
430   req->u.address.hostname = NULL;
431
432   return name;
433 }
434
435
436 static void
437 lookup_service_process (GUnixResolverRequest *req)
438 {
439   guchar *answer;
440   gint len, herr;
441   GError *error = NULL;
442
443   len = _g_asyncns_res_done (req->asyncns, req->qy, &answer);
444   if (len < 0)
445     herr = h_errno;
446   else
447     herr = 0;
448
449   req->u.service.targets =
450     _g_resolver_targets_from_res_query (req->u.service.service,
451                                         answer, len, herr, &error);
452   _g_asyncns_freeanswer (answer);
453
454   if (error)
455     {
456       g_simple_async_result_set_from_error (req->async_result, error);
457       g_error_free (error);
458     }
459 }
460
461 static void
462 lookup_service_free (GUnixResolverRequest *req)
463 {
464   g_free (req->u.service.service);
465   if (req->u.service.targets)
466     g_resolver_free_targets (req->u.service.targets);
467 }
468
469 static void
470 lookup_service_async (GResolver           *resolver,
471                       const char          *rrname,
472                       GCancellable        *cancellable,
473                       GAsyncReadyCallback  callback,
474                       gpointer             user_data)
475 {
476   GUnixResolver *gur = G_UNIX_RESOLVER (resolver);
477   GUnixResolverRequest *req;
478   _g_asyncns_query_t *qy;
479
480   qy = _g_asyncns_res_query (gur->asyncns, rrname, C_IN, T_SRV);
481   req = resolve_async (gur, qy, lookup_service_process, lookup_service_free,
482                        cancellable, callback, user_data, lookup_service_async);
483   req->u.service.service = g_strdup (rrname);
484 }
485
486 static GList *
487 lookup_service_finish (GResolver     *resolver,
488                        GAsyncResult  *result,
489                        GError       **error)
490 {
491   GSimpleAsyncResult *simple;
492   GUnixResolverRequest *req;
493   GList *targets;
494
495   g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (resolver), lookup_service_async), FALSE);
496   simple = G_SIMPLE_ASYNC_RESULT (result);
497
498   if (g_simple_async_result_propagate_error (simple, error))
499     return NULL;
500
501   req = g_simple_async_result_get_op_res_gpointer (simple);
502   targets = req->u.service.targets;
503   req->u.service.targets = NULL;
504
505   return targets;
506 }
507
508
509 static void
510 g_unix_resolver_class_init (GUnixResolverClass *unix_class)
511 {
512   GResolverClass *resolver_class = G_RESOLVER_CLASS (unix_class);
513   GObjectClass *object_class = G_OBJECT_CLASS (unix_class);
514
515   resolver_class->reload                   = g_unix_resolver_reload;
516   resolver_class->lookup_by_name_async     = lookup_by_name_async;
517   resolver_class->lookup_by_name_finish    = lookup_by_name_finish;
518   resolver_class->lookup_by_address_async  = lookup_by_address_async;
519   resolver_class->lookup_by_address_finish = lookup_by_address_finish;
520   resolver_class->lookup_service_async     = lookup_service_async;
521   resolver_class->lookup_service_finish    = lookup_service_finish;
522
523   object_class->finalize = g_unix_resolver_finalize;
524 }
525
526 #define __G_UNIX_RESOLVER_C__
527 #include "gioaliasdef.c"