Call sync close function directly in async implementation
[platform/upstream/glib.git] / gio / gsocketconnection.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright © 2008 Christian Kellner, Samuel Cormier-Iijima
4  *           © 2008 codethink
5  * Copyright © 2009 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  * Authors: Christian Kellner <gicmo@gnome.org>
23  *          Samuel Cormier-Iijima <sciyoshi@gmail.com>
24  *          Ryan Lortie <desrt@desrt.ca>
25  *          Alexander Larsson <alexl@redhat.com>
26  */
27
28 #include "config.h"
29
30 #include "gsocketconnection.h"
31
32 #include "gsocketoutputstream.h"
33 #include "gsocketinputstream.h"
34 #include <gio/giostream.h>
35 #include <gio/gsimpleasyncresult.h>
36 #include "gunixconnection.h"
37 #include "gtcpconnection.h"
38 #include "glibintl.h"
39
40 #include "gioalias.h"
41
42 /**
43  * SECTION:gsocketconnection
44  * @short_description: A socket connection
45  * @include: gio/gio.h
46  * @see_also: #GIOStream, #GSocketClient, #GSocketListener
47  *
48  * #GSocketConnection is a #GIOStream for a connected socket. They
49  * can be created either by #GSocketClient when connecting to a host,
50  * or by #GSocketListener when accepting a new client.
51  *
52  * The type of the #GSocketConnection object returned from these calls depends
53  * on the type of the underlying socket that is in use. For instance, for a
54  * TCP/IP connection it will be a #GTcpConnection.
55  *
56  * Chosing what type of object to construct is done with the socket connection
57  * factory, and it is possible for 3rd parties to register custom socket connection
58  * types for specific combination of socket family/type/protocol using
59  * g_socket_connection_factory_register_type().
60  *
61  * Since: 2.22
62  **/
63
64 G_DEFINE_TYPE (GSocketConnection,
65                g_socket_connection, G_TYPE_IO_STREAM);
66
67 enum
68 {
69   PROP_NONE,
70   PROP_SOCKET,
71 };
72
73 struct _GSocketConnectionPrivate
74 {
75   GSocket       *socket;
76   GInputStream  *input_stream;
77   GOutputStream *output_stream;
78 };
79
80 static gboolean g_socket_connection_close         (GIOStream            *stream,
81                                                    GCancellable         *cancellable,
82                                                    GError              **error);
83 static void     g_socket_connection_close_async   (GIOStream            *stream,
84                                                    int                   io_priority,
85                                                    GCancellable         *cancellable,
86                                                    GAsyncReadyCallback   callback,
87                                                    gpointer              user_data);
88 static gboolean g_socket_connection_close_finish  (GIOStream            *stream,
89                                                    GAsyncResult         *result,
90                                                    GError              **error);
91
92 static GInputStream *
93 g_socket_connection_get_input_stream (GIOStream *io_stream)
94 {
95   GSocketConnection *connection = G_SOCKET_CONNECTION (io_stream);
96
97   if (connection->priv->input_stream == NULL)
98     connection->priv->input_stream = (GInputStream *)
99       _g_socket_input_stream_new (connection->priv->socket);
100
101   return connection->priv->input_stream;
102 }
103
104 static GOutputStream *
105 g_socket_connection_get_output_stream (GIOStream *io_stream)
106 {
107   GSocketConnection *connection = G_SOCKET_CONNECTION (io_stream);
108
109   if (connection->priv->output_stream == NULL)
110     connection->priv->output_stream = (GOutputStream *)
111       _g_socket_output_stream_new (connection->priv->socket);
112
113   return connection->priv->output_stream;
114 }
115
116 /**
117  * g_socket_connection_get_socket:
118  * @connection: a #GSocketConnection.
119  *
120  * Gets the underlying #GSocket object of the connection.
121  * This can be useful if you want to do something unusual on it
122  * not supported by the #GSocketConnection APIs.
123  *
124  * Returns: a #GSocketAddress or %NULL on error.
125  *
126  * Since: 2.22
127  **/
128 GSocket *
129 g_socket_connection_get_socket (GSocketConnection *connection)
130 {
131   g_return_val_if_fail (G_IS_SOCKET_CONNECTION (connection), NULL);
132
133   return connection->priv->socket;
134 }
135
136 /**
137  * g_socket_connection_get_local_address:
138  * @connection: a #GSocketConnection.
139  * @error: #GError for error reporting, or %NULL to ignore.
140  *
141  * Try to get the local address of a socket connection.
142  *
143  * Returns: a #GSocketAddress or %NULL on error.
144  *     Free the returned object with g_object_unref().
145  *
146  * Since: 2.22
147  **/
148 GSocketAddress *
149 g_socket_connection_get_local_address (GSocketConnection  *connection,
150                                        GError  **error)
151 {
152   return g_socket_get_local_address (connection->priv->socket, error);
153 }
154
155 /**
156  * g_socket_connection_get_remote_address:
157  * @connection: a #GSocketConnection.
158  * @error: #GError for error reporting, or %NULL to ignore.
159  *
160  * Try to get the remove address of a socket connection.
161  *
162  * Returns: a #GSocketAddress or %NULL on error.
163  *     Free the returned object with g_object_unref().
164  *
165  * Since: 2.22
166  **/
167 GSocketAddress *
168 g_socket_connection_get_remote_address (GSocketConnection  *connection,
169                                         GError  **error)
170 {
171   return g_socket_get_remote_address (connection->priv->socket, error);
172 }
173
174 static void
175 g_socket_connection_get_property (GObject *object, guint prop_id,
176                                   GValue *value, GParamSpec *pspec)
177 {
178   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
179
180   switch (prop_id)
181     {
182      case PROP_SOCKET:
183       g_value_set_object (value, connection->priv->socket);
184       break;
185
186      default:
187       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
188     }
189 }
190
191 static void
192 g_socket_connection_set_property (GObject *object, guint prop_id,
193                                   const GValue *value, GParamSpec *pspec)
194 {
195   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
196
197   switch (prop_id)
198     {
199      case PROP_SOCKET:
200       connection->priv->socket = G_SOCKET (g_value_dup_object (value));
201       break;
202
203      default:
204       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
205     }
206 }
207
208 static void
209 g_socket_connection_constructed (GObject *object)
210 {
211   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
212
213   g_assert (connection->priv->socket != NULL);
214 }
215
216 static void
217 g_socket_connection_finalize (GObject *object)
218 {
219   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
220
221   if (connection->priv->input_stream)
222     g_object_unref (connection->priv->input_stream);
223
224   if (connection->priv->output_stream)
225     g_object_unref (connection->priv->output_stream);
226
227   g_object_unref (connection->priv->socket);
228
229   G_OBJECT_CLASS (g_socket_connection_parent_class)
230     ->finalize (object);
231 }
232
233 static void
234 g_socket_connection_class_init (GSocketConnectionClass *klass)
235 {
236   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
237   GIOStreamClass *stream_class = G_IO_STREAM_CLASS (klass);
238
239   g_type_class_add_private (klass, sizeof (GSocketConnectionPrivate));
240
241   gobject_class->set_property = g_socket_connection_set_property;
242   gobject_class->get_property = g_socket_connection_get_property;
243   gobject_class->constructed = g_socket_connection_constructed;
244   gobject_class->finalize = g_socket_connection_finalize;
245
246   stream_class->get_input_stream = g_socket_connection_get_input_stream;
247   stream_class->get_output_stream = g_socket_connection_get_output_stream;
248   stream_class->close_fn = g_socket_connection_close;
249   stream_class->close_async = g_socket_connection_close_async;
250   stream_class->close_finish = g_socket_connection_close_finish;
251
252   g_object_class_install_property (gobject_class, PROP_SOCKET,
253     g_param_spec_object ("socket",
254                          P_("Socket"),
255                          P_("The underlying GSocket"),
256                          G_TYPE_SOCKET, G_PARAM_CONSTRUCT_ONLY |
257                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
258 }
259
260 static void
261 g_socket_connection_init (GSocketConnection *connection)
262 {
263   connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection,
264                                                   G_TYPE_SOCKET_CONNECTION,
265                                                   GSocketConnectionPrivate);
266 }
267
268 static gboolean
269 g_socket_connection_close (GIOStream            *stream,
270                            GCancellable         *cancellable,
271                            GError              **error)
272 {
273   GSocketConnection *connection = G_SOCKET_CONNECTION (stream);
274
275   if (connection->priv->output_stream)
276     g_output_stream_close (connection->priv->output_stream,
277                            cancellable, NULL);
278   if (connection->priv->input_stream)
279     g_input_stream_close (connection->priv->input_stream,
280                           cancellable, NULL);
281
282   return g_socket_close (connection->priv->socket, error);
283 }
284
285
286 static void
287 g_socket_connection_close_async (GIOStream        *stream,
288                                  int               io_priority,
289                                  GCancellable     *cancellable,
290                                  GAsyncReadyCallback callback,
291                                  gpointer          user_data)
292 {
293   GSimpleAsyncResult *res;
294   GIOStreamClass *class;
295   GError *error;
296
297   class = G_IO_STREAM_GET_CLASS (stream);
298
299   /* socket close is not blocked, just do it! */
300   error = NULL;
301   if (class->close_fn &&
302       !class->close_fn (stream, cancellable, &error))
303     {
304       g_simple_async_report_gerror_in_idle (G_OBJECT (stream),
305                                             callback, user_data,
306                                             error);
307       g_error_free (error);
308       return;
309     }
310
311   res = g_simple_async_result_new (G_OBJECT (stream),
312                                    callback,
313                                    user_data,
314                                    g_socket_connection_close_async);
315   g_simple_async_result_complete_in_idle (res);
316   g_object_unref (res);
317 }
318
319 static gboolean
320 g_socket_connection_close_finish (GIOStream  *stream,
321                                   GAsyncResult  *result,
322                                   GError       **error)
323 {
324   return TRUE;
325 }
326
327 typedef struct {
328   GSocketFamily socket_family;
329   GSocketType socket_type;
330   int protocol;
331   GType implementation;
332 } ConnectionFactory;
333
334 static guint
335 connection_factory_hash (gconstpointer key)
336 {
337   const ConnectionFactory *factory = key;
338   guint h;
339
340   h = factory->socket_family ^ (factory->socket_type << 4) ^ (factory->protocol << 8);
341   /* This is likely to be small, so spread over whole
342      hash space to get some distribution */
343   h = h ^ (h << 8) ^ (h << 16) ^ (h << 24);
344
345   return h;
346 }
347
348 static gboolean
349 connection_factory_equal (gconstpointer _a,
350                           gconstpointer _b)
351 {
352   const ConnectionFactory *a = _a;
353   const ConnectionFactory *b = _b;
354
355   if (a->socket_family != b->socket_family)
356     return FALSE;
357
358   if (a->socket_type != b->socket_type)
359     return FALSE;
360
361   if (a->protocol != b->protocol)
362     return FALSE;
363
364   return TRUE;
365 }
366
367 static GHashTable *connection_factories = NULL;
368 G_LOCK_DEFINE_STATIC(connection_factories);
369
370 /**
371  * g_socket_connection_factory_register_type:
372  * @g_type: a #GType, inheriting from G_SOCKET_CONNECTION
373  * @family: a #GSocketFamily.
374  * @type: a #GSocketType
375  * @protocol: a protocol id
376  *
377  * Looks up the #GType to be used when creating socket connections on
378  * sockets with the specified @family,@type and @protocol.
379  *
380  * If no type is registered, the #GSocketConnection base type is returned.
381  *
382  * Since: 2.22
383  **/
384 void
385 g_socket_connection_factory_register_type (GType g_type,
386                                            GSocketFamily family,
387                                            GSocketType type,
388                                            gint protocol)
389 {
390   ConnectionFactory *factory;
391
392   g_return_if_fail (g_type_is_a (g_type, G_TYPE_SOCKET_CONNECTION));
393
394   G_LOCK (connection_factories);
395
396   if (connection_factories == NULL)
397     connection_factories = g_hash_table_new_full (connection_factory_hash,
398                                                   connection_factory_equal,
399                                                   (GDestroyNotify)g_free,
400                                                   NULL);
401
402   factory = g_new0 (ConnectionFactory, 1);
403   factory->socket_family = family;
404   factory->socket_type = type;
405   factory->protocol = protocol;
406   factory->implementation = g_type;
407
408   g_hash_table_insert (connection_factories,
409                        factory, factory);
410
411   G_UNLOCK (connection_factories);
412 }
413
414 static void
415 init_builtin_types (void)
416 {
417   volatile GType a_type;
418 #ifndef G_OS_WIN32
419   a_type = g_unix_connection_get_type ();
420 #endif
421   a_type = g_tcp_connection_get_type ();
422 }
423
424 /**
425  * g_socket_connection_factory_lookup_type:
426  * @family: a #GSocketFamily.
427  * @type: a #GSocketType
428  * @protocol_id: a protocol id
429  *
430  * Looks up the #GType to be used when creating socket connections on
431  * sockets with the specified @family,@type and @protocol_id.
432  *
433  * If no type is registered, the #GSocketConnection base type is returned.
434  *
435  * Returns: a #GType
436  * Since: 2.22
437  **/
438 GType
439 g_socket_connection_factory_lookup_type (GSocketFamily family,
440                                          GSocketType type,
441                                          gint protocol_id)
442 {
443   ConnectionFactory *factory, key;
444   GType g_type;
445
446   init_builtin_types ();
447
448   G_LOCK (connection_factories);
449
450   g_type = G_TYPE_SOCKET_CONNECTION;
451
452   if (connection_factories)
453     {
454       key.socket_family = family;
455       key.socket_type = type;
456       key.protocol = protocol_id;
457
458       factory = g_hash_table_lookup (connection_factories, &key);
459       if (factory)
460         g_type = factory->implementation;
461     }
462
463   G_UNLOCK (connection_factories);
464
465   return g_type;
466 }
467
468 /**
469  * g_socket_connection_factory_create_connection:
470  * @socket: a #GSocket.
471  *
472  * Creates a #GSocketConnection subclass of the right type for
473  * @socket.
474  *
475  * Returns: a #GSocketConnection
476  *
477  * Since: 2.22
478  **/
479 GSocketConnection *
480 g_socket_connection_factory_create_connection (GSocket *socket)
481 {
482   GType type;
483
484   type = g_socket_connection_factory_lookup_type (g_socket_get_family (socket),
485                                                   g_socket_get_socket_type (socket),
486                                                   g_socket_get_protocol_id (socket));
487   return g_object_new (type, "socket", socket, NULL);
488 }
489
490 #define __G_SOCKET_CONNECTION_C__
491 #include "gioaliasdef.c"