1 /* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
3 * GIO - GLib Input, Output and Streaming Library
5 * Copyright 2009-2011 Red Hat, Inc
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.
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.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, see
19 * <http://www.gnu.org/licenses/>.
21 * In addition, when the library is used with OpenSSL, a special
22 * exception applies. Refer to the LICENSE_EXCEPTION file for details.
30 #include "gtlsconnection-base.h"
31 #include "gtlsinputstream.h"
33 #include "gtlsoutputstream.h"
35 #include <glib/gi18n-lib.h>
36 #include <glib/gprintf.h>
39 * GTlsConnectionBase is the base abstract implementation of TLS and DTLS
40 * support, for both the client and server side of a connection. The choice
41 * between TLS and DTLS is made by setting the base-io-stream or
42 * base-socket properties — exactly one of them must be set at
45 * Client- and server-specific code is in the client and server concrete
46 * subclasses, although the line about where code is put is a little blurry,
47 * and there are various places in GTlsConnectionBase which check
48 * G_IS_TLS_CLIENT_CONNECTION(self) to switch to a client-only code path.
50 * This abstract class implements a lot of interfaces:
51 * • Derived from GTlsConnection (itself from GIOStream), for TLS and streaming
53 * • Implements GDtlsConnection and GDatagramBased, for DTLS and datagram
55 * • Implements GInitable for failable initialisation.
60 /* When operating in stream mode, as a GTlsConnection. These are
61 * mutually-exclusive with base_socket. There are two different
62 * GIOStreams here: (a) base_io_stream and (b) the GTlsConnection
63 * itself. base_io_stream is the GIOStream used to create the GTlsConnection,
64 * and corresponds to the GTlsConnection::base-io-stream property.
65 * base_istream and base_ostream are the GInputStream and GOutputStream,
66 * respectively, of base_io_stream. These are for the underlying sockets that
67 * don't know about TLS.
69 * Then the GTlsConnection also has tls_istream and tls_ostream, which
70 * wrap the aforementioned base streams with a TLS session.
72 * When operating in datagram mode, none of these are used.
74 GIOStream *base_io_stream;
75 GPollableInputStream *base_istream;
76 GPollableOutputStream *base_ostream;
77 GInputStream *tls_istream;
78 GOutputStream *tls_ostream;
80 /* When operating in datagram mode, as a GDtlsConnection, the
81 * GTlsConnection is itself the DTLS GDatagramBased. It uses base_socket
82 * for the underlying I/O. It is mutually-exclusive with base_io_stream and
85 GDatagramBased *base_socket;
87 GTlsDatabase *database;
88 GTlsInteraction *interaction;
90 GTlsCertificate *certificate;
91 gboolean missing_requested_client_certificate;
92 GError *interaction_error;
93 GTlsCertificate *peer_certificate;
94 GTlsCertificateFlags peer_certificate_errors;
96 GMutex verify_certificate_mutex;
97 GCond verify_certificate_condition;
98 gboolean peer_certificate_accepted;
99 gboolean peer_certificate_examined;
101 gboolean require_close_notify;
103 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
104 GTlsRehandshakeMode rehandshake_mode;
105 G_GNUC_END_IGNORE_DEPRECATIONS
107 /* need_handshake means the next claim_op() will get diverted into
108 * an implicit handshake (unless it's an OP_HANDSHAKE or OP_CLOSE*).
109 * need_finish_handshake means the next claim_op() will get diverted
110 * into finish_handshake() (unless it's an OP_CLOSE*).
112 * handshaking is TRUE as soon as a handshake thread is queued. For
113 * a sync handshake it becomes FALSE after finish_handshake()
114 * completes in the calling thread, but for an async implicit
115 * handshake, it becomes FALSE (and need_finish_handshake becomes
116 * TRUE) at the end of the handshaking thread (and then the next
117 * non-close op will call finish_handshake()). We can't just wait
118 * for async_handshake_thread_completed() to run, because it's
119 * possible that its main loop is being blocked by a synchronous op
120 * which is waiting for handshaking to become FALSE...
122 * started_handshake indicates that the current handshake attempt
123 * got at least as far as sending the first handshake packet (and so
124 * any error should be copied to handshake_error and returned on all
125 * future operations). ever_handshaked indicates that TLS has been
126 * successfully negotiated at some point.
128 gboolean need_handshake;
129 gboolean need_finish_handshake;
130 gboolean sync_handshake_in_progress;
131 gboolean started_handshake;
132 gboolean handshaking;
133 gboolean ever_handshaked;
134 GMainContext *handshake_context;
135 GTask *implicit_handshake;
136 GError *handshake_error;
137 GByteArray *app_data_buf;
139 /* read_closed means the read direction has closed; write_closed similarly.
140 * If (and only if) both are set, the entire GTlsConnection is closed. */
141 gboolean read_closing, read_closed;
142 gboolean write_closing, write_closed;
147 GCancellable *read_cancellable;
150 gint64 write_timeout;
152 GCancellable *write_cancellable;
154 gboolean successful_read_op;
156 gboolean is_system_certdb;
157 gboolean database_is_unset;
160 GCancellable *waiting_for_op;
162 gchar **advertised_protocols;
163 gchar *negotiated_protocol;
165 GTlsProtocolVersion protocol_version;
166 gchar *ciphersuite_name;
167 } GTlsConnectionBasePrivate;
169 static void g_tls_connection_base_dtls_connection_iface_init (GDtlsConnectionInterface *iface);
171 static void g_tls_connection_base_datagram_based_iface_init (GDatagramBasedInterface *iface);
173 static gboolean do_implicit_handshake (GTlsConnectionBase *tls,
175 GCancellable *cancellable,
178 static gboolean finish_handshake (GTlsConnectionBase *tls,
182 static void g_tls_connection_base_handshake_async (GTlsConnection *conn,
184 GCancellable *cancellable,
185 GAsyncReadyCallback callback,
188 static gboolean g_tls_connection_base_handshake (GTlsConnection *conn,
189 GCancellable *cancellable,
192 G_DEFINE_ABSTRACT_TYPE_WITH_CODE (GTlsConnectionBase, g_tls_connection_base, G_TYPE_TLS_CONNECTION,
193 G_ADD_PRIVATE (GTlsConnectionBase);
194 G_IMPLEMENT_INTERFACE (G_TYPE_DATAGRAM_BASED,
195 g_tls_connection_base_datagram_based_iface_init);
196 G_IMPLEMENT_INTERFACE (G_TYPE_DTLS_CONNECTION,
197 g_tls_connection_base_dtls_connection_iface_init);
204 /* For this class: */
207 /* For GTlsConnection and GDtlsConnection: */
208 PROP_REQUIRE_CLOSE_NOTIFY,
209 PROP_REHANDSHAKE_MODE,
210 PROP_USE_SYSTEM_CERTDB,
214 PROP_PEER_CERTIFICATE,
215 PROP_PEER_CERTIFICATE_ERRORS,
216 PROP_ADVERTISED_PROTOCOLS,
217 PROP_NEGOTIATED_PROTOCOL,
218 PROP_PROTOCOL_VERSION,
219 PROP_CIPHERSUITE_NAME
223 g_tls_connection_base_is_dtls (GTlsConnectionBase *tls)
225 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
227 return priv->base_socket != NULL;
231 g_tls_connection_base_init (GTlsConnectionBase *tls)
233 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
235 priv->need_handshake = TRUE;
236 priv->database_is_unset = TRUE;
237 priv->is_system_certdb = TRUE;
239 g_mutex_init (&priv->verify_certificate_mutex);
240 g_cond_init (&priv->verify_certificate_condition);
242 g_mutex_init (&priv->op_mutex);
244 priv->waiting_for_op = g_cancellable_new ();
248 g_tls_connection_base_finalize (GObject *object)
250 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (object);
251 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
253 g_clear_object (&priv->base_io_stream);
254 g_clear_object (&priv->base_socket);
256 g_clear_object (&priv->tls_istream);
257 g_clear_object (&priv->tls_ostream);
259 g_clear_object (&priv->database);
260 g_clear_object (&priv->certificate);
261 g_clear_error (&priv->interaction_error);
262 g_clear_object (&priv->peer_certificate);
264 g_mutex_clear (&priv->verify_certificate_mutex);
265 g_cond_clear (&priv->verify_certificate_condition);
267 g_clear_object (&priv->interaction);
269 g_clear_pointer (&priv->handshake_context, g_main_context_unref);
271 /* This must always be NULL at this point, as it holds a reference to @tls as
272 * its source object. However, we clear it anyway just in case this changes
274 g_clear_object (&priv->implicit_handshake);
276 g_clear_error (&priv->handshake_error);
277 g_clear_error (&priv->read_error);
278 g_clear_error (&priv->write_error);
279 g_clear_object (&priv->read_cancellable);
280 g_clear_object (&priv->write_cancellable);
282 g_clear_object (&priv->waiting_for_op);
283 g_mutex_clear (&priv->op_mutex);
285 g_clear_pointer (&priv->app_data_buf, g_byte_array_unref);
287 g_clear_pointer (&priv->advertised_protocols, g_strfreev);
288 g_clear_pointer (&priv->negotiated_protocol, g_free);
290 g_clear_pointer (&priv->ciphersuite_name, g_free);
292 G_OBJECT_CLASS (g_tls_connection_base_parent_class)->finalize (object);
296 g_tls_connection_base_get_property (GObject *object,
301 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (object);
302 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
303 GTlsBackend *backend;
307 case PROP_BASE_IO_STREAM:
308 g_value_set_object (value, priv->base_io_stream);
311 case PROP_BASE_SOCKET:
312 g_value_set_object (value, priv->base_socket);
315 case PROP_REQUIRE_CLOSE_NOTIFY:
316 g_value_set_boolean (value, priv->require_close_notify);
319 case PROP_REHANDSHAKE_MODE:
320 g_value_set_enum (value, priv->rehandshake_mode);
323 case PROP_USE_SYSTEM_CERTDB:
324 g_value_set_boolean (value, priv->is_system_certdb);
328 if (priv->database_is_unset)
330 backend = g_tls_backend_get_default ();
331 priv->database = g_tls_backend_get_default_database (backend);
332 priv->database_is_unset = FALSE;
334 g_value_set_object (value, priv->database);
337 case PROP_CERTIFICATE:
338 g_value_set_object (value, priv->certificate);
341 case PROP_INTERACTION:
342 g_value_set_object (value, priv->interaction);
345 case PROP_PEER_CERTIFICATE:
346 g_value_set_object (value, priv->peer_certificate);
349 case PROP_PEER_CERTIFICATE_ERRORS:
350 g_value_set_flags (value, priv->peer_certificate_errors);
353 case PROP_ADVERTISED_PROTOCOLS:
354 g_value_set_boxed (value, priv->advertised_protocols);
357 case PROP_NEGOTIATED_PROTOCOL:
358 g_value_set_string (value, priv->negotiated_protocol);
361 case PROP_PROTOCOL_VERSION:
362 g_value_set_enum (value, priv->protocol_version);
365 case PROP_CIPHERSUITE_NAME:
366 g_value_set_string (value, priv->ciphersuite_name);
370 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
375 g_tls_connection_base_set_property (GObject *object,
380 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (object);
381 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
382 GInputStream *istream;
383 GOutputStream *ostream;
384 gboolean system_certdb;
385 GTlsBackend *backend;
389 case PROP_BASE_IO_STREAM:
390 g_assert (!g_value_get_object (value) || !priv->base_socket);
392 if (priv->base_io_stream)
394 g_object_unref (priv->base_io_stream);
395 priv->base_istream = NULL;
396 priv->base_ostream = NULL;
398 priv->base_io_stream = g_value_dup_object (value);
399 if (!priv->base_io_stream)
402 istream = g_io_stream_get_input_stream (priv->base_io_stream);
403 ostream = g_io_stream_get_output_stream (priv->base_io_stream);
405 if (G_IS_POLLABLE_INPUT_STREAM (istream) &&
406 g_pollable_input_stream_can_poll (G_POLLABLE_INPUT_STREAM (istream)))
408 priv->base_istream = G_POLLABLE_INPUT_STREAM (istream);
409 priv->tls_istream = g_tls_input_stream_new (tls);
411 if (G_IS_POLLABLE_OUTPUT_STREAM (ostream) &&
412 g_pollable_output_stream_can_poll (G_POLLABLE_OUTPUT_STREAM (ostream)))
414 priv->base_ostream = G_POLLABLE_OUTPUT_STREAM (ostream);
415 priv->tls_ostream = g_tls_output_stream_new (tls);
419 case PROP_BASE_SOCKET:
420 g_assert (!g_value_get_object (value) || !priv->base_io_stream);
422 g_clear_object (&priv->base_socket);
423 priv->base_socket = g_value_dup_object (value);
426 case PROP_REQUIRE_CLOSE_NOTIFY:
427 priv->require_close_notify = g_value_get_boolean (value);
430 case PROP_REHANDSHAKE_MODE:
431 priv->rehandshake_mode = g_value_get_enum (value);
434 case PROP_USE_SYSTEM_CERTDB:
435 system_certdb = g_value_get_boolean (value);
436 if (system_certdb != priv->is_system_certdb)
438 g_clear_object (&priv->database);
441 backend = g_tls_backend_get_default ();
442 priv->database = g_tls_backend_get_default_database (backend);
444 priv->is_system_certdb = system_certdb;
445 priv->database_is_unset = FALSE;
450 g_clear_object (&priv->database);
451 priv->database = g_value_dup_object (value);
452 priv->is_system_certdb = FALSE;
453 priv->database_is_unset = FALSE;
456 case PROP_CERTIFICATE:
457 if (priv->certificate)
458 g_object_unref (priv->certificate);
459 priv->certificate = g_value_dup_object (value);
462 case PROP_INTERACTION:
463 g_clear_object (&priv->interaction);
464 priv->interaction = g_value_dup_object (value);
467 case PROP_ADVERTISED_PROTOCOLS:
468 g_clear_pointer (&priv->advertised_protocols, g_strfreev);
469 priv->advertised_protocols = g_value_dup_boxed (value);
473 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
478 G_TLS_CONNECTION_BASE_OP_HANDSHAKE,
479 G_TLS_CONNECTION_BASE_OP_READ,
480 G_TLS_CONNECTION_BASE_OP_WRITE,
481 G_TLS_CONNECTION_BASE_OP_CLOSE_READ,
482 G_TLS_CONNECTION_BASE_OP_CLOSE_WRITE,
483 G_TLS_CONNECTION_BASE_OP_CLOSE_BOTH,
484 } GTlsConnectionBaseOp;
487 op_to_string (GTlsConnectionBaseOp op)
491 case G_TLS_CONNECTION_BASE_OP_HANDSHAKE:
492 return "OP_HANDSHAKE";
493 case G_TLS_CONNECTION_BASE_OP_READ:
495 case G_TLS_CONNECTION_BASE_OP_WRITE:
497 case G_TLS_CONNECTION_BASE_OP_CLOSE_READ:
498 return "OP_CLOSE_READ";
499 case G_TLS_CONNECTION_BASE_OP_CLOSE_WRITE:
500 return "OP_CLOSE_WRITE";
501 case G_TLS_CONNECTION_BASE_OP_CLOSE_BOTH:
502 return "OP_CLOSE_BOTH";
505 g_assert_not_reached ();
511 status_to_string (GTlsConnectionBaseStatus st)
515 case G_TLS_CONNECTION_BASE_OK:
517 case G_TLS_CONNECTION_BASE_WOULD_BLOCK:
518 return "WOULD_BLOCK";
519 case G_TLS_CONNECTION_BASE_TIMED_OUT:
521 case G_TLS_CONNECTION_BASE_REHANDSHAKE:
522 return "REHANDSHAKE";
523 case G_TLS_CONNECTION_BASE_TRY_AGAIN:
525 case G_TLS_CONNECTION_BASE_ERROR:
529 g_assert_not_reached ();
531 return "UNKNOWN_STATUS";
535 claim_op (GTlsConnectionBase *tls,
536 GTlsConnectionBaseOp op,
538 GCancellable *cancellable,
541 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
543 g_tls_log_debug (tls, "claiming operation %s", op_to_string (op));
546 if (g_cancellable_set_error_if_cancelled (cancellable, error))
548 g_tls_log_debug (tls, "claim_op failed: cancelled");
552 g_mutex_lock (&priv->op_mutex);
554 if (((op == G_TLS_CONNECTION_BASE_OP_HANDSHAKE ||
555 op == G_TLS_CONNECTION_BASE_OP_READ) &&
556 (priv->read_closing || priv->read_closed)) ||
557 ((op == G_TLS_CONNECTION_BASE_OP_HANDSHAKE ||
558 op == G_TLS_CONNECTION_BASE_OP_WRITE) &&
559 (priv->write_closing || priv->write_closed)))
561 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CLOSED,
562 _("Connection is closed"));
563 g_mutex_unlock (&priv->op_mutex);
564 g_tls_log_debug (tls, "claim_op failed: connection is closed");
568 if (priv->handshake_error &&
569 op != G_TLS_CONNECTION_BASE_OP_CLOSE_BOTH &&
570 op != G_TLS_CONNECTION_BASE_OP_CLOSE_READ &&
571 op != G_TLS_CONNECTION_BASE_OP_CLOSE_WRITE)
574 *error = g_error_copy (priv->handshake_error);
575 g_mutex_unlock (&priv->op_mutex);
576 g_tls_log_debug (tls, "claim_op failed: %s", priv->handshake_error->message);
580 if (op != G_TLS_CONNECTION_BASE_OP_HANDSHAKE)
582 if (op != G_TLS_CONNECTION_BASE_OP_CLOSE_BOTH &&
583 op != G_TLS_CONNECTION_BASE_OP_CLOSE_READ &&
584 op != G_TLS_CONNECTION_BASE_OP_CLOSE_WRITE &&
585 priv->need_handshake && !priv->handshaking)
587 priv->handshaking = TRUE;
588 if (!do_implicit_handshake (tls, timeout, cancellable, error))
590 g_mutex_unlock (&priv->op_mutex);
591 g_tls_log_debug (tls, "claim_op failed: implicit handshake required");
596 if (priv->need_finish_handshake &&
597 priv->implicit_handshake)
599 GError *my_error = NULL;
602 priv->need_finish_handshake = FALSE;
604 g_mutex_unlock (&priv->op_mutex);
605 success = finish_handshake (tls, priv->implicit_handshake, &my_error);
606 g_clear_object (&priv->implicit_handshake);
607 g_clear_pointer (&priv->handshake_context, g_main_context_unref);
608 g_mutex_lock (&priv->op_mutex);
610 if (op != G_TLS_CONNECTION_BASE_OP_CLOSE_BOTH &&
611 op != G_TLS_CONNECTION_BASE_OP_CLOSE_READ &&
612 op != G_TLS_CONNECTION_BASE_OP_CLOSE_WRITE &&
613 (!success || g_cancellable_set_error_if_cancelled (cancellable, &my_error)))
615 g_propagate_error (error, my_error);
616 g_mutex_unlock (&priv->op_mutex);
617 g_tls_log_debug (tls, "claim_op failed: finish_handshake failed or operation has been cancelled");
621 g_clear_error (&my_error);
625 if (priv->handshaking &&
627 g_main_context_is_owner (priv->handshake_context))
629 /* Cannot perform a blocking operation during a handshake on the
630 * same thread that triggered the handshake. The only way this can
631 * occur is if the application is doing something weird in its
632 * accept-certificate callback. Allowing a blocking op would stall
633 * the handshake (forever, if there's no timeout). Even a close
634 * op would deadlock here.
636 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED, _("Cannot perform blocking operation during TLS handshake"));
637 g_mutex_unlock (&priv->op_mutex);
638 g_tls_log_debug (tls, "claim_op failed: cannot perform blocking operation during TLS handshake");
642 if ((op != G_TLS_CONNECTION_BASE_OP_WRITE && priv->reading) ||
643 (op != G_TLS_CONNECTION_BASE_OP_READ && priv->writing) ||
644 (op != G_TLS_CONNECTION_BASE_OP_HANDSHAKE && priv->handshaking))
649 gint result = 1; /* if the loop is never entered, it's as if we cancelled early */
651 g_cancellable_reset (priv->waiting_for_op);
653 g_mutex_unlock (&priv->op_mutex);
657 /* Intentionally not translated because this is not a fatal error to be
658 * presented to the user, and to avoid this showing up in profiling. */
659 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK, "Operation would block");
660 g_tls_log_debug (tls, "claim_op failed: operation would block");
664 g_cancellable_make_pollfd (priv->waiting_for_op, &fds[0]);
665 if (g_cancellable_make_pollfd (cancellable, &fds[1]))
670 /* Convert from microseconds to milliseconds. */
674 /* Poll until cancellation or the timeout is reached. */
675 start_time = g_get_monotonic_time ();
677 while (!g_cancellable_is_cancelled (priv->waiting_for_op) &&
678 !g_cancellable_is_cancelled (cancellable))
680 result = g_poll (fds, nfds, timeout);
684 if (result != -1 || errno != EINTR)
689 timeout -= (g_get_monotonic_time () - start_time) / 1000;
696 g_cancellable_release_fd (cancellable);
700 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
701 _("Socket I/O timed out"));
702 g_tls_log_debug (tls, "claim_op failed: socket I/O timed out");
709 if (op == G_TLS_CONNECTION_BASE_OP_HANDSHAKE)
710 priv->handshaking = TRUE;
711 if (op == G_TLS_CONNECTION_BASE_OP_CLOSE_BOTH ||
712 op == G_TLS_CONNECTION_BASE_OP_CLOSE_READ)
713 priv->read_closing = TRUE;
714 if (op == G_TLS_CONNECTION_BASE_OP_CLOSE_BOTH ||
715 op == G_TLS_CONNECTION_BASE_OP_CLOSE_WRITE)
716 priv->write_closing = TRUE;
718 if (op != G_TLS_CONNECTION_BASE_OP_WRITE)
719 priv->reading = TRUE;
720 if (op != G_TLS_CONNECTION_BASE_OP_READ)
721 priv->writing = TRUE;
723 g_mutex_unlock (&priv->op_mutex);
724 g_tls_log_debug (tls, "claiming operation %s succeeded", op_to_string (op));
729 yield_op (GTlsConnectionBase *tls,
730 GTlsConnectionBaseOp op,
731 GTlsConnectionBaseStatus status)
733 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
735 g_tls_log_debug (tls, "yielding operation %s", op_to_string (op));
737 g_mutex_lock (&priv->op_mutex);
739 if (op == G_TLS_CONNECTION_BASE_OP_HANDSHAKE)
740 priv->handshaking = FALSE;
741 else if (status == G_TLS_CONNECTION_BASE_REHANDSHAKE && !priv->handshaking)
742 priv->need_handshake = TRUE;
744 if (op == G_TLS_CONNECTION_BASE_OP_CLOSE_BOTH ||
745 op == G_TLS_CONNECTION_BASE_OP_CLOSE_READ)
746 priv->read_closing = FALSE;
747 if (op == G_TLS_CONNECTION_BASE_OP_CLOSE_BOTH ||
748 op == G_TLS_CONNECTION_BASE_OP_CLOSE_WRITE)
749 priv->write_closing = FALSE;
751 if (op != G_TLS_CONNECTION_BASE_OP_WRITE)
752 priv->reading = FALSE;
753 if (op != G_TLS_CONNECTION_BASE_OP_READ)
754 priv->writing = FALSE;
756 g_cancellable_cancel (priv->waiting_for_op);
757 g_mutex_unlock (&priv->op_mutex);
761 g_tls_connection_base_real_push_io (GTlsConnectionBase *tls,
762 GIOCondition direction,
764 GCancellable *cancellable)
766 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
768 if (direction & G_IO_IN)
770 priv->read_timeout = timeout;
771 priv->read_cancellable = cancellable;
772 g_clear_error (&priv->read_error);
775 if (direction & G_IO_OUT)
777 priv->write_timeout = timeout;
778 priv->write_cancellable = cancellable;
779 g_clear_error (&priv->write_error);
784 g_tls_connection_base_push_io (GTlsConnectionBase *tls,
785 GIOCondition direction,
787 GCancellable *cancellable)
789 g_assert (direction & (G_IO_IN | G_IO_OUT));
790 g_return_if_fail (G_IS_TLS_CONNECTION_BASE (tls));
792 G_TLS_CONNECTION_BASE_GET_CLASS (tls)->push_io (tls, direction,
793 timeout, cancellable);
796 static GTlsConnectionBaseStatus
797 g_tls_connection_base_real_pop_io (GTlsConnectionBase *tls,
798 GIOCondition direction,
802 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
803 GError *my_error = NULL;
805 /* This function MAY or MAY NOT set error when it fails! */
807 if (direction & G_IO_IN)
809 priv->read_cancellable = NULL;
812 my_error = priv->read_error;
813 priv->read_error = NULL;
816 g_clear_error (&priv->read_error);
819 if (direction & G_IO_OUT)
821 priv->write_cancellable = NULL;
822 if (!success && !my_error)
824 my_error = priv->write_error;
825 priv->write_error = NULL;
828 g_clear_error (&priv->write_error);
832 return G_TLS_CONNECTION_BASE_OK;
834 if (g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
836 g_propagate_error (error, my_error);
837 return G_TLS_CONNECTION_BASE_WOULD_BLOCK;
840 if (g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT))
842 g_propagate_error (error, my_error);
843 return G_TLS_CONNECTION_BASE_TIMED_OUT;
846 if (priv->missing_requested_client_certificate &&
847 !priv->successful_read_op)
849 g_assert (G_IS_TLS_CLIENT_CONNECTION (tls));
851 /* Probably the server requires a client certificate, but we failed to
852 * provide one. With TLS 1.3, the server is no longer able to tell us
853 * this, so we just have to guess. If there is an error from the TLS
854 * interaction (request for user certificate), we provide that. Otherwise,
855 * guess that G_TLS_ERROR_CERTIFICATE_REQUIRED is probably appropriate.
856 * This could be wrong, but only applies to the small minority of
857 * connections where a client cert is requested but not provided, and then
858 * then only if the client has never successfully read any data from the
859 * connection. This should hopefully be a rare enough case that returning
860 * G_TLS_ERROR_CERTIFICATE_REQUIRED incorrectly should not be common.
861 * Beware that a successful write operation does *not* indicate that the
862 * server has accepted our certificate: a write op can succeed on the
863 * client side before the client notices that the server has closed the
866 if (priv->interaction_error)
868 g_propagate_error (error, priv->interaction_error);
869 priv->interaction_error = NULL;
873 g_clear_error (error);
874 g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_CERTIFICATE_REQUIRED,
875 _("Server required TLS certificate"));
877 g_clear_error (&my_error);
881 g_propagate_error (error, my_error);
884 return G_TLS_CONNECTION_BASE_ERROR;
887 GTlsConnectionBaseStatus
888 g_tls_connection_base_pop_io (GTlsConnectionBase *tls,
889 GIOCondition direction,
893 g_assert (direction & (G_IO_IN | G_IO_OUT));
894 g_assert (!error || !*error);
895 g_return_val_if_fail (G_IS_TLS_CONNECTION_BASE (tls), G_TLS_CONNECTION_BASE_ERROR);
897 return G_TLS_CONNECTION_BASE_GET_CLASS (tls)->pop_io (tls, direction,
901 /* Checks whether the underlying base stream or GDatagramBased meets
904 g_tls_connection_base_base_check (GTlsConnectionBase *tls,
905 GIOCondition condition)
907 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
909 if (g_tls_connection_base_is_dtls (tls))
910 return g_datagram_based_condition_check (priv->base_socket, condition);
912 if (condition & G_IO_IN)
913 return g_pollable_input_stream_is_readable (priv->base_istream);
915 if (condition & G_IO_OUT)
916 return g_pollable_output_stream_is_writable (priv->base_ostream);
918 g_assert_not_reached ();
922 /* Checks whether the (D)TLS stream meets @condition; not the underlying base
923 * stream or GDatagramBased. */
925 g_tls_connection_base_check (GTlsConnectionBase *tls,
926 GIOCondition condition)
928 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
930 /* Racy, but worst case is that we just get WOULD_BLOCK back */
931 if (priv->need_finish_handshake)
934 /* If a handshake or close is in progress, then tls_istream and
935 * tls_ostream are blocked, regardless of the base stream status.
937 if (priv->handshaking)
940 if (((condition & G_IO_IN) && priv->read_closing) ||
941 ((condition & G_IO_OUT) && priv->write_closing))
944 /* Defer to the base stream or GDatagramBased. */
945 return g_tls_connection_base_base_check (tls, condition);
951 GTlsConnectionBase *tls;
953 /* Either a GDatagramBased (datagram mode), or a GPollableInputStream or
954 * a GPollableOutputStream (streaming mode):
958 GSource *child_source;
959 GIOCondition condition;
963 } GTlsConnectionBaseSource;
965 /* Use a custom dummy callback instead of g_source_set_dummy_callback(), as that
966 * uses a GClosure and is slow. (The GClosure is necessary to deal with any
967 * function prototype.) */
969 dummy_callback (gpointer data)
971 return G_SOURCE_CONTINUE;
975 tls_source_sync (GTlsConnectionBaseSource *tls_source)
977 GTlsConnectionBase *tls = tls_source->tls;
978 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
979 gboolean io_waiting, op_waiting;
981 /* Was the source destroyed earlier in this main context iteration? */
982 if (g_source_is_destroyed ((GSource *)tls_source))
985 g_mutex_lock (&priv->op_mutex);
986 if (((tls_source->condition & G_IO_IN) && priv->reading) ||
987 ((tls_source->condition & G_IO_OUT) && priv->writing) ||
988 (priv->handshaking && !priv->need_finish_handshake))
993 if (!op_waiting && !priv->need_handshake &&
994 !priv->need_finish_handshake)
998 g_mutex_unlock (&priv->op_mutex);
1000 if (op_waiting == tls_source->op_waiting &&
1001 io_waiting == tls_source->io_waiting)
1003 tls_source->op_waiting = op_waiting;
1004 tls_source->io_waiting = io_waiting;
1006 if (tls_source->child_source)
1008 g_source_remove_child_source ((GSource *)tls_source,
1009 tls_source->child_source);
1010 g_source_unref (tls_source->child_source);
1014 tls_source->child_source = g_cancellable_source_new (priv->waiting_for_op);
1015 else if (io_waiting && G_IS_DATAGRAM_BASED (tls_source->base))
1016 tls_source->child_source = g_datagram_based_create_source (priv->base_socket, tls_source->condition, NULL);
1017 else if (io_waiting && G_IS_POLLABLE_INPUT_STREAM (tls_source->base))
1018 tls_source->child_source = g_pollable_input_stream_create_source (priv->base_istream, NULL);
1019 else if (io_waiting && G_IS_POLLABLE_OUTPUT_STREAM (tls_source->base))
1020 tls_source->child_source = g_pollable_output_stream_create_source (priv->base_ostream, NULL);
1022 tls_source->child_source = g_timeout_source_new (0);
1024 g_source_set_callback (tls_source->child_source, dummy_callback, NULL, NULL);
1025 g_source_add_child_source ((GSource *)tls_source, tls_source->child_source);
1029 tls_source_dispatch (GSource *source,
1030 GSourceFunc callback,
1033 GDatagramBasedSourceFunc datagram_based_func = (GDatagramBasedSourceFunc)callback;
1034 GPollableSourceFunc pollable_func = (GPollableSourceFunc)callback;
1035 GTlsConnectionBaseSource *tls_source = (GTlsConnectionBaseSource *)source;
1038 if (G_IS_DATAGRAM_BASED (tls_source->base))
1039 ret = (*datagram_based_func) (G_DATAGRAM_BASED (tls_source->base),
1040 tls_source->condition, user_data);
1042 ret = (*pollable_func) (tls_source->base, user_data);
1045 tls_source_sync (tls_source);
1051 tls_source_finalize (GSource *source)
1053 GTlsConnectionBaseSource *tls_source = (GTlsConnectionBaseSource *)source;
1055 g_object_unref (tls_source->tls);
1056 g_source_unref (tls_source->child_source);
1060 g_tls_connection_tls_source_closure_callback (GObject *stream,
1063 GClosure *closure = data;
1065 GValue param = { 0, };
1066 GValue result_value = { 0, };
1069 g_value_init (&result_value, G_TYPE_BOOLEAN);
1071 g_value_init (¶m, G_TYPE_OBJECT);
1072 g_value_set_object (¶m, stream);
1074 g_closure_invoke (closure, &result_value, 1, ¶m, NULL);
1076 result = g_value_get_boolean (&result_value);
1077 g_value_unset (&result_value);
1078 g_value_unset (¶m);
1084 g_tls_connection_tls_source_dtls_closure_callback (GDatagramBased *datagram_based,
1085 GIOCondition condition,
1088 GClosure *closure = data;
1090 GValue param[2] = { G_VALUE_INIT, G_VALUE_INIT };
1091 GValue result_value = G_VALUE_INIT;
1094 g_value_init (&result_value, G_TYPE_BOOLEAN);
1096 g_value_init (¶m[0], G_TYPE_DATAGRAM_BASED);
1097 g_value_set_object (¶m[0], datagram_based);
1098 g_value_init (¶m[1], G_TYPE_IO_CONDITION);
1099 g_value_set_flags (¶m[1], condition);
1101 g_closure_invoke (closure, &result_value, 2, param, NULL);
1103 result = g_value_get_boolean (&result_value);
1104 g_value_unset (&result_value);
1105 g_value_unset (¶m[0]);
1106 g_value_unset (¶m[1]);
1111 static GSourceFuncs tls_source_funcs =
1115 tls_source_dispatch,
1116 tls_source_finalize,
1117 (GSourceFunc)g_tls_connection_tls_source_closure_callback,
1118 (GSourceDummyMarshal)g_cclosure_marshal_generic
1121 static GSourceFuncs dtls_source_funcs =
1125 tls_source_dispatch,
1126 tls_source_finalize,
1127 (GSourceFunc)g_tls_connection_tls_source_dtls_closure_callback,
1128 (GSourceDummyMarshal)g_cclosure_marshal_generic
1132 g_tls_connection_base_create_source (GTlsConnectionBase *tls,
1133 GIOCondition condition,
1134 GCancellable *cancellable)
1136 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1137 GSource *source, *cancellable_source;
1138 GTlsConnectionBaseSource *tls_source;
1140 if (g_tls_connection_base_is_dtls (tls))
1142 source = g_source_new (&dtls_source_funcs,
1143 sizeof (GTlsConnectionBaseSource));
1147 source = g_source_new (&tls_source_funcs,
1148 sizeof (GTlsConnectionBaseSource));
1150 g_source_set_name (source, "GTlsConnectionBaseSource");
1151 tls_source = (GTlsConnectionBaseSource *)source;
1152 tls_source->tls = g_object_ref (tls);
1153 tls_source->condition = condition;
1154 if (g_tls_connection_base_is_dtls (tls))
1155 tls_source->base = G_OBJECT (tls);
1156 else if (priv->tls_istream && condition & G_IO_IN)
1157 tls_source->base = G_OBJECT (priv->tls_istream);
1158 else if (priv->tls_ostream && condition & G_IO_OUT)
1159 tls_source->base = G_OBJECT (priv->tls_ostream);
1161 g_assert_not_reached ();
1163 tls_source->op_waiting = (gboolean) -1;
1164 tls_source->io_waiting = (gboolean) -1;
1165 tls_source_sync (tls_source);
1169 cancellable_source = g_cancellable_source_new (cancellable);
1170 g_source_set_callback (cancellable_source, dummy_callback, NULL, NULL);
1171 g_source_add_child_source (source, cancellable_source);
1172 g_source_unref (cancellable_source);
1179 g_tls_connection_base_dtls_create_source (GDatagramBased *datagram_based,
1180 GIOCondition condition,
1181 GCancellable *cancellable)
1183 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (datagram_based);
1185 return g_tls_connection_base_create_source (tls, condition, cancellable);
1189 g_tls_connection_base_condition_check (GDatagramBased *datagram_based,
1190 GIOCondition condition)
1192 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (datagram_based);
1194 return g_tls_connection_base_check (tls, condition) ? condition : 0;
1198 g_tls_connection_base_condition_wait (GDatagramBased *datagram_based,
1199 GIOCondition condition,
1201 GCancellable *cancellable,
1204 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (datagram_based);
1205 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1208 gint result = 1; /* if the loop is never entered, it's as if we cancelled early */
1211 if (g_cancellable_set_error_if_cancelled (cancellable, error))
1214 /* Convert from microseconds to milliseconds. */
1216 timeout = timeout / 1000;
1218 start_time = g_get_monotonic_time ();
1220 g_cancellable_make_pollfd (priv->waiting_for_op, &fds[0]);
1223 if (g_cancellable_make_pollfd (cancellable, &fds[1]))
1226 while (!g_tls_connection_base_condition_check (datagram_based, condition) &&
1227 !g_cancellable_is_cancelled (cancellable))
1229 result = g_poll (fds, n_fds, timeout);
1232 if (result != -1 || errno != EINTR)
1237 timeout -= (g_get_monotonic_time () - start_time) / 1000;
1244 g_cancellable_release_fd (cancellable);
1248 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
1249 _("Socket I/O timed out"));
1253 return !g_cancellable_set_error_if_cancelled (cancellable, error);
1256 static GTlsCertificateFlags
1257 verify_peer_certificate (GTlsConnectionBase *tls,
1258 GTlsCertificate *peer_certificate)
1260 GTlsConnectionBaseClass *tls_class = G_TLS_CONNECTION_BASE_GET_CLASS (tls);
1261 GSocketConnectable *peer_identity = NULL;
1262 GTlsDatabase *database;
1263 GTlsCertificateFlags errors = 0;
1266 is_client = G_IS_TLS_CLIENT_CONNECTION (tls);
1270 if (!g_tls_connection_base_is_dtls (tls))
1271 peer_identity = g_tls_client_connection_get_server_identity (G_TLS_CLIENT_CONNECTION (tls));
1273 peer_identity = g_dtls_client_connection_get_server_identity (G_DTLS_CLIENT_CONNECTION (tls));
1276 errors |= G_TLS_CERTIFICATE_BAD_IDENTITY;
1279 database = g_tls_connection_get_database (G_TLS_CONNECTION (tls));
1282 errors |= G_TLS_CERTIFICATE_UNKNOWN_CA;
1283 errors |= g_tls_certificate_verify (peer_certificate, peer_identity, NULL);
1287 GError *error = NULL;
1289 g_assert (tls_class->verify_chain);
1290 errors |= tls_class->verify_chain (tls,
1292 is_client ? G_TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER : G_TLS_DATABASE_PURPOSE_AUTHENTICATE_CLIENT,
1294 g_tls_connection_get_interaction (G_TLS_CONNECTION (tls)),
1295 G_TLS_DATABASE_VERIFY_NONE,
1300 g_tls_log_debug (tls, "failure verifying certificate chain: %s", error->message);
1301 g_assert (errors != 0);
1302 g_clear_error (&error);
1306 if (tls_class->verify_peer_certificate)
1307 errors |= tls_class->verify_peer_certificate (tls, peer_certificate, errors);
1313 accept_or_reject_peer_certificate (gpointer user_data)
1315 GTlsConnectionBase *tls = user_data;
1316 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1317 GTlsCertificate *peer_certificate = NULL;
1318 GTlsCertificateFlags peer_certificate_errors = 0;
1319 gboolean accepted = FALSE;
1321 /* This function must be called from the handshake context thread
1322 * (probably the main thread, NOT the handshake thread) because
1323 * it emits notifies that are application-visible.
1325 g_assert (priv->handshake_context);
1326 g_assert (g_main_context_is_owner (priv->handshake_context));
1328 peer_certificate = G_TLS_CONNECTION_BASE_GET_CLASS (tls)->retrieve_peer_certificate (tls);
1330 if (peer_certificate)
1332 peer_certificate_errors = verify_peer_certificate (tls, peer_certificate);
1334 if (G_IS_TLS_CLIENT_CONNECTION (tls))
1336 GTlsCertificateFlags validation_flags;
1338 if (!g_tls_connection_base_is_dtls (tls))
1340 g_tls_client_connection_get_validation_flags (G_TLS_CLIENT_CONNECTION (tls));
1343 g_dtls_client_connection_get_validation_flags (G_DTLS_CLIENT_CONNECTION (tls));
1345 if ((peer_certificate_errors & validation_flags) == 0)
1351 gboolean sync_handshake_in_progress;
1353 g_mutex_lock (&priv->op_mutex);
1354 sync_handshake_in_progress = priv->sync_handshake_in_progress;
1355 g_mutex_unlock (&priv->op_mutex);
1357 if (sync_handshake_in_progress)
1358 g_main_context_pop_thread_default (priv->handshake_context);
1360 accepted = g_tls_connection_emit_accept_certificate (G_TLS_CONNECTION (tls),
1362 peer_certificate_errors);
1364 if (sync_handshake_in_progress)
1365 g_main_context_push_thread_default (priv->handshake_context);
1368 else if (G_IS_TLS_SERVER_CONNECTION (tls))
1370 GTlsAuthenticationMode mode = 0;
1373 "authentication-mode", &mode,
1376 if (mode != G_TLS_AUTHENTICATION_REQUIRED)
1380 g_mutex_lock (&priv->verify_certificate_mutex);
1382 priv->peer_certificate_accepted = accepted;
1384 /* Warning: the API documentation indicates that these properties are not
1385 * set until *after* accept-certificate.
1387 g_clear_object (&priv->peer_certificate);
1388 priv->peer_certificate = g_steal_pointer (&peer_certificate);
1389 priv->peer_certificate_errors = peer_certificate_errors;
1391 g_object_notify (G_OBJECT (tls), "peer-certificate");
1392 g_object_notify (G_OBJECT (tls), "peer-certificate-errors");
1394 /* This has to be the very last statement before signaling the
1395 * condition variable because otherwise the code could spuriously
1396 * wakeup and continue before we are done here.
1398 priv->peer_certificate_examined = TRUE;
1400 g_cond_signal (&priv->verify_certificate_condition);
1401 g_mutex_unlock (&priv->verify_certificate_mutex);
1403 return G_SOURCE_REMOVE;
1407 g_tls_connection_base_handshake_thread_verify_certificate (GTlsConnectionBase *tls)
1409 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1412 g_tls_log_debug (tls, "verifying peer certificate");
1414 g_mutex_lock (&priv->verify_certificate_mutex);
1415 priv->peer_certificate_examined = FALSE;
1416 priv->peer_certificate_accepted = FALSE;
1417 g_mutex_unlock (&priv->verify_certificate_mutex);
1419 /* Invoke the callback on the handshake context's thread. This is
1420 * necessary because we need to ensure the accept-certificate signal
1421 * is emitted on the original thread.
1423 g_assert (priv->handshake_context);
1424 g_main_context_invoke (priv->handshake_context, accept_or_reject_peer_certificate, tls);
1426 /* We'll block the handshake thread until the original thread has
1427 * decided whether to accept the certificate.
1429 g_mutex_lock (&priv->verify_certificate_mutex);
1430 while (!priv->peer_certificate_examined)
1431 g_cond_wait (&priv->verify_certificate_condition, &priv->verify_certificate_mutex);
1432 accepted = priv->peer_certificate_accepted;
1433 g_mutex_unlock (&priv->verify_certificate_mutex);
1439 g_tls_connection_base_get_binding_data (GTlsConnection *conn,
1440 GTlsChannelBindingType type,
1444 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (conn);
1445 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1446 GTlsConnectionBaseClass *tls_class = G_TLS_CONNECTION_BASE_GET_CLASS (tls);
1448 g_assert (tls_class->get_channel_binding_data);
1450 if (!priv->ever_handshaked || priv->need_handshake)
1452 g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR,
1453 G_TLS_CHANNEL_BINDING_ERROR_INVALID_STATE,
1454 _("Handshake is not finished, no channel binding information yet"));
1458 return tls_class->get_channel_binding_data (tls, type, data, error);
1462 g_tls_connection_base_dtls_get_binding_data (GDtlsConnection *conn,
1463 GTlsChannelBindingType type,
1467 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (conn);
1469 return g_tls_connection_base_get_binding_data ((GTlsConnection *)tls,
1473 #if GLIB_CHECK_VERSION(2, 69, 0)
1474 static const gchar *
1475 g_tls_connection_base_get_negotiated_protocol (GTlsConnection *conn)
1477 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (conn);
1478 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1480 return priv->negotiated_protocol;
1484 static const gchar *
1485 g_tls_connection_base_dtls_get_negotiated_protocol (GDtlsConnection *conn)
1487 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (conn);
1488 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1490 return priv->negotiated_protocol;
1494 handshake_thread (GTask *task,
1497 GCancellable *cancellable)
1499 GTlsConnectionBase *tls = object;
1500 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1501 GTlsConnectionBaseClass *tls_class = G_TLS_CONNECTION_BASE_GET_CLASS (tls);
1502 GError *error = NULL;
1506 g_tls_log_debug (tls, "TLS handshake thread starts");
1508 /* A timeout, in microseconds, must be provided as a gint64* task_data. */
1509 g_assert (task_data);
1510 start_time = g_get_monotonic_time ();
1511 timeout = *((gint64 *)task_data);
1513 priv->started_handshake = FALSE;
1514 priv->missing_requested_client_certificate = FALSE;
1516 if (!claim_op (tls, G_TLS_CONNECTION_BASE_OP_HANDSHAKE,
1517 timeout, cancellable, &error))
1519 g_task_return_error (task, error);
1520 g_tls_log_debug (tls, "TLS handshake thread failed: claiming op failed");
1524 g_clear_error (&priv->handshake_error);
1526 if (priv->ever_handshaked && !priv->need_handshake)
1528 GTlsConnectionBaseStatus status;
1530 if (tls_class->handshake_thread_safe_renegotiation_status (tls) != G_TLS_SAFE_RENEGOTIATION_SUPPORTED_BY_PEER)
1532 g_task_return_new_error (task, G_TLS_ERROR, G_TLS_ERROR_MISC,
1533 _("Peer does not support safe renegotiation"));
1534 g_tls_log_debug (tls, "TLS handshake thread failed: peer does not support safe renegotiation");
1538 /* Adjust the timeout for the next operation in the sequence. */
1541 timeout -= (g_get_monotonic_time () - start_time);
1546 status = tls_class->handshake_thread_request_rehandshake (tls, timeout, cancellable, &error);
1547 if (status != G_TLS_CONNECTION_BASE_OK)
1549 g_task_return_error (task, error);
1550 g_tls_log_debug (tls, "TLS handshake thread failed: %s", error->message);
1555 /* Adjust the timeout for the next operation in the sequence. */
1558 timeout -= (g_get_monotonic_time () - start_time);
1563 priv->started_handshake = TRUE;
1564 tls_class->handshake_thread_handshake (tls, timeout, cancellable, &error);
1565 priv->need_handshake = FALSE;
1569 g_task_return_error (task, error);
1570 g_tls_log_debug (tls, "TLS handshake thread failed: %s", error->message);
1574 priv->ever_handshaked = TRUE;
1575 g_task_return_boolean (task, TRUE);
1576 g_tls_log_debug (tls, "TLS handshake thread succeeded");
1581 sync_handshake_thread_completed (GObject *object,
1582 GAsyncResult *result,
1585 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (object);
1586 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1587 gpointer source_tag;
1589 g_tls_log_debug (tls, "synchronous TLS handshake thread completed");
1591 source_tag = g_task_get_source_tag (G_TASK (result));
1592 g_assert (source_tag == do_implicit_handshake || source_tag == g_tls_connection_base_handshake);
1593 g_assert (g_task_is_valid (result, object));
1595 g_assert (g_main_context_is_owner (priv->handshake_context));
1597 g_mutex_lock (&priv->op_mutex);
1598 priv->sync_handshake_in_progress = FALSE;
1599 g_mutex_unlock (&priv->op_mutex);
1601 g_main_context_wakeup (priv->handshake_context);
1605 crank_sync_handshake_context (GTlsConnectionBase *tls,
1606 GCancellable *cancellable)
1608 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1610 /* need_finish_handshake will be set inside sync_handshake_thread_completed(),
1611 * which should only ever be invoked while iterating the handshake context
1612 * here. So need_finish_handshake should only change on this thread.
1614 * FIXME: This function is not cancellable. We should figure out how to
1615 * support cancellation. We must not return from this function before it is
1616 * safe to destroy handshake_context, but it's not safe to destroy
1617 * handshake_context until after the handshake has completed. And the
1618 * handshake operation is not cancellable, so we have a problem.
1620 g_mutex_lock (&priv->op_mutex);
1621 priv->sync_handshake_in_progress = TRUE;
1622 while (priv->sync_handshake_in_progress)
1624 g_mutex_unlock (&priv->op_mutex);
1625 g_main_context_iteration (priv->handshake_context, TRUE);
1626 g_mutex_lock (&priv->op_mutex);
1628 g_mutex_unlock (&priv->op_mutex);
1632 finish_handshake (GTlsConnectionBase *tls,
1636 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1637 GTlsConnectionBaseClass *tls_class = G_TLS_CONNECTION_BASE_GET_CLASS (tls);
1638 gchar *original_negotiated_protocol;
1639 gchar *original_ciphersuite_name;
1640 GTlsProtocolVersion original_protocol_version;
1642 GError *my_error = NULL;
1644 g_tls_log_debug (tls, "finishing TLS handshake");
1646 original_negotiated_protocol = g_steal_pointer (&priv->negotiated_protocol);
1647 original_ciphersuite_name = g_steal_pointer (&priv->ciphersuite_name);
1648 original_protocol_version = priv->protocol_version;
1650 success = g_task_propagate_boolean (task, &my_error);
1653 if (tls_class->is_session_resumed && tls_class->is_session_resumed (tls))
1655 /* Because this session was resumed, we skipped certificate
1656 * verification on this handshake, so we missed our earlier
1657 * chance to set peer_certificate and peer_certificate_errors.
1658 * Do so here instead.
1660 * The certificate has already been accepted, so we don't do
1661 * anything with the result here.
1663 g_mutex_lock (&priv->verify_certificate_mutex);
1665 g_clear_object (&priv->peer_certificate);
1666 priv->peer_certificate = G_TLS_CONNECTION_BASE_GET_CLASS (tls)->retrieve_peer_certificate (tls);
1667 priv->peer_certificate_errors = verify_peer_certificate (tls, priv->peer_certificate);
1669 g_object_notify (G_OBJECT (tls), "peer-certificate");
1670 g_object_notify (G_OBJECT (tls), "peer-certificate-errors");
1672 priv->peer_certificate_examined = TRUE;
1673 priv->peer_certificate_accepted = TRUE;
1674 g_mutex_unlock (&priv->verify_certificate_mutex);
1677 /* FIXME: Return an error from the handshake thread instead. */
1678 if (priv->peer_certificate && !priv->peer_certificate_accepted)
1680 g_set_error_literal (&my_error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
1681 _("Unacceptable TLS certificate"));
1686 tls_class->complete_handshake (tls,
1688 &priv->negotiated_protocol,
1689 &priv->protocol_version,
1690 &priv->ciphersuite_name,
1691 /* If we already have an error, ignore further errors. */
1692 my_error ? NULL : &my_error);
1694 if (g_strcmp0 (original_negotiated_protocol, priv->negotiated_protocol) != 0)
1695 g_object_notify (G_OBJECT (tls), "negotiated-protocol");
1696 g_free (original_negotiated_protocol);
1698 if (original_protocol_version != priv->protocol_version)
1699 g_object_notify (G_OBJECT (tls), "protocol-version");
1701 if (g_strcmp0 (original_ciphersuite_name, priv->ciphersuite_name) != 0)
1702 g_object_notify (G_OBJECT (tls), "ciphersuite-name");
1703 g_free (original_ciphersuite_name);
1705 if (my_error && priv->started_handshake)
1706 priv->handshake_error = g_error_copy (my_error);
1709 g_tls_log_debug (tls, "TLS handshake has finished successfully");
1713 g_tls_log_debug (tls, "TLS handshake has finished with error: %s", my_error->message);
1714 g_propagate_error (error, my_error);
1719 g_tls_connection_base_handshake (GTlsConnection *conn,
1720 GCancellable *cancellable,
1723 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (conn);
1724 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1725 GTlsConnectionBaseClass *tls_class = G_TLS_CONNECTION_BASE_GET_CLASS (tls);
1728 gint64 *timeout = NULL;
1729 GError *my_error = NULL;
1731 g_tls_log_debug (tls, "Starting synchronous TLS handshake");
1733 g_assert (!priv->handshake_context);
1734 priv->handshake_context = g_main_context_new ();
1736 g_main_context_push_thread_default (priv->handshake_context);
1738 if (tls_class->prepare_handshake)
1739 tls_class->prepare_handshake (tls, priv->advertised_protocols);
1741 task = g_task_new (conn, cancellable, sync_handshake_thread_completed, NULL);
1742 g_task_set_source_tag (task, g_tls_connection_base_handshake);
1743 g_task_set_name (task, "[glib-networking] g_tls_connection_base_handshake");
1745 timeout = g_new0 (gint64, 1);
1746 *timeout = -1; /* blocking */
1747 g_task_set_task_data (task, timeout, g_free);
1749 g_task_run_in_thread (task, handshake_thread);
1750 crank_sync_handshake_context (tls, cancellable);
1752 success = finish_handshake (tls, task, &my_error);
1753 g_object_unref (task);
1755 g_main_context_pop_thread_default (priv->handshake_context);
1756 g_clear_pointer (&priv->handshake_context, g_main_context_unref);
1758 yield_op (tls, G_TLS_CONNECTION_BASE_OP_HANDSHAKE,
1759 G_TLS_CONNECTION_BASE_OK);
1762 g_propagate_error (error, my_error);
1767 g_tls_connection_base_dtls_handshake (GDtlsConnection *conn,
1768 GCancellable *cancellable,
1771 return g_tls_connection_base_handshake (G_TLS_CONNECTION (conn),
1772 cancellable, error);
1775 /* In the async version we use two GTasks; one to run
1776 * handshake_thread() and then call async_handshake_thread_completed(),
1777 * and a second to call the caller's original callback after we call
1778 * finish_handshake().
1782 async_handshake_thread_completed (GObject *object,
1783 GAsyncResult *result,
1786 GTask *caller_task = user_data;
1787 GTlsConnectionBase *tls = g_task_get_source_object (caller_task);
1788 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1789 GError *error = NULL;
1790 gboolean need_finish_handshake, success;
1792 g_tls_log_debug (tls, "Asynchronous TLS handshake thread completed");
1794 g_assert (g_task_is_valid (result, object));
1795 g_assert (g_task_get_source_tag (G_TASK (result)) == g_tls_connection_base_handshake_async);
1797 g_mutex_lock (&priv->op_mutex);
1798 if (priv->need_finish_handshake)
1800 need_finish_handshake = TRUE;
1801 priv->need_finish_handshake = FALSE;
1804 need_finish_handshake = FALSE;
1805 g_mutex_unlock (&priv->op_mutex);
1807 /* We have to clear handshake_context before g_task_return_* because it can
1808 * return immediately to application code inside g_task_return_*,
1809 * and the application code could then start a new TLS operation.
1811 * But we can't clear until after finish_handshake().
1813 if (need_finish_handshake)
1815 success = finish_handshake (tls, G_TASK (result), &error);
1817 g_clear_pointer (&priv->handshake_context, g_main_context_unref);
1820 g_task_return_boolean (caller_task, TRUE);
1822 g_task_return_error (caller_task, error);
1826 g_clear_pointer (&priv->handshake_context, g_main_context_unref);
1828 if (priv->handshake_error)
1829 g_task_return_error (caller_task, g_error_copy (priv->handshake_error));
1831 g_task_return_boolean (caller_task, TRUE);
1834 g_object_unref (caller_task);
1838 async_handshake_thread (GTask *task,
1841 GCancellable *cancellable)
1843 GTlsConnectionBase *tls = object;
1844 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1846 g_tls_log_debug (tls, "Asynchronous TLS handshake thread starts");
1848 handshake_thread (task, object, task_data, cancellable);
1850 g_mutex_lock (&priv->op_mutex);
1851 priv->need_finish_handshake = TRUE;
1852 /* yield_op will clear handshaking too, but we don't want the
1853 * connection to be briefly "handshaking && need_finish_handshake"
1854 * after we unlock the mutex.
1856 priv->handshaking = FALSE;
1857 g_mutex_unlock (&priv->op_mutex);
1859 yield_op (tls, G_TLS_CONNECTION_BASE_OP_HANDSHAKE,
1860 G_TLS_CONNECTION_BASE_OK);
1864 g_tls_connection_base_handshake_async (GTlsConnection *conn,
1866 GCancellable *cancellable,
1867 GAsyncReadyCallback callback,
1870 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (conn);
1871 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1872 GTlsConnectionBaseClass *tls_class = G_TLS_CONNECTION_BASE_GET_CLASS (tls);
1873 GTask *thread_task, *caller_task;
1874 gint64 *timeout = NULL;
1876 g_tls_log_debug (tls, "Starting asynchronous TLS handshake");
1878 g_assert (!priv->handshake_context);
1879 priv->handshake_context = g_main_context_ref_thread_default ();
1881 if (tls_class->prepare_handshake)
1882 tls_class->prepare_handshake (tls, priv->advertised_protocols);
1884 caller_task = g_task_new (conn, cancellable, callback, user_data);
1885 g_task_set_source_tag (caller_task, g_tls_connection_base_handshake_async);
1886 g_task_set_name (caller_task, "[glib-networking] g_tls_connection_base_handshake_async (caller task)");
1887 g_task_set_priority (caller_task, io_priority);
1889 thread_task = g_task_new (conn, cancellable, async_handshake_thread_completed, caller_task);
1890 g_task_set_source_tag (thread_task, g_tls_connection_base_handshake_async);
1891 g_task_set_name (caller_task, "[glib-networking] g_tls_connection_base_handshake_async (thread task)");
1892 g_task_set_priority (thread_task, io_priority);
1894 timeout = g_new0 (gint64, 1);
1895 *timeout = -1; /* blocking */
1896 g_task_set_task_data (thread_task, timeout, g_free);
1898 g_task_run_in_thread (thread_task, async_handshake_thread);
1899 g_object_unref (thread_task);
1903 g_tls_connection_base_handshake_finish (GTlsConnection *conn,
1904 GAsyncResult *result,
1907 g_return_val_if_fail (g_task_is_valid (result, conn), FALSE);
1908 g_return_val_if_fail (g_task_get_source_tag (G_TASK (result)) == g_tls_connection_base_handshake_async, FALSE);
1910 return g_task_propagate_boolean (G_TASK (result), error);
1914 g_tls_connection_base_dtls_handshake_async (GDtlsConnection *conn,
1916 GCancellable *cancellable,
1917 GAsyncReadyCallback callback,
1920 g_tls_connection_base_handshake_async (G_TLS_CONNECTION (conn), io_priority,
1921 cancellable, callback, user_data);
1925 g_tls_connection_base_dtls_handshake_finish (GDtlsConnection *conn,
1926 GAsyncResult *result,
1929 return g_tls_connection_base_handshake_finish (G_TLS_CONNECTION (conn),
1934 do_implicit_handshake (GTlsConnectionBase *tls,
1936 GCancellable *cancellable,
1939 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1940 GTlsConnectionBaseClass *tls_class = G_TLS_CONNECTION_BASE_GET_CLASS (tls);
1941 gint64 *thread_timeout = NULL;
1943 g_tls_log_debug (tls, "Implicit TLS handshaking starts");
1945 /* We have op_mutex */
1947 g_assert (!priv->handshake_context);
1950 priv->handshake_context = g_main_context_new ();
1951 g_main_context_push_thread_default (priv->handshake_context);
1955 priv->handshake_context = g_main_context_ref_thread_default ();
1958 g_assert (!priv->implicit_handshake);
1959 priv->implicit_handshake = g_task_new (tls, cancellable,
1960 timeout ? sync_handshake_thread_completed : NULL,
1962 g_task_set_source_tag (priv->implicit_handshake, do_implicit_handshake);
1963 g_task_set_name (priv->implicit_handshake, "[glib-networking] do_implicit_handshake");
1965 thread_timeout = g_new0 (gint64, 1);
1966 g_task_set_task_data (priv->implicit_handshake,
1967 thread_timeout, g_free);
1969 if (tls_class->prepare_handshake)
1970 tls_class->prepare_handshake (tls, priv->advertised_protocols);
1974 GError *my_error = NULL;
1977 /* In the blocking case, run the handshake operation synchronously in
1978 * another thread, and delegate handling the timeout to that thread; it
1979 * should return G_IO_ERROR_TIMED_OUT iff (timeout > 0) and the operation
1980 * times out. If (timeout < 0) it should block indefinitely until the
1981 * operation is complete or errors. */
1982 *thread_timeout = timeout;
1984 g_mutex_unlock (&priv->op_mutex);
1986 g_task_run_in_thread (priv->implicit_handshake, handshake_thread);
1988 crank_sync_handshake_context (tls, cancellable);
1990 success = finish_handshake (tls,
1991 priv->implicit_handshake,
1994 g_main_context_pop_thread_default (priv->handshake_context);
1995 g_clear_pointer (&priv->handshake_context, g_main_context_unref);
1996 g_clear_object (&priv->implicit_handshake);
1998 yield_op (tls, G_TLS_CONNECTION_BASE_OP_HANDSHAKE,
1999 G_TLS_CONNECTION_BASE_OK);
2001 g_mutex_lock (&priv->op_mutex);
2004 g_propagate_error (error, my_error);
2009 /* In the non-blocking case, start the asynchronous handshake operation
2010 * and return EWOULDBLOCK to the caller, who will handle polling for
2011 * completion of the handshake and whatever operation they actually cared
2012 * about. Run the actual operation as blocking in its thread. */
2013 *thread_timeout = -1; /* blocking */
2015 g_task_run_in_thread (priv->implicit_handshake,
2016 async_handshake_thread);
2018 /* Intentionally not translated because this is not a fatal error to be
2019 * presented to the user, and to avoid this showing up in profiling. */
2020 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK, "Operation would block");
2026 g_tls_connection_base_read (GTlsConnectionBase *tls,
2030 GCancellable *cancellable,
2033 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2034 GTlsConnectionBaseStatus status;
2037 g_tls_log_debug (tls, "starting to read data from TLS connection");
2041 if (!claim_op (tls, G_TLS_CONNECTION_BASE_OP_READ,
2042 timeout, cancellable, error))
2045 if (priv->app_data_buf && !priv->handshaking)
2047 nread = MIN (count, priv->app_data_buf->len);
2048 memcpy (buffer, priv->app_data_buf->data, nread);
2049 if (nread == priv->app_data_buf->len)
2050 g_clear_pointer (&priv->app_data_buf, g_byte_array_unref);
2052 g_byte_array_remove_range (priv->app_data_buf, 0, nread);
2053 status = G_TLS_CONNECTION_BASE_OK;
2057 status = G_TLS_CONNECTION_BASE_GET_CLASS (tls)->
2058 read_fn (tls, buffer, count, timeout, &nread, cancellable, error);
2061 yield_op (tls, G_TLS_CONNECTION_BASE_OP_READ, status);
2063 while (status == G_TLS_CONNECTION_BASE_REHANDSHAKE);
2065 if (status == G_TLS_CONNECTION_BASE_OK)
2067 priv->successful_read_op = TRUE;
2068 g_tls_log_debug (tls, "successfully read %" G_GSSIZE_FORMAT " bytes from TLS connection", nread);
2072 g_tls_log_debug (tls, "reading data from TLS connection has failed: %s", status_to_string (status));
2077 g_tls_connection_base_read_message (GTlsConnectionBase *tls,
2078 GInputVector *vectors,
2081 GCancellable *cancellable,
2084 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2085 GTlsConnectionBaseStatus status = G_TLS_CONNECTION_BASE_OK;
2088 g_tls_log_debug (tls, "starting to read messages from TLS connection");
2091 if (!claim_op (tls, G_TLS_CONNECTION_BASE_OP_READ,
2092 timeout, cancellable, error))
2095 /* Copy data out of the app data buffer first. */
2096 if (priv->app_data_buf && !priv->handshaking)
2100 for (guint i = 0; i < num_vectors && priv->app_data_buf; i++)
2103 GInputVector *vec = &vectors[i];
2105 count = MIN (vec->size, priv->app_data_buf->len);
2108 memcpy (vec->buffer, priv->app_data_buf->data, count);
2109 if (count == priv->app_data_buf->len)
2110 g_clear_pointer (&priv->app_data_buf, g_byte_array_unref);
2112 g_byte_array_remove_range (priv->app_data_buf, 0, count);
2117 g_assert (G_TLS_CONNECTION_BASE_GET_CLASS (tls)->read_message_fn);
2118 status = G_TLS_CONNECTION_BASE_GET_CLASS (tls)->
2119 read_message_fn (tls, vectors, num_vectors, timeout, &nread, cancellable, error);
2122 yield_op (tls, G_TLS_CONNECTION_BASE_OP_READ, status);
2123 } while (status == G_TLS_CONNECTION_BASE_REHANDSHAKE);
2125 if (status == G_TLS_CONNECTION_BASE_OK)
2127 priv->successful_read_op = TRUE;
2128 g_tls_log_debug (tls, "successfully read %" G_GSSIZE_FORMAT " bytes from TLS connection", nread);
2132 g_tls_log_debug (tls, "reading message from TLS connection has failed: %s", status_to_string (status));
2137 g_tls_connection_base_receive_messages (GDatagramBased *datagram_based,
2138 GInputMessage *messages,
2142 GCancellable *cancellable,
2145 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (datagram_based);
2146 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2148 GError *child_error = NULL;
2150 if (flags != G_SOCKET_MSG_NONE)
2152 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2153 _("Receive flags are not supported"));
2157 for (i = 0; i < num_messages && !child_error; i++)
2159 GInputMessage *message = &messages[i];
2160 gssize n_bytes_read;
2162 n_bytes_read = g_tls_connection_base_read_message (tls,
2164 message->num_vectors,
2169 if (message->address)
2170 *message->address = NULL;
2171 message->flags = G_SOCKET_MSG_NONE;
2172 if (message->control_messages)
2173 *message->control_messages = NULL;
2174 message->num_control_messages = 0;
2176 if (n_bytes_read > 0)
2178 message->bytes_received = n_bytes_read;
2180 else if (n_bytes_read == 0)
2186 (g_error_matches (child_error,
2187 G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
2188 g_error_matches (child_error,
2189 G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
2191 /* Blocked or timed out after receiving some messages successfully. */
2192 g_clear_error (&child_error);
2197 /* Error, including G_IO_ERROR_WOULD_BLOCK or G_IO_ERROR_TIMED_OUT on
2198 * the first message; or G_IO_ERROR_CANCELLED at any time. */
2205 g_propagate_error (error, child_error);
2209 priv->successful_read_op = TRUE;
2214 g_tls_connection_base_write (GTlsConnectionBase *tls,
2218 GCancellable *cancellable,
2221 GTlsConnectionBaseStatus status;
2224 g_tls_log_debug (tls, "starting to write %" G_GSIZE_FORMAT " bytes to TLS connection", count);
2228 if (!claim_op (tls, G_TLS_CONNECTION_BASE_OP_WRITE,
2229 timeout, cancellable, error))
2232 status = G_TLS_CONNECTION_BASE_GET_CLASS (tls)->
2233 write_fn (tls, buffer, count, timeout, &nwrote, cancellable, error);
2235 yield_op (tls, G_TLS_CONNECTION_BASE_OP_WRITE, status);
2237 while (status == G_TLS_CONNECTION_BASE_REHANDSHAKE);
2239 if (status == G_TLS_CONNECTION_BASE_OK)
2241 g_tls_log_debug (tls, "successfully write %" G_GSSIZE_FORMAT " bytes to TLS connection", nwrote);
2245 g_tls_log_debug (tls, "writing data to TLS connection has failed: %s", status_to_string (status));
2250 g_tls_connection_base_write_message (GTlsConnectionBase *tls,
2251 GOutputVector *vectors,
2254 GCancellable *cancellable,
2257 GTlsConnectionBaseStatus status;
2260 g_tls_log_debug (tls, "starting to write messages to TLS connection");
2263 if (!claim_op (tls, G_TLS_CONNECTION_BASE_OP_WRITE,
2264 timeout, cancellable, error))
2267 g_assert (G_TLS_CONNECTION_BASE_GET_CLASS (tls)->read_message_fn);
2268 status = G_TLS_CONNECTION_BASE_GET_CLASS (tls)->
2269 write_message_fn (tls, vectors, num_vectors, timeout, &nwrote, cancellable, error);
2271 yield_op (tls, G_TLS_CONNECTION_BASE_OP_WRITE, status);
2272 } while (status == G_TLS_CONNECTION_BASE_REHANDSHAKE);
2274 if (status == G_TLS_CONNECTION_BASE_OK)
2276 g_tls_log_debug (tls, "successfully write %" G_GSSIZE_FORMAT " bytes to TLS connection", nwrote);
2280 g_tls_log_debug (tls, "writing messages to TLS connection has failed: %s", status_to_string (status));
2285 g_tls_connection_base_send_messages (GDatagramBased *datagram_based,
2286 GOutputMessage *messages,
2290 GCancellable *cancellable,
2293 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (datagram_based);
2295 GError *child_error = NULL;
2297 if (flags != G_SOCKET_MSG_NONE)
2299 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2300 _("Send flags are not supported"));
2304 for (i = 0; i < num_messages && !child_error; i++)
2306 GOutputMessage *message = &messages[i];
2307 gssize n_bytes_sent;
2309 n_bytes_sent = g_tls_connection_base_write_message (tls,
2311 message->num_vectors,
2316 if (n_bytes_sent >= 0)
2318 message->bytes_sent = n_bytes_sent;
2321 (g_error_matches (child_error,
2322 G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK) ||
2323 g_error_matches (child_error,
2324 G_IO_ERROR, G_IO_ERROR_TIMED_OUT)))
2326 /* Blocked or timed out after sending some messages successfully. */
2327 g_clear_error (&child_error);
2332 /* Error, including G_IO_ERROR_WOULD_BLOCK or G_IO_ERROR_TIMED_OUT
2333 * on the first message; or G_IO_ERROR_CANCELLED at any time. */
2340 g_propagate_error (error, child_error);
2347 static GInputStream *
2348 g_tls_connection_base_get_input_stream (GIOStream *stream)
2350 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (stream);
2351 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2353 return priv->tls_istream;
2356 static GOutputStream *
2357 g_tls_connection_base_get_output_stream (GIOStream *stream)
2359 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (stream);
2360 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2362 return priv->tls_ostream;
2366 g_tls_connection_base_close_internal (GIOStream *stream,
2367 GTlsDirection direction,
2369 GCancellable *cancellable,
2372 GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (stream);
2373 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2374 GTlsConnectionBaseOp op;
2375 GTlsConnectionBaseStatus status;
2376 gboolean success = TRUE;
2377 GError *close_error = NULL, *stream_error = NULL;
2379 g_tls_log_debug (tls, "starting to close the TLS connection");
2381 /* This can be called from g_io_stream_close(), g_input_stream_close(),
2382 * g_output_stream_close(), or g_tls_connection_close(). In all cases, we only
2383 * do the close_fn() for writing. The difference is how we set the flags on
2384 * this class and how the underlying stream is closed.
2387 g_return_val_if_fail (direction != G_TLS_DIRECTION_NONE, FALSE);
2389 if (direction == G_TLS_DIRECTION_BOTH)
2390 op = G_TLS_CONNECTION_BASE_OP_CLOSE_BOTH;
2391 else if (direction == G_TLS_DIRECTION_READ)
2392 op = G_TLS_CONNECTION_BASE_OP_CLOSE_READ;
2394 op = G_TLS_CONNECTION_BASE_OP_CLOSE_WRITE;
2396 if (!claim_op (tls, op, timeout, cancellable, error))
2399 if (priv->ever_handshaked && !priv->write_closed &&
2400 direction & G_TLS_DIRECTION_WRITE)
2402 status = G_TLS_CONNECTION_BASE_GET_CLASS (tls)->
2403 close_fn (tls, timeout, cancellable, &close_error);
2405 priv->write_closed = TRUE;
2408 status = G_TLS_CONNECTION_BASE_OK;
2410 if (!priv->read_closed && direction & G_TLS_DIRECTION_READ)
2411 priv->read_closed = TRUE;
2413 /* Close the underlying streams. Do this even if the close_fn() call failed,
2414 * as the parent GIOStream will have set its internal closed flag and hence
2415 * this implementation will never be called again. */
2416 if (priv->base_io_stream)
2418 if (direction == G_TLS_DIRECTION_BOTH)
2419 success = g_io_stream_close (priv->base_io_stream,
2420 cancellable, &stream_error);
2421 else if (direction & G_TLS_DIRECTION_READ)
2422 success = g_input_stream_close (g_io_stream_get_input_stream (priv->base_io_stream),
2423 cancellable, &stream_error);
2424 else if (direction & G_TLS_DIRECTION_WRITE)
2425 success = g_output_stream_close (g_io_stream_get_output_stream (priv->base_io_stream),
2426 cancellable, &stream_error);
2428 else if (g_tls_connection_base_is_dtls (tls))
2430 /* We do not close underlying #GDatagramBaseds. There is no
2431 * g_datagram_based_close() method since different datagram-based
2432 * protocols vary wildly in how they close. */
2437 g_assert_not_reached ();
2440 yield_op (tls, op, status);
2442 /* Propagate errors. */
2443 if (status != G_TLS_CONNECTION_BASE_OK)
2445 g_tls_log_debug (tls, "error closing TLS connection: %s", close_error->message);
2446 g_propagate_error (error, close_error);
2447 g_clear_error (&stream_error);
2451 g_tls_log_debug (tls, "error closing TLS connection: %s", stream_error->message);
2452 g_propagate_error (error, stream_error);
2453 g_clear_error (&close_error);
2457 g_tls_log_debug (tls, "the TLS connection has been closed successfully");
2460 return success && status == G_TLS_CONNECTION_BASE_OK;
2464 g_tls_connection_base_close (GIOStream *stream,
2465 GCancellable *cancellable,
2468 return g_tls_connection_base_close_internal (stream,
2469 G_TLS_DIRECTION_BOTH,
2471 cancellable, error);
2475 g_tls_connection_base_dtls_shutdown (GDtlsConnection *conn,
2476 gboolean shutdown_read,
2477 gboolean shutdown_write,
2478 GCancellable *cancellable,
2481 GTlsDirection direction = G_TLS_DIRECTION_NONE;
2484 direction |= G_TLS_DIRECTION_READ;
2486 direction |= G_TLS_DIRECTION_WRITE;
2488 return g_tls_connection_base_close_internal (G_IO_STREAM (conn),
2491 cancellable, error);
2494 /* We do async close as synchronous-in-a-thread so we don't need to
2495 * implement G_IO_IN/G_IO_OUT flip-flopping just for this one case
2496 * (since handshakes are also done synchronously now).
2499 close_thread (GTask *task,
2502 GCancellable *cancellable)
2504 GIOStream *stream = object;
2505 GTlsDirection direction;
2506 GError *error = NULL;
2508 direction = GPOINTER_TO_INT (g_task_get_task_data (task));
2510 if (!g_tls_connection_base_close_internal (stream, direction,
2512 cancellable, &error))
2513 g_task_return_error (task, error);
2515 g_task_return_boolean (task, TRUE);
2519 g_tls_connection_base_close_internal_async (GIOStream *stream,
2520 GTlsDirection direction,
2522 GCancellable *cancellable,
2523 GAsyncReadyCallback callback,
2528 task = g_task_new (stream, cancellable, callback, user_data);
2529 g_task_set_source_tag (task, g_tls_connection_base_close_internal_async);
2530 g_task_set_name (task, "[glib-networking] g_tls_connection_base_close_internal_async");
2531 g_task_set_priority (task, io_priority);
2532 g_task_set_task_data (task, GINT_TO_POINTER (direction), NULL);
2533 g_task_run_in_thread (task, close_thread);
2534 g_object_unref (task);
2538 g_tls_connection_base_close_async (GIOStream *stream,
2540 GCancellable *cancellable,
2541 GAsyncReadyCallback callback,
2544 g_tls_connection_base_close_internal_async (stream, G_TLS_DIRECTION_BOTH,
2545 io_priority, cancellable,
2546 callback, user_data);
2550 g_tls_connection_base_close_finish (GIOStream *stream,
2551 GAsyncResult *result,
2554 g_return_val_if_fail (g_task_is_valid (result, stream), FALSE);
2555 g_return_val_if_fail (g_task_get_source_tag (G_TASK (result)) == g_tls_connection_base_close_internal_async, FALSE);
2557 return g_task_propagate_boolean (G_TASK (result), error);
2561 g_tls_connection_base_dtls_shutdown_async (GDtlsConnection *conn,
2562 gboolean shutdown_read,
2563 gboolean shutdown_write,
2565 GCancellable *cancellable,
2566 GAsyncReadyCallback callback,
2569 GTlsDirection direction = G_TLS_DIRECTION_NONE;
2572 direction |= G_TLS_DIRECTION_READ;
2574 direction |= G_TLS_DIRECTION_WRITE;
2576 g_tls_connection_base_close_internal_async (G_IO_STREAM (conn), direction,
2577 io_priority, cancellable,
2578 callback, user_data);
2582 g_tls_connection_base_dtls_shutdown_finish (GDtlsConnection *conn,
2583 GAsyncResult *result,
2586 g_return_val_if_fail (g_task_is_valid (result, conn), FALSE);
2587 g_return_val_if_fail (g_task_get_source_tag (G_TASK (result)) == g_tls_connection_base_close_internal_async, FALSE);
2589 return g_task_propagate_boolean (G_TASK (result), error);
2593 g_tls_connection_base_dtls_set_advertised_protocols (GDtlsConnection *conn,
2594 const gchar * const *protocols)
2596 g_object_set (conn, "advertised-protocols", protocols, NULL);
2600 g_tls_connection_base_get_base_socket (GTlsConnectionBase *tls)
2602 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2604 g_assert (g_tls_connection_base_is_dtls (tls));
2606 return priv->base_socket;
2610 g_tls_connection_base_get_base_iostream (GTlsConnectionBase *tls)
2612 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2614 g_assert (!g_tls_connection_base_is_dtls (tls));
2616 return priv->base_io_stream;
2619 GPollableInputStream *
2620 g_tls_connection_base_get_base_istream (GTlsConnectionBase *tls)
2622 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2624 g_assert (!g_tls_connection_base_is_dtls (tls));
2626 return priv->base_istream;
2629 GPollableOutputStream *
2630 g_tls_connection_base_get_base_ostream (GTlsConnectionBase *tls)
2632 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2634 g_assert (!g_tls_connection_base_is_dtls (tls));
2636 return priv->base_ostream;
2640 g_tls_connection_base_handshake_thread_set_missing_requested_client_certificate (GTlsConnectionBase *tls)
2642 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2644 priv->missing_requested_client_certificate = TRUE;
2648 g_tls_connection_base_get_read_error (GTlsConnectionBase *tls)
2650 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2652 return &priv->read_error;
2656 g_tls_connection_base_get_write_error (GTlsConnectionBase *tls)
2658 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2660 return &priv->write_error;
2664 g_tls_connection_base_get_read_timeout (GTlsConnectionBase *tls)
2666 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2668 return priv->read_timeout;
2672 g_tls_connection_base_get_write_timeout (GTlsConnectionBase *tls)
2674 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2676 return priv->write_timeout;
2680 g_tls_connection_base_get_read_cancellable (GTlsConnectionBase *tls)
2682 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2684 return priv->read_cancellable;
2688 g_tls_connection_base_get_write_cancellable (GTlsConnectionBase *tls)
2690 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2692 return priv->write_cancellable;
2696 g_tls_connection_base_is_handshaking (GTlsConnectionBase *tls)
2698 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2700 return priv->handshaking;
2704 g_tls_connection_base_ever_handshaked (GTlsConnectionBase *tls)
2706 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2708 return priv->ever_handshaked;
2712 g_tls_connection_base_handshake_thread_request_certificate (GTlsConnectionBase *tls)
2714 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2715 GTlsInteractionResult res = G_TLS_INTERACTION_UNHANDLED;
2716 GTlsInteraction *interaction;
2717 GTlsConnection *conn;
2719 g_return_val_if_fail (G_IS_TLS_CONNECTION_BASE (tls), FALSE);
2721 conn = G_TLS_CONNECTION (tls);
2723 g_clear_error (&priv->interaction_error);
2725 interaction = g_tls_connection_get_interaction (conn);
2729 res = g_tls_interaction_invoke_request_certificate (interaction, conn, 0,
2730 priv->read_cancellable,
2731 &priv->interaction_error);
2732 return res != G_TLS_INTERACTION_FAILED;
2736 g_tls_connection_base_handshake_thread_ask_password (GTlsConnectionBase *tls,
2737 GTlsPassword *password)
2739 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2740 GTlsInteractionResult res = G_TLS_INTERACTION_UNHANDLED;
2741 GTlsInteraction *interaction;
2743 g_return_val_if_fail (G_IS_TLS_CONNECTION_BASE (tls), FALSE);
2745 g_clear_error (&priv->interaction_error);
2747 interaction = g_tls_connection_get_interaction (G_TLS_CONNECTION (tls));
2751 res = g_tls_interaction_invoke_ask_password (interaction, password,
2752 priv->read_cancellable,
2753 &priv->interaction_error);
2754 return res != G_TLS_INTERACTION_FAILED;
2758 g_tls_connection_base_handshake_thread_buffer_application_data (GTlsConnectionBase *tls,
2762 GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2764 if (!priv->app_data_buf)
2765 priv->app_data_buf = g_byte_array_new ();
2767 g_byte_array_append (priv->app_data_buf, data, length);
2771 g_tls_connection_base_class_init (GTlsConnectionBaseClass *klass)
2773 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
2774 GTlsConnectionClass *connection_class = G_TLS_CONNECTION_CLASS (klass);
2775 GIOStreamClass *iostream_class = G_IO_STREAM_CLASS (klass);
2777 gobject_class->get_property = g_tls_connection_base_get_property;
2778 gobject_class->set_property = g_tls_connection_base_set_property;
2779 gobject_class->finalize = g_tls_connection_base_finalize;
2781 connection_class->handshake = g_tls_connection_base_handshake;
2782 connection_class->handshake_async = g_tls_connection_base_handshake_async;
2783 connection_class->handshake_finish = g_tls_connection_base_handshake_finish;
2784 connection_class->get_binding_data = g_tls_connection_base_get_binding_data;
2785 #if GLIB_CHECK_VERSION(2, 69, 0)
2786 connection_class->get_negotiated_protocol = g_tls_connection_base_get_negotiated_protocol;
2789 iostream_class->get_input_stream = g_tls_connection_base_get_input_stream;
2790 iostream_class->get_output_stream = g_tls_connection_base_get_output_stream;
2791 iostream_class->close_fn = g_tls_connection_base_close;
2792 iostream_class->close_async = g_tls_connection_base_close_async;
2793 iostream_class->close_finish = g_tls_connection_base_close_finish;
2795 klass->push_io = g_tls_connection_base_real_push_io;
2796 klass->pop_io = g_tls_connection_base_real_pop_io;
2798 /* For GTlsConnection and GDtlsConnection: */
2799 g_object_class_override_property (gobject_class, PROP_BASE_IO_STREAM, "base-io-stream");
2800 g_object_class_override_property (gobject_class, PROP_BASE_SOCKET, "base-socket");
2801 g_object_class_override_property (gobject_class, PROP_REQUIRE_CLOSE_NOTIFY, "require-close-notify");
2802 g_object_class_override_property (gobject_class, PROP_REHANDSHAKE_MODE, "rehandshake-mode");
2803 g_object_class_override_property (gobject_class, PROP_USE_SYSTEM_CERTDB, "use-system-certdb");
2804 g_object_class_override_property (gobject_class, PROP_DATABASE, "database");
2805 g_object_class_override_property (gobject_class, PROP_CERTIFICATE, "certificate");
2806 g_object_class_override_property (gobject_class, PROP_INTERACTION, "interaction");
2807 g_object_class_override_property (gobject_class, PROP_PEER_CERTIFICATE, "peer-certificate");
2808 g_object_class_override_property (gobject_class, PROP_PEER_CERTIFICATE_ERRORS, "peer-certificate-errors");
2809 g_object_class_override_property (gobject_class, PROP_ADVERTISED_PROTOCOLS, "advertised-protocols");
2810 g_object_class_override_property (gobject_class, PROP_NEGOTIATED_PROTOCOL, "negotiated-protocol");
2811 g_object_class_override_property (gobject_class, PROP_PROTOCOL_VERSION, "protocol-version");
2812 g_object_class_override_property (gobject_class, PROP_CIPHERSUITE_NAME, "ciphersuite-name");
2816 g_tls_connection_base_dtls_connection_iface_init (GDtlsConnectionInterface *iface)
2818 iface->handshake = g_tls_connection_base_dtls_handshake;
2819 iface->handshake_async = g_tls_connection_base_dtls_handshake_async;
2820 iface->handshake_finish = g_tls_connection_base_dtls_handshake_finish;
2821 iface->shutdown = g_tls_connection_base_dtls_shutdown;
2822 iface->shutdown_async = g_tls_connection_base_dtls_shutdown_async;
2823 iface->shutdown_finish = g_tls_connection_base_dtls_shutdown_finish;
2824 iface->set_advertised_protocols = g_tls_connection_base_dtls_set_advertised_protocols;
2825 iface->get_negotiated_protocol = g_tls_connection_base_dtls_get_negotiated_protocol;
2826 iface->get_binding_data = g_tls_connection_base_dtls_get_binding_data;
2830 g_tls_connection_base_datagram_based_iface_init (GDatagramBasedInterface *iface)
2832 iface->receive_messages = g_tls_connection_base_receive_messages;
2833 iface->send_messages = g_tls_connection_base_send_messages;
2834 iface->create_source = g_tls_connection_base_dtls_create_source;
2835 iface->condition_check = g_tls_connection_base_condition_check;
2836 iface->condition_wait = g_tls_connection_base_condition_wait;