gio: port networking classes from GSimpleAsyncResult to GTask
[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  * Since: 2.22
23  */
24
25 #include "config.h"
26 #include "gtcpconnection.h"
27 #include "gasyncresult.h"
28 #include "gtask.h"
29 #include "giostream.h"
30 #include "glibintl.h"
31
32
33 G_DEFINE_TYPE_WITH_CODE (GTcpConnection, g_tcp_connection,
34                          G_TYPE_SOCKET_CONNECTION,
35   g_socket_connection_factory_register_type (g_define_type_id,
36                                              G_SOCKET_FAMILY_IPV4,
37                                              G_SOCKET_TYPE_STREAM,
38                                              G_SOCKET_PROTOCOL_DEFAULT);
39   g_socket_connection_factory_register_type (g_define_type_id,
40                                              G_SOCKET_FAMILY_IPV6,
41                                              G_SOCKET_TYPE_STREAM,
42                                              G_SOCKET_PROTOCOL_DEFAULT);
43   g_socket_connection_factory_register_type (g_define_type_id,
44                                              G_SOCKET_FAMILY_IPV4,
45                                              G_SOCKET_TYPE_STREAM,
46                                              G_SOCKET_PROTOCOL_TCP);
47   g_socket_connection_factory_register_type (g_define_type_id,
48                                              G_SOCKET_FAMILY_IPV6,
49                                              G_SOCKET_TYPE_STREAM,
50                                              G_SOCKET_PROTOCOL_TCP);
51                          );
52
53 static gboolean g_tcp_connection_close       (GIOStream            *stream,
54                                               GCancellable         *cancellable,
55                                               GError              **error);
56 static void     g_tcp_connection_close_async (GIOStream            *stream,
57                                               int                   io_priority,
58                                               GCancellable         *cancellable,
59                                               GAsyncReadyCallback   callback,
60                                               gpointer              user_data);
61
62 struct _GTcpConnectionPrivate
63 {
64   guint graceful_disconnect : 1;
65 };
66
67
68 enum
69 {
70   PROP_0,
71   PROP_GRACEFUL_DISCONNECT
72 };
73
74 static void
75 g_tcp_connection_init (GTcpConnection *connection)
76 {
77   connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection,
78                                                   G_TYPE_TCP_CONNECTION,
79                                                   GTcpConnectionPrivate);
80   connection->priv->graceful_disconnect = FALSE;
81 }
82
83 static void
84 g_tcp_connection_get_property (GObject    *object,
85                                guint       prop_id,
86                                GValue     *value,
87                                GParamSpec *pspec)
88 {
89   GTcpConnection *connection = G_TCP_CONNECTION (object);
90
91   switch (prop_id)
92     {
93       case PROP_GRACEFUL_DISCONNECT:
94         g_value_set_boolean (value, connection->priv->graceful_disconnect);
95         break;
96
97       default:
98         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
99     }
100 }
101
102 static void
103 g_tcp_connection_set_property (GObject      *object,
104                                guint         prop_id,
105                                const GValue *value,
106                                GParamSpec   *pspec)
107 {
108   GTcpConnection *connection = G_TCP_CONNECTION (object);
109
110   switch (prop_id)
111     {
112       case PROP_GRACEFUL_DISCONNECT:
113         g_tcp_connection_set_graceful_disconnect (connection,
114                                                   g_value_get_boolean (value));
115         break;
116
117       default:
118         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
119     }
120 }
121
122 static void
123 g_tcp_connection_class_init (GTcpConnectionClass *class)
124 {
125   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
126   GIOStreamClass *stream_class = G_IO_STREAM_CLASS (class);
127
128   g_type_class_add_private (class, sizeof (GTcpConnectionPrivate));
129
130   gobject_class->set_property = g_tcp_connection_set_property;
131   gobject_class->get_property = g_tcp_connection_get_property;
132
133   stream_class->close_fn = g_tcp_connection_close;
134   stream_class->close_async = g_tcp_connection_close_async;
135
136   g_object_class_install_property (gobject_class, PROP_GRACEFUL_DISCONNECT,
137                                    g_param_spec_boolean ("graceful-disconnect",
138                                                          P_("Graceful Disconnect"),
139                                                          P_("Whether or not close does a graceful disconnect"),
140                                                          FALSE,
141                                                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
142
143 }
144
145 static gboolean
146 g_tcp_connection_close (GIOStream     *stream,
147                         GCancellable  *cancellable,
148                         GError       **error)
149 {
150   GTcpConnection *connection = G_TCP_CONNECTION (stream);
151   GSocket *socket;
152   char buffer[1024];
153   gssize ret;
154   gboolean had_error;
155
156   socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (stream));
157   had_error = FALSE;
158
159   if (connection->priv->graceful_disconnect &&
160       !g_cancellable_is_cancelled (cancellable) /* Cancelled -> close fast */)
161     {
162       if (!g_socket_shutdown (socket, FALSE, TRUE, error))
163         {
164           error = NULL; /* Ignore further errors */
165           had_error = TRUE;
166         }
167       else
168         {
169           while (TRUE)
170             {
171               ret = g_socket_receive_with_blocking (socket,  buffer, sizeof (buffer),
172                                                     TRUE, cancellable, error);
173               if (ret < 0)
174                 {
175                   had_error = TRUE;
176                   error = NULL;
177                   break;
178                 }
179               if (ret == 0)
180                 break;
181             }
182         }
183     }
184
185   return G_IO_STREAM_CLASS (g_tcp_connection_parent_class)
186     ->close_fn (stream, cancellable, error) && !had_error;
187 }
188
189 /* consumes @error */
190 static void
191 async_close_finish (GTask    *task,
192                     GError   *error)
193 {
194   GIOStreamClass *parent = G_IO_STREAM_CLASS (g_tcp_connection_parent_class);
195   GIOStream *stream = g_task_get_source_object (task);
196   GCancellable *cancellable = g_task_get_cancellable (task);
197
198   /* Close underlying stream, ignoring further errors if we already
199    * have one.
200    */
201   if (error)
202     parent->close_fn (stream, cancellable, NULL);
203   else
204     parent->close_fn (stream, cancellable, &error);
205
206   if (error)
207     g_task_return_error (task, error);
208   else
209     g_task_return_boolean (task, TRUE);
210 }
211
212
213 static gboolean
214 close_read_ready (GSocket        *socket,
215                   GIOCondition    condition,
216                   GTask          *task)
217 {
218   GError *error = NULL;
219   char buffer[1024];
220   gssize ret;
221
222   ret = g_socket_receive_with_blocking (socket,  buffer, sizeof (buffer),
223                                         FALSE, g_task_get_cancellable (task),
224                                         &error);
225   if (ret < 0)
226     {
227       if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
228         {
229           g_error_free (error);
230           return TRUE;
231         }
232       else
233         {
234           async_close_finish (task, error);
235           g_object_unref (task);
236           return FALSE;
237         }
238     }
239
240   if (ret == 0)
241     {
242       async_close_finish (task, NULL);
243       return FALSE;
244     }
245
246   return TRUE;
247 }
248
249
250 static void
251 g_tcp_connection_close_async (GIOStream           *stream,
252                               int                  io_priority,
253                               GCancellable        *cancellable,
254                               GAsyncReadyCallback  callback,
255                               gpointer             user_data)
256 {
257   GTcpConnection *connection = G_TCP_CONNECTION (stream);
258   GSocket *socket;
259   GSource *source;
260   GError *error;
261   GTask *task;
262
263   if (connection->priv->graceful_disconnect &&
264       !g_cancellable_is_cancelled (cancellable) /* Cancelled -> close fast */)
265     {
266       task = g_task_new (stream, cancellable, callback, user_data);
267       g_task_set_priority (task, io_priority);
268
269       socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (stream));
270
271       error = NULL;
272       if (!g_socket_shutdown (socket, FALSE, TRUE, &error))
273         {
274           g_task_return_error (task, error);
275           g_object_unref (task);
276           return;
277         }
278
279       source = g_socket_create_source (socket, G_IO_IN, cancellable);
280       g_task_attach_source (task, source, (GSourceFunc) close_read_ready);
281       g_source_unref (source);
282
283       return;
284     }
285
286   G_IO_STREAM_CLASS (g_tcp_connection_parent_class)
287     ->close_async (stream, io_priority, cancellable, callback, user_data);
288 }
289
290 /**
291  * g_tcp_connection_set_graceful_disconnect:
292  * @connection: a #GTcpConnection
293  * @graceful_disconnect: Whether to do graceful disconnects or not
294  *
295  * This enabled graceful disconnects on close. A graceful disconnect
296  * means that we signal the receiving end that the connection is terminated
297  * and wait for it to close the connection before closing the connection.
298  *
299  * A graceful disconnect means that we can be sure that we successfully sent
300  * all the outstanding data to the other end, or get an error reported.
301  * However, it also means we have to wait for all the data to reach the
302  * other side and for it to acknowledge this by closing the socket, which may
303  * take a while. For this reason it is disabled by default.
304  *
305  * Since: 2.22
306  */
307 void
308 g_tcp_connection_set_graceful_disconnect (GTcpConnection *connection,
309                                           gboolean        graceful_disconnect)
310 {
311   graceful_disconnect = !!graceful_disconnect;
312   if (graceful_disconnect != connection->priv->graceful_disconnect)
313     {
314       connection->priv->graceful_disconnect = graceful_disconnect;
315       g_object_notify (G_OBJECT (connection), "graceful-disconnect");
316     }
317 }
318
319 /**
320  * g_tcp_connection_get_graceful_disconnect:
321  * @connection: a #GTcpConnection
322  *
323  * Checks if graceful disconnects are used. See
324  * g_tcp_connection_set_graceful_disconnect().
325  *
326  * Returns: %TRUE if graceful disconnect is used on close, %FALSE otherwise
327  *
328  * Since: 2.22
329  */
330 gboolean
331 g_tcp_connection_get_graceful_disconnect (GTcpConnection *connection)
332 {
333   return connection->priv->graceful_disconnect;
334 }