gkdbus: Fix underflow and unreachable code bug
[platform/upstream/glib.git] / gio / gpollableoutputstream.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright (C) 2010 Red Hat, Inc.
4  *
5  * SPDX-License-Identifier: LGPL-2.1-or-later
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.1 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, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "config.h"
22
23 #include <errno.h>
24
25 #include "gpollableoutputstream.h"
26 #include "gasynchelper.h"
27 #include "gfiledescriptorbased.h"
28 #include "glibintl.h"
29
30 /**
31  * SECTION:gpollableoutputstream
32  * @short_description: Interface for pollable output streams
33  * @include: gio/gio.h
34  * @see_also: #GOutputStream, #GFileDescriptorBased, #GPollableInputStream
35  *
36  * #GPollableOutputStream is implemented by #GOutputStreams that
37  * can be polled for readiness to write. This can be used when
38  * interfacing with a non-GIO API that expects
39  * UNIX-file-descriptor-style asynchronous I/O rather than GIO-style.
40  *
41  * Some classes may implement #GPollableOutputStream but have only certain
42  * instances of that class be pollable. If g_pollable_output_stream_can_poll()
43  * returns %FALSE, then the behavior of other #GPollableOutputStream methods is
44  * undefined.
45  *
46  * Since: 2.28
47  */
48
49 G_DEFINE_INTERFACE (GPollableOutputStream, g_pollable_output_stream, G_TYPE_OUTPUT_STREAM)
50
51 static gboolean g_pollable_output_stream_default_can_poll           (GPollableOutputStream *stream);
52 static gssize   g_pollable_output_stream_default_write_nonblocking  (GPollableOutputStream  *stream,
53                                                                      const void             *buffer,
54                                                                      gsize                   count,
55                                                                      GError                **error);
56 static GPollableReturn g_pollable_output_stream_default_writev_nonblocking (GPollableOutputStream  *stream,
57                                                                             const GOutputVector    *vectors,
58                                                                             gsize                   n_vectors,
59                                                                             gsize                  *bytes_written,
60                                                                             GError                **error);
61
62 static void
63 g_pollable_output_stream_default_init (GPollableOutputStreamInterface *iface)
64 {
65   iface->can_poll           = g_pollable_output_stream_default_can_poll;
66   iface->write_nonblocking  = g_pollable_output_stream_default_write_nonblocking;
67   iface->writev_nonblocking = g_pollable_output_stream_default_writev_nonblocking;
68 }
69
70 static gboolean
71 g_pollable_output_stream_default_can_poll (GPollableOutputStream *stream)
72 {
73   return TRUE;
74 }
75
76 /**
77  * g_pollable_output_stream_can_poll:
78  * @stream: a #GPollableOutputStream.
79  *
80  * Checks if @stream is actually pollable. Some classes may implement
81  * #GPollableOutputStream but have only certain instances of that
82  * class be pollable. If this method returns %FALSE, then the behavior
83  * of other #GPollableOutputStream methods is undefined.
84  *
85  * For any given stream, the value returned by this method is constant;
86  * a stream cannot switch from pollable to non-pollable or vice versa.
87  *
88  * Returns: %TRUE if @stream is pollable, %FALSE if not.
89  *
90  * Since: 2.28
91  */
92 gboolean
93 g_pollable_output_stream_can_poll (GPollableOutputStream *stream)
94 {
95   g_return_val_if_fail (G_IS_POLLABLE_OUTPUT_STREAM (stream), FALSE);
96
97   return G_POLLABLE_OUTPUT_STREAM_GET_INTERFACE (stream)->can_poll (stream);
98 }
99
100 /**
101  * g_pollable_output_stream_is_writable:
102  * @stream: a #GPollableOutputStream.
103  *
104  * Checks if @stream can be written.
105  *
106  * Note that some stream types may not be able to implement this 100%
107  * reliably, and it is possible that a call to g_output_stream_write()
108  * after this returns %TRUE would still block. To guarantee
109  * non-blocking behavior, you should always use
110  * g_pollable_output_stream_write_nonblocking(), which will return a
111  * %G_IO_ERROR_WOULD_BLOCK error rather than blocking.
112  *
113  * The behaviour of this method is undefined if
114  * g_pollable_output_stream_can_poll() returns %FALSE for @stream.
115  *
116  * Returns: %TRUE if @stream is writable, %FALSE if not. If an error
117  *   has occurred on @stream, this will result in
118  *   g_pollable_output_stream_is_writable() returning %TRUE, and the
119  *   next attempt to write will return the error.
120  *
121  * Since: 2.28
122  */
123 gboolean
124 g_pollable_output_stream_is_writable (GPollableOutputStream *stream)
125 {
126   g_return_val_if_fail (G_IS_POLLABLE_OUTPUT_STREAM (stream), FALSE);
127
128   return G_POLLABLE_OUTPUT_STREAM_GET_INTERFACE (stream)->is_writable (stream);
129 }
130
131 /**
132  * g_pollable_output_stream_create_source:
133  * @stream: a #GPollableOutputStream.
134  * @cancellable: (nullable): a #GCancellable, or %NULL
135  *
136  * Creates a #GSource that triggers when @stream can be written, or
137  * @cancellable is triggered or an error occurs. The callback on the
138  * source is of the #GPollableSourceFunc type.
139  *
140  * As with g_pollable_output_stream_is_writable(), it is possible that
141  * the stream may not actually be writable even after the source
142  * triggers, so you should use g_pollable_output_stream_write_nonblocking()
143  * rather than g_output_stream_write() from the callback.
144  *
145  * The behaviour of this method is undefined if
146  * g_pollable_output_stream_can_poll() returns %FALSE for @stream.
147  *
148  * Returns: (transfer full): a new #GSource
149  *
150  * Since: 2.28
151  */
152 GSource *
153 g_pollable_output_stream_create_source (GPollableOutputStream *stream,
154                                         GCancellable          *cancellable)
155 {
156   g_return_val_if_fail (G_IS_POLLABLE_OUTPUT_STREAM (stream), NULL);
157
158   return G_POLLABLE_OUTPUT_STREAM_GET_INTERFACE (stream)->
159           create_source (stream, cancellable);
160 }
161
162 static gssize
163 g_pollable_output_stream_default_write_nonblocking (GPollableOutputStream  *stream,
164                                                     const void             *buffer,
165                                                     gsize                   count,
166                                                     GError                **error)
167 {
168   if (!g_pollable_output_stream_is_writable (stream))
169     {
170       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK,
171                            g_strerror (EAGAIN));
172       return -1;
173     }
174
175   return G_OUTPUT_STREAM_GET_CLASS (stream)->
176     write_fn (G_OUTPUT_STREAM (stream), buffer, count, NULL, error);
177 }
178
179 static GPollableReturn
180 g_pollable_output_stream_default_writev_nonblocking (GPollableOutputStream  *stream,
181                                                      const GOutputVector    *vectors,
182                                                      gsize                   n_vectors,
183                                                      gsize                  *bytes_written,
184                                                      GError                **error)
185 {
186   gsize _bytes_written = 0;
187   GPollableOutputStreamInterface *iface = G_POLLABLE_OUTPUT_STREAM_GET_INTERFACE (stream);
188   gsize i;
189   GError *err = NULL;
190
191   for (i = 0; i < n_vectors; i++)
192     {
193       gssize res;
194
195       /* Would we overflow here? In that case simply return and let the caller
196        * handle this like a short write */
197       if (_bytes_written > G_MAXSIZE - vectors[i].size)
198         break;
199
200       res = iface->write_nonblocking (stream, vectors[i].buffer, vectors[i].size, &err);
201       if (res == -1)
202         {
203           if (bytes_written)
204             *bytes_written = _bytes_written;
205
206           /* If something was written already we handle this like a short
207            * write and assume that the next call would either give the same
208            * error again or successfully finish writing without errors or data
209            * loss
210            */
211           if (_bytes_written > 0)
212             {
213               g_clear_error (&err);
214               return G_POLLABLE_RETURN_OK;
215             }
216           else if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
217             {
218               g_clear_error (&err);
219               return G_POLLABLE_RETURN_WOULD_BLOCK;
220             }
221           else
222             {
223               g_propagate_error (error, err);
224               return G_POLLABLE_RETURN_FAILED;
225             }
226         }
227
228       _bytes_written += res;
229       /* if we had a short write break the loop here */
230       if ((gsize) res < vectors[i].size)
231         break;
232     }
233
234   if (bytes_written)
235     *bytes_written = _bytes_written;
236
237   return G_POLLABLE_RETURN_OK;
238 }
239
240 /**
241  * g_pollable_output_stream_write_nonblocking:
242  * @stream: a #GPollableOutputStream
243  * @buffer: (array length=count) (element-type guint8): a buffer to write
244  *     data from
245  * @count: the number of bytes you want to write
246  * @cancellable: (nullable): a #GCancellable, or %NULL
247  * @error: #GError for error reporting, or %NULL to ignore.
248  *
249  * Attempts to write up to @count bytes from @buffer to @stream, as
250  * with g_output_stream_write(). If @stream is not currently writable,
251  * this will immediately return %G_IO_ERROR_WOULD_BLOCK, and you can
252  * use g_pollable_output_stream_create_source() to create a #GSource
253  * that will be triggered when @stream is writable.
254  *
255  * Note that since this method never blocks, you cannot actually
256  * use @cancellable to cancel it. However, it will return an error
257  * if @cancellable has already been cancelled when you call, which
258  * may happen if you call this method after a source triggers due
259  * to having been cancelled.
260  *
261  * Also note that if %G_IO_ERROR_WOULD_BLOCK is returned some underlying
262  * transports like D/TLS require that you re-send the same @buffer and
263  * @count in the next write call.
264  *
265  * The behaviour of this method is undefined if
266  * g_pollable_output_stream_can_poll() returns %FALSE for @stream.
267  *
268  * Virtual: write_nonblocking
269  * Returns: the number of bytes written, or -1 on error (including
270  *   %G_IO_ERROR_WOULD_BLOCK).
271  */
272 gssize
273 g_pollable_output_stream_write_nonblocking (GPollableOutputStream  *stream,
274                                             const void             *buffer,
275                                             gsize                   count,
276                                             GCancellable           *cancellable,
277                                             GError                **error)
278 {
279   gssize res;
280
281   g_return_val_if_fail (G_IS_POLLABLE_OUTPUT_STREAM (stream), -1);
282   g_return_val_if_fail (buffer != NULL, 0);
283
284   if (g_cancellable_set_error_if_cancelled (cancellable, error))
285     return -1;
286
287   if (count == 0)
288     return 0;
289
290   if (((gssize) count) < 0)
291     {
292       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
293                    _("Too large count value passed to %s"), G_STRFUNC);
294       return -1;
295     }
296
297   if (cancellable)
298     g_cancellable_push_current (cancellable);
299
300   res = G_POLLABLE_OUTPUT_STREAM_GET_INTERFACE (stream)->
301     write_nonblocking (stream, buffer, count, error);
302
303   if (cancellable)
304     g_cancellable_pop_current (cancellable);
305
306   return res;
307 }
308
309 /**
310  * g_pollable_output_stream_writev_nonblocking:
311  * @stream: a #GPollableOutputStream
312  * @vectors: (array length=n_vectors): the buffer containing the #GOutputVectors to write.
313  * @n_vectors: the number of vectors to write
314  * @bytes_written: (out) (optional): location to store the number of bytes that were
315  *     written to the stream
316  * @cancellable: (nullable): a #GCancellable, or %NULL
317  * @error: #GError for error reporting, or %NULL to ignore.
318  *
319  * Attempts to write the bytes contained in the @n_vectors @vectors to @stream,
320  * as with g_output_stream_writev(). If @stream is not currently writable,
321  * this will immediately return %@G_POLLABLE_RETURN_WOULD_BLOCK, and you can
322  * use g_pollable_output_stream_create_source() to create a #GSource
323  * that will be triggered when @stream is writable. @error will *not* be
324  * set in that case.
325  *
326  * Note that since this method never blocks, you cannot actually
327  * use @cancellable to cancel it. However, it will return an error
328  * if @cancellable has already been cancelled when you call, which
329  * may happen if you call this method after a source triggers due
330  * to having been cancelled.
331  *
332  * Also note that if %G_POLLABLE_RETURN_WOULD_BLOCK is returned some underlying
333  * transports like D/TLS require that you re-send the same @vectors and
334  * @n_vectors in the next write call.
335  *
336  * The behaviour of this method is undefined if
337  * g_pollable_output_stream_can_poll() returns %FALSE for @stream.
338  *
339  * Virtual: writev_nonblocking
340  *
341  * Returns: %@G_POLLABLE_RETURN_OK on success, %G_POLLABLE_RETURN_WOULD_BLOCK
342  * if the stream is not currently writable (and @error is *not* set), or
343  * %G_POLLABLE_RETURN_FAILED if there was an error in which case @error will
344  * be set.
345  *
346  * Since: 2.60
347  */
348 GPollableReturn
349 g_pollable_output_stream_writev_nonblocking (GPollableOutputStream  *stream,
350                                              const GOutputVector    *vectors,
351                                              gsize                   n_vectors,
352                                              gsize                  *bytes_written,
353                                              GCancellable           *cancellable,
354                                              GError                **error)
355 {
356   GPollableOutputStreamInterface *iface;
357   GPollableReturn res;
358   gsize _bytes_written = 0;
359
360   if (bytes_written)
361     *bytes_written = 0;
362
363   g_return_val_if_fail (G_IS_POLLABLE_OUTPUT_STREAM (stream), G_POLLABLE_RETURN_FAILED);
364   g_return_val_if_fail (vectors != NULL || n_vectors == 0, G_POLLABLE_RETURN_FAILED);
365   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), G_POLLABLE_RETURN_FAILED);
366   g_return_val_if_fail (error == NULL || *error == NULL, G_POLLABLE_RETURN_FAILED);
367
368   if (g_cancellable_set_error_if_cancelled (cancellable, error))
369     return G_POLLABLE_RETURN_FAILED;
370
371   if (n_vectors == 0)
372     return G_POLLABLE_RETURN_OK;
373
374   iface = G_POLLABLE_OUTPUT_STREAM_GET_INTERFACE (stream);
375   g_return_val_if_fail (iface->writev_nonblocking != NULL, G_POLLABLE_RETURN_FAILED);
376
377   if (cancellable)
378     g_cancellable_push_current (cancellable);
379
380   res = iface->
381     writev_nonblocking (stream, vectors, n_vectors, &_bytes_written, error);
382
383   if (cancellable)
384     g_cancellable_pop_current (cancellable);
385
386   if (res == G_POLLABLE_RETURN_FAILED)
387     g_warn_if_fail (error == NULL || (*error != NULL && !g_error_matches (*error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)));
388   else if (res == G_POLLABLE_RETURN_WOULD_BLOCK)
389     g_warn_if_fail (error == NULL || *error == NULL);
390
391   /* in case of not-OK nothing must've been written */
392   g_warn_if_fail (res == G_POLLABLE_RETURN_OK || _bytes_written == 0);
393
394   if (bytes_written)
395     *bytes_written = _bytes_written;
396
397   return res;
398 }