soup-websocket-connection.c 60.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
 * soup-websocket-connection.c: This file was originally part of Cockpit.
 *
 * Copyright 2013, 2014 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; If not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <string.h>

#include "soup-websocket-connection.h"
#include "soup-enum-types.h"
27
#include "soup-io-stream.h"
28
#include "soup-uri.h"
29
#include "soup-websocket-extension.h"
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

/*
 * SECTION:websocketconnection
 * @title: SoupWebsocketConnection
 * @short_description: A WebSocket connection
 *
 * A #SoupWebsocketConnection is a WebSocket connection to a peer.
 * This API is modeled after the W3C API for interacting with
 * WebSockets.
 *
 * The #SoupWebsocketConnection:state property will indicate the
 * state of the connection.
 *
 * Use soup_websocket_connection_send() to send a message to the peer.
 * When a message is received the #SoupWebsocketConnection::message
 * signal will fire.
 *
 * The soup_websocket_connection_close() function will perform an
 * orderly close of the connection. The
 * #SoupWebsocketConnection::closed signal will fire once the
 * connection closes, whether it was initiated by this side or the
 * peer.
 *
 * Connect to the #SoupWebsocketConnection::closing signal to detect
 * when either peer begins closing the connection.
 */

/**
 * SoupWebsocketConnection:
 *
 * A class representing a WebSocket connection.
 *
 * Since: 2.50
 */

/**
 * SoupWebsocketConnectionClass:
 * @message: default handler for the #SoupWebsocketConnection::message signal
 * @error: default handler for the #SoupWebsocketConnection::error signal
 * @closing: the default handler for the #SoupWebsocketConnection:closing signal
 * @closed: default handler for the #SoupWebsocketConnection::closed signal
71
 * @pong: default handler for the #SoupWebsocketConnection::pong signal
72 73 74 75 76 77 78 79 80 81 82 83 84 85
 *
 * The abstract base class for #SoupWebsocketConnection
 *
 * Since: 2.50
 */

enum {
	PROP_0,
	PROP_IO_STREAM,
	PROP_CONNECTION_TYPE,
	PROP_URI,
	PROP_ORIGIN,
	PROP_PROTOCOL,
	PROP_STATE,
86
	PROP_MAX_INCOMING_PAYLOAD_SIZE,
87
	PROP_KEEPALIVE_INTERVAL,
88
	PROP_EXTENSIONS
89 90 91 92 93 94 95
};

enum {
	MESSAGE,
	ERROR,
	CLOSING,
	CLOSED,
96
	PONG,
97 98 99 100 101
	NUM_SIGNALS
};

static guint signals[NUM_SIGNALS] = { 0, };

Italo Guerrieri's avatar
Italo Guerrieri committed
102 103 104 105 106 107
typedef enum {
	SOUP_WEBSOCKET_QUEUE_NORMAL = 0,
	SOUP_WEBSOCKET_QUEUE_URGENT = 1 << 0,
	SOUP_WEBSOCKET_QUEUE_LAST = 1 << 1,
} SoupWebsocketQueueFlags;

108 109 110 111
typedef struct {
	GBytes *data;
	gsize sent;
	gsize amount;
Italo Guerrieri's avatar
Italo Guerrieri committed
112
	SoupWebsocketQueueFlags flags;
113
	gboolean pending;
114 115 116 117 118 119 120 121
} Frame;

struct _SoupWebsocketConnectionPrivate {
	GIOStream *io_stream;
	SoupWebsocketConnectionType connection_type;
	SoupURI *uri;
	char *origin;
	char *protocol;
122
	guint64 max_incoming_payload_size;
123
	guint keepalive_interval;
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

	gushort peer_close_code;
	char *peer_close_data;
	gboolean close_sent;
	gboolean close_received;
	gboolean dirty_close;
	GSource *close_timeout;

	GMainContext *main_context;

	gboolean io_closing;
	gboolean io_closed;

	GPollableInputStream *input;
	GSource *input_source;
	GByteArray *incoming;

	GPollableOutputStream *output;
	GSource *output_source;
	GQueue outgoing;

	/* Current message being assembled */
	guint8 message_opcode;
	GByteArray *message_data;
148 149

	GSource *keepalive_timeout;
150 151

	GList *extensions;
152 153
};

154
#define MAX_INCOMING_PAYLOAD_SIZE_DEFAULT   128 * 1024
155
#define READ_BUFFER_SIZE 1024
156

157
G_DEFINE_TYPE_WITH_PRIVATE (SoupWebsocketConnection, soup_websocket_connection, G_TYPE_OBJECT)
158 159 160 161

static void queue_frame (SoupWebsocketConnection *self, SoupWebsocketQueueFlags flags,
			 gpointer data, gsize len, gsize amount);

162 163 164
static void emit_error_and_close (SoupWebsocketConnection *self,
				  GError *error, gboolean prejudice);

165 166
static void protocol_error_and_close (SoupWebsocketConnection *self);

167 168 169 170 171
static gboolean on_web_socket_input (GObject *pollable_stream,
				     gpointer user_data);
static gboolean on_web_socket_output (GObject *pollable_stream,
				      gpointer user_data);

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
/* Code below is based on g_utf8_validate() implementation,
 * but handling NULL characters as valid, as expected by
 * WebSockets and compliant with RFC 3629.
 */
#define VALIDATE_BYTE(mask, expect)                             \
        G_STMT_START {                                          \
          if (G_UNLIKELY((*(guchar *)p & (mask)) != (expect)))  \
                  return FALSE;                                 \
        } G_STMT_END

/* see IETF RFC 3629 Section 4 */
static gboolean
utf8_validate (const char *str,
               gsize max_len)

