typo in documentation
[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
53  * depends on the type of the underlying socket that is in use. For
54  * instance, for a TCP/IP connection it will be a #GTcpConnection.
55  *
56  * Chosing what type of object to construct is done with the socket
57  * connection factory, and it is possible for 3rd parties to register
58  * custom socket connection types for specific combination of socket
59  * family/type/protocol using 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 remote 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,
176                                   guint       prop_id,
177                                   GValue     *value,
178                                   GParamSpec *pspec)
179 {
180   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
181
182   switch (prop_id)
183     {
184      case PROP_SOCKET:
185       g_value_set_object (value, connection->priv->socket);
186       break;
187
188      default:
189       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
190     }
191 }
192
193 static void
194 g_socket_connection_set_property (GObject      *object,
195                                   guint         prop_id,
196                                   const GValue *value,
197                                   GParamSpec   *pspec)
198 {
199   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
200
201   switch (prop_id)
202     {
203      case PROP_SOCKET:
204       connection->priv->socket = G_SOCKET (g_value_dup_object (value));
205       break;
206
207      default:
208       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
209     }
210 }
211
212 static void
213 g_socket_connection_constructed (GObject *object)
214 {
215   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
216
217   g_assert (connection->priv->socket != NULL);
218 }
219
220 static void
221 g_socket_connection_finalize (GObject *object)
222 {
223   GSocketConnection *connection = G_SOCKET_CONNECTION (object);
224
225   if (connection->priv->input_stream)
226     g_object_unref (connection->priv->input_stream);
227
228   if (connection->priv->output_stream)
229     g_object_unref (connection->priv->output_stream);
230
231   g_object_unref (connection->priv->socket);
232
233   G_OBJECT_CLASS (g_socket_connection_parent_class)
234     ->finalize (object);
235 }
236
237 static void
238 g_socket_connection_class_init (GSocketConnectionClass *klass)
239 {
240   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
241   GIOStreamClass *stream_class = G_IO_STREAM_CLASS (klass);
242
243   g_type_class_add_private (klass, sizeof (GSocketConnectionPrivate));
244
245   gobject_class->set_property = g_socket_connection_set_property;
246   gobject_class->get_property = g_socket_connection_get_property;
247   gobject_class->constructed = g_socket_connection_constructed;
248   gobject_class->finalize = g_socket_connection_finalize;
249
250   stream_class->get_input_stream = g_socket_connection_get_input_stream;
251   stream_class->get_output_stream = g_socket_connection_get_output_stream;
252   stream_class->close_fn = g_socket_connection_close;
253   stream_class->close_async = g_socket_connection_close_async;
254   stream_class->close_finish = g_socket_connection_close_finish;
255
256   g_object_class_install_property (gobject_class,
257                                    PROP_SOCKET,
258                                    g_param_spec_object ("socket",
259                                                         P_("Socket"),
260                                                         P_("The underlying GSocket"),
261                                                         G_TYPE_SOCKET,
262                                                         G_PARAM_CONSTRUCT_ONLY |
263                                                         G_PARAM_READWRITE |
264                                                         G_PARAM_STATIC_STRINGS));
265 }
266
267 static void
268 g_socket_connection_init (GSocketConnection *connection)
269 {
270   connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection,
271                                                   G_TYPE_SOCKET_CONNECTION,
272                                                   GSocketConnectionPrivate);
273 }
274
275 static gboolean
276 g_socket_connection_close (GIOStream     *stream,
277                            GCancellable  *cancellable,
278                            GError       **error)
279 {
280   GSocketConnection *connection = G_SOCKET_CONNECTION (stream);
281
282   if (connection->priv->output_stream)
283     g_output_stream_close (connection->priv->output_stream,
284                            cancellable, NULL);
285   if (connection->priv->input_stream)
286     g_input_stream_close (connection->priv->input_stream,
287                           cancellable, NULL);
288
289   return g_socket_close (connection->priv->socket, error);
290 }
291
292
293 static void
294 g_socket_connection_close_async (GIOStream           *stream,
295                                  int                  io_priority,
296                                  GCancellable        *cancellable,
297                                  GAsyncReadyCallback  callback,
298                                  gpointer             user_data)
299 {
300   GSimpleAsyncResult *res;
301   GIOStreamClass *class;
302   GError *error;
303
304   class = G_IO_STREAM_GET_CLASS (stream);
305
306   /* socket close is not blocked, just do it! */
307   error = NULL;
308   if (class->close_fn &&
309       !class->close_fn (stream, cancellable, &error))
310     {
311       g_simple_async_report_gerror_in_idle (G_OBJECT (stream),
312                                             callback, user_data,
313                                             error);
314       g_error_free (error);
315       return;
316     }
317
318   res = g_simple_async_result_new (G_OBJECT (stream),
319                                    callback,
320                                    user_data,
321                                    g_socket_connection_close_async);
322   g_simple_async_result_complete_in_idle (res);
323   g_object_unref (res);
324 }
325
326 static gboolean
327 g_socket_connection_close_finish (GIOStream     *stream,
328                                   GAsyncResult  *result,
329                                   GError       **error)
330 {
331   return TRUE;
332 }
333
334 typedef struct {
335   GSocketFamily socket_family;
336   GSocketType socket_type;
337   int protocol;
338   GType implementation;
339 } ConnectionFactory;
340
341 static guint
342 connection_factory_hash (gconstpointer key)
343 {
344   const ConnectionFactory *factory = key;
345   guint h;
346
347   h = factory->socket_family ^ (factory->socket_type << 4) ^ (factory->protocol << 8);
348   /* This is likely to be small, so spread over whole
349      hash space to get some distribution */
350   h = h ^ (h << 8) ^ (h << 16) ^ (h << 24);
351
352   return h;
353 }
354
355 static gboolean
356 connection_factory_equal (gconstpointer _a,
357                           gconstpointer _b)
358 {
359   const ConnectionFactory *a = _a;
360   const ConnectionFactory *b = _b;
361
362   if (a->socket_family != b->socket_family)
363     return FALSE;
364
365   if (a->socket_type != b->socket_type)
366     return FALSE;
367
368   if (a->protocol != b->protocol)
369     return FALSE;
370
371   return TRUE;
372 }
373
374 static GHashTable *connection_factories = NULL;
375 G_LOCK_DEFINE_STATIC(connection_factories);
376
377 /**
378  * g_socket_connection_factory_register_type:
379  * @g_type: a #GType, inheriting from %G_TYPE_SOCKET_CONNECTION
380  * @family: a #GSocketFamily
381  * @type: a #GSocketType
382  * @protocol: a protocol id
383  *
384  * Looks up the #GType to be used when creating socket connections on
385  * sockets with the specified @family,@type and @protocol.
386  *
387  * If no type is registered, the #GSocketConnection base type is returned.
388  *
389  * Since: 2.22
390  */
391 void
392 g_socket_connection_factory_register_type (GType         g_type,
393                                            GSocketFamily family,
394                                            GSocketType   type,
395                                            gint          protocol)
396 {
397   ConnectionFactory *factory;
398
399   g_return_if_fail (g_type_is_a (g_type, G_TYPE_SOCKET_CONNECTION));
400
401   G_LOCK (connection_factories);
402
403   if (connection_factories == NULL)
404     connection_factories = g_hash_table_new_full (connection_factory_hash,
405                                                   connection_factory_equal,
406                                                   (GDestroyNotify)g_free,
407                                                   NULL);
408
409   factory = g_new0 (ConnectionFactory, 1);
410   factory->socket_family = family;
411   factory->socket_type = type;
412   factory->protocol = protocol;
413   factory->implementation = g_type;
414
415   g_hash_table_insert (connection_factories,
416                        factory, factory);
417
418   G_UNLOCK (connection_factories);
419 }
420
421 static void
422 init_builtin_types (void)
423 {
424   volatile GType a_type;
425 #ifndef G_OS_WIN32
426   a_type = g_unix_connection_get_type ();
427 #endif
428   a_type = g_tcp_connection_get_type ();
429 }
430
431 /**
432  * g_socket_connection_factory_lookup_type:
433  * @family: a #GSocketFamily
434  * @type: a #GSocketType
435  * @protocol_id: a protocol id
436  *
437  * Looks up the #GType to be used when creating socket connections on
438  * sockets with the specified @family,@type and @protocol_id.
439  *
440  * If no type is registered, the #GSocketConnection base type is returned.
441  *
442  * Returns: a #GType
443  *
444  * Since: 2.22
445  */
446 GType
447 g_socket_connection_factory_lookup_type (GSocketFamily family,
448                                          GSocketType   type,
449                                          gint          protocol_id)
450 {
451   ConnectionFactory *factory, key;
452   GType g_type;
453
454   init_builtin_types ();
455
456   G_LOCK (connection_factories);
457
458   g_type = G_TYPE_SOCKET_CONNECTION;
459
460   if (connection_factories)
461     {
462       key.socket_family = family;
463       key.socket_type = type;
464       key.protocol = protocol_id;
465
466       factory = g_hash_table_lookup (connection_factories, &key);
467       if (factory)
468         g_type = factory->implementation;
469     }
470
471   G_UNLOCK (connection_factories);
472
473   return g_type;
474 }
475
476 /**
477  * g_socket_connection_factory_create_connection:
478  * @socket: a #GSocket
479  *
480  * Creates a #GSocketConnection subclass of the right type for
481  * @socket.
482  *
483  * Returns: a #GSocketConnection
484  *
485  * Since: 2.22
486  */
487 GSocketConnection *
488 g_socket_connection_factory_create_connection (GSocket *socket)
489 {
490   GType type;
491
492   type = g_socket_connection_factory_lookup_type (g_socket_get_family (socket),
493                                                   g_socket_get_socket_type (socket),
494                                                   g_socket_get_protocol (socket));
495   return g_object_new (type, "socket", socket, NULL);
496 }
497
498 #define __G_SOCKET_CONNECTION_C__
499 #include "gioaliasdef.c"