Import all the highlevel socket classes from gnio
[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: High-level socket connection stream
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 GSocket *
117 g_socket_connection_get_socket (GSocketConnection *connection)
118 {
119   g_return_val_if_fail (G_IS_SOCKET_CONNECTION (connection), NULL);
120
121   return connection->priv->socket;
122 }
123
124 /**
125  * g_socket_connection_get_local_address:
126  * @connection: a #GSocketConnection.
127  * @error: #GError for error reporting, or %NULL to ignore.
128  *
129  * Try to get the local address of a socket connection.
130  *
131  * Returns: a #GSocketAddress or %NULL on error.
132  *
133  * Since: 2.22
134  **/
135 GSocketAddress *
136 g_socket_connection_get_local_address (GSocketConnection  *connection,
137                                        GError  **error)
138 {
139   return g_socket_get_local_address (connection->priv->socket, error);
140 }
141
142 /**
143  * g_socket_connection_get_remote_address:
144  * @connection: a #GSocketConnection.
145  * @error: #GError for error reporting, or %NULL to ignore.
146  *
147  * Try to get the remove address of a socket connection.
148  *
149  * Returns: a #GSocketAddress or %NULL on error.
150  *
151  * Since: 2.22
152  **/
153 GSocketAddress *
154 g_socket_connection_get_remote_address (GSocketConnection  *connection,
155                                         GError  **error)
156 {
157   return g_socket_get_remote_address (connection->priv->socket, error);
158 }
159
160 static void
161 g_socket_connection_get_property (GObject *object, guint prop_id,
162                                   GValue *value, GParamSpec *pspec)
163 {
164   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
165
166   switch (prop_id)
167     {
168      case PROP_SOCKET:
169       g_value_set_object (value, connection->priv->socket);
170       break;
171
172      default:
173       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
174     }
175 }
176
177 static void
178 g_socket_connection_set_property (GObject *object, guint prop_id,
179                                   const GValue *value, GParamSpec *pspec)
180 {
181   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
182
183   switch (prop_id)
184     {
185      case PROP_SOCKET:
186       connection->priv->socket = G_SOCKET (g_value_dup_object (value));
187       break;
188
189      default:
190       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
191     }
192 }
193
194 static void
195 g_socket_connection_constructed (GObject *object)
196 {
197   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
198
199   g_assert (connection->priv->socket != NULL);
200 }
201
202 static void
203 g_socket_connection_finalize (GObject *object)
204 {
205   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
206
207   if (connection->priv->input_stream)
208     g_object_unref (connection->priv->input_stream);
209
210   if (connection->priv->output_stream)
211     g_object_unref (connection->priv->output_stream);
212
213   g_object_unref (connection->priv->socket);
214
215   G_OBJECT_CLASS (g_socket_connection_parent_class)
216     ->finalize (object);
217 }
218
219 static void
220 g_socket_connection_class_init (GSocketConnectionClass *klass)
221 {
222   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
223   GIOStreamClass *stream_class = G_IO_STREAM_CLASS (klass);
224
225   g_type_class_add_private (klass, sizeof (GSocketConnectionPrivate));
226
227   gobject_class->set_property = g_socket_connection_set_property;
228   gobject_class->get_property = g_socket_connection_get_property;
229   gobject_class->constructed = g_socket_connection_constructed;
230   gobject_class->finalize = g_socket_connection_finalize;
231
232   stream_class->get_input_stream = g_socket_connection_get_input_stream;
233   stream_class->get_output_stream = g_socket_connection_get_output_stream;
234   stream_class->close_fn = g_socket_connection_close;
235   stream_class->close_async = g_socket_connection_close_async;
236   stream_class->close_finish = g_socket_connection_close_finish;
237
238   g_object_class_install_property (gobject_class, PROP_SOCKET,
239     g_param_spec_object ("socket",
240                          P_("Socket"),
241                          P_("The underlying GSocket"),
242                          G_TYPE_SOCKET, G_PARAM_CONSTRUCT_ONLY |
243                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
244 }
245
246 static void
247 g_socket_connection_init (GSocketConnection *connection)
248 {
249   connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection,
250                                                   G_TYPE_SOCKET_CONNECTION,
251                                                   GSocketConnectionPrivate);
252 }
253
254 static gboolean
255 g_socket_connection_close (GIOStream            *stream,
256                            GCancellable         *cancellable,
257                            GError              **error)
258 {
259   GSocketConnection *connection = G_SOCKET_CONNECTION (stream);
260
261   if (connection->priv->output_stream)
262     g_output_stream_close (connection->priv->output_stream,
263                            cancellable, NULL);
264   if (connection->priv->input_stream)
265     g_input_stream_close (connection->priv->input_stream,
266                           cancellable, NULL);
267
268   return g_socket_close (connection->priv->socket, error);
269 }
270
271
272 static void
273 g_socket_connection_close_async (GIOStream        *stream,
274                                  int               io_priority,
275                                  GCancellable     *cancellable,
276                                  GAsyncReadyCallback callback,
277                                  gpointer          user_data)
278 {
279   GSimpleAsyncResult *res;
280   GError *error;
281
282   /* socket close is not blocked, just do it! */
283   error = NULL;
284   if (!g_io_stream_close (stream, cancellable, &error))
285     {
286       g_simple_async_report_gerror_in_idle (G_OBJECT (stream),
287                                             callback, user_data,
288                                             error);
289       g_error_free (error);
290       return;
291     }
292
293   res = g_simple_async_result_new (G_OBJECT (stream),
294                                    callback,
295                                    user_data,
296                                    g_socket_connection_close_async);
297   g_simple_async_result_complete_in_idle (res);
298   g_object_unref (res);
299 }
300
301 static gboolean
302 g_socket_connection_close_finish (GIOStream  *stream,
303                                   GAsyncResult  *result,
304                                   GError       **error)
305 {
306   return TRUE;
307 }
308
309 typedef struct {
310   GSocketFamily socket_family;
311   GSocketType socket_type;
312   int protocol;
313   GType implementation;
314 } ConnectionFactory;
315
316 static guint
317 connection_factory_hash (gconstpointer key)
318 {
319   const ConnectionFactory *factory = key;
320   guint h;
321
322   h = factory->socket_family ^ (factory->socket_type << 4) ^ (factory->protocol << 8);
323   /* This is likely to be small, so spread over whole
324      hash space to get some distribution */
325   h = h ^ (h << 8) ^ (h << 16) ^ (h << 24);
326
327   return h;
328 }
329
330 static gboolean
331 connection_factory_equal (gconstpointer _a,
332                           gconstpointer _b)
333 {
334   const ConnectionFactory *a = _a;
335   const ConnectionFactory *b = _b;
336
337   if (a->socket_family != b->socket_family)
338     return FALSE;
339
340   if (a->socket_type != b->socket_type)
341     return FALSE;
342
343   if (a->protocol != b->protocol)
344     return FALSE;
345
346   return TRUE;
347 }
348
349 static GHashTable *connection_factories = NULL;
350 G_LOCK_DEFINE_STATIC(connection_factories);
351
352 /**
353  * g_socket_connection_factory_register_type:
354  * @g_type: a #GType, inheriting from G_SOCKET_CONNECTION
355  * @family: a #GSocketFamily.
356  * @type: a #GSocketType
357  * @protocol: a protocol id
358  *
359  * Looks up the #GType to be used when creating socket connections on
360  * sockets with the specified @family,@type and @protocol_id.
361  *
362  * If no type is registered, the #GSocketConnection base type is returned.
363  *
364  * Returns: a #GType
365  * Since: 2.22
366  **/
367 void
368 g_socket_connection_factory_register_type (GType g_type,
369                                            GSocketFamily family,
370                                            GSocketType type,
371                                            gint protocol)
372 {
373   ConnectionFactory *factory;
374
375   g_return_if_fail (g_type_is_a (g_type, G_TYPE_SOCKET_CONNECTION));
376
377   G_LOCK (connection_factories);
378
379   if (connection_factories == NULL)
380     connection_factories = g_hash_table_new_full (connection_factory_hash,
381                                                   connection_factory_equal,
382                                                   (GDestroyNotify)g_free,
383                                                   NULL);
384
385   factory = g_new0 (ConnectionFactory, 1);
386   factory->socket_family = family;
387   factory->socket_type = type;
388   factory->protocol = protocol;
389   factory->implementation = g_type;
390
391   g_hash_table_insert (connection_factories,
392                        factory, factory);
393
394   G_UNLOCK (connection_factories);
395 }
396
397 static void
398 init_builtin_types (void)
399 {
400   volatile GType a_type;
401 #ifndef G_OS_WIN32
402   a_type = g_unix_connection_get_type ();
403 #endif
404   a_type = g_tcp_connection_get_type ();
405 }
406
407 /**
408  * g_socket_connection_factory_lookup_type:
409  * @family: a #GSocketFamily.
410  * @type: a #GSocketType
411  * @protocol_id: a protocol id
412  *
413  * Looks up the #GType to be used when creating socket connections on
414  * sockets with the specified @family,@type and @protocol_id.
415  *
416  * If no type is registered, the #GSocketConnection base type is returned.
417  *
418  * Returns: a #GType
419  * Since: 2.22
420  **/
421 GType
422 g_socket_connection_factory_lookup_type (GSocketFamily family,
423                                          GSocketType type,
424                                          gint protocol_id)
425 {
426   ConnectionFactory *factory, key;
427   GType g_type;
428
429   init_builtin_types ();
430
431   G_LOCK (connection_factories);
432
433   g_type = G_TYPE_SOCKET_CONNECTION;
434
435   if (connection_factories)
436     {
437       key.socket_family = family;
438       key.socket_type = type;
439       key.protocol = protocol_id;
440
441       factory = g_hash_table_lookup (connection_factories, &key);
442       if (factory)
443         g_type = factory->implementation;
444     }
445
446   G_UNLOCK (connection_factories);
447
448   return g_type;
449 }
450
451 /**
452  * g_socket_connection_factory_create_connection:
453  * @socket: a #GSocket.
454  *
455  * Creates a #GSocketConnection subclass of the right type for
456  * @socket.
457  *
458  * Returns: a #GSocketConnection
459  *
460  * Since: 2.22
461  **/
462 GSocketConnection *
463 g_socket_connection_factory_create_connection (GSocket *socket)
464 {
465   GType type;
466
467   type = g_socket_connection_factory_lookup_type (g_socket_get_family (socket),
468                                                   g_socket_get_socket_type (socket),
469                                                   g_socket_get_protocol_id (socket));
470   return g_object_new (type, "socket", socket, NULL);
471 }
472
473 #define __G_SOCKET_CONNECTION_C__
474 #include "gioaliasdef.c"