{
        const gchar *p;

        for (p = str; ((p - str) < max_len); p++) {
                if (*(guchar *)p < 128)
                        /* done */;
                else {
                        if (*(guchar *)p < 0xe0) { /* 110xxxxx */
                                if (G_UNLIKELY (max_len - (p - str) < 2))
                                        return FALSE;

                                if (G_UNLIKELY (*(guchar *)p < 0xc2))
                                        return FALSE;
                        } else {
                                if (*(guchar *)p < 0xf0) { /* 1110xxxx */
                                        if (G_UNLIKELY (max_len - (p - str) < 3))
                                                return FALSE;

                                        switch (*(guchar *)p++ & 0x0f) {
                                        case 0:
                                                VALIDATE_BYTE(0xe0, 0xa0); /* 0xa0 ... 0xbf */
                                                break;
                                        case 0x0d:
                                                VALIDATE_BYTE(0xe0, 0x80); /* 0x80 ... 0x9f */
                                                break;
                                        default:
                                                VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
                                        }
                                } else if (*(guchar *)p < 0xf5) { /* 11110xxx excluding out-of-range */
                                        if (G_UNLIKELY (max_len - (p - str) < 4))
                                                return FALSE;

                                        switch (*(guchar *)p++ & 0x07) {
                                        case 0:
                                                VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
                                                if (G_UNLIKELY((*(guchar *)p & 0x30) == 0))
                                                        return FALSE;
                                                break;
                                        case 4:
                                                VALIDATE_BYTE(0xf0, 0x80); /* 0x80 ... 0x8f */
                                                break;
                                        default:
                                                VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
                                        }
                                        p++;
                                        VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
                                } else {
                                        return FALSE;
                                }
                        }

                        p++;
                        VALIDATE_BYTE(0xc0, 0x80); /* 10xxxxxx */
                }
        }

        return TRUE;
}

#undef VALIDATE_BYTE

248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
static void
frame_free (gpointer data)
{
	Frame *frame = data;

	if (frame) {
		g_bytes_unref (frame->data);
		g_slice_free (Frame, frame);
	}
}

static void
soup_websocket_connection_init (SoupWebsocketConnection *self)
{
	SoupWebsocketConnectionPrivate *pv;

264
	pv = self->pv = soup_websocket_connection_get_instance_private (self);
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

	pv->incoming = g_byte_array_sized_new (1024);
	g_queue_init (&pv->outgoing);
	pv->main_context = g_main_context_ref_thread_default ();
}

static void
on_iostream_closed (GObject *source,
                    GAsyncResult *result,
                    gpointer user_data)
{
	SoupWebsocketConnection *self = user_data;
	SoupWebsocketConnectionPrivate *pv = self->pv;
	GError *error = NULL;

	/* We treat connection as closed even if close fails */
	pv->io_closed = TRUE;
	g_io_stream_close_finish (pv->io_stream, result, &error);

	if (error) {
		g_debug ("error closing web socket stream: %s", error->message);
		if (!pv->dirty_close)
			g_signal_emit (self, signals[ERROR], 0, error);
		pv->dirty_close = TRUE;
		g_error_free (error);
	}

	g_assert (soup_websocket_connection_get_state (self) == SOUP_WEBSOCKET_STATE_CLOSED);
	g_debug ("closed: completed io stream close");
	g_signal_emit (self, signals[CLOSED], 0);

	g_object_unref (self);
}

static void
300 301 302 303 304 305 306 307 308 309 310 311 312 313
soup_websocket_connection_start_input_source (SoupWebsocketConnection *self)
{
	SoupWebsocketConnectionPrivate *pv = self->pv;

	if (pv->input_source)
		return;

	pv->input_source = g_pollable_input_stream_create_source (pv->input, NULL);
	g_source_set_callback (pv->input_source, (GSourceFunc)on_web_socket_input, self, NULL);
	g_source_attach (pv->input_source, pv->main_context);
}

static void
soup_websocket_connection_stop_input_source (SoupWebsocketConnection *self)
314 315 316 317 318 319 320 321 322 323 324 325
{
	SoupWebsocketConnectionPrivate *pv = self->pv;

	if (pv->input_source) {
		g_debug ("stopping input source");
		g_source_destroy (pv->input_source);
		g_source_unref (pv->input_source);
		pv->input_source = NULL;
	}
}

static void
326 327 328 329 330 331 332 333 334 335 336 337 338 339
soup_websocket_connection_start_output_source (SoupWebsocketConnection *self)
{
	SoupWebsocketConnectionPrivate *pv = self->pv;

	if (pv->output_source)
		return;

	pv->output_source = g_pollable_output_stream_create_source (pv->output, NULL);
	g_source_set_callback (pv->output_source, (GSourceFunc)on_web_socket_output, self, NULL);
	g_source_attach (pv->output_source, pv->main_context);
}

static void
soup_websocket_connection_stop_output_source (SoupWebsocketConnection *self)
340 341 342 343 344 345 346 347 348 349 350
{
	SoupWebsocketConnectionPrivate *pv = self->pv;

	if (pv->output_source) {
		g_debug ("stopping output source");
		g_source_destroy (pv->output_source);
		g_source_unref (pv->output_source);
		pv->output_source = NULL;
	}
}

351 352 353 354 355 356 357 358 359 360 361 362
static void
keepalive_stop_timeout (SoupWebsocketConnection *self)
{
	SoupWebsocketConnectionPrivate *pv = self->pv;

	if (pv->keepalive_timeout) {
		g_source_destroy (pv->keepalive_timeout);
		g_source_unref (pv->keepalive_timeout);
		pv->keepalive_timeout = NULL;
	}
}

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
static void
close_io_stop_timeout (SoupWebsocketConnection *self)
{
	SoupWebsocketConnectionPrivate *pv = self->pv;

	if (pv->close_timeout) {
		g_source_destroy (pv->close_timeout);
		g_source_unref (pv->close_timeout);
		pv->close_timeout = NULL;
	}
}

static void
close_io_stream (SoupWebsocketConnection *self)
{
	SoupWebsocketConnectionPrivate *pv = self->pv;

380
	keepalive_stop_timeout (self);
381 382 383
	close_io_stop_timeout (self);

	if (!pv->io_closing) {
384 385
		soup_websocket_connection_stop_input_source (self);
		soup_websocket_connection_stop_output_source (self);
386 387 388 389 390 391 392 393 394 395 396 397 398 399
		pv->io_closing = TRUE;
		g_debug ("closing io stream");
		g_io_stream_close_async (pv->io_stream, G_PRIORITY_DEFAULT,
					 NULL, on_iostream_closed, g_object_ref (self));
	}

	g_object_notify (G_OBJECT (self), "state");
}

