Imported Upstream version 2.72.alpha
[platform/upstream/glib-networking.git] / tls / base / gtlsconnection-base.c
1 /* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /*
3  * GIO - GLib Input, Output and Streaming Library
4  *
5  * Copyright 2009-2011 Red Hat, Inc
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.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
19  * <http://www.gnu.org/licenses/>.
20  *
21  * In addition, when the library is used with OpenSSL, a special
22  * exception applies. Refer to the LICENSE_EXCEPTION file for details.
23  */
24
25 #include "config.h"
26 #include "glib.h"
27
28 #include <errno.h>
29
30 #include "gtlsconnection-base.h"
31 #include "gtlsinputstream.h"
32 #include "gtlslog.h"
33 #include "gtlsoutputstream.h"
34
35 #include <glib/gi18n-lib.h>
36 #include <glib/gprintf.h>
37
38 /*
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
43  * construction time.
44  *
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.
49  *
50  * This abstract class implements a lot of interfaces:
51  *  • Derived from GTlsConnection (itself from GIOStream), for TLS and streaming
52  *    communications.
53  *  • Implements GDtlsConnection and GDatagramBased, for DTLS and datagram
54  *    communications.
55  *  • Implements GInitable for failable initialisation.
56  */
57
58 typedef struct
59 {
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.
68    *
69    * Then the GTlsConnection also has tls_istream and tls_ostream, which
70    * wrap the aforementioned base streams with a TLS session.
71    *
72    * When operating in datagram mode, none of these are used.
73    */
74   GIOStream             *base_io_stream;
75   GPollableInputStream  *base_istream;
76   GPollableOutputStream *base_ostream;
77   GInputStream          *tls_istream;
78   GOutputStream         *tls_ostream;
79
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
83    * the other streams.
84    */
85   GDatagramBased        *base_socket;
86
87   GTlsDatabase          *database;
88   GTlsInteraction       *interaction;
89
90   GTlsCertificate       *certificate;
91   gboolean               missing_requested_client_certificate;
92   GError                *interaction_error;
93   GTlsCertificate       *peer_certificate;
94   GTlsCertificateFlags   peer_certificate_errors;
95
96   GMutex                 verify_certificate_mutex;
97   GCond                  verify_certificate_condition;
98   gboolean               peer_certificate_accepted;
99   gboolean               peer_certificate_examined;
100
101   gboolean               require_close_notify;
102
103 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
104   GTlsRehandshakeMode    rehandshake_mode;
105 G_GNUC_END_IGNORE_DEPRECATIONS
106
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*).
111    *
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...
121    *
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.
127    */
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;
138
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;
143
144   gboolean       reading;
145   gint64         read_timeout;
146   GError        *read_error;
147   GCancellable  *read_cancellable;
148
149   gboolean       writing;
150   gint64         write_timeout;
151   GError        *write_error;
152   GCancellable  *write_cancellable;
153
154   gboolean       successful_read_op;
155
156   gboolean       is_system_certdb;
157   gboolean       database_is_unset;
158
159   GMutex         op_mutex;
160   GCancellable  *waiting_for_op;
161
162   gchar        **advertised_protocols;
163   gchar         *negotiated_protocol;
164
165   GTlsProtocolVersion  protocol_version;
166   gchar               *ciphersuite_name;
167 } GTlsConnectionBasePrivate;
168
169 static void g_tls_connection_base_dtls_connection_iface_init (GDtlsConnectionInterface *iface);
170
171 static void g_tls_connection_base_datagram_based_iface_init  (GDatagramBasedInterface  *iface);
172
173 static gboolean do_implicit_handshake (GTlsConnectionBase  *tls,
174                                        gint64               timeout,
175                                        GCancellable        *cancellable,
176                                        GError             **error);
177
178 static gboolean finish_handshake (GTlsConnectionBase  *tls,
179                                   GTask               *task,
180                                   GError             **error);
181
182 static void g_tls_connection_base_handshake_async (GTlsConnection      *conn,
183                                                    int                  io_priority,
184                                                    GCancellable        *cancellable,
185                                                    GAsyncReadyCallback  callback,
186                                                    gpointer             user_data);
187
188 static gboolean g_tls_connection_base_handshake (GTlsConnection   *conn,
189                                                  GCancellable     *cancellable,
190                                                  GError          **error);
191
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);
198                                   );
199
200
201 enum
202 {
203   PROP_0,
204   /* For this class: */
205   PROP_BASE_IO_STREAM,
206   PROP_BASE_SOCKET,
207   /* For GTlsConnection and GDtlsConnection: */
208   PROP_REQUIRE_CLOSE_NOTIFY,
209   PROP_REHANDSHAKE_MODE,
210   PROP_USE_SYSTEM_CERTDB,
211   PROP_DATABASE,
212   PROP_CERTIFICATE,
213   PROP_INTERACTION,
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
220 };
221
222 gboolean
223 g_tls_connection_base_is_dtls (GTlsConnectionBase *tls)
224 {
225   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
226
227   return priv->base_socket != NULL;
228 }
229
230 static void
231 g_tls_connection_base_init (GTlsConnectionBase *tls)
232 {
233   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
234
235   priv->need_handshake = TRUE;
236   priv->database_is_unset = TRUE;
237   priv->is_system_certdb = TRUE;
238
239   g_mutex_init (&priv->verify_certificate_mutex);
240   g_cond_init (&priv->verify_certificate_condition);
241
242   g_mutex_init (&priv->op_mutex);
243
244   priv->waiting_for_op = g_cancellable_new ();
245 }
246
247 static void
248 g_tls_connection_base_finalize (GObject *object)
249 {
250   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (object);
251   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
252
253   g_clear_object (&priv->base_io_stream);
254   g_clear_object (&priv->base_socket);
255
256   g_clear_object (&priv->tls_istream);
257   g_clear_object (&priv->tls_ostream);
258
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);
263
264   g_mutex_clear (&priv->verify_certificate_mutex);
265   g_cond_clear (&priv->verify_certificate_condition);
266
267   g_clear_object (&priv->interaction);
268
269   g_clear_pointer (&priv->handshake_context, g_main_context_unref);
270
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
273    * in future. */
274   g_clear_object (&priv->implicit_handshake);
275
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);
281
282   g_clear_object (&priv->waiting_for_op);
283   g_mutex_clear (&priv->op_mutex);
284
285   g_clear_pointer (&priv->app_data_buf, g_byte_array_unref);
286
287   g_clear_pointer (&priv->advertised_protocols, g_strfreev);
288   g_clear_pointer (&priv->negotiated_protocol, g_free);
289
290   g_clear_pointer (&priv->ciphersuite_name, g_free);
291
292   G_OBJECT_CLASS (g_tls_connection_base_parent_class)->finalize (object);
293 }
294
295 static void
296 g_tls_connection_base_get_property (GObject    *object,
297                                     guint       prop_id,
298                                     GValue     *value,
299                                     GParamSpec *pspec)
300 {
301   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (object);
302   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
303   GTlsBackend *backend;
304
305   switch (prop_id)
306     {
307     case PROP_BASE_IO_STREAM:
308       g_value_set_object (value, priv->base_io_stream);
309       break;
310
311     case PROP_BASE_SOCKET:
312       g_value_set_object (value, priv->base_socket);
313       break;
314
315     case PROP_REQUIRE_CLOSE_NOTIFY:
316       g_value_set_boolean (value, priv->require_close_notify);
317       break;
318
319     case PROP_REHANDSHAKE_MODE:
320       g_value_set_enum (value, priv->rehandshake_mode);
321       break;
322
323     case PROP_USE_SYSTEM_CERTDB:
324       g_value_set_boolean (value, priv->is_system_certdb);
325       break;
326
327     case PROP_DATABASE:
328       if (priv->database_is_unset)
329         {
330           backend = g_tls_backend_get_default ();
331           priv->database =  g_tls_backend_get_default_database (backend);
332           priv->database_is_unset = FALSE;
333         }
334       g_value_set_object (value, priv->database);
335       break;
336
337     case PROP_CERTIFICATE:
338       g_value_set_object (value, priv->certificate);
339       break;
340
341     case PROP_INTERACTION:
342       g_value_set_object (value, priv->interaction);
343       break;
344
345     case PROP_PEER_CERTIFICATE:
346       g_value_set_object (value, priv->peer_certificate);
347       break;
348
349     case PROP_PEER_CERTIFICATE_ERRORS:
350       g_value_set_flags (value, priv->peer_certificate_errors);
351       break;
352
353     case PROP_ADVERTISED_PROTOCOLS:
354       g_value_set_boxed (value, priv->advertised_protocols);
355       break;
356
357     case PROP_NEGOTIATED_PROTOCOL:
358       g_value_set_string (value, priv->negotiated_protocol);
359       break;
360
361     case PROP_PROTOCOL_VERSION:
362       g_value_set_enum (value, priv->protocol_version);
363       break;
364
365     case PROP_CIPHERSUITE_NAME:
366       g_value_set_string (value, priv->ciphersuite_name);
367       break;
368
369     default:
370       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
371     }
372 }
373
374 static void
375 g_tls_connection_base_set_property (GObject      *object,
376                                     guint         prop_id,
377                                     const GValue *value,
378                                     GParamSpec   *pspec)
379 {
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;
386
387   switch (prop_id)
388     {
389     case PROP_BASE_IO_STREAM:
390       g_assert (!g_value_get_object (value) || !priv->base_socket);
391
392       if (priv->base_io_stream)
393         {
394           g_object_unref (priv->base_io_stream);
395           priv->base_istream = NULL;
396           priv->base_ostream = NULL;
397         }
398       priv->base_io_stream = g_value_dup_object (value);
399       if (!priv->base_io_stream)
400         return;
401
402       istream = g_io_stream_get_input_stream (priv->base_io_stream);
403       ostream = g_io_stream_get_output_stream (priv->base_io_stream);
404
405       if (G_IS_POLLABLE_INPUT_STREAM (istream) &&
406           g_pollable_input_stream_can_poll (G_POLLABLE_INPUT_STREAM (istream)))
407         {
408           priv->base_istream = G_POLLABLE_INPUT_STREAM (istream);
409           priv->tls_istream = g_tls_input_stream_new (tls);
410         }
411       if (G_IS_POLLABLE_OUTPUT_STREAM (ostream) &&
412           g_pollable_output_stream_can_poll (G_POLLABLE_OUTPUT_STREAM (ostream)))
413         {
414           priv->base_ostream = G_POLLABLE_OUTPUT_STREAM (ostream);
415           priv->tls_ostream = g_tls_output_stream_new (tls);
416         }
417       break;
418
419     case PROP_BASE_SOCKET:
420       g_assert (!g_value_get_object (value) || !priv->base_io_stream);
421
422       g_clear_object (&priv->base_socket);
423       priv->base_socket = g_value_dup_object (value);
424       break;
425
426     case PROP_REQUIRE_CLOSE_NOTIFY:
427       priv->require_close_notify = g_value_get_boolean (value);
428       break;
429
430     case PROP_REHANDSHAKE_MODE:
431       priv->rehandshake_mode = g_value_get_enum (value);
432       break;
433
434     case PROP_USE_SYSTEM_CERTDB:
435       system_certdb = g_value_get_boolean (value);
436       if (system_certdb != priv->is_system_certdb)
437         {
438           g_clear_object (&priv->database);
439           if (system_certdb)
440             {
441               backend = g_tls_backend_get_default ();
442               priv->database = g_tls_backend_get_default_database (backend);
443             }
444           priv->is_system_certdb = system_certdb;
445           priv->database_is_unset = FALSE;
446         }
447       break;
448
449     case PROP_DATABASE:
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;
454       break;
455
456     case PROP_CERTIFICATE:
457       if (priv->certificate)
458         g_object_unref (priv->certificate);
459       priv->certificate = g_value_dup_object (value);
460       break;
461
462     case PROP_INTERACTION:
463       g_clear_object (&priv->interaction);
464       priv->interaction = g_value_dup_object (value);
465       break;
466
467     case PROP_ADVERTISED_PROTOCOLS:
468       g_clear_pointer (&priv->advertised_protocols, g_strfreev);
469       priv->advertised_protocols = g_value_dup_boxed (value);
470       break;
471
472     default:
473       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
474     }
475 }
476
477 typedef enum {
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;
485
486 static const gchar *
487 op_to_string (GTlsConnectionBaseOp op)
488 {
489   switch (op)
490     {
491     case G_TLS_CONNECTION_BASE_OP_HANDSHAKE:
492       return "OP_HANDSHAKE";
493     case G_TLS_CONNECTION_BASE_OP_READ:
494       return "OP_READ";
495     case G_TLS_CONNECTION_BASE_OP_WRITE:
496       return "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";
503     }
504
505   g_assert_not_reached ();
506
507   return "UNKNOWN_OP";
508 }
509
510 static const gchar *
511 status_to_string (GTlsConnectionBaseStatus st)
512 {
513   switch (st)
514     {
515     case G_TLS_CONNECTION_BASE_OK:
516       return "BASE_OK";
517     case G_TLS_CONNECTION_BASE_WOULD_BLOCK:
518       return "WOULD_BLOCK";
519     case G_TLS_CONNECTION_BASE_TIMED_OUT:
520       return "TIMED_OUT";
521     case G_TLS_CONNECTION_BASE_REHANDSHAKE:
522       return "REHANDSHAKE";
523     case G_TLS_CONNECTION_BASE_TRY_AGAIN:
524       return "TRY_AGAIN";
525     case G_TLS_CONNECTION_BASE_ERROR:
526       return "ERROR";
527     }
528
529   g_assert_not_reached ();
530
531   return "UNKNOWN_STATUS";
532 }
533
534 static gboolean
535 claim_op (GTlsConnectionBase    *tls,
536           GTlsConnectionBaseOp   op,
537           gint64                 timeout,
538           GCancellable          *cancellable,
539           GError               **error)
540 {
541   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
542
543   g_tls_log_debug (tls, "claiming operation %s", op_to_string (op));
544
545  try_again:
546   if (g_cancellable_set_error_if_cancelled (cancellable, error))
547     {
548       g_tls_log_debug (tls, "claim_op failed: cancelled");
549       return FALSE;
550     }
551
552   g_mutex_lock (&priv->op_mutex);
553
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)))
560     {
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");
565       return FALSE;
566     }
567
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)
572     {
573       if (error)
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);
577       return FALSE;
578     }
579
580   if (op != G_TLS_CONNECTION_BASE_OP_HANDSHAKE)
581     {
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)
586         {
587           priv->handshaking = TRUE;
588           if (!do_implicit_handshake (tls, timeout, cancellable, error))
589             {
590               g_mutex_unlock (&priv->op_mutex);
591               g_tls_log_debug (tls, "claim_op failed: implicit handshake required");
592               return FALSE;
593             }
594         }
595
596       if (priv->need_finish_handshake &&
597           priv->implicit_handshake)
598         {
599           GError *my_error = NULL;
600           gboolean success;
601
602           priv->need_finish_handshake = FALSE;
603
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);
609
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)))
614             {
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");
618               return FALSE;
619             }
620
621           g_clear_error (&my_error);
622         }
623     }
624
625   if (priv->handshaking &&
626       timeout != 0 &&
627       g_main_context_is_owner (priv->handshake_context))
628     {
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.
635        */
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");
639       return FALSE;
640     }
641
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))
645     {
646       GPollFD fds[2];
647       int nfds;
648       gint64 start_time;
649       gint result = 1; /* if the loop is never entered, it's as if we cancelled early */
650
651       g_cancellable_reset (priv->waiting_for_op);
652
653       g_mutex_unlock (&priv->op_mutex);
654
655       if (timeout == 0)
656         {
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");
661           return FALSE;
662         }
663
664       g_cancellable_make_pollfd (priv->waiting_for_op, &fds[0]);
665       if (g_cancellable_make_pollfd (cancellable, &fds[1]))
666         nfds = 2;
667       else
668         nfds = 1;
669
670       /* Convert from microseconds to milliseconds. */
671       if (timeout != -1)
672         timeout /= 1000;
673
674       /* Poll until cancellation or the timeout is reached. */
675       start_time = g_get_monotonic_time ();
676
677       while (!g_cancellable_is_cancelled (priv->waiting_for_op) &&
678              !g_cancellable_is_cancelled (cancellable))
679         {
680           result = g_poll (fds, nfds, timeout);
681
682           if (result == 0)
683             break;
684           if (result != -1 || errno != EINTR)
685             continue;
686
687           if (timeout != -1)
688             {
689               timeout -= (g_get_monotonic_time () - start_time) / 1000;
690               if (timeout < 0)
691                 timeout = 0;
692             }
693         }
694
695       if (nfds > 1)
696         g_cancellable_release_fd (cancellable);
697
698       if (result == 0)
699         {
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");
703           return FALSE;
704         }
705
706       goto try_again;
707     }
708
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;
717
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;
722
723   g_mutex_unlock (&priv->op_mutex);
724   g_tls_log_debug (tls, "claiming operation %s succeeded", op_to_string (op));
725   return TRUE;
726 }
727
728 static void
729 yield_op (GTlsConnectionBase       *tls,
730           GTlsConnectionBaseOp      op,
731           GTlsConnectionBaseStatus  status)
732 {
733   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
734
735   g_tls_log_debug (tls, "yielding operation %s", op_to_string (op));
736
737   g_mutex_lock (&priv->op_mutex);
738
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;
743
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;
750
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;
755
756   g_cancellable_cancel (priv->waiting_for_op);
757   g_mutex_unlock (&priv->op_mutex);
758 }
759
760 static void
761 g_tls_connection_base_real_push_io (GTlsConnectionBase *tls,
762                                     GIOCondition        direction,
763                                     gint64              timeout,
764                                     GCancellable       *cancellable)
765 {
766   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
767
768   if (direction & G_IO_IN)
769     {
770       priv->read_timeout = timeout;
771       priv->read_cancellable = cancellable;
772       g_clear_error (&priv->read_error);
773     }
774
775   if (direction & G_IO_OUT)
776     {
777       priv->write_timeout = timeout;
778       priv->write_cancellable = cancellable;
779       g_clear_error (&priv->write_error);
780     }
781 }
782
783 void
784 g_tls_connection_base_push_io (GTlsConnectionBase *tls,
785                                GIOCondition        direction,
786                                gint64              timeout,
787                                GCancellable       *cancellable)
788 {
789   g_assert (direction & (G_IO_IN | G_IO_OUT));
790   g_return_if_fail (G_IS_TLS_CONNECTION_BASE (tls));
791
792   G_TLS_CONNECTION_BASE_GET_CLASS (tls)->push_io (tls, direction,
793                                                   timeout, cancellable);
794 }
795
796 static GTlsConnectionBaseStatus
797 g_tls_connection_base_real_pop_io (GTlsConnectionBase  *tls,
798                                    GIOCondition         direction,
799                                    gboolean             success,
800                                    GError             **error)
801 {
802   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
803   GError *my_error = NULL;
804
805   /* This function MAY or MAY NOT set error when it fails! */
806
807   if (direction & G_IO_IN)
808     {
809       priv->read_cancellable = NULL;
810       if (!success)
811         {
812           my_error = priv->read_error;
813           priv->read_error = NULL;
814         }
815       else
816         g_clear_error (&priv->read_error);
817     }
818
819   if (direction & G_IO_OUT)
820     {
821       priv->write_cancellable = NULL;
822       if (!success && !my_error)
823         {
824           my_error = priv->write_error;
825           priv->write_error = NULL;
826         }
827       else
828         g_clear_error (&priv->write_error);
829     }
830
831   if (success)
832     return G_TLS_CONNECTION_BASE_OK;
833
834   if (g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
835     {
836       g_propagate_error (error, my_error);
837       return G_TLS_CONNECTION_BASE_WOULD_BLOCK;
838     }
839
840   if (g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT))
841     {
842       g_propagate_error (error, my_error);
843       return G_TLS_CONNECTION_BASE_TIMED_OUT;
844     }
845
846   if (priv->missing_requested_client_certificate &&
847       !priv->successful_read_op)
848     {
849       g_assert (G_IS_TLS_CLIENT_CONNECTION (tls));
850
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
864        * connection.
865        */
866       if (priv->interaction_error)
867         {
868           g_propagate_error (error, priv->interaction_error);
869           priv->interaction_error = NULL;
870         }
871       else
872         {
873           g_clear_error (error);
874           g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_CERTIFICATE_REQUIRED,
875                                _("Server required TLS certificate"));
876         }
877       g_clear_error (&my_error);
878     }
879   else if (my_error)
880     {
881       g_propagate_error (error, my_error);
882     }
883
884   return G_TLS_CONNECTION_BASE_ERROR;
885 }
886
887 GTlsConnectionBaseStatus
888 g_tls_connection_base_pop_io (GTlsConnectionBase  *tls,
889                               GIOCondition         direction,
890                               gboolean             success,
891                               GError             **error)
892 {
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);
896
897   return G_TLS_CONNECTION_BASE_GET_CLASS (tls)->pop_io (tls, direction,
898                                                         success, error);
899 }
900
901 /* Checks whether the underlying base stream or GDatagramBased meets
902  * @condition. */
903 gboolean
904 g_tls_connection_base_base_check (GTlsConnectionBase *tls,
905                                   GIOCondition        condition)
906 {
907   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
908
909   if (g_tls_connection_base_is_dtls (tls))
910     return g_datagram_based_condition_check (priv->base_socket, condition);
911
912   if (condition & G_IO_IN)
913     return g_pollable_input_stream_is_readable (priv->base_istream);
914
915   if (condition & G_IO_OUT)
916     return g_pollable_output_stream_is_writable (priv->base_ostream);
917
918   g_assert_not_reached ();
919   return FALSE;
920 }
921
922 /* Checks whether the (D)TLS stream meets @condition; not the underlying base
923  * stream or GDatagramBased. */
924 gboolean
925 g_tls_connection_base_check (GTlsConnectionBase  *tls,
926                              GIOCondition         condition)
927 {
928   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
929
930   /* Racy, but worst case is that we just get WOULD_BLOCK back */
931   if (priv->need_finish_handshake)
932     return TRUE;
933
934   /* If a handshake or close is in progress, then tls_istream and
935    * tls_ostream are blocked, regardless of the base stream status.
936    */
937   if (priv->handshaking)
938     return FALSE;
939
940   if (((condition & G_IO_IN) && priv->read_closing) ||
941       ((condition & G_IO_OUT) && priv->write_closing))
942     return FALSE;
943
944   /* Defer to the base stream or GDatagramBased. */
945   return g_tls_connection_base_base_check (tls, condition);
946 }
947
948 typedef struct {
949   GSource             source;
950
951   GTlsConnectionBase *tls;
952
953   /* Either a GDatagramBased (datagram mode), or a GPollableInputStream or
954    * a GPollableOutputStream (streaming mode):
955    */
956   GObject            *base;
957
958   GSource            *child_source;
959   GIOCondition        condition;
960
961   gboolean            io_waiting;
962   gboolean            op_waiting;
963 } GTlsConnectionBaseSource;
964
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.) */
968 static gboolean
969 dummy_callback (gpointer data)
970 {
971   return G_SOURCE_CONTINUE;
972 }
973
974 static void
975 tls_source_sync (GTlsConnectionBaseSource *tls_source)
976 {
977   GTlsConnectionBase *tls = tls_source->tls;
978   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
979   gboolean io_waiting, op_waiting;
980
981   /* Was the source destroyed earlier in this main context iteration? */
982   if (g_source_is_destroyed ((GSource *)tls_source))
983     return;
984
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))
989     op_waiting = TRUE;
990   else
991     op_waiting = FALSE;
992
993   if (!op_waiting && !priv->need_handshake &&
994       !priv->need_finish_handshake)
995     io_waiting = TRUE;
996   else
997     io_waiting = FALSE;
998   g_mutex_unlock (&priv->op_mutex);
999
1000   if (op_waiting == tls_source->op_waiting &&
1001       io_waiting == tls_source->io_waiting)
1002     return;
1003   tls_source->op_waiting = op_waiting;
1004   tls_source->io_waiting = io_waiting;
1005
1006   if (tls_source->child_source)
1007     {
1008       g_source_remove_child_source ((GSource *)tls_source,
1009                                     tls_source->child_source);
1010       g_source_unref (tls_source->child_source);
1011     }
1012
1013   if (op_waiting)
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);
1021   else
1022     tls_source->child_source = g_timeout_source_new (0);
1023
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);
1026 }
1027
1028 static gboolean
1029 tls_source_dispatch (GSource     *source,
1030                      GSourceFunc  callback,
1031                      gpointer     user_data)
1032 {
1033   GDatagramBasedSourceFunc datagram_based_func = (GDatagramBasedSourceFunc)callback;
1034   GPollableSourceFunc pollable_func = (GPollableSourceFunc)callback;
1035   GTlsConnectionBaseSource *tls_source = (GTlsConnectionBaseSource *)source;
1036   gboolean ret;
1037
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);
1041   else
1042     ret = (*pollable_func) (tls_source->base, user_data);
1043
1044   if (ret)
1045     tls_source_sync (tls_source);
1046
1047   return ret;
1048 }
1049
1050 static void
1051 tls_source_finalize (GSource *source)
1052 {
1053   GTlsConnectionBaseSource *tls_source = (GTlsConnectionBaseSource *)source;
1054
1055   g_object_unref (tls_source->tls);
1056   g_source_unref (tls_source->child_source);
1057 }
1058
1059 static gboolean
1060 g_tls_connection_tls_source_closure_callback (GObject  *stream,
1061                                               gpointer  data)
1062 {
1063   GClosure *closure = data;
1064
1065   GValue param = { 0, };
1066   GValue result_value = { 0, };
1067   gboolean result;
1068
1069   g_value_init (&result_value, G_TYPE_BOOLEAN);
1070
1071   g_value_init (&param, G_TYPE_OBJECT);
1072   g_value_set_object (&param, stream);
1073
1074   g_closure_invoke (closure, &result_value, 1, &param, NULL);
1075
1076   result = g_value_get_boolean (&result_value);
1077   g_value_unset (&result_value);
1078   g_value_unset (&param);
1079
1080   return result;
1081 }
1082
1083 static gboolean
1084 g_tls_connection_tls_source_dtls_closure_callback (GDatagramBased *datagram_based,
1085                                                    GIOCondition    condition,
1086                                                    gpointer        data)
1087 {
1088   GClosure *closure = data;
1089
1090   GValue param[2] = { G_VALUE_INIT, G_VALUE_INIT };
1091   GValue result_value = G_VALUE_INIT;
1092   gboolean result;
1093
1094   g_value_init (&result_value, G_TYPE_BOOLEAN);
1095
1096   g_value_init (&param[0], G_TYPE_DATAGRAM_BASED);
1097   g_value_set_object (&param[0], datagram_based);
1098   g_value_init (&param[1], G_TYPE_IO_CONDITION);
1099   g_value_set_flags (&param[1], condition);
1100
1101   g_closure_invoke (closure, &result_value, 2, param, NULL);
1102
1103   result = g_value_get_boolean (&result_value);
1104   g_value_unset (&result_value);
1105   g_value_unset (&param[0]);
1106   g_value_unset (&param[1]);
1107
1108   return result;
1109 }
1110
1111 static GSourceFuncs tls_source_funcs =
1112 {
1113   NULL,
1114   NULL,
1115   tls_source_dispatch,
1116   tls_source_finalize,
1117   (GSourceFunc)g_tls_connection_tls_source_closure_callback,
1118   (GSourceDummyMarshal)g_cclosure_marshal_generic
1119 };
1120
1121 static GSourceFuncs dtls_source_funcs =
1122 {
1123   NULL,
1124   NULL,
1125   tls_source_dispatch,
1126   tls_source_finalize,
1127   (GSourceFunc)g_tls_connection_tls_source_dtls_closure_callback,
1128   (GSourceDummyMarshal)g_cclosure_marshal_generic
1129 };
1130
1131 GSource *
1132 g_tls_connection_base_create_source (GTlsConnectionBase  *tls,
1133                                      GIOCondition         condition,
1134                                      GCancellable        *cancellable)
1135 {
1136   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1137   GSource *source, *cancellable_source;
1138   GTlsConnectionBaseSource *tls_source;
1139
1140   if (g_tls_connection_base_is_dtls (tls))
1141     {
1142       source = g_source_new (&dtls_source_funcs,
1143                              sizeof (GTlsConnectionBaseSource));
1144     }
1145   else
1146     {
1147       source = g_source_new (&tls_source_funcs,
1148                              sizeof (GTlsConnectionBaseSource));
1149     }
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);
1160   else
1161     g_assert_not_reached ();
1162
1163   tls_source->op_waiting = (gboolean) -1;
1164   tls_source->io_waiting = (gboolean) -1;
1165   tls_source_sync (tls_source);
1166
1167   if (cancellable)
1168     {
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);
1173     }
1174
1175   return source;
1176 }
1177
1178 static GSource *
1179 g_tls_connection_base_dtls_create_source (GDatagramBased  *datagram_based,
1180                                           GIOCondition     condition,
1181                                           GCancellable    *cancellable)
1182 {
1183   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (datagram_based);
1184
1185   return g_tls_connection_base_create_source (tls, condition, cancellable);
1186 }
1187
1188 static GIOCondition
1189 g_tls_connection_base_condition_check (GDatagramBased  *datagram_based,
1190                                          GIOCondition     condition)
1191 {
1192   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (datagram_based);
1193
1194   return g_tls_connection_base_check (tls, condition) ? condition : 0;
1195 }
1196
1197 static gboolean
1198 g_tls_connection_base_condition_wait (GDatagramBased  *datagram_based,
1199                                       GIOCondition     condition,
1200                                       gint64           timeout,
1201                                       GCancellable    *cancellable,
1202                                       GError         **error)
1203 {
1204   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (datagram_based);
1205   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1206   GPollFD fds[2];
1207   guint n_fds;
1208   gint result = 1; /* if the loop is never entered, it's as if we cancelled early */
1209   gint64 start_time;
1210
1211   if (g_cancellable_set_error_if_cancelled (cancellable, error))
1212     return FALSE;
1213
1214   /* Convert from microseconds to milliseconds. */
1215   if (timeout != -1)
1216     timeout = timeout / 1000;
1217
1218   start_time = g_get_monotonic_time ();
1219
1220   g_cancellable_make_pollfd (priv->waiting_for_op, &fds[0]);
1221   n_fds = 1;
1222
1223   if (g_cancellable_make_pollfd (cancellable, &fds[1]))
1224     n_fds++;
1225
1226   while (!g_tls_connection_base_condition_check (datagram_based, condition) &&
1227          !g_cancellable_is_cancelled (cancellable))
1228     {
1229       result = g_poll (fds, n_fds, timeout);
1230       if (result == 0)
1231         break;
1232       if (result != -1 || errno != EINTR)
1233         continue;
1234
1235       if (timeout != -1)
1236         {
1237           timeout -= (g_get_monotonic_time () - start_time) / 1000;
1238           if (timeout < 0)
1239             timeout = 0;
1240         }
1241     }
1242
1243   if (n_fds > 1)
1244     g_cancellable_release_fd (cancellable);
1245
1246   if (result == 0)
1247     {
1248       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
1249                            _("Socket I/O timed out"));
1250       return FALSE;
1251     }
1252
1253   return !g_cancellable_set_error_if_cancelled (cancellable, error);
1254 }
1255
1256 static GTlsCertificateFlags
1257 verify_peer_certificate (GTlsConnectionBase *tls,
1258                          GTlsCertificate    *peer_certificate)
1259 {
1260   GTlsConnectionBaseClass *tls_class = G_TLS_CONNECTION_BASE_GET_CLASS (tls);
1261   GSocketConnectable *peer_identity = NULL;
1262   GTlsDatabase *database;
1263   GTlsCertificateFlags errors = 0;
1264   gboolean is_client;
1265
1266   is_client = G_IS_TLS_CLIENT_CONNECTION (tls);
1267
1268   if (is_client)
1269     {
1270       if (!g_tls_connection_base_is_dtls (tls))
1271         peer_identity = g_tls_client_connection_get_server_identity (G_TLS_CLIENT_CONNECTION (tls));
1272       else
1273         peer_identity = g_dtls_client_connection_get_server_identity (G_DTLS_CLIENT_CONNECTION (tls));
1274
1275       if (!peer_identity)
1276         errors |= G_TLS_CERTIFICATE_BAD_IDENTITY;
1277     }
1278
1279   database = g_tls_connection_get_database (G_TLS_CONNECTION (tls));
1280   if (!database)
1281     {
1282       errors |= G_TLS_CERTIFICATE_UNKNOWN_CA;
1283       errors |= g_tls_certificate_verify (peer_certificate, peer_identity, NULL);
1284     }
1285   else
1286     {
1287       GError *error = NULL;
1288
1289       g_assert (tls_class->verify_chain);
1290       errors |= tls_class->verify_chain (tls,
1291                                          peer_certificate,
1292                                          is_client ? G_TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER : G_TLS_DATABASE_PURPOSE_AUTHENTICATE_CLIENT,
1293                                          peer_identity,
1294                                          g_tls_connection_get_interaction (G_TLS_CONNECTION (tls)),
1295                                          G_TLS_DATABASE_VERIFY_NONE,
1296                                          NULL,
1297                                          &error);
1298       if (error)
1299         {
1300           g_tls_log_debug (tls, "failure verifying certificate chain: %s", error->message);
1301           g_assert (errors != 0);
1302           g_clear_error (&error);
1303         }
1304     }
1305
1306   if (tls_class->verify_peer_certificate)
1307     errors |= tls_class->verify_peer_certificate (tls, peer_certificate, errors);
1308
1309   return errors;
1310 }
1311
1312 static gboolean
1313 accept_or_reject_peer_certificate (gpointer user_data)
1314 {
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;
1320
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.
1324    */
1325   g_assert (priv->handshake_context);
1326   g_assert (g_main_context_is_owner (priv->handshake_context));
1327
1328   peer_certificate = G_TLS_CONNECTION_BASE_GET_CLASS (tls)->retrieve_peer_certificate (tls);
1329
1330   if (peer_certificate)
1331     {
1332       peer_certificate_errors = verify_peer_certificate (tls, peer_certificate);
1333
1334       if (G_IS_TLS_CLIENT_CONNECTION (tls))
1335         {
1336           GTlsCertificateFlags validation_flags;
1337
1338           if (!g_tls_connection_base_is_dtls (tls))
1339             validation_flags =
1340               g_tls_client_connection_get_validation_flags (G_TLS_CLIENT_CONNECTION (tls));
1341           else
1342             validation_flags =
1343               g_dtls_client_connection_get_validation_flags (G_DTLS_CLIENT_CONNECTION (tls));
1344
1345           if ((peer_certificate_errors & validation_flags) == 0)
1346             accepted = TRUE;
1347         }
1348
1349       if (!accepted)
1350         {
1351           gboolean sync_handshake_in_progress;
1352
1353           g_mutex_lock (&priv->op_mutex);
1354           sync_handshake_in_progress = priv->sync_handshake_in_progress;
1355           g_mutex_unlock (&priv->op_mutex);
1356
1357           if (sync_handshake_in_progress)
1358             g_main_context_pop_thread_default (priv->handshake_context);
1359
1360           accepted = g_tls_connection_emit_accept_certificate (G_TLS_CONNECTION (tls),
1361                                                                peer_certificate,
1362                                                                peer_certificate_errors);
1363
1364           if (sync_handshake_in_progress)
1365             g_main_context_push_thread_default (priv->handshake_context);
1366         }
1367     }
1368   else if (G_IS_TLS_SERVER_CONNECTION (tls))
1369     {
1370       GTlsAuthenticationMode mode = 0;
1371
1372       g_object_get (tls,
1373                     "authentication-mode", &mode,
1374                     NULL);
1375
1376       if (mode != G_TLS_AUTHENTICATION_REQUIRED)
1377         accepted = TRUE;
1378     }
1379
1380   g_mutex_lock (&priv->verify_certificate_mutex);
1381
1382   priv->peer_certificate_accepted = accepted;
1383
1384   /* Warning: the API documentation indicates that these properties are not
1385    * set until *after* accept-certificate.
1386    */
1387   g_clear_object (&priv->peer_certificate);
1388   priv->peer_certificate = g_steal_pointer (&peer_certificate);
1389   priv->peer_certificate_errors = peer_certificate_errors;
1390
1391   g_object_notify (G_OBJECT (tls), "peer-certificate");
1392   g_object_notify (G_OBJECT (tls), "peer-certificate-errors");
1393
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.
1397    */
1398   priv->peer_certificate_examined = TRUE;
1399
1400   g_cond_signal (&priv->verify_certificate_condition);
1401   g_mutex_unlock (&priv->verify_certificate_mutex);
1402
1403   return G_SOURCE_REMOVE;
1404 }
1405
1406 gboolean
1407 g_tls_connection_base_handshake_thread_verify_certificate (GTlsConnectionBase *tls)
1408 {
1409   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1410   gboolean accepted;
1411
1412   g_tls_log_debug (tls, "verifying peer certificate");
1413
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);
1418
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.
1422    */
1423   g_assert (priv->handshake_context);
1424   g_main_context_invoke (priv->handshake_context, accept_or_reject_peer_certificate, tls);
1425
1426   /* We'll block the handshake thread until the original thread has
1427    * decided whether to accept the certificate.
1428    */
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);
1434
1435   return accepted;
1436 }
1437
1438 static gboolean
1439 g_tls_connection_base_get_binding_data (GTlsConnection          *conn,
1440                                         GTlsChannelBindingType   type,
1441                                         GByteArray              *data,
1442                                         GError                 **error)
1443 {
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);
1447
1448   g_assert (tls_class->get_channel_binding_data);
1449
1450   if (!priv->ever_handshaked || priv->need_handshake)
1451     {
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"));
1455       return FALSE;
1456     }
1457
1458   return tls_class->get_channel_binding_data (tls, type, data, error);
1459 }
1460
1461 static gboolean
1462 g_tls_connection_base_dtls_get_binding_data (GDtlsConnection         *conn,
1463                                              GTlsChannelBindingType   type,
1464                                              GByteArray              *data,
1465                                              GError                 **error)
1466 {
1467   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (conn);
1468
1469   return g_tls_connection_base_get_binding_data ((GTlsConnection *)tls,
1470                                                  type, data, error);
1471 }
1472
1473 #if GLIB_CHECK_VERSION(2, 69, 0)
1474 static const gchar *
1475 g_tls_connection_base_get_negotiated_protocol (GTlsConnection *conn)
1476 {
1477   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (conn);
1478   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1479
1480   return priv->negotiated_protocol;
1481 }
1482 #endif
1483
1484 static const gchar *
1485 g_tls_connection_base_dtls_get_negotiated_protocol (GDtlsConnection *conn)
1486 {
1487   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (conn);
1488   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1489
1490   return priv->negotiated_protocol;
1491 }
1492
1493 static void
1494 handshake_thread (GTask        *task,
1495                   gpointer      object,
1496                   gpointer      task_data,
1497                   GCancellable *cancellable)
1498 {
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;
1503   gint64 start_time;
1504   gint64 timeout;
1505
1506   g_tls_log_debug (tls, "TLS handshake thread starts");
1507
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);
1512
1513   priv->started_handshake = FALSE;
1514   priv->missing_requested_client_certificate = FALSE;
1515
1516   if (!claim_op (tls, G_TLS_CONNECTION_BASE_OP_HANDSHAKE,
1517                  timeout, cancellable, &error))
1518     {
1519       g_task_return_error (task, error);
1520       g_tls_log_debug (tls, "TLS handshake thread failed: claiming op failed");
1521       return;
1522     }
1523
1524   g_clear_error (&priv->handshake_error);
1525
1526   if (priv->ever_handshaked && !priv->need_handshake)
1527     {
1528       GTlsConnectionBaseStatus status;
1529
1530       if (tls_class->handshake_thread_safe_renegotiation_status (tls) != G_TLS_SAFE_RENEGOTIATION_SUPPORTED_BY_PEER)
1531         {
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");
1535           return;
1536         }
1537
1538       /* Adjust the timeout for the next operation in the sequence. */
1539       if (timeout > 0)
1540         {
1541           timeout -= (g_get_monotonic_time () - start_time);
1542           if (timeout <= 0)
1543             timeout = 1;
1544         }
1545
1546       status = tls_class->handshake_thread_request_rehandshake (tls, timeout, cancellable, &error);
1547       if (status != G_TLS_CONNECTION_BASE_OK)
1548         {
1549           g_task_return_error (task, error);
1550           g_tls_log_debug (tls, "TLS handshake thread failed: %s", error->message);
1551           return;
1552         }
1553     }
1554
1555   /* Adjust the timeout for the next operation in the sequence. */
1556   if (timeout > 0)
1557     {
1558       timeout -= (g_get_monotonic_time () - start_time);
1559       if (timeout <= 0)
1560         timeout = 1;
1561     }
1562
1563   priv->started_handshake = TRUE;
1564   tls_class->handshake_thread_handshake (tls, timeout, cancellable, &error);
1565   priv->need_handshake = FALSE;
1566
1567   if (error)
1568     {
1569       g_task_return_error (task, error);
1570       g_tls_log_debug (tls, "TLS handshake thread failed: %s", error->message);
1571     }
1572   else
1573     {
1574       priv->ever_handshaked = TRUE;
1575       g_task_return_boolean (task, TRUE);
1576       g_tls_log_debug (tls, "TLS handshake thread succeeded");
1577     }
1578 }
1579
1580 static void
1581 sync_handshake_thread_completed (GObject      *object,
1582                                  GAsyncResult *result,
1583                                  gpointer      user_data)
1584 {
1585   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (object);
1586   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1587   gpointer source_tag;
1588
1589   g_tls_log_debug (tls, "synchronous TLS handshake thread completed");
1590
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));
1594
1595   g_assert (g_main_context_is_owner (priv->handshake_context));
1596
1597   g_mutex_lock (&priv->op_mutex);
1598   priv->sync_handshake_in_progress = FALSE;
1599   g_mutex_unlock (&priv->op_mutex);
1600
1601   g_main_context_wakeup (priv->handshake_context);
1602 }
1603
1604 static void
1605 crank_sync_handshake_context (GTlsConnectionBase *tls,
1606                               GCancellable       *cancellable)
1607 {
1608   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1609
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.
1613    *
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.
1619    */
1620   g_mutex_lock (&priv->op_mutex);
1621   priv->sync_handshake_in_progress = TRUE;
1622   while (priv->sync_handshake_in_progress)
1623     {
1624       g_mutex_unlock (&priv->op_mutex);
1625       g_main_context_iteration (priv->handshake_context, TRUE);
1626       g_mutex_lock (&priv->op_mutex);
1627     }
1628   g_mutex_unlock (&priv->op_mutex);
1629 }
1630
1631 static gboolean
1632 finish_handshake (GTlsConnectionBase  *tls,
1633                   GTask               *task,
1634                   GError             **error)
1635 {
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;
1641   gboolean success;
1642   GError *my_error = NULL;
1643
1644   g_tls_log_debug (tls, "finishing TLS handshake");
1645
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;
1649
1650   success = g_task_propagate_boolean (task, &my_error);
1651   if (success)
1652     {
1653       if (tls_class->is_session_resumed && tls_class->is_session_resumed (tls))
1654         {
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.
1659            *
1660            * The certificate has already been accepted, so we don't do
1661            * anything with the result here.
1662            */
1663           g_mutex_lock (&priv->verify_certificate_mutex);
1664
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);
1668
1669           g_object_notify (G_OBJECT (tls), "peer-certificate");
1670           g_object_notify (G_OBJECT (tls), "peer-certificate-errors");
1671
1672           priv->peer_certificate_examined = TRUE;
1673           priv->peer_certificate_accepted = TRUE;
1674           g_mutex_unlock (&priv->verify_certificate_mutex);
1675         }
1676
1677       /* FIXME: Return an error from the handshake thread instead. */
1678       if (priv->peer_certificate && !priv->peer_certificate_accepted)
1679         {
1680           g_set_error_literal (&my_error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
1681                                _("Unacceptable TLS certificate"));
1682           success = FALSE;
1683         }
1684     }
1685
1686   tls_class->complete_handshake (tls,
1687                                  success,
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);
1693
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);
1697
1698   if (original_protocol_version != priv->protocol_version)
1699     g_object_notify (G_OBJECT (tls), "protocol-version");
1700
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);
1704
1705   if (my_error && priv->started_handshake)
1706     priv->handshake_error = g_error_copy (my_error);
1707
1708   if (!my_error) {
1709     g_tls_log_debug (tls, "TLS handshake has finished successfully");
1710     return TRUE;
1711   }
1712
1713   g_tls_log_debug (tls, "TLS handshake has finished with error: %s", my_error->message);
1714   g_propagate_error (error, my_error);
1715   return FALSE;
1716 }
1717
1718 static gboolean
1719 g_tls_connection_base_handshake (GTlsConnection   *conn,
1720                                  GCancellable     *cancellable,
1721                                  GError          **error)
1722 {
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);
1726   GTask *task;
1727   gboolean success;
1728   gint64 *timeout = NULL;
1729   GError *my_error = NULL;
1730
1731   g_tls_log_debug (tls, "Starting synchronous TLS handshake");
1732
1733   g_assert (!priv->handshake_context);
1734   priv->handshake_context = g_main_context_new ();
1735
1736   g_main_context_push_thread_default (priv->handshake_context);
1737
1738   if (tls_class->prepare_handshake)
1739     tls_class->prepare_handshake (tls, priv->advertised_protocols);
1740
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");
1744
1745   timeout = g_new0 (gint64, 1);
1746   *timeout = -1; /* blocking */
1747   g_task_set_task_data (task, timeout, g_free);
1748
1749   g_task_run_in_thread (task, handshake_thread);
1750   crank_sync_handshake_context (tls, cancellable);
1751
1752   success = finish_handshake (tls, task, &my_error);
1753   g_object_unref (task);
1754
1755   g_main_context_pop_thread_default (priv->handshake_context);
1756   g_clear_pointer (&priv->handshake_context, g_main_context_unref);
1757
1758   yield_op (tls, G_TLS_CONNECTION_BASE_OP_HANDSHAKE,
1759             G_TLS_CONNECTION_BASE_OK);
1760
1761   if (my_error)
1762     g_propagate_error (error, my_error);
1763   return success;
1764 }
1765
1766 static gboolean
1767 g_tls_connection_base_dtls_handshake (GDtlsConnection  *conn,
1768                                       GCancellable     *cancellable,
1769                                       GError          **error)
1770 {
1771   return g_tls_connection_base_handshake (G_TLS_CONNECTION (conn),
1772                                           cancellable, error);
1773 }
1774
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().
1779  */
1780
1781 static void
1782 async_handshake_thread_completed (GObject      *object,
1783                                   GAsyncResult *result,
1784                                   gpointer      user_data)
1785 {
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;
1791
1792   g_tls_log_debug (tls, "Asynchronous TLS handshake thread completed");
1793
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);
1796
1797   g_mutex_lock (&priv->op_mutex);
1798   if (priv->need_finish_handshake)
1799     {
1800       need_finish_handshake = TRUE;
1801       priv->need_finish_handshake = FALSE;
1802     }
1803   else
1804     need_finish_handshake = FALSE;
1805   g_mutex_unlock (&priv->op_mutex);
1806
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.
1810    *
1811    * But we can't clear until after finish_handshake().
1812    */
1813   if (need_finish_handshake)
1814     {
1815       success = finish_handshake (tls, G_TASK (result), &error);
1816
1817       g_clear_pointer (&priv->handshake_context, g_main_context_unref);
1818
1819       if (success)
1820         g_task_return_boolean (caller_task, TRUE);
1821       else
1822         g_task_return_error (caller_task, error);
1823     }
1824   else
1825     {
1826       g_clear_pointer (&priv->handshake_context, g_main_context_unref);
1827
1828       if (priv->handshake_error)
1829         g_task_return_error (caller_task, g_error_copy (priv->handshake_error));
1830       else
1831         g_task_return_boolean (caller_task, TRUE);
1832     }
1833
1834   g_object_unref (caller_task);
1835 }
1836
1837 static void
1838 async_handshake_thread (GTask        *task,
1839                         gpointer      object,
1840                         gpointer      task_data,
1841                         GCancellable *cancellable)
1842 {
1843   GTlsConnectionBase *tls = object;
1844   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
1845
1846   g_tls_log_debug (tls, "Asynchronous TLS handshake thread starts");
1847
1848   handshake_thread (task, object, task_data, cancellable);
1849
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.
1855    */
1856   priv->handshaking = FALSE;
1857   g_mutex_unlock (&priv->op_mutex);
1858
1859   yield_op (tls, G_TLS_CONNECTION_BASE_OP_HANDSHAKE,
1860             G_TLS_CONNECTION_BASE_OK);
1861 }
1862
1863 static void
1864 g_tls_connection_base_handshake_async (GTlsConnection      *conn,
1865                                        int                  io_priority,
1866                                        GCancellable        *cancellable,
1867                                        GAsyncReadyCallback  callback,
1868                                        gpointer             user_data)
1869 {
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;
1875
1876   g_tls_log_debug (tls, "Starting asynchronous TLS handshake");
1877
1878   g_assert (!priv->handshake_context);
1879   priv->handshake_context = g_main_context_ref_thread_default ();
1880
1881   if (tls_class->prepare_handshake)
1882     tls_class->prepare_handshake (tls, priv->advertised_protocols);
1883
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);
1888
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);
1893
1894   timeout = g_new0 (gint64, 1);
1895   *timeout = -1; /* blocking */
1896   g_task_set_task_data (thread_task, timeout, g_free);
1897
1898   g_task_run_in_thread (thread_task, async_handshake_thread);
1899   g_object_unref (thread_task);
1900 }
1901
1902 static gboolean
1903 g_tls_connection_base_handshake_finish (GTlsConnection  *conn,
1904                                         GAsyncResult    *result,
1905                                         GError         **error)
1906 {
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);
1909
1910   return g_task_propagate_boolean (G_TASK (result), error);
1911 }
1912
1913 static void
1914 g_tls_connection_base_dtls_handshake_async (GDtlsConnection     *conn,
1915                                             int                  io_priority,
1916                                             GCancellable        *cancellable,
1917                                             GAsyncReadyCallback  callback,
1918                                             gpointer             user_data)
1919 {
1920   g_tls_connection_base_handshake_async (G_TLS_CONNECTION (conn), io_priority,
1921                                          cancellable, callback, user_data);
1922 }
1923
1924 static gboolean
1925 g_tls_connection_base_dtls_handshake_finish (GDtlsConnection  *conn,
1926                                              GAsyncResult     *result,
1927                                              GError          **error)
1928 {
1929   return g_tls_connection_base_handshake_finish (G_TLS_CONNECTION (conn),
1930                                                  result, error);
1931 }
1932
1933 static gboolean
1934 do_implicit_handshake (GTlsConnectionBase  *tls,
1935                        gint64               timeout,
1936                        GCancellable        *cancellable,
1937                        GError             **error)
1938 {
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;
1942
1943   g_tls_log_debug (tls, "Implicit TLS handshaking starts");
1944
1945   /* We have op_mutex */
1946
1947   g_assert (!priv->handshake_context);
1948   if (timeout != 0)
1949     {
1950       priv->handshake_context = g_main_context_new ();
1951       g_main_context_push_thread_default (priv->handshake_context);
1952     }
1953   else
1954     {
1955       priv->handshake_context = g_main_context_ref_thread_default ();
1956     }
1957
1958   g_assert (!priv->implicit_handshake);
1959   priv->implicit_handshake = g_task_new (tls, cancellable,
1960                                          timeout ? sync_handshake_thread_completed : NULL,
1961                                          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");
1964
1965   thread_timeout = g_new0 (gint64, 1);
1966   g_task_set_task_data (priv->implicit_handshake,
1967                         thread_timeout, g_free);
1968
1969   if (tls_class->prepare_handshake)
1970     tls_class->prepare_handshake (tls, priv->advertised_protocols);
1971
1972   if (timeout != 0)
1973     {
1974       GError *my_error = NULL;
1975       gboolean success;
1976
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;
1983
1984       g_mutex_unlock (&priv->op_mutex);
1985
1986       g_task_run_in_thread (priv->implicit_handshake, handshake_thread);
1987
1988       crank_sync_handshake_context (tls, cancellable);
1989
1990       success = finish_handshake (tls,
1991                                   priv->implicit_handshake,
1992                                   &my_error);
1993
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);
1997
1998       yield_op (tls, G_TLS_CONNECTION_BASE_OP_HANDSHAKE,
1999                 G_TLS_CONNECTION_BASE_OK);
2000
2001       g_mutex_lock (&priv->op_mutex);
2002
2003       if (my_error)
2004         g_propagate_error (error, my_error);
2005       return success;
2006     }
2007   else
2008     {
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 */
2014
2015       g_task_run_in_thread (priv->implicit_handshake,
2016                             async_handshake_thread);
2017
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");
2021       return FALSE;
2022     }
2023 }
2024
2025 gssize
2026 g_tls_connection_base_read (GTlsConnectionBase  *tls,
2027                             void                *buffer,
2028                             gsize                count,
2029                             gint64               timeout,
2030                             GCancellable        *cancellable,
2031                             GError             **error)
2032 {
2033   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2034   GTlsConnectionBaseStatus status;
2035   gssize nread;
2036
2037   g_tls_log_debug (tls, "starting to read data from TLS connection");
2038
2039   do
2040     {
2041       if (!claim_op (tls, G_TLS_CONNECTION_BASE_OP_READ,
2042                      timeout, cancellable, error))
2043         return -1;
2044
2045       if (priv->app_data_buf && !priv->handshaking)
2046         {
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);
2051           else
2052             g_byte_array_remove_range (priv->app_data_buf, 0, nread);
2053           status = G_TLS_CONNECTION_BASE_OK;
2054         }
2055       else
2056         {
2057           status = G_TLS_CONNECTION_BASE_GET_CLASS (tls)->
2058             read_fn (tls, buffer, count, timeout, &nread, cancellable, error);
2059         }
2060
2061       yield_op (tls, G_TLS_CONNECTION_BASE_OP_READ, status);
2062     }
2063   while (status == G_TLS_CONNECTION_BASE_REHANDSHAKE);
2064
2065   if (status == G_TLS_CONNECTION_BASE_OK)
2066     {
2067       priv->successful_read_op = TRUE;
2068       g_tls_log_debug (tls, "successfully read %" G_GSSIZE_FORMAT " bytes from TLS connection", nread);
2069       return nread;
2070     }
2071
2072   g_tls_log_debug (tls, "reading data from TLS connection has failed: %s", status_to_string (status));
2073   return -1;
2074 }
2075
2076 static gssize
2077 g_tls_connection_base_read_message (GTlsConnectionBase  *tls,
2078                                     GInputVector        *vectors,
2079                                     guint                num_vectors,
2080                                     gint64               timeout,
2081                                     GCancellable        *cancellable,
2082                                     GError             **error)
2083 {
2084   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2085   GTlsConnectionBaseStatus status = G_TLS_CONNECTION_BASE_OK;
2086   gssize nread;
2087
2088   g_tls_log_debug (tls, "starting to read messages from TLS connection");
2089
2090   do {
2091     if (!claim_op (tls, G_TLS_CONNECTION_BASE_OP_READ,
2092                    timeout, cancellable, error))
2093       return -1;
2094
2095     /* Copy data out of the app data buffer first. */
2096     if (priv->app_data_buf && !priv->handshaking)
2097       {
2098         nread = 0;
2099
2100         for (guint i = 0; i < num_vectors && priv->app_data_buf; i++)
2101           {
2102             gsize count;
2103             GInputVector *vec = &vectors[i];
2104
2105             count = MIN (vec->size, priv->app_data_buf->len);
2106             nread += count;
2107
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);
2111             else
2112               g_byte_array_remove_range (priv->app_data_buf, 0, count);
2113           }
2114       }
2115     else
2116       {
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);
2120       }
2121
2122     yield_op (tls, G_TLS_CONNECTION_BASE_OP_READ, status);
2123   } while (status == G_TLS_CONNECTION_BASE_REHANDSHAKE);
2124
2125   if (status == G_TLS_CONNECTION_BASE_OK)
2126     {
2127       priv->successful_read_op = TRUE;
2128       g_tls_log_debug (tls, "successfully read %" G_GSSIZE_FORMAT " bytes from TLS connection", nread);
2129       return nread;
2130     }
2131
2132   g_tls_log_debug (tls, "reading message from TLS connection has failed: %s", status_to_string (status));
2133   return -1;
2134 }
2135
2136 static gint
2137 g_tls_connection_base_receive_messages (GDatagramBased  *datagram_based,
2138                                         GInputMessage   *messages,
2139                                         guint            num_messages,
2140                                         gint             flags,
2141                                         gint64           timeout,
2142                                         GCancellable    *cancellable,
2143                                         GError         **error)
2144 {
2145   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (datagram_based);
2146   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2147   guint i;
2148   GError *child_error = NULL;
2149
2150   if (flags != G_SOCKET_MSG_NONE)
2151     {
2152       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2153                    _("Receive flags are not supported"));
2154       return -1;
2155     }
2156
2157   for (i = 0; i < num_messages && !child_error; i++)
2158     {
2159       GInputMessage *message = &messages[i];
2160       gssize n_bytes_read;
2161
2162       n_bytes_read = g_tls_connection_base_read_message (tls,
2163                                                          message->vectors,
2164                                                          message->num_vectors,
2165                                                          timeout,
2166                                                          cancellable,
2167                                                          &child_error);
2168
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;
2175
2176       if (n_bytes_read > 0)
2177         {
2178           message->bytes_received = n_bytes_read;
2179         }
2180       else if (n_bytes_read == 0)
2181         {
2182           /* EOS. */
2183           break;
2184         }
2185       else if (i > 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)))
2190         {
2191           /* Blocked or timed out after receiving some messages successfully. */
2192           g_clear_error (&child_error);
2193           break;
2194         }
2195       else
2196         {
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. */
2199           break;
2200         }
2201     }
2202
2203   if (child_error)
2204     {
2205       g_propagate_error (error, child_error);
2206       return -1;
2207     }
2208
2209   priv->successful_read_op = TRUE;
2210   return i;
2211 }
2212
2213 gssize
2214 g_tls_connection_base_write (GTlsConnectionBase  *tls,
2215                              const void          *buffer,
2216                              gsize                count,
2217                              gint64               timeout,
2218                              GCancellable        *cancellable,
2219                              GError             **error)
2220 {
2221   GTlsConnectionBaseStatus status;
2222   gssize nwrote;
2223
2224   g_tls_log_debug (tls, "starting to write %" G_GSIZE_FORMAT " bytes to TLS connection", count);
2225
2226   do
2227     {
2228       if (!claim_op (tls, G_TLS_CONNECTION_BASE_OP_WRITE,
2229                      timeout, cancellable, error))
2230         return -1;
2231
2232       status = G_TLS_CONNECTION_BASE_GET_CLASS (tls)->
2233         write_fn (tls, buffer, count, timeout, &nwrote, cancellable, error);
2234
2235       yield_op (tls, G_TLS_CONNECTION_BASE_OP_WRITE, status);
2236     }
2237   while (status == G_TLS_CONNECTION_BASE_REHANDSHAKE);
2238
2239   if (status == G_TLS_CONNECTION_BASE_OK)
2240     {
2241       g_tls_log_debug (tls, "successfully write %" G_GSSIZE_FORMAT " bytes to TLS connection", nwrote);
2242       return nwrote;
2243     }
2244
2245   g_tls_log_debug (tls, "writing data to TLS connection has failed: %s", status_to_string (status));
2246   return -1;
2247 }
2248
2249 static gssize
2250 g_tls_connection_base_write_message (GTlsConnectionBase  *tls,
2251                                      GOutputVector       *vectors,
2252                                      guint                num_vectors,
2253                                      gint64               timeout,
2254                                      GCancellable        *cancellable,
2255                                      GError             **error)
2256 {
2257   GTlsConnectionBaseStatus status;
2258   gssize nwrote;
2259
2260   g_tls_log_debug (tls, "starting to write messages to TLS connection");
2261
2262   do {
2263     if (!claim_op (tls, G_TLS_CONNECTION_BASE_OP_WRITE,
2264                    timeout, cancellable, error))
2265       return -1;
2266
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);
2270
2271     yield_op (tls, G_TLS_CONNECTION_BASE_OP_WRITE, status);
2272   } while (status == G_TLS_CONNECTION_BASE_REHANDSHAKE);
2273
2274   if (status == G_TLS_CONNECTION_BASE_OK)
2275     {
2276       g_tls_log_debug (tls, "successfully write %" G_GSSIZE_FORMAT " bytes to TLS connection", nwrote);
2277       return nwrote;
2278     }
2279
2280   g_tls_log_debug (tls, "writing messages to TLS connection has failed: %s", status_to_string (status));
2281   return -1;
2282 }
2283
2284 static gint
2285 g_tls_connection_base_send_messages (GDatagramBased  *datagram_based,
2286                                      GOutputMessage  *messages,
2287                                      guint            num_messages,
2288                                      gint             flags,
2289                                      gint64           timeout,
2290                                      GCancellable    *cancellable,
2291                                      GError         **error)
2292 {
2293   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (datagram_based);
2294   guint i;
2295   GError *child_error = NULL;
2296
2297   if (flags != G_SOCKET_MSG_NONE)
2298     {
2299       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
2300                    _("Send flags are not supported"));
2301       return -1;
2302     }
2303
2304   for (i = 0; i < num_messages && !child_error; i++)
2305     {
2306       GOutputMessage *message = &messages[i];
2307       gssize n_bytes_sent;
2308
2309       n_bytes_sent = g_tls_connection_base_write_message (tls,
2310                                                           message->vectors,
2311                                                           message->num_vectors,
2312                                                           timeout,
2313                                                           cancellable,
2314                                                           &child_error);
2315
2316       if (n_bytes_sent >= 0)
2317         {
2318           message->bytes_sent = n_bytes_sent;
2319         }
2320       else if (i > 0 &&
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)))
2325         {
2326           /* Blocked or timed out after sending some messages successfully. */
2327           g_clear_error (&child_error);
2328           break;
2329         }
2330       else
2331         {
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. */
2334           break;
2335         }
2336     }
2337
2338   if (child_error)
2339     {
2340       g_propagate_error (error, child_error);
2341       return -1;
2342     }
2343
2344   return i;
2345 }
2346
2347 static GInputStream *
2348 g_tls_connection_base_get_input_stream (GIOStream *stream)
2349 {
2350   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (stream);
2351   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2352
2353   return priv->tls_istream;
2354 }
2355
2356 static GOutputStream *
2357 g_tls_connection_base_get_output_stream (GIOStream *stream)
2358 {
2359   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (stream);
2360   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2361
2362   return priv->tls_ostream;
2363 }
2364
2365 gboolean
2366 g_tls_connection_base_close_internal (GIOStream      *stream,
2367                                       GTlsDirection   direction,
2368                                       gint64          timeout,
2369                                       GCancellable   *cancellable,
2370                                       GError        **error)
2371 {
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;
2378
2379   g_tls_log_debug (tls, "starting to close the TLS connection");
2380
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.
2385    */
2386
2387   g_return_val_if_fail (direction != G_TLS_DIRECTION_NONE, FALSE);
2388
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;
2393   else
2394     op = G_TLS_CONNECTION_BASE_OP_CLOSE_WRITE;
2395
2396   if (!claim_op (tls, op, timeout, cancellable, error))
2397     return FALSE;
2398
2399   if (priv->ever_handshaked && !priv->write_closed &&
2400       direction & G_TLS_DIRECTION_WRITE)
2401     {
2402       status = G_TLS_CONNECTION_BASE_GET_CLASS (tls)->
2403         close_fn (tls, timeout, cancellable, &close_error);
2404
2405       priv->write_closed = TRUE;
2406     }
2407   else
2408     status = G_TLS_CONNECTION_BASE_OK;
2409
2410   if (!priv->read_closed && direction & G_TLS_DIRECTION_READ)
2411     priv->read_closed = TRUE;
2412
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)
2417     {
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);
2427     }
2428   else if (g_tls_connection_base_is_dtls (tls))
2429     {
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. */
2433       success = TRUE;
2434     }
2435   else
2436     {
2437       g_assert_not_reached ();
2438     }
2439
2440   yield_op (tls, op, status);
2441
2442   /* Propagate errors. */
2443   if (status != G_TLS_CONNECTION_BASE_OK)
2444     {
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);
2448     }
2449   else if (!success)
2450     {
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);
2454     }
2455   else
2456     {
2457       g_tls_log_debug (tls, "the TLS connection has been closed successfully");
2458     }
2459
2460   return success && status == G_TLS_CONNECTION_BASE_OK;
2461 }
2462
2463 static gboolean
2464 g_tls_connection_base_close (GIOStream     *stream,
2465                              GCancellable  *cancellable,
2466                              GError       **error)
2467 {
2468   return g_tls_connection_base_close_internal (stream,
2469                                                G_TLS_DIRECTION_BOTH,
2470                                                -1,  /* blocking */
2471                                                cancellable, error);
2472 }
2473
2474 static gboolean
2475 g_tls_connection_base_dtls_shutdown (GDtlsConnection  *conn,
2476                                      gboolean          shutdown_read,
2477                                      gboolean          shutdown_write,
2478                                      GCancellable     *cancellable,
2479                                      GError          **error)
2480 {
2481   GTlsDirection direction = G_TLS_DIRECTION_NONE;
2482
2483   if (shutdown_read)
2484     direction |= G_TLS_DIRECTION_READ;
2485   if (shutdown_write)
2486     direction |= G_TLS_DIRECTION_WRITE;
2487
2488   return g_tls_connection_base_close_internal (G_IO_STREAM (conn),
2489                                                direction,
2490                                                -1, /* blocking */
2491                                                cancellable, error);
2492 }
2493
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).
2497  */
2498 static void
2499 close_thread (GTask        *task,
2500               gpointer      object,
2501               gpointer      task_data,
2502               GCancellable *cancellable)
2503 {
2504   GIOStream *stream = object;
2505   GTlsDirection direction;
2506   GError *error = NULL;
2507
2508   direction = GPOINTER_TO_INT (g_task_get_task_data (task));
2509
2510   if (!g_tls_connection_base_close_internal (stream, direction,
2511                                              -1, /* blocking */
2512                                              cancellable, &error))
2513     g_task_return_error (task, error);
2514   else
2515     g_task_return_boolean (task, TRUE);
2516 }
2517
2518 static void
2519 g_tls_connection_base_close_internal_async (GIOStream           *stream,
2520                                             GTlsDirection        direction,
2521                                             int                  io_priority,
2522                                             GCancellable        *cancellable,
2523                                             GAsyncReadyCallback  callback,
2524                                             gpointer             user_data)
2525 {
2526   GTask *task;
2527
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);
2535 }
2536
2537 static void
2538 g_tls_connection_base_close_async (GIOStream           *stream,
2539                                    int                  io_priority,
2540                                    GCancellable        *cancellable,
2541                                    GAsyncReadyCallback  callback,
2542                                    gpointer             user_data)
2543 {
2544   g_tls_connection_base_close_internal_async (stream, G_TLS_DIRECTION_BOTH,
2545                                               io_priority, cancellable,
2546                                               callback, user_data);
2547 }
2548
2549 static gboolean
2550 g_tls_connection_base_close_finish (GIOStream           *stream,
2551                                     GAsyncResult        *result,
2552                                     GError             **error)
2553 {
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);
2556
2557   return g_task_propagate_boolean (G_TASK (result), error);
2558 }
2559
2560 static void
2561 g_tls_connection_base_dtls_shutdown_async (GDtlsConnection     *conn,
2562                                            gboolean             shutdown_read,
2563                                            gboolean             shutdown_write,
2564                                            int                  io_priority,
2565                                            GCancellable        *cancellable,
2566                                            GAsyncReadyCallback  callback,
2567                                            gpointer             user_data)
2568 {
2569   GTlsDirection direction = G_TLS_DIRECTION_NONE;
2570
2571   if (shutdown_read)
2572     direction |= G_TLS_DIRECTION_READ;
2573   if (shutdown_write)
2574     direction |= G_TLS_DIRECTION_WRITE;
2575
2576   g_tls_connection_base_close_internal_async (G_IO_STREAM (conn), direction,
2577                                               io_priority, cancellable,
2578                                               callback, user_data);
2579 }
2580
2581 static gboolean
2582 g_tls_connection_base_dtls_shutdown_finish (GDtlsConnection  *conn,
2583                                             GAsyncResult     *result,
2584                                             GError          **error)
2585 {
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);
2588
2589   return g_task_propagate_boolean (G_TASK (result), error);
2590 }
2591
2592 static void
2593 g_tls_connection_base_dtls_set_advertised_protocols (GDtlsConnection     *conn,
2594                                                      const gchar * const *protocols)
2595 {
2596   g_object_set (conn, "advertised-protocols", protocols, NULL);
2597 }
2598
2599 GDatagramBased *
2600 g_tls_connection_base_get_base_socket (GTlsConnectionBase *tls)
2601 {
2602   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2603
2604  g_assert (g_tls_connection_base_is_dtls (tls));
2605
2606   return priv->base_socket;
2607 }
2608
2609 GIOStream *
2610 g_tls_connection_base_get_base_iostream (GTlsConnectionBase *tls)
2611 {
2612   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2613
2614  g_assert (!g_tls_connection_base_is_dtls (tls));
2615
2616   return priv->base_io_stream;
2617 }
2618
2619 GPollableInputStream *
2620 g_tls_connection_base_get_base_istream (GTlsConnectionBase *tls)
2621 {
2622   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2623
2624   g_assert (!g_tls_connection_base_is_dtls (tls));
2625
2626   return priv->base_istream;
2627 }
2628
2629 GPollableOutputStream *
2630 g_tls_connection_base_get_base_ostream (GTlsConnectionBase *tls)
2631 {
2632   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2633
2634   g_assert (!g_tls_connection_base_is_dtls (tls));
2635
2636   return priv->base_ostream;
2637 }
2638
2639 void
2640 g_tls_connection_base_handshake_thread_set_missing_requested_client_certificate (GTlsConnectionBase *tls)
2641 {
2642   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2643
2644   priv->missing_requested_client_certificate = TRUE;
2645 }
2646
2647 GError **
2648 g_tls_connection_base_get_read_error (GTlsConnectionBase *tls)
2649 {
2650   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2651
2652   return &priv->read_error;
2653 }
2654
2655 GError **
2656 g_tls_connection_base_get_write_error (GTlsConnectionBase *tls)
2657 {
2658   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2659
2660   return &priv->write_error;
2661 }
2662
2663 gint64
2664 g_tls_connection_base_get_read_timeout (GTlsConnectionBase *tls)
2665 {
2666   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2667
2668   return priv->read_timeout;
2669 }
2670
2671 gint64
2672 g_tls_connection_base_get_write_timeout (GTlsConnectionBase *tls)
2673 {
2674   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2675
2676   return priv->write_timeout;
2677 }
2678
2679 GCancellable *
2680 g_tls_connection_base_get_read_cancellable (GTlsConnectionBase *tls)
2681 {
2682   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2683
2684   return priv->read_cancellable;
2685 }
2686
2687 GCancellable *
2688 g_tls_connection_base_get_write_cancellable (GTlsConnectionBase *tls)
2689 {
2690   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2691
2692   return priv->write_cancellable;
2693 }
2694
2695 gboolean
2696 g_tls_connection_base_is_handshaking (GTlsConnectionBase *tls)
2697 {
2698   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2699
2700   return priv->handshaking;
2701 }
2702
2703 gboolean
2704 g_tls_connection_base_ever_handshaked (GTlsConnectionBase *tls)
2705 {
2706   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2707
2708   return priv->ever_handshaked;
2709 }
2710
2711 gboolean
2712 g_tls_connection_base_handshake_thread_request_certificate (GTlsConnectionBase *tls)
2713 {
2714   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2715   GTlsInteractionResult res = G_TLS_INTERACTION_UNHANDLED;
2716   GTlsInteraction *interaction;
2717   GTlsConnection *conn;
2718
2719   g_return_val_if_fail (G_IS_TLS_CONNECTION_BASE (tls), FALSE);
2720
2721   conn = G_TLS_CONNECTION (tls);
2722
2723   g_clear_error (&priv->interaction_error);
2724
2725   interaction = g_tls_connection_get_interaction (conn);
2726   if (!interaction)
2727     return FALSE;
2728
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;
2733 }
2734
2735 gboolean
2736 g_tls_connection_base_handshake_thread_ask_password (GTlsConnectionBase *tls,
2737                                                      GTlsPassword       *password)
2738 {
2739   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2740   GTlsInteractionResult res = G_TLS_INTERACTION_UNHANDLED;
2741   GTlsInteraction *interaction;
2742
2743   g_return_val_if_fail (G_IS_TLS_CONNECTION_BASE (tls), FALSE);
2744
2745   g_clear_error (&priv->interaction_error);
2746
2747   interaction = g_tls_connection_get_interaction (G_TLS_CONNECTION (tls));
2748   if (!interaction)
2749     return FALSE;
2750
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;
2755 }
2756
2757 void
2758 g_tls_connection_base_handshake_thread_buffer_application_data (GTlsConnectionBase *tls,
2759                                                                 guint8             *data,
2760                                                                 gsize               length)
2761 {
2762   GTlsConnectionBasePrivate *priv = g_tls_connection_base_get_instance_private (tls);
2763
2764   if (!priv->app_data_buf)
2765     priv->app_data_buf = g_byte_array_new ();
2766
2767   g_byte_array_append (priv->app_data_buf, data, length);
2768 }
2769
2770 static void
2771 g_tls_connection_base_class_init (GTlsConnectionBaseClass *klass)
2772 {
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);
2776
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;
2780
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;
2787 #endif
2788
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;
2794
2795   klass->push_io = g_tls_connection_base_real_push_io;
2796   klass->pop_io = g_tls_connection_base_real_pop_io;
2797
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");
2813 }
2814
2815 static void
2816 g_tls_connection_base_dtls_connection_iface_init (GDtlsConnectionInterface *iface)
2817 {
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;
2827 }
2828
2829 static void
2830 g_tls_connection_base_datagram_based_iface_init (GDatagramBasedInterface *iface)
2831 {
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;
2837 }