Support g_main_context_push_thread_default() in gio
[platform/upstream/glib.git] / gio / gtcpconnection.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright © 2008, 2009 Codethink Limited
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License as published
7  * by the Free Software Foundation; either version 2 of the licence or (at
8  * your option) any later version.
9  *
10  * See the included COPYING file for more information.
11  */
12
13 /**
14  * SECTION: gtcpconnection
15  * @title: GTcpConnection
16  * @short_description: a TCP #GSocketConnection
17  * @see_also: #GSocketConnection.
18  *
19  * This is the subclass of #GSocketConnection that is created
20  * for TCP/IP sockets.
21  *
22  * It is currently empty; it offers no additional functionality
23  * over its base class.
24  *
25  * Eventually, some TCP-specific socket stuff will be added.
26  *
27  * Since: 2.22
28  */
29
30 #include "config.h"
31 #include "gtcpconnection.h"
32 #include "gasyncresult.h"
33 #include "gsimpleasyncresult.h"
34 #include "giostream.h"
35 #include "glibintl.h"
36
37 #include "gioalias.h"
38
39 G_DEFINE_TYPE_WITH_CODE (GTcpConnection, g_tcp_connection,
40                          G_TYPE_SOCKET_CONNECTION,
41   g_socket_connection_factory_register_type (g_define_type_id,
42                                              G_SOCKET_FAMILY_IPV4,
43                                              G_SOCKET_TYPE_STREAM,
44                                              G_SOCKET_PROTOCOL_DEFAULT);
45   g_socket_connection_factory_register_type (g_define_type_id,
46                                              G_SOCKET_FAMILY_IPV6,
47                                              G_SOCKET_TYPE_STREAM,
48                                              G_SOCKET_PROTOCOL_DEFAULT);
49   g_socket_connection_factory_register_type (g_define_type_id,
50                                              G_SOCKET_FAMILY_IPV4,
51                                              G_SOCKET_TYPE_STREAM,
52                                              G_SOCKET_PROTOCOL_TCP);
53   g_socket_connection_factory_register_type (g_define_type_id,
54                                              G_SOCKET_FAMILY_IPV6,
55                                              G_SOCKET_TYPE_STREAM,
56                                              G_SOCKET_PROTOCOL_TCP);
57                          );
58
59 static gboolean g_tcp_connection_close       (GIOStream            *stream,
60                                               GCancellable         *cancellable,
61                                               GError              **error);
62 static void     g_tcp_connection_close_async (GIOStream            *stream,
63                                               int                   io_priority,
64                                               GCancellable         *cancellable,
65                                               GAsyncReadyCallback   callback,
66                                               gpointer              user_data);
67
68 struct _GTcpConnectionPrivate
69 {
70   guint graceful_disconnect : 1;
71 };
72
73
74 enum
75 {
76   PROP_0,
77   PROP_GRACEFUL_DISCONNECT
78 };
79
80 static void
81 g_tcp_connection_init (GTcpConnection *connection)
82 {
83   connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection,
84                                                   G_TYPE_TCP_CONNECTION,
85                                                   GTcpConnectionPrivate);
86   connection->priv->graceful_disconnect = FALSE;
87 }
88
89 static void
90 g_tcp_connection_get_property (GObject    *object,
91                                guint       prop_id,
92                                GValue     *value,
93                                GParamSpec *pspec)
94 {
95   GTcpConnection *connection = G_TCP_CONNECTION (object);
96
97   switch (prop_id)
98     {
99       case PROP_GRACEFUL_DISCONNECT:
100         g_value_set_boolean (value, connection->priv->graceful_disconnect);
101         break;
102
103       default:
104         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
105     }
106 }
107
108 static void
109 g_tcp_connection_set_property (GObject      *object,
110                                guint         prop_id,
111                                const GValue *value,
112                                GParamSpec   *pspec)
113 {
114   GTcpConnection *connection = G_TCP_CONNECTION (object);
115
116   switch (prop_id)
117     {
118       case PROP_GRACEFUL_DISCONNECT:
119         g_tcp_connection_set_graceful_disconnect (connection,
120                                                   g_value_get_boolean (value));
121         break;
122
123       default:
124         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
125     }
126 }
127
128 static void
129 g_tcp_connection_class_init (GTcpConnectionClass *class)
130 {
131   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
132   GIOStreamClass *stream_class = G_IO_STREAM_CLASS (class);
133
134   g_type_class_add_private (class, sizeof (GTcpConnectionPrivate));
135
136   gobject_class->set_property = g_tcp_connection_set_property;
137   gobject_class->get_property = g_tcp_connection_get_property;
138
139   stream_class->close_fn = g_tcp_connection_close;
140   stream_class->close_async = g_tcp_connection_close_async;
141
142   g_object_class_install_property (gobject_class, PROP_GRACEFUL_DISCONNECT,
143                                    g_param_spec_boolean ("graceful-disconnect",
144                                                          P_("Graceful Disconnect"),
145                                                          P_("Whether or not close does a graceful disconnect"),
146                                                          FALSE,
147                                                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
148
149 }
150
151 static gboolean
152 g_tcp_connection_close (GIOStream     *stream,
153                         GCancellable  *cancellable,
154                         GError       **error)
155 {
156   GTcpConnection *connection = G_TCP_CONNECTION (stream);
157   GSocket *socket;
158   char buffer[1024];
159   gssize ret;
160   GError *my_error;
161   gboolean had_error;
162
163   socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (stream));
164   had_error = FALSE;
165
166   if (connection->priv->graceful_disconnect &&
167       !g_cancellable_is_cancelled (cancellable) /* Cancelled -> close fast */)
168     {
169       if (!g_socket_shutdown (socket, FALSE, TRUE, error))
170         {
171           error = NULL; /* Ignore further errors */
172           had_error = TRUE;
173         }
174       else
175         {
176           while (TRUE)
177             {
178               my_error = NULL;
179               ret = g_socket_receive (socket,  buffer, sizeof (buffer),
180                                       cancellable, &my_error);
181               if (ret < 0)
182                 {
183                   if (g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
184                     g_error_free (my_error);
185                   else
186                     {
187                       had_error = TRUE;
188                       g_propagate_error (error, my_error);
189                       error = NULL;
190                       break;
191                     }
192                 }
193               if (ret == 0)
194                 break;
195             }
196         }
197     }
198
199   return G_IO_STREAM_CLASS (g_tcp_connection_parent_class)
200     ->close_fn (stream, cancellable, error) && !had_error;
201 }
202
203 typedef struct {
204   GSimpleAsyncResult *res;
205   GCancellable *cancellable;
206 } CloseAsyncData;
207
208 static void
209 close_async_data_free (CloseAsyncData *data)
210 {
211   g_object_unref (data->res);
212   if (data->cancellable)
213     g_object_unref (data->cancellable);
214   g_free (data);
215 }
216
217 static void
218 async_close_finish (CloseAsyncData *data,
219                     GError         *error,
220                     gboolean        in_mainloop)
221 {
222   GIOStreamClass *parent = G_IO_STREAM_CLASS (g_tcp_connection_parent_class);
223   GIOStream *stream;
224   GError *my_error;
225
226   stream = G_IO_STREAM (g_async_result_get_source_object (G_ASYNC_RESULT (data->res)));
227
228   /* Doesn't block, ignore error */
229   if (error)
230     {
231       parent->close_fn (stream, data->cancellable, NULL);
232       g_simple_async_result_set_from_error (data->res, error);
233     }
234   else
235     {
236       my_error = NULL;
237       parent->close_fn (stream, data->cancellable, &my_error);
238       if (my_error)
239         {
240           g_simple_async_result_set_from_error (data->res, my_error);
241           g_error_free (my_error);
242         }
243     }
244
245   if (in_mainloop)
246     g_simple_async_result_complete (data->res);
247   else
248     g_simple_async_result_complete_in_idle (data->res);
249 }
250
251 static gboolean
252 close_read_ready (GSocket        *socket,
253                   GIOCondition    condition,
254                   CloseAsyncData *data)
255 {
256   GError *error = NULL;
257   char buffer[1024];
258   gssize ret;
259
260   ret = g_socket_receive (socket,  buffer, sizeof (buffer),
261                           data->cancellable, &error);
262   if (ret < 0)
263     {
264       if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
265         g_error_free (error);
266       else
267         {
268           async_close_finish (data, error, TRUE);
269           g_error_free (error);
270           return FALSE;
271         }
272     }
273
274   if (ret == 0)
275     {
276       async_close_finish (data, NULL, TRUE);
277       return FALSE;
278     }
279
280   return TRUE;
281 }
282
283
284 static void
285 g_tcp_connection_close_async (GIOStream           *stream,
286                               int                  io_priority,
287                               GCancellable        *cancellable,
288                               GAsyncReadyCallback  callback,
289                               gpointer             user_data)
290 {
291   GTcpConnection *connection = G_TCP_CONNECTION (stream);
292   CloseAsyncData *data;
293   GSocket *socket;
294   GSource *source;
295   GError *error;
296
297   if (connection->priv->graceful_disconnect &&
298       !g_cancellable_is_cancelled (cancellable) /* Cancelled -> close fast */)
299     {
300       data = g_new (CloseAsyncData, 1);
301       data->res =
302         g_simple_async_result_new (G_OBJECT (stream), callback, user_data,
303                                    g_tcp_connection_close_async);
304       if (cancellable)
305         data->cancellable = g_object_ref (cancellable);
306       else
307         data->cancellable = NULL;
308
309       socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (stream));
310
311       error = NULL;
312       if (!g_socket_shutdown (socket, FALSE, TRUE, &error))
313         {
314           async_close_finish (data, error, FALSE);
315           g_error_free (error);
316           close_async_data_free (data);
317           return;
318         }
319
320       source = g_socket_create_source (socket, G_IO_IN, cancellable);
321       g_source_set_callback (source,
322                              (GSourceFunc) close_read_ready,
323                              data, (GDestroyNotify)close_async_data_free);
324       g_source_attach (source, g_main_context_get_thread_default ());
325       g_source_unref (source);
326
327       return;
328     }
329
330   return G_IO_STREAM_CLASS (g_tcp_connection_parent_class)
331     ->close_async (stream, io_priority, cancellable, callback, user_data);
332 }
333
334 /**
335  * g_tcp_connection_set_graceful_disconnect:
336  * @connection: a #GTcpConnection
337  * @graceful_disconnect: Whether to do graceful disconnects or not
338  *
339  * This enabled graceful disconnects on close. A graceful disconnect
340  * means that we signal the recieving end that the connection is terminated
341  * and wait for it to close the connection before closing the connection.
342  *
343  * A graceful disconnect means that we can be sure that we successfully sent
344  * all the outstanding data to the other end, or get an error reported.
345  * However, it also means we have to wait for all the data to reach the
346  * other side and for it to acknowledge this by closing the socket, which may
347  * take a while. For this reason it is disabled by default.
348  *
349  * Since: 2.22
350  */
351 void
352 g_tcp_connection_set_graceful_disconnect (GTcpConnection *connection,
353                                           gboolean        graceful_disconnect)
354 {
355   graceful_disconnect = !!graceful_disconnect;
356   if (graceful_disconnect != connection->priv->graceful_disconnect)
357     {
358       connection->priv->graceful_disconnect = graceful_disconnect;
359       g_object_notify (G_OBJECT (connection), "graceful-disconnect");
360     }
361 }
362
363 /**
364  * g_tcp_connection_get_graceful_disconnect:
365  * @connection: a #GTcpConnection
366  *
367  * Checks if graceful disconnects are used. See
368  * g_tcp_connection_set_graceful_disconnect().
369  *
370  * Returns: %TRUE if graceful disconnect is used on close, %FALSE otherwise
371  *
372  * Since: 2.22
373  */
374 gboolean
375 g_tcp_connection_get_graceful_disconnect (GTcpConnection *connection)
376 {
377   return connection->priv->graceful_disconnect;
378 }
379
380
381 #define __G_TCP_CONNECTION_C__
382 #include "gioaliasdef.c"