static void
shutdown_wr_io_stream (SoupWebsocketConnection *self)
{
	SoupWebsocketConnectionPrivate *pv = self->pv;
	GSocket *socket;
400
	GIOStream *base_iostream;
401 402
	GError *error = NULL;

403
	soup_websocket_connection_stop_output_source (self);
404

405 406 407 408 409 410
	base_iostream = SOUP_IS_IO_STREAM (pv->io_stream) ?
		soup_io_stream_get_base_iostream (SOUP_IO_STREAM (pv->io_stream)) :
		pv->io_stream;

	if (G_IS_SOCKET_CONNECTION (base_iostream)) {
		socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (base_iostream));
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
		g_socket_shutdown (socket, FALSE, TRUE, &error);
		if (error != NULL) {
			g_debug ("error shutting down io stream: %s", error->message);
			g_error_free (error);
		}
	}

	g_object_notify (G_OBJECT (self), "state");
}

static gboolean
on_timeout_close_io (gpointer user_data)
{
	SoupWebsocketConnection *self = SOUP_WEBSOCKET_CONNECTION (user_data);
	SoupWebsocketConnectionPrivate *pv = self->pv;

	pv->close_timeout = 0;

	g_debug ("peer did not close io when expected");
	close_io_stream (self);

	return FALSE;
}

static void
close_io_after_timeout (SoupWebsocketConnection *self)
{
	SoupWebsocketConnectionPrivate *pv = self->pv;
	const int timeout = 5;

	if (pv->close_timeout)
		return;

	g_debug ("waiting %d seconds for peer to close io", timeout);
	pv->close_timeout = g_timeout_source_new_seconds (timeout);
	g_source_set_callback (pv->close_timeout, on_timeout_close_io, self, NULL);
	g_source_attach (pv->close_timeout, pv->main_context);
}

static void
xor_with_mask (const guint8 *mask,
	       guint8 *data,
	       gsize len)
{
	gsize n;

	/* Do the masking */
	for (n = 0; n < len; n++)
		data[n] ^= mask[n & 3];
}

static void
send_message (SoupWebsocketConnection *self,
	      SoupWebsocketQueueFlags flags,
	      guint8 opcode,
	      const guint8 *data,
	      gsize length)
{
469
	gsize buffered_amount;
470 471 472 473
	GByteArray *bytes;
	gsize frame_len;
	guint8 *outer;
	guint8 *mask = 0;
474
	guint at;
475 476 477
	GBytes *filtered_bytes;
	GList *l;
	GError *error = NULL;
478

479 480 481 482 483
	if (!(soup_websocket_connection_get_state (self) == SOUP_WEBSOCKET_STATE_OPEN)) {
		g_debug ("Ignoring message since the connection is closed or is closing");
		return;
	}

484 485 486 487
	bytes = g_byte_array_sized_new (14 + length);
	outer = bytes->data;
	outer[0] = 0x80 | opcode;

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
	filtered_bytes = g_bytes_new_static (data, length);
	for (l = self->pv->extensions; l != NULL; l = g_list_next (l)) {
		SoupWebsocketExtension *extension;

		extension = (SoupWebsocketExtension *)l->data;
		filtered_bytes = soup_websocket_extension_process_outgoing_message (extension, outer, filtered_bytes, &error);
		if (error) {
			emit_error_and_close (self, error, FALSE);
			return;
		}
	}

	data = g_bytes_get_data (filtered_bytes, &length);
	buffered_amount = length;

503
	/* If control message, check payload size */
504 505
	if (opcode & 0x08) {
		if (length > 125) {
506 507 508
			g_warning ("WebSocket control message payload exceeds size limit");
			protocol_error_and_close (self);
			return;
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
		}

		buffered_amount = 0;
	}

	if (length < 126) {
		outer[1] = (0xFF & length); /* mask | 7-bit-len */
		bytes->len = 2;
	} else if (length < 65536) {
		outer[1] = 126; /* mask | 16-bit-len */
		outer[2] = (length >> 8) & 0xFF;
		outer[3] = (length >> 0) & 0xFF;
		bytes->len = 4;
	} else {
		outer[1] = 127; /* mask | 64-bit-len */
Dan Winship's avatar
Dan Winship committed
524
#if GLIB_SIZEOF_SIZE_T > 4
525 526 527 528
		outer[2] = (length >> 56) & 0xFF;
		outer[3] = (length >> 48) & 0xFF;
		outer[4] = (length >> 40) & 0xFF;
		outer[5] = (length >> 32) & 0xFF;
Dan Winship's avatar
Dan Winship committed
529 530 531
#else
		outer[2] = outer[3] = outer[4] = outer[5] = 0;
#endif
532 533 534 535 536 537 538 539 540 541 542
		outer[6] = (length >> 24) & 0xFF;
		outer[7] = (length >> 16) & 0xFF;
		outer[8] = (length >> 8) & 0xFF;
		outer[9] = (length >> 0) & 0xFF;
		bytes->len = 10;
	}

	/* The server side doesn't need to mask, so we don't. There's
	 * probably a client somewhere that's not expecting it.
	 */
	if (self->pv->connection_type == SOUP_WEBSOCKET_CONNECTION_CLIENT) {
543
		guint32 rnd = g_random_int ();
544 545
		outer[1] |= 0x80;
		mask = outer + bytes->len;
546
		memcpy (mask, &rnd, sizeof (rnd));
547 548 549
		bytes->len += 4;
	}

550
	at = bytes->len;
551 552 553
	g_byte_array_append (bytes, data, length);

	if (self->pv->connection_type == SOUP_WEBSOCKET_CONNECTION_CLIENT)
554
		xor_with_mask (mask, bytes->data + at, length);
555 556 557 558

	frame_len = bytes->len;
	queue_frame (self, flags, g_byte_array_free (bytes, FALSE),
		     frame_len, buffered_amount);
559
	g_bytes_unref (filtered_bytes);
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
	g_debug ("queued %d frame of len %u", (int)opcode, (guint)frame_len);
}

