Add GResolver, a glib-ish interface to DNS
[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 <resolv.h>
28 #include <stdio.h>
29 #include <string.h>
30
31 #include "gunixresolver.h"
32 #include "gnetworkingprivate.h"
33
34 #include "gcancellable.h"
35 #include "gsimpleasyncresult.h"
36 #include "gsocketaddress.h"
37
38 #include "gioalias.h"
39
40 G_DEFINE_TYPE (GUnixResolver, g_unix_resolver, G_TYPE_THREADED_RESOLVER)
41
42 static gboolean g_unix_resolver_watch (GIOChannel   *iochannel,
43                                        GIOCondition  condition,
44                                        gpointer      user_data);
45
46 static void
47 g_unix_resolver_init (GUnixResolver *gur)
48 {
49   gint fd;
50   GIOChannel *io;
51
52   /* FIXME: how many workers? */
53   gur->asyncns = _g_asyncns_new (2);
54
55   fd = _g_asyncns_fd (gur->asyncns);
56   io = g_io_channel_unix_new (fd);
57   gur->watch = g_io_add_watch (io, G_IO_IN | G_IO_HUP | G_IO_ERR,
58                                g_unix_resolver_watch, gur);
59   g_io_channel_unref (io);
60 }
61
62 static void
63 g_unix_resolver_finalize (GObject *object)
64 {
65   GUnixResolver *gur = G_UNIX_RESOLVER (object);
66
67   if (gur->watch)
68     g_source_remove (gur->watch);
69   _g_asyncns_free (gur->asyncns);
70
71   G_OBJECT_CLASS (g_unix_resolver_parent_class)->finalize (object);
72 }
73
74 /* The various request possibilities:
75  *
76  * 1. Synchronous: handed off to the base class (GThreadedResolver);
77  *    since it's never possible to cancel a synchronous request in a
78  *    single-threaded program, the request is done in the calling
79  *    thread.
80  *
81  * 2. Asynchronous: An appropriate _g_asyncns_query_t is created, and
82  *    then a GUnixResolverRequest is created with that query and a
83  *    GSimpleAsyncResult. Two sub-possibilities:
84  *
85  *      a. The resolution completes: g_unix_resolver_watch() sees that
86  *         the request has completed, and calls
87  *         g_unix_resolver_request_complete(), which detaches the
88  *         "cancelled" signal handler (if it was present) and then
89  *         immediately completes the async_result (since
90  *         g_unix_resolver_watch() is already run from main-loop
91  *         time.) After completing the async_result, it unrefs it,
92  *         causing the req to be freed as well.
93  *
94  *      b. The resolution is cancelled: request_cancelled() calls
95  *         _g_asyncns_cancel() to cancel the resolution. Then it calls
96  *         g_unix_resolver_request_complete(), which detaches the
97  *         signal handler, and queues async_result to complete in an
98  *         idle handler. It then unrefs the async_result to ensure
99  *         that after its callback runs, it will be destroyed, in turn
100  *         causing the req to be freed. Because the asyncns resolution
101  *         was cancelled, g_unix_resolver_watch() will never be
102  *         triggered for this req.
103  *
104  *    Since there's only a single thread, it's not possible for the
105  *    request to both complete and be cancelled "at the same time",
106  *    and each of the two possibilities takes steps to block the other
107  *    from being able to happen later, so it's always safe to free req
108  *    after the async_result completes.
109  */
110
111 typedef struct _GUnixResolverRequest GUnixResolverRequest;
112 typedef void (*GUnixResolverFreeFunc) (GUnixResolverRequest *);
113
114 struct _GUnixResolverRequest {
115   GUnixResolver *gur;
116
117   _g_asyncns_query_t *qy;
118   union {
119     gchar *hostname;
120     GInetAddress *address;
121     gchar *service;
122   } u;
123   GUnixResolverFreeFunc free_func;
124
125   GCancellable *cancellable;
126   GSimpleAsyncResult *async_result;
127
128 };
129
130 static void g_unix_resolver_request_free (GUnixResolverRequest *req);
131 static void request_cancelled (GCancellable *cancellable,
132                                gpointer      user_data);
133
134 static GUnixResolverRequest *
135 g_unix_resolver_request_new (GUnixResolver         *gur,
136                              _g_asyncns_query_t    *qy,
137                              GUnixResolverFreeFunc  free_func,
138                              GCancellable          *cancellable,
139                              GSimpleAsyncResult    *async_result)
140 {
141   GUnixResolverRequest *req;
142
143   req = g_slice_new0 (GUnixResolverRequest);
144   req->gur = g_object_ref (gur);
145   req->qy = qy;
146   req->free_func = free_func;
147
148   if (cancellable)
149     {
150       req->cancellable = g_object_ref (cancellable);
151       g_signal_connect (cancellable, "cancelled",
152                         G_CALLBACK (request_cancelled), req);
153     }
154
155   req->async_result = g_object_ref (async_result);
156
157   g_simple_async_result_set_op_res_gpointer (req->async_result, req, (GDestroyNotify)g_unix_resolver_request_free);
158
159   return req;
160 }
161
162 static void
163 g_unix_resolver_request_free (GUnixResolverRequest *req)
164 {
165   /* If the user didn't call _finish the qy will still be around. */
166   if (req->qy)
167     _g_asyncns_cancel (req->gur->asyncns, req->qy);
168
169   /* We don't have to free req->cancellable and req->async_result,
170    * since they must already have been freed if we're here.
171    */
172
173   g_slice_free (GUnixResolverRequest, req);
174 }
175
176 static void
177 g_unix_resolver_request_complete (GUnixResolverRequest *req,
178                                   gboolean              need_idle)
179 {
180   if (req->cancellable)
181     {
182       g_signal_handlers_disconnect_by_func (req->cancellable, request_cancelled, req);
183       g_object_unref (req->cancellable);
184       req->cancellable = NULL;
185     }
186
187   if (need_idle)
188     g_simple_async_result_complete_in_idle (req->async_result);
189   else
190     g_simple_async_result_complete (req->async_result);
191
192   /* If we completed_in_idle, that will have taken an extra ref on
193    * req->async_result; if not, then we're already done. Either way we
194    * need to unref the async_result to make sure it eventually is
195    * destroyed, causing req to be freed.
196    */
197   g_object_unref (req->async_result);
198 }
199
200 static void
201 request_cancelled (GCancellable *cancellable,
202                    gpointer      user_data)
203 {
204   GUnixResolverRequest *req = user_data;
205   GError *error = NULL;
206
207   _g_asyncns_cancel (req->gur->asyncns, req->qy);
208   req->qy = NULL;
209
210   g_cancellable_set_error_if_cancelled (cancellable, &error);
211   g_simple_async_result_set_from_error (req->async_result, error);
212   g_error_free (error);
213
214   g_unix_resolver_request_complete (req, TRUE);
215 }
216
217 static gboolean
218 g_unix_resolver_watch (GIOChannel   *iochannel,
219                        GIOCondition  condition,
220                        gpointer      user_data)
221 {
222   GUnixResolver *gur = user_data;
223   _g_asyncns_query_t *qy;
224   GUnixResolverRequest *req;
225
226   if (condition & (G_IO_HUP | G_IO_ERR))
227     {
228       /* Shouldn't happen. Should we create a new asyncns? FIXME */
229       g_warning ("asyncns died");
230       gur->watch = 0;
231       return FALSE;
232     }
233
234   while (_g_asyncns_wait (gur->asyncns, FALSE) == 0 &&
235          (qy = _g_asyncns_getnext (gur->asyncns)) != NULL)
236     {
237       req = _g_asyncns_getuserdata (gur->asyncns, qy);
238       g_unix_resolver_request_complete (req, FALSE);
239     }
240
241   return TRUE;
242 }
243
244 static GUnixResolverRequest *
245 resolve_async (GUnixResolver         *gur,
246                _g_asyncns_query_t    *qy,
247                GUnixResolverFreeFunc  free_func,
248                GCancellable          *cancellable,
249                GAsyncReadyCallback    callback,
250                gpointer               user_data,
251                gpointer               tag)
252 {
253   GSimpleAsyncResult *result;
254   GUnixResolverRequest *req;
255
256   result = g_simple_async_result_new (G_OBJECT (gur), callback, user_data, tag);
257   req = g_unix_resolver_request_new (gur, qy, free_func, cancellable, result);
258   g_object_unref (result);
259   _g_asyncns_setuserdata (gur->asyncns, qy, req);
260
261   return req;
262 }
263
264 static void
265 lookup_by_name_free (GUnixResolverRequest *req)
266 {
267   g_free (req->u.hostname);
268 }
269
270 static void
271 lookup_by_name_async (GResolver           *resolver,
272                       const gchar         *hostname,
273                       GCancellable        *cancellable,
274                       GAsyncReadyCallback  callback,
275                       gpointer             user_data)
276 {
277   GUnixResolver *gur = G_UNIX_RESOLVER (resolver);
278   GUnixResolverRequest *req;
279   _g_asyncns_query_t *qy;
280
281   qy = _g_asyncns_getaddrinfo (gur->asyncns, hostname, NULL,
282                                &_g_resolver_addrinfo_hints);
283   req = resolve_async (gur, qy, lookup_by_name_free, cancellable,
284                        callback, user_data, lookup_by_name_async);
285   req->u.hostname = g_strdup (hostname);
286 }
287
288 static GList *
289 lookup_by_name_finish (GResolver     *resolver,
290                        GAsyncResult  *result,
291                        GError       **error)
292 {
293   GSimpleAsyncResult *simple;
294   GUnixResolverRequest *req;
295   struct addrinfo *res;
296   gint retval;
297   GList *addresses;
298
299   g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (resolver), lookup_by_name_async), FALSE);
300   simple = G_SIMPLE_ASYNC_RESULT (result);
301
302   req = g_simple_async_result_get_op_res_gpointer (simple);
303   retval = _g_asyncns_getaddrinfo_done (req->gur->asyncns, req->qy, &res);
304   req->qy = NULL;
305   addresses = _g_resolver_addresses_from_addrinfo (req->u.hostname, res, retval, error);
306   if (res)
307     freeaddrinfo (res);
308
309   return addresses;
310 }
311
312
313 static void
314 lookup_by_address_free (GUnixResolverRequest *req)
315 {
316   g_object_unref (req->u.address);
317 }
318
319 static void
320 lookup_by_address_async (GResolver           *resolver,
321                          GInetAddress        *address,
322                          GCancellable        *cancellable,
323                          GAsyncReadyCallback  callback,
324                          gpointer             user_data)
325 {
326   GUnixResolver *gur = G_UNIX_RESOLVER (resolver);
327   GUnixResolverRequest *req;
328   _g_asyncns_query_t *qy;
329   struct sockaddr_storage sockaddr;
330   gsize sockaddr_size;
331
332   _g_resolver_address_to_sockaddr (address, &sockaddr, &sockaddr_size);
333   qy = _g_asyncns_getnameinfo (gur->asyncns,
334                                (struct sockaddr *)&sockaddr, sockaddr_size,
335                                NI_NAMEREQD, TRUE, FALSE);
336   req = resolve_async (gur, qy, lookup_by_address_free, cancellable,
337                        callback, user_data, lookup_by_address_async);
338   req->u.address = g_object_ref (address);
339 }
340
341 static gchar *
342 lookup_by_address_finish (GResolver     *resolver,
343                           GAsyncResult  *result,
344                           GError       **error)
345 {
346   GSimpleAsyncResult *simple;
347   GUnixResolverRequest *req;
348   gchar host[NI_MAXHOST], *name;
349   gint retval;
350
351   g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (resolver), lookup_by_address_async), FALSE);
352   simple = G_SIMPLE_ASYNC_RESULT (result);
353
354   req = g_simple_async_result_get_op_res_gpointer (simple);
355   retval = _g_asyncns_getnameinfo_done (req->gur->asyncns, req->qy,
356                                         host, sizeof (host), NULL, 0);
357   req->qy = NULL;
358   name = _g_resolver_name_from_nameinfo (req->u.address, host, retval, error);
359
360   return name;
361 }
362
363
364 static void
365 lookup_service_free (GUnixResolverRequest *req)
366 {
367   g_free (req->u.service);
368 }
369
370 static void
371 lookup_service_async (GResolver           *resolver,
372                       const char          *rrname,
373                       GCancellable        *cancellable,
374                       GAsyncReadyCallback  callback,
375                       gpointer             user_data)
376 {
377   GUnixResolver *gur = G_UNIX_RESOLVER (resolver);
378   GUnixResolverRequest *req;
379   _g_asyncns_query_t *qy;
380
381   qy = _g_asyncns_res_query (gur->asyncns, rrname, C_IN, T_SRV);
382   req = resolve_async (gur, qy, lookup_service_free, cancellable,
383                        callback, user_data, lookup_service_async);
384   req->u.service = g_strdup (rrname);
385 }
386
387 static GList *
388 lookup_service_finish (GResolver     *resolver,
389                        GAsyncResult  *result,
390                        GError       **error)
391 {
392   GSimpleAsyncResult *simple;
393   GUnixResolverRequest *req;
394   guchar *answer;
395   gint len, herr;
396   GList *targets;
397
398   g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (resolver), lookup_service_async), FALSE);
399   simple = G_SIMPLE_ASYNC_RESULT (result);
400
401   req = g_simple_async_result_get_op_res_gpointer (simple);
402   len = _g_asyncns_res_done (req->gur->asyncns, req->qy, &answer);
403   req->qy = NULL;
404   if (len < 0)
405     herr = h_errno;
406   else
407     herr = 0;
408
409   targets = _g_resolver_targets_from_res_query (req->u.service, answer, len, herr, error);
410   _g_asyncns_freeanswer (answer);
411
412   return targets;
413 }
414
415
416 static void
417 g_unix_resolver_class_init (GUnixResolverClass *unix_class)
418 {
419   GResolverClass *resolver_class = G_RESOLVER_CLASS (unix_class);
420   GObjectClass *object_class = G_OBJECT_CLASS (unix_class);
421
422   resolver_class->lookup_by_name_async     = lookup_by_name_async;
423   resolver_class->lookup_by_name_finish    = lookup_by_name_finish;
424   resolver_class->lookup_by_address_async  = lookup_by_address_async;
425   resolver_class->lookup_by_address_finish = lookup_by_address_finish;
426   resolver_class->lookup_service_async     = lookup_service_async;
427   resolver_class->lookup_service_finish    = lookup_service_finish;
428
429   object_class->finalize = g_unix_resolver_finalize;
430 }
431
432 #define __G_UNIX_RESOLVER_C__
433 #include "gioaliasdef.c"