static void
send_close (SoupWebsocketConnection *self,
	    SoupWebsocketQueueFlags flags,
	    gushort code,
	    const char *reason)
{
	/* Note that send_message truncates as expected */
	char buffer[128];
	gsize len = 0;

	if (code != 0) {
		buffer[len++] = code >> 8;
		buffer[len++] = code & 0xFF;
		if (reason)
			len += g_strlcpy (buffer + len, reason, sizeof (buffer) - len);
	}

	send_message (self, flags, 0x08, (guint8 *)buffer, len);
	self->pv->close_sent = TRUE;
582 583

	keepalive_stop_timeout (self);
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
}

static void
emit_error_and_close (SoupWebsocketConnection *self,
		      GError *error,
		      gboolean prejudice)
{
	gboolean ignore = FALSE;
	gushort code;

	if (soup_websocket_connection_get_state (self) == SOUP_WEBSOCKET_STATE_CLOSED) {
		g_error_free (error);
		return;
	}

	if (error && error->domain == SOUP_WEBSOCKET_ERROR)
		code = error->code;
	else
		code = SOUP_WEBSOCKET_CLOSE_GOING_AWAY;

	self->pv->dirty_close = TRUE;
	g_signal_emit (self, signals[ERROR], 0, error);
	g_error_free (error);

	/* If already closing, just ignore this stuff */
	switch (soup_websocket_connection_get_state (self)) {
	case SOUP_WEBSOCKET_STATE_CLOSED:
		ignore = TRUE;
		break;
	case SOUP_WEBSOCKET_STATE_CLOSING:
		ignore = !prejudice;
		break;
	default:
		break;
	}

	if (ignore) {
		g_debug ("already closing/closed, ignoring error");
	} else if (prejudice) {
		g_debug ("forcing close due to error");
		close_io_stream (self);
	} else {
		g_debug ("requesting close due to error");
		send_close (self, SOUP_WEBSOCKET_QUEUE_URGENT | SOUP_WEBSOCKET_QUEUE_LAST, code, NULL);
	}
}

static void
protocol_error_and_close_full (SoupWebsocketConnection *self,
                               gboolean prejudice)
{
	GError *error;

	error = g_error_new_literal (SOUP_WEBSOCKET_ERROR,
				     SOUP_WEBSOCKET_CLOSE_PROTOCOL_ERROR,
				     self->pv->connection_type == SOUP_WEBSOCKET_CONNECTION_SERVER ?
				     "Received invalid WebSocket response from the client" :
				     "Received invalid WebSocket response from the server");
	emit_error_and_close (self, error, prejudice);
}

static void
protocol_error_and_close (SoupWebsocketConnection *self)
{
	protocol_error_and_close_full (self, FALSE);
}

static void
bad_data_error_and_close (SoupWebsocketConnection *self)
{
	GError *error;

	error = g_error_new_literal (SOUP_WEBSOCKET_ERROR,
				     SOUP_WEBSOCKET_CLOSE_BAD_DATA,
				     self->pv->connection_type == SOUP_WEBSOCKET_CONNECTION_SERVER ?
				     "Received invalid WebSocket data from the client" :
				     "Received invalid WebSocket data from the server");
	emit_error_and_close (self, error, FALSE);
}

static void
too_big_error_and_close (SoupWebsocketConnection *self,
Dan Winship's avatar
Dan Winship committed
666
                         guint64 payload_len)
667 668 669 670 671 672 673 674
{
	GError *error;

	error = g_error_new_literal (SOUP_WEBSOCKET_ERROR,
				     SOUP_WEBSOCKET_CLOSE_TOO_BIG,
				     self->pv->connection_type == SOUP_WEBSOCKET_CONNECTION_SERVER ?
				     "Received extremely large WebSocket data from the client" :
				     "Received extremely large WebSocket data from the server");
675
	g_debug ("%s is trying to frame of size %" G_GUINT64_FORMAT " or greater, but max supported size is %" G_GUINT64_FORMAT,
676
		 self->pv->connection_type == SOUP_WEBSOCKET_CONNECTION_SERVER ? "server" : "client",
677
	         payload_len, self->pv->max_incoming_payload_size);
678 679 680
	emit_error_and_close (self, error, TRUE);
}

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
static void
close_connection (SoupWebsocketConnection *self,
                  gushort                  code,
                  const char              *data)
{
	SoupWebsocketQueueFlags flags;
	SoupWebsocketConnectionPrivate *pv;

	pv = self->pv;

	if (pv->close_sent) {
		g_debug ("close code already sent");
		return;
	}

	/* Validate the closing code received by the peer */
	switch (code) {
	case SOUP_WEBSOCKET_CLOSE_NORMAL:
	case SOUP_WEBSOCKET_CLOSE_GOING_AWAY:
	case SOUP_WEBSOCKET_CLOSE_PROTOCOL_ERROR:
	case SOUP_WEBSOCKET_CLOSE_UNSUPPORTED_DATA:
	case SOUP_WEBSOCKET_CLOSE_BAD_DATA:
	case SOUP_WEBSOCKET_CLOSE_POLICY_VIOLATION:
	case SOUP_WEBSOCKET_CLOSE_TOO_BIG:
		break;
	case SOUP_WEBSOCKET_CLOSE_NO_EXTENSION:
		if (pv->connection_type == SOUP_WEBSOCKET_CONNECTION_SERVER) {
			g_debug ("Wrong closing code %d received for a server connection",
			         code);
		}
711
		break;
712 713 714 715 716
	case SOUP_WEBSOCKET_CLOSE_SERVER_ERROR:
		if (pv->connection_type != SOUP_WEBSOCKET_CONNECTION_SERVER) {
			g_debug ("Wrong closing code %d received for a non server connection",
			         code);
		}
717
		break;
718 719 720 721
	case SOUP_WEBSOCKET_CLOSE_NO_STATUS:
		/* This is special case to send a close message with no body */
		code = 0;
		break;
722
	default:
Italo Guerrieri's avatar
Italo Guerrieri committed
723 724 725 726 727
		if (code < 3000) {
			g_debug ("Wrong closing code %d received", code);
			protocol_error_and_close (self);
			return;
		}
728 729 730 731 732 733 734 735
	}

	g_signal_emit (self, signals[CLOSING], 0);

	if (pv->close_received)
		g_debug ("responding to close request");

	flags = 0;
736
	if (pv->close_received)
737 738 739 740 741
		flags |= SOUP_WEBSOCKET_QUEUE_LAST;
	send_close (self, flags, code, data);
	close_io_after_timeout (self);
}

742 743 744 745 746 747 748 749 750 751 752 753
static void
receive_close (SoupWebsocketConnection *self,
	       const guint8 *data,
	       gsize len)
{
	SoupWebsocketConnectionPrivate *pv = self->pv;

	pv->peer_close_code = 0;
	g_free (pv->peer_close_data);
	pv->peer_close_data = NULL;
	pv->close_received = TRUE;

Italo Guerrieri's avatar
Italo Guerrieri committed
754 755 756
	switch (len) {
	case 0:
		/* Send a clean close when having an empty payload */
757
		pv->peer_close_code = SOUP_WEBSOCKET_CLOSE_NO_STATUS;
Italo Guerrieri's avatar
Italo Guerrieri committed
758 759 760 761 762 763 764 765
		close_connection (self, 1000, NULL);
		return;
	case 1:
		/* Send a protocol error since the close code is incomplete */
		protocol_error_and_close (self);
		return;
	default:
		/* Store the code/data payload */
766
		pv->peer_close_code = (guint16)data[0] << 8 | data[1];
Italo Guerrieri's avatar
Italo Guerrieri committed
767
		break;
768
	}
Italo Guerrieri's avatar
Italo Guerrieri committed
769

770 771 772
	if (len > 2) {
		data += 2;
		len -= 2;
773
		
774
		if (!utf8_validate ((const char *)data, len)) {
775
			g_debug ("received non-UTF8 close data: %d '%.*s' %d", (int)len, (int)len, (char *)data, (int)data[0]);
776 777 778 779 780
			protocol_error_and_close (self);
			return;
		}

		pv->peer_close_data = g_strndup ((char *)data, len);
781 782 783 784 785 786 787 788
	}

	/* Once we receive close response on server, close immediately */
	if (pv->close_sent) {
		shutdown_wr_io_stream (self);
		if (pv->connection_type == SOUP_WEBSOCKET_CONNECTION_SERVER)
			close_io_stream (self);
	} else {
Italo Guerrieri's avatar
Italo Guerrieri committed
789
		close_connection (self, pv->peer_close_code, pv->peer_close_data);
790 791 792 793 794 795 796 797 798 799 800 801 802
	}
}

static void
receive_ping (SoupWebsocketConnection *self,
                      const guint8 *data,
                      gsize len)
{
	/* Send back a pong with same data */
	g_debug ("received ping, responding");
	send_message (self, SOUP_WEBSOCKET_QUEUE_URGENT, 0x0A, data, len);
}

803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
static void
receive_pong (SoupWebsocketConnection *self,
                      const guint8 *data,
                      gsize len)
{
	GByteArray *bytes;

	g_debug ("received pong message");

	bytes = g_byte_array_sized_new (len + 1);
	g_byte_array_append (bytes, data, len);
	/* Always null terminate, as a convenience */
	g_byte_array_append (bytes, (guchar *)"\0", 1);
	/* But don't include the null terminator in the byte count */
	bytes->len--;

	g_signal_emit (self, signals[PONG], 0, bytes);
	g_byte_array_unref (bytes);

}

824 825 826 827 828
static void
process_contents (SoupWebsocketConnection *self,
		  gboolean control,
		  gboolean fin,
		  guint8 opcode,
829
		  GBytes *payload_data)
830 831 832
{
	SoupWebsocketConnectionPrivate *pv = self->pv;
	GBytes *message;
833 834 835 836
	gconstpointer payload;
	gsize payload_len;

	payload = g_bytes_get_data (payload_data, &payload_len);
837

838 839 840
	if (pv->close_sent && pv->close_received)
		return;

841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
	if (control) {
		/* Control frames must never be fragmented */
		if (!fin) {
			g_debug ("received fragmented control frame");
			protocol_error_and_close (self);
			return;
		}

		g_debug ("received control frame %d with %d payload", (int)opcode, (int)payload_len);

		switch (opcode) {
		case 0x08:
			receive_close (self, payload, payload_len);
			break;
		case 0x09:
			receive_ping (self, payload, payload_len);
			break;
		case 0x0A:
859
			receive_pong (self, payload, payload_len);
860 861 862
			break;
		default:
			g_debug ("received unsupported control frame: %d", (int)opcode);
Italo Guerrieri's avatar
Italo Guerrieri committed
863 864
			protocol_error_and_close (self);
			return;
865 866 867 868 869 870 871 872 873
		}
	} else if (pv->close_received) {
		g_debug ("received message after close was received");
	} else {
		/* A message frame */

		if (!fin && opcode) {
			/* Initial fragment of a message */
			if (pv->message_data) {
Isaac Jurado's avatar
Isaac Jurado committed
874
				g_debug ("received out of order initial message fragment");
875 876 877
				protocol_error_and_close (self);
				return;
			}
Isaac Jurado's avatar
Isaac Jurado committed
878
			g_debug ("received initial fragment frame %d with %d payload", (int)opcode, (int)payload_len);
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
		} else if (!fin && !opcode) {
			/* Middle fragment of a message */
			if (!pv->message_data) {
				g_debug ("received out of order middle message fragment");
				protocol_error_and_close (self);
				return;
			}
			g_debug ("received middle fragment frame with %d payload", (int)payload_len);
		} else if (fin && !opcode) {
			/* Last fragment of a message */
			if (!pv->message_data) {
				g_debug ("received out of order ending message fragment");
				protocol_error_and_close (self);
				return;
			}
			g_debug ("received last fragment frame with %d payload", (int)payload_len);
		} else {
			/* An unfragmented message */
			g_assert (opcode != 0);
			if (pv->message_data) {
				g_debug ("received unfragmented message when fragment was expected");
				protocol_error_and_close (self);
				return;
			}
			g_debug ("received frame %d with %d payload", (int)opcode, (int)payload_len);
		}

		if (opcode) {
			pv->message_opcode = opcode;
Dan Winship's avatar
Dan Winship committed
908
			pv->message_data = g_byte_array_sized_new (payload_len + 1);
909 910 911 912 913 914 915 916 917
		}

		switch (pv->message_opcode) {
		case 0x01:
		case 0x02:
			g_byte_array_append (pv->message_data, payload, payload_len);
			break;
		default:
			g_debug ("received unknown data frame: %d", (int)opcode);
Italo Guerrieri's avatar
Italo Guerrieri committed
918 919
			protocol_error_and_close (self);
			return;
920 921 922 923
		}

		/* Actually deliver the message? */
		if (fin) {
Italo Guerrieri's avatar
Italo Guerrieri committed
924
			if (pv->message_opcode == 0x01 &&
925 926
			    !utf8_validate((const char *)pv->message_data->data,
					   pv->message_data->len)) {
Italo Guerrieri's avatar
Italo Guerrieri committed
927 928 929 930 931 932 933 934 935 936 937 938

				g_debug ("received invalid non-UTF8 text data");

				/* Discard the entire message */
				g_byte_array_unref (pv->message_data);
				pv->message_data = NULL;
				pv->message_opcode = 0;

				bad_data_error_and_close (self);
				return;
			}

939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
			/* Always null terminate, as a convenience */
			g_byte_array_append (pv->message_data, (guchar *)"\0", 1);

			/* But don't include the null terminator in the byte count */
			pv->message_data->len--;

			opcode = pv->message_opcode;
			message = g_byte_array_free_to_bytes (pv->message_data);
			pv->message_data = NULL;
			pv->message_opcode = 0;
			g_debug ("message: delivering %d with %d length",
				 (int)opcode, (int)g_bytes_get_size (message));
			g_signal_emit (self, signals[MESSAGE], 0, (int)opcode, message);
			g_bytes_unref (message);
		}
	}
}

static gboolean
process_frame (SoupWebsocketConnection *self)
{
	guint8 *header;
	guint8 *payload;
	guint64 payload_len;
	guint8 *mask;
	gboolean fin;
	gboolean control;
	gboolean masked;
	guint8 opcode;
	gsize len;
	gsize at;
970 971 972
	GBytes *filtered_bytes;
	GList *l;
	GError *error = NULL;
973 974 975 976 977 978 979 980 981 982 983

	len = self->pv->incoming->len;
	if (len < 2)
		return FALSE; /* need more data */

	header = self->pv->incoming->data;
	fin = ((header[0] & 0x80) != 0);
	control = header[0] & 0x08;
	opcode = header[0] & 0x0f;
	masked = ((header[1] & 0x80) != 0);

984 985 986 987 988 989 990 991 992
	if (self->pv->connection_type == SOUP_WEBSOCKET_CONNECTION_CLIENT && masked) {
		/* A server MUST NOT mask any frames that it sends to the client.
		 * A client MUST close a connection if it detects a masked frame.
		 */
		g_debug ("A server must not mask any frames that it sends to the client.");
		protocol_error_and_close (self);
		return FALSE;
	}

993 994 995 996 997 998 999 1000 1001
	if (self->pv->connection_type == SOUP_WEBSOCKET_CONNECTION_SERVER && !masked) {
		/* The server MUST close the connection upon receiving a frame
		 * that is not masked.
		 */
		g_debug ("The client should always mask frames");
		protocol_error_and_close (self);
                return FALSE;
        }

1002 1003
	switch (header[1] & 0x7f) {
	case 126:
1004 1005 1006
		/* If 126, the following 2 bytes interpreted as a 16-bit
		 * unsigned integer are the payload length.
		 */
1007 1008 1009 1010 1011
		at = 4;
		if (len < at)
			return FALSE; /* need more data */
		payload_len = (((guint16)header[2] << 8) |
			       ((guint16)header[3] << 0));
1012 1013 1014 1015 1016 1017

		/* The minimal number of bytes MUST be used to encode the length. */
		if (payload_len <= 125) {
			protocol_error_and_close (self);
			return FALSE;
		}
1018 1019
		break;
	case 127:
1020 1021 1022 1023
		/* If 127, the following 8 bytes interpreted as a 64-bit
		 * unsigned integer (the most significant bit MUST be 0)
		 * are the payload length.
		 */
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
		at = 10;
		if (len < at)
			return FALSE; /* need more data */
		payload_len = (((guint64)header[2] << 56) |
			       ((guint64)header[3] << 48) |
			       ((guint64)header[4] << 40) |
			       ((guint64)header[5] << 32) |
			       ((guint64)header[6] << 24) |
			       ((guint64)header[7] << 16) |
			       ((guint64)header[8] << 8) |
			       ((guint64)header[9] << 0));
1035 1036 1037 1038 1039 1040

		/* The minimal number of bytes MUST be used to encode the length. */
		if (payload_len <= G_MAXUINT16) {
			protocol_error_and_close (self);
			return FALSE;
		}
1041 1042 1043 1044 1045 1046 1047 1048
		break;
	default:
		payload_len = header[1] & 0x7f;
		at = 2;
		break;
	}

	/* Safety valve */
1049 1050
	if (self->pv->max_incoming_payload_size > 0 &&
	    payload_len >= self->pv->max_incoming_payload_size) {
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
		too_big_error_and_close (self, payload_len);
		return FALSE;
	}

	if (len < at + payload_len)
		return FALSE; /* need more data */

	payload = header + at;

	if (masked) {
		mask = header + at;
		payload += 4;
		at += 4;

		if (len < at + payload_len)
			return FALSE; /* need more data */

		xor_with_mask (mask, payload, payload_len);
	}

1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
	filtered_bytes = g_bytes_new_static (payload, payload_len);
	for (l = self->pv->extensions; l != NULL; l = g_list_next (l)) {
		SoupWebsocketExtension *extension;

		extension = (SoupWebsocketExtension *)l->data;
		filtered_bytes = soup_websocket_extension_process_incoming_message (extension, self->pv->incoming->data, filtered_bytes, &error);
		if (error) {
			emit_error_and_close (self, error, FALSE);
			g_bytes_unref (filtered_bytes);

			return FALSE;
		}
	}

	/* After being processed by extensions reserved bits must be 0 */
	if (header[0] & 0x70) {
		protocol_error_and_close (self);
		g_bytes_unref (filtered_bytes);

		return FALSE;
	}

1093 1094 1095
	/* Note that now that we've unmasked, we've modified the buffer, we can
	 * only return below via discarding or processing the message
	 */
1096 1097
	process_contents (self, control, fin, opcode, filtered_bytes);
	g_bytes_unref (filtered_bytes);
1098 1099 1100

	/* Move past the parsed frame */
	g_byte_array_remove_range (self->pv->incoming, 0, at + payload_len);
1101

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
	return TRUE;
}

static void
process_incoming (SoupWebsocketConnection *self)
{
	while (process_frame (self))
		;
}

1112 1113
static void
soup_websocket_connection_read (SoupWebsocketConnection *self)
1114 1115 1116 1117 1118 1119 1120
{
	SoupWebsocketConnectionPrivate *pv = self->pv;
	GError *error = NULL;
	gboolean end = FALSE;
	gssize count;
	gsize len;

1121 1122
	soup_websocket_connection_stop_input_source (self);

1123 1124
	do {
		len = pv->incoming->len;
1125
		g_byte_array_set_size (pv->incoming, len + READ_BUFFER_SIZE);
1126 1127 1128

		count = g_pollable_input_stream_read_nonblocking (pv->input,
								  pv->incoming->data + len,
1129
								  READ_BUFFER_SIZE, NULL, &error);
1130 1131 1132 1133 1134 1135
		if (count < 0) {
			if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
				g_error_free (error);
				count = 0;
			} else {
				emit_error_and_close (self, error, TRUE);
1136
				return;
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
			}
		} else if (count == 0) {
			end = TRUE;
		}

		pv->incoming->len = len + count;
	} while (count > 0);

	process_incoming (self);

	if (end) {
		if (!pv->close_sent || !pv->close_received) {
			pv->dirty_close = TRUE;
			g_debug ("connection unexpectedly closed by peer");
		} else {
			g_debug ("peer has closed socket");
		}

		close_io_stream (self);
1156
		return;
1157 1158
	}

1159
	soup_websocket_connection_start_input_source (self);
1160 1161 1162
}

static gboolean
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
on_web_socket_input (GObject *pollable_stream,
		     gpointer user_data)
{
	soup_websocket_connection_read (SOUP_WEBSOCKET_CONNECTION (user_data));

	return G_SOURCE_REMOVE;
}

static void
soup_websocket_connection_write (SoupWebsocketConnection *self)
1173 1174 1175 1176 1177 1178 1179 1180
{
	SoupWebsocketConnectionPrivate *pv = self->pv;
	const guint8 *data;
	GError *error = NULL;
	Frame *frame;
	gssize count;
	gsize len;

1181 1182
	soup_websocket_connection_stop_output_source (self);

1183 1184
	if (soup_websocket_connection_get_state (self) == SOUP_WEBSOCKET_STATE_CLOSED) {
		g_debug ("Ignoring message since the connection is closed");
1185
		return;
1186 1187
	}

1188 1189 1190
	frame = g_queue_peek_head (&pv->outgoing);

	/* No more frames to send */
1191 1192
	if (frame == NULL)
		return;
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206

	data = g_bytes_get_data (frame->data, &len);
	g_assert (len > 0);
	g_assert (len > frame->sent);

	count = g_pollable_output_stream_write_nonblocking (pv->output,
							    data + frame->sent,
							    len - frame->sent,
							    NULL, &error);

	if (count < 0) {
		if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
			g_clear_error (&error);
			count = 0;
1207 1208 1209

			g_debug ("failed to send frame because it would block, marking as pending");
			frame->pending = TRUE;
1210 1211
		} else {
			emit_error_and_close (self, error, TRUE);
1212
			return;
1213 1214 1215 1216 1217 1218 1219 1220
		}
	}

	frame->sent += count;
	if (frame->sent >= len) {
		g_debug ("sent frame");
		g_queue_pop_head (&pv->outgoing);

Italo Guerrieri's avatar
Italo Guerrieri committed
1221
		if (frame->flags & SOUP_WEBSOCKET_QUEUE_LAST) {
1222 1223 1224 1225 1226 1227 1228 1229
			if (pv->connection_type == SOUP_WEBSOCKET_CONNECTION_SERVER) {
				close_io_stream (self);
			} else {
				shutdown_wr_io_stream (self);
				close_io_after_timeout (self);
			}
		}
		frame_free (frame);
1230 1231 1232

		if (g_queue_is_empty (&pv->outgoing))
			return;
1233 1234
	}

1235
	soup_websocket_connection_start_output_source (self);
1236 1237
}

1238 1239 1240
static gboolean
on_web_socket_output (GObject *pollable_stream,
		      gpointer user_data)
1241
{
1242
	soup_websocket_connection_write (SOUP_WEBSOCKET_CONNECTION (user_data));
1243

1244
	return G_SOURCE_REMOVE;
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
}

static void
queue_frame (SoupWebsocketConnection *self,
	     SoupWebsocketQueueFlags flags,
	     gpointer data,
	     gsize len,
	     gsize amount)
{
	SoupWebsocketConnectionPrivate *pv = self->pv;
	Frame *frame;

	g_return_if_fail (SOUP_IS_WEBSOCKET_CONNECTION (self));
	g_return_if_fail (pv->close_sent == FALSE);
	g_return_if_fail (data != NULL);
	g_return_if_fail (len > 0);

	frame = g_slice_new0 (Frame);
	frame->data = g_bytes_new_take (data, len);
	frame->amount = amount;
Italo Guerrieri's avatar
Italo Guerrieri committed
1265
	frame->flags = flags;
1266 1267 1268

	/* If urgent put at front of queue */
	if (flags & SOUP_WEBSOCKET_QUEUE_URGENT) {
Italo Guerrieri's avatar
Italo Guerrieri committed
1269 1270
		GList *l;

1271
		/* Find out the first frame that is not urgent or partially sent or pending */
Italo Guerrieri's avatar
Italo Guerrieri committed
1272 1273 1274 1275
		for (l = g_queue_peek_head_link (&pv->outgoing); l != NULL; l = l->next) {
			Frame *prev = l->data;

			if (!(prev->flags & SOUP_WEBSOCKET_QUEUE_URGENT) &&
1276
			    prev->sent == 0 && !prev->pending)
Italo Guerrieri's avatar
Italo Guerrieri committed
1277
				break;
1278
		}
Italo Guerrieri's avatar
Italo Guerrieri committed
1279 1280

		g_queue_insert_before (&pv->outgoing, l, frame);
1281 1282 1283 1284
	} else {
		g_queue_push_tail (&pv->outgoing, frame);
	}

1285
	soup_websocket_connection_write (self);
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
}

static void
soup_websocket_connection_constructed (GObject *object)
{
	SoupWebsocketConnection *self = SOUP_WEBSOCKET_CONNECTION (object);
	SoupWebsocketConnectionPrivate *pv = self->pv;
	GInputStream *is;
	GOutputStream *os;

	G_OBJECT_CLASS (soup_websocket_connection_parent_class)->constructed (object);

	g_return_if_fail (pv->io_stream != NULL);

	is = g_io_stream_get_input_stream (pv->io_stream);
	g_return_if_fail (G_IS_POLLABLE_INPUT_STREAM (is));
	pv->input = G_POLLABLE_INPUT_STREAM (is);
	g_return_if_fail (g_pollable_input_stream_can_poll (pv->input));

	os = g_io_stream_get_output_stream (pv->io_stream);
	g_return_if_fail (G_IS_POLLABLE_OUTPUT_STREAM (os));
	pv->output = G_POLLABLE_OUTPUT_STREAM (os);
	g_return_if_fail (g_pollable_output_stream_can_poll (pv->output));

1310
	soup_websocket_connection_start_input_source (self);
1311 1312 1313 1314 1315 1316 1317 1318 1319
}

static void
soup_websocket_connection_get_property (GObject *object,
					guint prop_id,
					GValue *value,
					GParamSpec *pspec)
{
	SoupWebsocketConnection *self = SOUP_WEBSOCKET_CONNECTION (object);
1320
	SoupWebsocketConnectionPrivate *pv = self->pv;
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346

	switch (prop_id) {
	case PROP_IO_STREAM:
		g_value_set_object (value, soup_websocket_connection_get_io_stream (self));
		break;

	case PROP_CONNECTION_TYPE:
		g_value_set_enum (value, soup_websocket_connection_get_connection_type (self));
		break;

	case PROP_URI:
		g_value_set_boxed (value, soup_websocket_connection_get_uri (self));
		break;

	case PROP_ORIGIN:
		g_value_set_string (value, soup_websocket_connection_get_origin (self));
		break;

	case PROP_PROTOCOL:
		g_value_set_string (value, soup_websocket_connection_get_protocol (self));
		break;

	case PROP_STATE:
		g_value_set_enum (value, soup_websocket_connection_get_state (self));
		break;

1347 1348 1349 1350
	case PROP_MAX_INCOMING_PAYLOAD_SIZE:
		g_value_set_uint64 (value, pv->max_incoming_payload_size);
		break;

1351 1352 1353 1354
	case PROP_KEEPALIVE_INTERVAL:
		g_value_set_uint (value, pv->keepalive_interval);
		break;

1355 1356 1357 1358
	case PROP_EXTENSIONS:
		g_value_set_pointer (value, pv->extensions);
		break;

1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

static void
soup_websocket_connection_set_property (GObject *object,
					guint prop_id,
					const GValue *value,
					GParamSpec *pspec)
{
	SoupWebsocketConnection *self = SOUP_WEBSOCKET_CONNECTION (object);
	SoupWebsocketConnectionPrivate *pv = self->pv;

	switch (prop_id) {
	case PROP_IO_STREAM:
		g_return_if_fail (pv->io_stream == NULL);
		pv->io_stream = g_value_dup_object (value);
		break;

	case PROP_CONNECTION_TYPE:
		pv->connection_type = g_value_get_enum (value);
		break;

	case PROP_URI:
		g_return_if_fail (pv->uri == NULL);
		pv->uri = g_value_dup_boxed (value);
		break;

	case PROP_ORIGIN:
		g_return_if_fail (pv->origin == NULL);
		pv->origin = g_value_dup_string (value);
		break;

	case PROP_PROTOCOL:
		g_return_if_fail (pv->protocol == NULL);
		pv->protocol = g_value_dup_string (value);
		break;

1399 1400 1401 1402
	case PROP_MAX_INCOMING_PAYLOAD_SIZE:
		pv->max_incoming_payload_size = g_value_get_uint64 (value);
		break;

1403 1404 1405 1406 1407
	case PROP_KEEPALIVE_INTERVAL:
		soup_websocket_connection_set_keepalive_interval (self,
		                                                  g_value_get_uint (value));
		break;

1408 1409 1410 1411
	case PROP_EXTENSIONS:
		pv->extensions = g_value_get_pointer (value);
		break;

1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

static void
soup_websocket_connection_dispose (GObject *object)
{
	SoupWebsocketConnection *self = SOUP_WEBSOCKET_CONNECTION (object);

	self->pv->dirty_close = TRUE;
	close_io_stream (self);

	G_OBJECT_CLASS (soup_websocket_connection_parent_class)->dispose (object);
}

static void
soup_websocket_connection_finalize (GObject *object)
{
	SoupWebsocketConnection *self = SOUP_WEBSOCKET_CONNECTION (object);
	SoupWebsocketConnectionPrivate *pv = self->pv;

	g_free (pv->peer_close_data);

	g_main_context_unref (pv->main_context);

	if (pv->incoming)
		g_byte_array_free (pv->incoming, TRUE);
	while (!g_queue_is_empty (&pv->outgoing))
		frame_free (g_queue_pop_head (&pv->outgoing));

	g_clear_object (&pv->io_stream);
	g_assert (!pv->input_source);
	g_assert (!pv->output_source);
	g_assert (pv->io_closing);
	g_assert (pv->io_closed);
	g_assert (!pv->close_timeout);
1450
	g_assert (!pv->keepalive_timeout);