Debian Codegraph @

src/ws/websocketconnection.c

raw
1 /*
2 * Copyright (C) 2013 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 #include "config.h"
7
8 #ifdef G_LOG_DOMAIN
9 #undef G_LOG_DOMAIN
10 #endif
11 #define G_LOG_DOMAIN "WebSocket"
12
13 #include "websocket.h"
14 #include "websocketprivate.h"
15
16 #include "cockpitflow.h"
17
18 #include <string.h>
19
20 /*
21 * SECTION:websocketconnection
22 * @title: WebSocketConnection
23 * @short_description: A WebSocket connection
24 *
25 * A #WebSocketConnection is a WebSocket connection to a peer. This API is modeled
26 * after the W3C API for interacting with WebSockets.
27 *
28 * Use the #WebSocketClient or #WebSocketServer derived classes on the
29 * appropriate sides. As a client, to connect to a Websocket server, use the
30 * web_socket_client_new() function. To handle a WebSocket connection from
31 * a client, you can use the web_socket_server_new_for_stream() function.
32 *
33 * The #WebSocketConnection:ready-state property will indicate the state of the
34 * connection. You can only send messages once the connection is in the
35 * %WEB_SOCKET_STATE_OPEN state. The #WebSocketConnection::open signal will fire
36 * when transitioning to this state.
37 *
38 * Use web_socket_connection_send() to send a message to the peer. When a
39 * message is received the #WebSocketConnection::message signal will fire.
40 *
41 * The web_socket_connection_close() function will perform an orderly close
42 * of the connection. The #WebSocketConnection::close signal will fire once
43 * the connection closes, whether it was initiated by this side or the peer.
44 *
45 * Connect to the #WebSocketConnection::closing signal to detect when either
46 * peer begins closing the connection. You can prevent closure of this side
47 * by returning %FALSE from the signal handler. You should in that case
48 * call the web_socket_connection_close() function at a later time to complete
49 * the close.
50 */
51
52 /**
53 * WebSocketConnection:
54 *
55 * An abstract base class representing a WebSocket connection. Use
56 * instances of the derived #WebSocketClient or #WebSocketServer classes.
57 */
58
59 /**
60 * WebSocketConnectionClass:
61 * @server_behavior: set by #WebSocketServer to %TRUE
62 * @handshake: used by derived classes to handle received HTTP handshake
63 * @open: default handler for the #WebSocketConnection::open signal
64 * @message: default handler for the #WebSocketConnection::message signal
65 * @error: default handler for the #WebSocketConnection::error signal
66 * @closing: the default handler for the #WebSocketConnection:closing signal
67 * @close: default handler for the #WebSocketConnection::close signal
68 *
69 * The abstract base class for #WebSocketConnection
70 */
71
72 enum {
73 PROP_0,
74 PROP_URL,
75 PROP_PROTOCOL,
76 PROP_READY_STATE,
77 PROP_BUFFERED_AMOUNT,
78 PROP_IO_STREAM,
79 };
80
81 enum {
82 OPEN,
83 MESSAGE,
84 ERROR,
85 CLOSING,
86 CLOSE,
87 NUM_SIGNALS
88 };
89
90 static guint signals[NUM_SIGNALS] = { 0, };
91
92 typedef struct {
93 GBytes *data;
94 gboolean last;
95 gsize sent;
96 gsize amount;
97 } Frame;
98
99 typedef struct
100 {
101 /* FALSE if client, TRUE if server */
102 gboolean server_side;
103
104 /*
105 * On the client this is the url we connect to,
106 * on the server, the one the socket lives at
107 */
108 gchar *url;
109 gchar *chosen_protocol;
110
111 GSource *start_idle;
112 gboolean handshake_done;
113
114 gushort peer_close_code;
115 gchar *peer_close_data;
116 gboolean close_sent;
117 gboolean close_received;
118 gboolean dirty_close;
119 GSource *close_timeout;
120
121 GMainContext *main_context;
122
123 GIOStream *io_stream;
124 gboolean io_open;
125 gboolean io_closed;
126
127 GPollableInputStream *input;
128 GSource *input_source;
129 GByteArray *incoming;
130
131 GPollableOutputStream *output;
132 GSource *output_source;
133 gsize output_queued;
134 GQueue outgoing;
135
136 /* Current message being assembled */
137 guint8 message_opcode;
138 GByteArray *message_data;
139
140 /* Pressure which throttles input on this web socket */
141 CockpitFlow *pressure;
142 gulong pressure_sig;
143 } WebSocketConnectionPrivate;
144
145 #define MAX_PAYLOAD 128 * 1024
146
147 /* The queue size above which we consider applying back pressure */
148 #define QUEUE_PRESSURE 1UL * 1024UL * 1024UL /* 1 megabyte */
149
150 static void web_socket_connection_flow_iface_init (CockpitFlowInterface *iface);
151
152 G_DEFINE_ABSTRACT_TYPE_WITH_CODE (WebSocketConnection, web_socket_connection, G_TYPE_OBJECT,
153 G_ADD_PRIVATE(WebSocketConnection)
154 G_IMPLEMENT_INTERFACE (COCKPIT_TYPE_FLOW, web_socket_connection_flow_iface_init));
155
156 #define GET_PRIV(self) ((WebSocketConnectionPrivate *) web_socket_connection_get_instance_private(self))
157
158 static void
159 frame_free (gpointer data)
160 {
161 Frame *frame = data;
162 if (frame)
163 {
164 g_bytes_unref (frame->data);
165 g_slice_free (Frame, frame);
166 }
167 }
168
169 static void
170 web_socket_connection_init (WebSocketConnection *self)
171 {
172 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
173
174 g_queue_init (&pv->outgoing);
175 pv->main_context = g_main_context_ref_thread_default ();
176 }
177
178 static void
179 on_iostream_closed (GObject *source,
180 GAsyncResult *result,
181 gpointer user_data)
182 {
183 WebSocketConnection *self = user_data;
184 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
185 GError *error = NULL;
186 gboolean unused;
187
188 /* We treat connection as closed even if close fails */
189 pv->io_closed = TRUE;
190 g_io_stream_close_finish (pv->io_stream, result, &error);
191
192 if (error)
193 {
194 g_message ("error closing web socket stream: %s", error->message);
195 if (!pv->dirty_close)
196 g_signal_emit (self, signals[ERROR], 0, error, &unused);
197 pv->dirty_close = TRUE;
198 g_error_free (error);
199 }
200
201 g_assert (web_socket_connection_get_ready_state (self) == WEB_SOCKET_STATE_CLOSED);
202 g_debug ("closed: completed io stream close");
203 g_signal_emit (self, signals[CLOSE], 0);
204
205 g_object_unref (self);
206 }
207
208 static void
209 stop_input (WebSocketConnection *self)
210 {
211 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
212
213 if (pv->input_source)
214 {
215 g_debug ("stopping input source");
216 g_source_destroy (pv->input_source);
217 g_source_unref (pv->input_source);
218 pv->input_source = NULL;
219 }
220 }
221
222 static void
223 stop_output (WebSocketConnection *self)
224 {
225 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
226
227 if (pv->output_source)
228 {
229 g_debug ("stopping output source");
230 g_source_destroy (pv->output_source);
231 g_source_unref (pv->output_source);
232 pv->output_source = NULL;
233 }
234 }
235
236 static void
237 close_io_stop_timeout (WebSocketConnection *self)
238 {
239 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
240
241 if (pv->close_timeout)
242 {
243 g_source_destroy (pv->close_timeout);
244 g_source_unref (pv->close_timeout);
245 pv->close_timeout = NULL;
246 }
247
248 if (pv->start_idle)
249 {
250 g_source_destroy (pv->start_idle);
251 g_source_unref (pv->start_idle);
252 pv->start_idle = NULL;
253 }
254 }
255
256 static void
257 close_io_stream (WebSocketConnection *self)
258 {
259 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
260
261 close_io_stop_timeout (self);
262
263 /* Close a connection that's not yet open */
264 if (!pv->io_stream && !pv->io_closed)
265 {
266 pv->io_closed = TRUE;
267 g_assert (web_socket_connection_get_ready_state (self) == WEB_SOCKET_STATE_CLOSED);
268 g_debug ("closed: no stream was opened");
269 g_signal_emit (self, signals[CLOSE], 0);
270 }
271
272 /* Close an open stream, which is not yet close_async'ing */
273 else if (pv->io_open)
274 {
275 stop_input (self);
276 stop_output (self);
277 pv->io_open = FALSE;
278 g_debug ("closing io stream");
279 g_io_stream_close_async (pv->io_stream, G_PRIORITY_DEFAULT,
280 NULL, on_iostream_closed, g_object_ref (self));
281 }
282
283 g_object_notify (G_OBJECT (self), "ready-state");
284 }
285
286 static void
287 shutdown_wr_io_stream (WebSocketConnection *self)
288 {
289 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
290 GSocket *socket;
291 GError *error = NULL;
292
293 stop_output (self);
294
295 if (G_IS_SOCKET_CONNECTION (pv->io_stream))
296 {
297 socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (pv->io_stream));
298 g_socket_shutdown (socket, FALSE, TRUE, &error);
299 if (error != NULL)
300 {
301 g_message ("error shutting down io stream: %s", error->message);
302 g_error_free (error);
303 }
304 }
305
306 g_object_notify (G_OBJECT (self), "ready-state");
307 }
308
309 static gboolean
310 on_timeout_close_io (gpointer user_data)
311 {
312 WebSocketConnection *self = WEB_SOCKET_CONNECTION (user_data);
313 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
314
315 pv->close_timeout = 0;
316 g_message ("peer did not close io when expected");
317
318 close_io_stream (self);
319
320 return FALSE;
321 }
322
323 static void
324 close_io_after_timeout (WebSocketConnection *self)
325 {
326 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
327 const gint timeout = 5;
328
329 if (pv->close_timeout)
330 return;
331
332 g_debug ("waiting %d seconds for peer to close io", timeout);
333 pv->close_timeout = g_timeout_source_new_seconds (timeout);
334 g_source_set_callback (pv->close_timeout, on_timeout_close_io, self, NULL);
335 g_source_attach (pv->close_timeout, pv->main_context);
336 }
337
338 static void
339 xor_with_mask_rfc6455 (const guint8 *mask,
340 guint8 *data,
341 gsize len)
342 {
343 g_assert (mask != NULL);
344 g_assert (data != NULL);
345
346 /* Do the masking */
347 for (gsize n = 0; n < len; n++)
348 data[n] ^= mask[n & 3];
349 }
350
351 static void
352 send_prefixed_message_rfc6455 (WebSocketConnection *self,
353 WebSocketQueueFlags flags,
354 guint8 opcode,
355 const guint8 *prefix,
356 gsize prefix_len,
357 const guint8 *payload,
358 gsize payload_len)
359 {
360 gsize amount;
361 GByteArray *bytes;
362 gsize frame_len;
363 guint8 *outer;
364 guint8 *mask = 0;
365 guint8 *at;
366 gsize len;
367 guint64 size;
368
369 len = payload_len + prefix_len;
370 amount = len;
371
372 bytes = g_byte_array_sized_new (14 + len);
373 outer = bytes->data;
374 outer[0] = 0x80 | opcode;
375
376 /* If control message, truncate payload */
377 if (opcode & 0x08)
378 {
379 if (len > 125)
380 {
381 g_warning ("Truncating WebSocket control message payload");
382 if (prefix_len > 125)
383 prefix_len = 125;
384 payload_len = 125 - prefix_len;
385 len = 125;
386 }
387
388 /* Buffered amount of bytes is zero for control messages */
389 amount = 0;
390 }
391
392 size = len;
393 if (size < 126)
394 {
395 outer[1] = (0xFF & size); /* mask | 7-bit-len */
396 bytes->len = 2;
397 }
398 else if (size < 65536)
399 {
400 outer[1] = 126; /* mask | 16-bit-len */
401 outer[2] = (size >> 8) & 0xFF;
402 outer[3] = (size >> 0) & 0xFF;
403 bytes->len = 4;
404 }
405 else
406 {
407 outer[1] = 127; /* mask | 64-bit-len */
408 outer[2] = (size >> 56) & 0xFF;
409 outer[3] = (size >> 48) & 0xFF;
410 outer[4] = (size >> 40) & 0xFF;
411 outer[5] = (size >> 32) & 0xFF;
412 outer[6] = (size >> 24) & 0xFF;
413 outer[7] = (size >> 16) & 0xFF;
414 outer[8] = (size >> 8) & 0xFF;
415 outer[9] = (size >> 0) & 0xFF;
416 bytes->len = 10;
417 }
418
419 /*
420 * The server side doesn't need to mask, so we don't. There's
421 * probably a client somewhere that's not expecting it.
422 */
423 const gboolean is_client_side = !GET_PRIV(self)->server_side;
424 if (is_client_side)
425 {
426 guint32 rand = g_random_int ();
427 outer[1] |= 0x80;
428 mask = outer + bytes->len;
429 memcpy (mask, &rand, sizeof (guint32));
430 bytes->len += 4;
431 }
432
433 at = bytes->data + bytes->len;
434 g_byte_array_append (bytes, prefix, prefix_len);
435 g_byte_array_append (bytes, payload, payload_len);
436
437 if (is_client_side)
438 xor_with_mask_rfc6455 (mask, at, len);
439
440 frame_len = bytes->len;
441 _web_socket_connection_queue (self, flags, g_byte_array_free (bytes, FALSE),
442 frame_len, amount);
443 g_debug ("queued rfc6455 %d frame of len %u", (gint)opcode, (guint)frame_len);
444 }
445
446 static void
447 send_message_rfc6455 (WebSocketConnection *self,
448 WebSocketQueueFlags flags,
449 guint8 opcode,
450 const guint8 *payload,
451 gsize payload_len)
452 {
453 return send_prefixed_message_rfc6455 (self, flags, opcode, NULL, 0, payload, payload_len);
454 }
455
456 static void
457 send_close_rfc6455 (WebSocketConnection *self,
458 WebSocketQueueFlags flags,
459 gushort code,
460 const gchar *reason)
461 {
462 /* Note that send_message truncates as expected */
463 gchar buffer[128];
464 gsize len = 0;
465
466 if (code != 0)
467 {
468 buffer[len++] = code >> 8;
469 buffer[len++] = code & 0xFF;
470 if (reason)
471 len += g_strlcpy (buffer + len, reason, sizeof (buffer) - len);
472 }
473
474 send_message_rfc6455 (self, flags, 0x08, (guint8 *)buffer, len);
475 GET_PRIV(self)->close_sent = TRUE;
476 }
477
478 gboolean
479 _web_socket_connection_error (WebSocketConnection *self,
480 GError *error)
481 {
482 gboolean unused;
483
484 if (web_socket_connection_get_ready_state (self) != WEB_SOCKET_STATE_CLOSED)
485 {
486 if (error)
487 {
488 GET_PRIV(self)->dirty_close = TRUE;
489 g_signal_emit (self, signals[ERROR], 0, error, &unused);
490 }
491
492 g_error_free (error);
493 return TRUE;
494 }
495
496 g_error_free (error);
497 return FALSE;
498 }
499
500 void
501 _web_socket_connection_error_and_close (WebSocketConnection *self,
502 GError *error,
503 gboolean prejudice)
504 {
505 gboolean ignore = FALSE;
506 gushort code;
507
508 if (error && error->domain == WEB_SOCKET_ERROR)
509 code = error->code;
510 else
511 code = WEB_SOCKET_CLOSE_GOING_AWAY;
512
513 if (!GET_PRIV(self)->server_side && error && error->domain == G_TLS_ERROR)
514 {
515 GET_PRIV(self)->peer_close_code = WEB_SOCKET_CLOSE_TLS_HANDSHAKE;
516 if (g_error_matches (error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS) ||
517 g_error_matches (error, G_TLS_ERROR, G_TLS_ERROR_MISC))
518 {
519 GET_PRIV(self)->peer_close_data = g_strdup ("protocol-error");
520 }
521 else if (g_error_matches (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE))
522 {
523 GET_PRIV(self)->peer_close_data = g_strdup ("unknown-hostkey");
524 }
525 }
526
527 if (!_web_socket_connection_error (self, error))
528 return;
529
530 if (!GET_PRIV(self)->handshake_done)
531 prejudice = TRUE;
532
533 /* If already closing, so just ignore this stuff */
534 switch (web_socket_connection_get_ready_state (self))
535 {
536 case WEB_SOCKET_STATE_CLOSED:
537 ignore = TRUE;
538 break;
539 case WEB_SOCKET_STATE_CLOSING:
540 ignore = !prejudice;
541 break;
542 default:
543 break;
544 }
545
546 if (ignore)
547 {
548 g_debug ("already closing/closed, ignoring error");
549 }
550 else if (prejudice)
551 {
552 g_debug ("forcing close due to error");
553 close_io_stream (self);
554 }
555 else
556 {
557 g_debug ("requesting close due to error");
558 send_close_rfc6455 (self, WEB_SOCKET_QUEUE_URGENT | WEB_SOCKET_QUEUE_LAST, code, NULL);
559 }
560 }
561
562 static void
563 protocol_error_and_close_full (WebSocketConnection *self,
564 gboolean prejudice)
565 {
566 GError *error = g_error_new_literal (WEB_SOCKET_ERROR,
567 WEB_SOCKET_CLOSE_PROTOCOL,
568 GET_PRIV(self)->server_side ?
569 "Received invalid WebSocket response from the server" :
570 "Received invalid WebSocket response from the client");
571 _web_socket_connection_error_and_close (self, error, prejudice);
572 }
573
574 static void
575 protocol_error_and_close (WebSocketConnection *self)
576 {
577 protocol_error_and_close_full (self, FALSE);
578 }
579
580 static void
581 bad_data_error_and_close (WebSocketConnection *self)
582 {
583 GError *error = g_error_new_literal (WEB_SOCKET_ERROR,
584 WEB_SOCKET_CLOSE_BAD_DATA,
585 GET_PRIV(self)->server_side ?
586 "Received invalid WebSocket data from the server" :
587 "Received invalid WebSocket data from the client");
588 _web_socket_connection_error_and_close (self, error, FALSE);
589 }
590
591 static void
592 too_big_error_and_close (WebSocketConnection *self,
593 gsize payload_len)
594 {
595 GError *error = g_error_new_literal (WEB_SOCKET_ERROR,
596 WEB_SOCKET_CLOSE_TOO_BIG,
597 GET_PRIV(self)->server_side ?
598 "Received extremely large WebSocket data from the server" :
599 "Received extremely large WebSocket data from the client");
600 g_message ("%s is trying to frame of size %" G_GSIZE_FORMAT " or greater, but max supported size is 128KiB",
601 GET_PRIV(self)->server_side ? "server" : "client", payload_len);
602 _web_socket_connection_error_and_close (self, error, TRUE);
603
604 /* The input is in an invalid state now */
605 stop_input (self);
606 }
607
608 static gboolean
609 web_socket_connection_default_error (WebSocketConnection *connection,
610 GError *error)
611 {
612 if (g_error_matches (error, G_TLS_ERROR, G_TLS_ERROR_EOF))
613 g_debug ("web socket error: %s", error->message);
614 else
615 g_message ("%s", error->message);
616 return TRUE;
617 }
618
619 static gboolean
620 web_socket_connection_default_closing (WebSocketConnection *self)
621 {
622 return TRUE;
623 }
624
625 static void
626 receive_close_rfc6455 (WebSocketConnection *self,
627 const guint8 *data,
628 gsize len)
629 {
630 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
631
632 pv->peer_close_code = 0;
633 g_free (pv->peer_close_data);
634 pv->peer_close_data = NULL;
635 pv->close_received = TRUE;
636
637 /* Store the code/data payload */
638 if (len >= 2)
639 {
640 pv->peer_close_code = (guint16)data[0] << 8 | data[1];
641 }
642 if (len > 2)
643 {
644 data += 2;
645 len -= 2;
646 if (g_utf8_validate ((gchar *)data, len, NULL))
647 pv->peer_close_data = g_strndup ((gchar *)data, len);
648 else
649 g_message ("received non-UTF8 close data: %d '%.*s' %d", (int)len, (int)len, (gchar *)data, (int)data[0]);
650 }
651
652 /* Once we receive close response on server, close immediately */
653 if (pv->close_sent)
654 {
655 shutdown_wr_io_stream (self);
656 if (pv->server_side)
657 close_io_stream (self);
658 }
659
660 else
661 {
662 /* Send back the response */
663 web_socket_connection_close (self, pv->peer_close_code, NULL);
664 }
665 }
666
667 static void
668 receive_ping_rfc6455 (WebSocketConnection *self,
669 const guint8 *data,
670 gsize len)
671 {
672 /* Send back a pong with same data */
673 g_debug ("received ping, responding");
674 send_message_rfc6455 (self, WEB_SOCKET_QUEUE_URGENT, 0x0A, data, len);
675 }
676
677 static void
678 process_contents_rfc6455 (WebSocketConnection *self,
679 gboolean control,
680 gboolean fin,
681 guint8 opcode,
682 gconstpointer payload,
683 gsize payload_len)
684 {
685 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
686 GBytes *message;
687
688 if (control)
689 {
690 /* Control frames must never be fragmented */
691 if (!fin)
692 {
693 g_message ("received fragmented control frame");
694 protocol_error_and_close (self);
695 return;
696 }
697
698 g_debug ("received control frame %d with %d payload", (int)opcode, (int)payload_len);
699
700 switch (opcode)
701 {
702 case 0x08:
703 receive_close_rfc6455 (self, payload, payload_len);
704 break;
705 case 0x09:
706 receive_ping_rfc6455 (self, payload, payload_len);
707 break;
708 case 0x0A:
709 break;
710 default:
711 g_message ("received unsupported control frame: %d", (gint)opcode);
712 break;
713 }
714 }
715
716 else if (pv->close_received)
717 {
718 g_message ("received message after close was received");
719 }
720
721 /* A message frame */
722 else
723 {
724 /* Initial fragment of a message */
725 if (!fin && opcode)
726 {
727 if (pv->message_data)
728 {
729 g_message ("received out of order initial message fragment");
730 protocol_error_and_close (self);
731 return;
732 }
733 g_debug ("received initial fragment frame %d with %d payload", (int)opcode, (int)payload_len);
734 }
735
736 /* Middle fragment of a message */
737 else if (!fin && !opcode)
738 {
739 if (!pv->message_data)
740 {
741 g_message ("received out of order middle message fragment");
742 protocol_error_and_close (self);
743 return;
744 }
745 g_debug ("received middle fragment frame with %d payload", (int)payload_len);
746 }
747
748 /* Last fragment of a message */
749 else if (fin && !opcode)
750 {
751 if (!pv->message_data)
752 {
753 g_message ("received out of order ending message fragment");
754 protocol_error_and_close (self);
755 return;
756 }
757 g_debug ("received last fragment frame with %d payload", (int)payload_len);
758 }
759
760 /* An unfragmented message */
761 else
762 {
763 g_assert (opcode != 0);
764 if (pv->message_data)
765 {
766 g_message ("received unfragmented message when fragment was expected");
767 protocol_error_and_close (self);
768 return;
769 }
770 g_debug ("received frame %d with %d payload", (int)opcode, (int)payload_len);
771 }
772
773 if (opcode)
774 {
775 pv->message_opcode = opcode;
776 pv->message_data = g_byte_array_sized_new (payload_len);
777 }
778
779 switch (pv->message_opcode)
780 {
781 case 0x01:
782 if (!g_utf8_validate ((gchar *)payload, payload_len, NULL))
783 {
784 g_message ("received invalid non-UTF8 text data");
785
786 /* Discard the entire message */
787 g_byte_array_unref (pv->message_data);
788 pv->message_data = NULL;
789 pv->message_opcode = 0;
790
791 bad_data_error_and_close (self);
792 return;
793 }
794 /* fall through */
795 case 0x02:
796 g_byte_array_append (pv->message_data, payload, payload_len);
797 break;
798 default:
799 g_debug ("received unknown data frame: %d", (gint)opcode);
800 break;
801 }
802
803 /* Actually deliver the message? */
804 if (fin)
805 {
806 /* Always null terminate, as a convenience */
807 g_byte_array_append (pv->message_data, (guchar *)"\0", 1);
808
809 /* But don't include the null terminator in the byte count */
810 pv->message_data->len--;
811
812 opcode = pv->message_opcode;
813 message = g_byte_array_free_to_bytes (pv->message_data);
814 pv->message_data = NULL;
815 pv->message_opcode = 0;
816 g_debug ("message: delivering %d with %d length",
817 (int)opcode, (int)g_bytes_get_size (message));
818 g_signal_emit (self, signals[MESSAGE], 0, (int)opcode, message);
819 g_bytes_unref (message);
820 }
821 }
822 }
823
824 static gboolean
825 process_frame_rfc6455 (WebSocketConnection *self)
826 {
827 guint8 *header;
828 guint8 *payload;
829 guint64 payload_len;
830 guint8 *mask;
831 gboolean fin;
832 gboolean control;
833 gboolean masked;
834 guint8 opcode;
835 gsize len;
836 gsize at;
837
838 len = GET_PRIV(self)->incoming->len;
839 if (len < 2)
840 return FALSE; /* need more data */
841
842 header = GET_PRIV(self)->incoming->data;
843 fin = ((header[0] & 0x80) != 0);
844 control = header[0] & 0x08;
845 opcode = header[0] & 0x0f;
846 masked = ((header[1] & 0x80) != 0);
847
848 switch (header[1] & 0x7f)
849 {
850 case 126:
851 at = 4;
852 if (len < at)
853 return FALSE; /* need more data */
854 payload_len = ((guint16)header[2] << 8) |
855 ((guint16)header[3] << 0);
856 break;
857 case 127:
858 at = 10;
859 if (len < at)
860 return FALSE; /* need more data */
861 payload_len = ((guint64)header[2] << 56) |
862 ((guint64)header[3] << 48) |
863 ((guint64)header[4] << 40) |
864 ((guint64)header[5] << 32) |
865 ((guint64)header[6] << 24) |
866 ((guint64)header[7] << 16) |
867 ((guint64)header[8] << 8) |
868 ((guint64)header[9] << 0);
869 break;
870 default:
871 payload_len = header[1] & 0x7f;
872 at = 2;
873 break;
874 }
875
876 /* Safety valve */
877 if (payload_len >= MAX_PAYLOAD)
878 {
879 too_big_error_and_close (self, payload_len);
880 return FALSE;
881 }
882
883 if (len < at + payload_len)
884 return FALSE; /* need more data */
885
886 payload = header + at;
887
888 if (masked)
889 {
890 mask = header + at;
891 payload += 4;
892 at += 4;
893
894 if (len < at + payload_len)
895 return FALSE; /* need more data */
896
897 xor_with_mask_rfc6455 (mask, payload, payload_len);
898 }
899
900 /*
901 * Note that now that we've unmasked, we've modified the buffer, we can
902 * only return below via discarding or processing the message
903 */
904 process_contents_rfc6455 (self, control, fin, opcode, payload, payload_len);
905
906 /* Move past the parsed frame */
907 g_byte_array_remove_range (GET_PRIV(self)->incoming, 0, at + payload_len);
908 return TRUE;
909 }
910
911 static void
912 process_incoming (WebSocketConnection *self)
913 {
914 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
915 WebSocketConnectionClass *klass;
916 gboolean more;
917
918 if (!pv->handshake_done)
919 {
920 klass = WEB_SOCKET_CONNECTION_GET_CLASS (self);
921 g_assert (klass->handshake != NULL);
922 if ((klass->handshake) (self, pv->incoming))
923 {
924 pv->handshake_done = TRUE;
925 g_object_notify (G_OBJECT (self), "ready-state");
926 g_signal_emit (self, signals[OPEN], 0);
927 }
928 }
929
930 if (pv->handshake_done)
931 {
932 do
933 {
934 more = process_frame_rfc6455 (self);
935 }
936 while (more);
937 }
938 }
939
940 static gboolean
941 on_web_socket_input (GObject *pollable_stream,
942 gpointer user_data)
943 {
944 WebSocketConnection *self = WEB_SOCKET_CONNECTION (user_data);
945 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
946 GError *error = NULL;
947 gboolean end = FALSE;
948 gssize count;
949 gsize len;
950
951 do
952 {
953 len = pv->incoming->len;
954 g_byte_array_set_size (pv->incoming, len + 1024);
955
956 count = g_pollable_input_stream_read_nonblocking (pv->input,
957 pv->incoming->data + len,
958 1024, NULL, &error);
959
960 if (count < 0)
961 {
962 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
963 {
964 g_error_free (error);
965 count = 0;
966 }
967 else
968 {
969 _web_socket_connection_error_and_close (self, error, TRUE);
970 return TRUE;
971 }
972 }
973 else if (count == 0)
974 {
975 end = TRUE;
976 }
977
978 pv->incoming->len = len + count;
979 }
980 while (count > 0);
981
982 process_incoming (self);
983
984 if (end)
985 {
986 if (!pv->close_sent || !pv->close_received)
987 {
988 pv->dirty_close = TRUE;
989 g_message ("connection unexpectedly closed by peer");
990 }
991 else
992 {
993 g_debug ("peer has closed socket");
994 }
995
996 close_io_stream (self);
997 }
998
999 return TRUE;
1000 }
1001
1002 static void
1003 start_input (WebSocketConnection *self)
1004 {
1005 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
1006
1007 g_debug ("starting input source");
1008 pv->input_source = g_pollable_input_stream_create_source (pv->input, NULL);
1009 g_source_set_callback (pv->input_source, (GSourceFunc)on_web_socket_input, self, NULL);
1010 g_source_attach (pv->input_source, pv->main_context);
1011 }
1012
1013 static gboolean
1014 on_web_socket_output (GObject *pollable_stream,
1015 gpointer user_data)
1016 {
1017 WebSocketConnection *self = WEB_SOCKET_CONNECTION (user_data);
1018 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
1019 const guint8 *data;
1020 GError *error = NULL;
1021 gsize before;
1022 Frame *frame;
1023 gssize count;
1024 gsize len;
1025
1026 frame = g_queue_peek_head (&pv->outgoing);
1027
1028 /* No more frames to send */
1029 if (frame == NULL)
1030 {
1031 stop_output (self);
1032 return TRUE;
1033 }
1034
1035 data = g_bytes_get_data (frame->data, &len);
1036 g_assert (len > 0);
1037 g_assert (len > frame->sent);
1038
1039 count = g_pollable_output_stream_write_nonblocking (pv->output,
1040 data + frame->sent,
1041 len - frame->sent,
1042 NULL, &error);
1043
1044 if (count < 0)
1045 {
1046 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1047 {
1048 g_clear_error (&error);
1049 count = 0;
1050 }
1051 else
1052 {
1053 _web_socket_connection_error_and_close (self, error, TRUE);
1054 return FALSE;
1055 }
1056 }
1057
1058 before = pv->output_queued;
1059
1060 frame->sent += count;
1061 if (frame->sent >= len)
1062 {
1063 g_debug ("sent frame");
1064 g_queue_pop_head (&pv->outgoing);
1065 g_assert (len <= pv->output_queued);
1066 pv->output_queued -= len;
1067
1068 if (frame->last)
1069 {
1070 if (pv->server_side)
1071 {
1072 close_io_stream (self);
1073 }
1074 else
1075 {
1076 shutdown_wr_io_stream (self);
1077 close_io_after_timeout (self);
1078 }
1079 }
1080 frame_free (frame);
1081 }
1082
1083 /*
1084 * If we're controlling another flow, turn off back pressure when
1085 * our output buffer size becomes less than the low mark.
1086 */
1087 if (before >= QUEUE_PRESSURE && GET_PRIV(self)->output_queued < QUEUE_PRESSURE)
1088 cockpit_flow_emit_pressure (COCKPIT_FLOW (self), FALSE);
1089
1090 return TRUE;
1091 }
1092
1093 static void
1094 start_output (WebSocketConnection *self)
1095 {
1096 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
1097
1098 if (pv->output_source)
1099 return;
1100
1101 g_debug ("starting output source");
1102 pv->output_source = g_pollable_output_stream_create_source (pv->output, NULL);
1103 g_source_set_callback (pv->output_source, (GSourceFunc)on_web_socket_output, self, NULL);
1104 g_source_attach (pv->output_source, pv->main_context);
1105 }
1106
1107 void
1108 _web_socket_connection_queue (WebSocketConnection *self,
1109 WebSocketQueueFlags flags,
1110 gpointer data,
1111 gsize len,
1112 gsize amount)
1113 {
1114 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
1115 gsize before;
1116 Frame *frame;
1117 Frame *prev;
1118
1119 g_return_if_fail (WEB_SOCKET_IS_CONNECTION (self));
1120 g_return_if_fail (pv->close_sent == FALSE);
1121 g_return_if_fail (data != NULL);
1122 g_return_if_fail (len > 0);
1123
1124 frame = g_slice_new0 (Frame);
1125 frame->data = g_bytes_new_take (data, len);
1126 frame->amount = amount;
1127 frame->last = (flags & WEB_SOCKET_QUEUE_LAST) ? TRUE : FALSE;
1128
1129 /* If urgent put at front of queue */
1130 if (flags & WEB_SOCKET_QUEUE_URGENT)
1131 {
1132 /* But we can't interrupt a message already partially sent */
1133 prev = g_queue_pop_head (&pv->outgoing);
1134 if (prev == NULL)
1135 {
1136 g_queue_push_head (&pv->outgoing, frame);
1137 }
1138 else if (prev->sent > 0)
1139 {
1140 g_queue_push_head (&pv->outgoing, frame);
1141 g_queue_push_head (&pv->outgoing, prev);
1142 }
1143 else
1144 {
1145 g_queue_push_head (&pv->outgoing, prev);
1146 g_queue_push_head (&pv->outgoing, frame);
1147 }
1148 }
1149 else
1150 {
1151 g_queue_push_tail (&pv->outgoing, frame);
1152 }
1153
1154 before = pv->output_queued;
1155 g_return_if_fail (G_MAXSIZE - len > pv->output_queued);
1156 pv->output_queued += len;
1157
1158 /*
1159 * If we have two much data queued, and are controlling another flow
1160 * tell it to stop sending data, each time we cross over the high bound.
1161 */
1162 if (before < QUEUE_PRESSURE && GET_PRIV(self)->output_queued >= QUEUE_PRESSURE)
1163 cockpit_flow_emit_pressure (COCKPIT_FLOW (self), TRUE);
1164
1165 start_output (self);
1166 }
1167
1168 static gboolean
1169 check_streams (WebSocketConnection *self)
1170 {
1171 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
1172
1173 if (!pv->input || !g_pollable_input_stream_can_poll (pv->input))
1174 {
1175 g_critical ("WebSocket input stream is invalid or cannot poll");
1176 return FALSE;
1177 }
1178
1179 if (!pv->output || !g_pollable_output_stream_can_poll (pv->output))
1180 {
1181 g_critical ("WebSocket output stream is invalid or cannot poll");
1182 return FALSE;
1183 }
1184
1185 return TRUE;
1186 }
1187
1188 void
1189 _web_socket_connection_take_incoming (WebSocketConnection *self,
1190 GByteArray *input_buffer)
1191 {
1192 g_return_if_fail (WEB_SOCKET_IS_CONNECTION (self));
1193
1194 g_return_if_fail (GET_PRIV(self)->incoming == NULL);
1195 GET_PRIV(self)->incoming = input_buffer;
1196 }
1197
1198 static gboolean
1199 on_idle_start_input (gpointer user_data)
1200 {
1201 WebSocketConnection *self = WEB_SOCKET_CONNECTION (user_data);
1202
1203 g_source_unref (GET_PRIV(self)->start_idle);
1204 GET_PRIV(self)->start_idle = NULL;
1205
1206 if (check_streams (self))
1207 {
1208 start_input (self);
1209 process_incoming (self);
1210 }
1211
1212 return FALSE;
1213 }
1214
1215 void
1216 _web_socket_connection_take_io_stream (WebSocketConnection *self,
1217 GIOStream *io_stream)
1218 {
1219 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
1220 GInputStream *is;
1221 GOutputStream *os;
1222
1223 g_return_if_fail (WEB_SOCKET_IS_CONNECTION (self));
1224 g_return_if_fail (G_IS_IO_STREAM (io_stream));
1225
1226 g_return_if_fail (pv->io_stream == NULL);
1227 pv->io_stream = io_stream;
1228
1229 is = g_io_stream_get_input_stream (io_stream);
1230 os = g_io_stream_get_output_stream (io_stream);
1231
1232 if (G_IS_POLLABLE_INPUT_STREAM (is))
1233 pv->input = G_POLLABLE_INPUT_STREAM (is);
1234 if (G_IS_POLLABLE_OUTPUT_STREAM (os))
1235 pv->output = G_POLLABLE_OUTPUT_STREAM (os);
1236
1237 pv->io_open = TRUE;
1238 g_object_notify (G_OBJECT (self), "io-stream");
1239
1240 /* Start handshake from the main context */
1241 pv->start_idle = g_idle_source_new ();
1242 g_source_set_priority (pv->start_idle, G_PRIORITY_HIGH);
1243 g_source_set_callback (pv->start_idle, (GSourceFunc)on_idle_start_input,
1244 g_object_ref (self), g_object_unref);
1245 g_source_attach (pv->start_idle, pv->main_context);
1246 }
1247
1248 static void
1249 web_socket_connection_constructed (GObject *object)
1250 {
1251 WebSocketConnection *self = WEB_SOCKET_CONNECTION (object);
1252 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
1253 WebSocketConnectionClass *klass;
1254
1255 G_OBJECT_CLASS (web_socket_connection_parent_class)->constructed (object);
1256
1257 /*
1258 * Here we choose a side to be based on our derived class. The handshake
1259 * is different on either client/server side, as is the expectation of
1260 * how to mask data.
1261 */
1262 klass = WEB_SOCKET_CONNECTION_GET_CLASS (self);
1263 pv->server_side = klass->server_behavior;
1264
1265 if (!pv->incoming)
1266 pv->incoming = g_byte_array_sized_new (1024);
1267 }
1268
1269 static void
1270 web_socket_connection_get_property (GObject *object,
1271 guint prop_id,
1272 GValue *value,
1273 GParamSpec *pspec)
1274 {
1275 WebSocketConnection *self = WEB_SOCKET_CONNECTION (object);
1276
1277 switch (prop_id)
1278 {
1279 case PROP_URL:
1280 g_value_set_string (value, web_socket_connection_get_url (self));
1281 break;
1282
1283 case PROP_PROTOCOL:
1284 g_value_set_string (value, web_socket_connection_get_protocol (self));
1285 break;
1286
1287 case PROP_READY_STATE:
1288 g_value_set_int (value, web_socket_connection_get_ready_state (self));
1289 break;
1290
1291 case PROP_BUFFERED_AMOUNT:
1292 g_value_set_ulong (value, web_socket_connection_get_buffered_amount (self));
1293 break;
1294
1295 case PROP_IO_STREAM:
1296 g_value_set_object (value, web_socket_connection_get_io_stream (self));
1297 break;
1298
1299 default:
1300 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1301 break;
1302 }
1303 }
1304
1305 static void
1306 web_socket_connection_set_property (GObject *object,
1307 guint prop_id,
1308 const GValue *value,
1309 GParamSpec *pspec)
1310 {
1311 WebSocketConnection *self = WEB_SOCKET_CONNECTION (object);
1312 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
1313 GIOStream *io_stream;
1314
1315 switch (prop_id)
1316 {
1317 case PROP_URL:
1318 g_return_if_fail (pv->url == NULL);
1319 pv->url = g_value_dup_string (value);
1320 break;
1321
1322 case PROP_IO_STREAM:
1323 g_return_if_fail (pv->io_stream == NULL);
1324 io_stream = g_value_dup_object (value);
1325 if (io_stream)
1326 _web_socket_connection_take_io_stream (self, io_stream);
1327 break;
1328
1329 default:
1330 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1331 break;
1332 }
1333 }
1334
1335 static void
1336 web_socket_connection_dispose (GObject *object)
1337 {
1338 WebSocketConnection *self = WEB_SOCKET_CONNECTION (object);
1339
1340 GET_PRIV(self)->dirty_close = TRUE;
1341 close_io_stream (self);
1342
1343 cockpit_flow_throttle (COCKPIT_FLOW (self), NULL);
1344 g_assert (GET_PRIV(self)->pressure == NULL);
1345
1346 G_OBJECT_CLASS (web_socket_connection_parent_class)->dispose (object);
1347 }
1348
1349 static void
1350 web_socket_connection_finalize (GObject *object)
1351 {
1352 WebSocketConnection *self = WEB_SOCKET_CONNECTION (object);
1353 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
1354
1355 g_free (pv->url);
1356 g_free (pv->chosen_protocol);
1357 g_free (pv->peer_close_data);
1358
1359 g_main_context_unref (pv->main_context);
1360
1361 if (pv->incoming)
1362 g_byte_array_free (pv->incoming, TRUE);
1363 while (!g_queue_is_empty (&pv->outgoing))
1364 frame_free (g_queue_pop_head (&pv->outgoing));
1365 pv->output_queued = 0;
1366
1367 g_clear_object (&pv->io_stream);
1368 g_assert (!pv->input_source);
1369 g_assert (!pv->output_source);
1370 g_assert (!pv->io_open);
1371 g_assert (pv->io_closed);
1372 g_assert (!pv->close_timeout);
1373
1374 if (pv->start_idle)
1375 g_source_unref (pv->start_idle);
1376 if (pv->message_data)
1377 g_byte_array_free (pv->message_data, TRUE);
1378
1379 G_OBJECT_CLASS (web_socket_connection_parent_class)->finalize (object);
1380 }
1381
1382 static void
1383 web_socket_connection_class_init (WebSocketConnectionClass *klass)
1384 {
1385 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1386
1387 gobject_class->constructed = web_socket_connection_constructed;
1388 gobject_class->get_property = web_socket_connection_get_property;
1389 gobject_class->set_property = web_socket_connection_set_property;
1390 gobject_class->dispose = web_socket_connection_dispose;
1391 gobject_class->finalize = web_socket_connection_finalize;
1392
1393 /**
1394 * WebSocketConnection:url:
1395 *
1396 * The URL of the WebSocket.
1397 *
1398 * For servers this represents the address of the WebSocket, and
1399 * for clients it is the address connected to. This is required
1400 * as a construct property.
1401 */
1402 g_object_class_install_property (gobject_class, PROP_URL,
1403 g_param_spec_string ("url", "URL", "The WebSocket URL", NULL,
1404 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
1405
1406 /**
1407 * WebSocketConnection:protocol:
1408 *
1409 * The chosen protocol. Only becomes valid after the #WebSocketConnection:open
1410 * signal has been fired, and when we are in the %WEB_SOCKET_STATE_OPEN state.
1411 *
1412 * May be NULL if neither peer cares about protocols.
1413 */
1414 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
1415 g_param_spec_string ("protocol", "Protocol", "The chosen WebSocket protocol", NULL,
1416 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1417
1418 /**
1419 * WebSocketConnection:ready-state:
1420 *
1421 * The current state of the WebSocket.
1422 */
1423 g_object_class_install_property (gobject_class, PROP_READY_STATE,
1424 g_param_spec_int ("ready-state", "Ready state", "Ready state ",
1425 WEB_SOCKET_STATE_CONNECTING, WEB_SOCKET_STATE_CLOSED, WEB_SOCKET_STATE_CONNECTING,
1426 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1427
1428 /**
1429 * WebSocketConnection:buffered-amount:
1430 *
1431 * This represents caller provided data passed into the
1432 * web_socket_connection_send() function, which has been queued but not
1433 * yet been sent.
1434 */
1435 g_object_class_install_property (gobject_class, PROP_BUFFERED_AMOUNT,
1436 g_param_spec_ulong ("buffered-amount", "Buffered amount", "Outstanding amount of data buffered",
1437 0, G_MAXULONG, 0,
1438 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1439
1440 /**
1441 * WebSocketConnection:io-stream:
1442 *
1443 * The underlying IO stream the WebSocket is communicating over. For servers
1444 * this must be specified as a construct property. For clients, this may be
1445 * specified, if you have a stream that you've already connected to.
1446 *
1447 * The input and output streams must be pollable streams.
1448 */
1449 g_object_class_install_property (gobject_class, PROP_IO_STREAM,
1450 g_param_spec_object ("io-stream", "IO Stream", "Underlying io stream", G_TYPE_IO_STREAM,
1451 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
1452
1453 /**
1454 * WebSocketConnection::open:
1455 * @self: the WebSocket
1456 *
1457 * Emitted when the connection opens and is ready for communication.
1458 *
1459 * This will be emitted at most once. But if the connection fails during
1460 * connecting, then this signal will not be emitted.
1461 */
1462 signals[OPEN] = g_signal_new ("open",
1463 WEB_SOCKET_TYPE_CONNECTION,
1464 G_SIGNAL_RUN_FIRST,
1465 G_STRUCT_OFFSET (WebSocketConnectionClass, open),
1466 NULL, NULL, g_cclosure_marshal_generic,
1467 G_TYPE_NONE, 0);
1468
1469 /**
1470 * WebSocketConnection::message:
1471 * @self: the WebSocket
1472 * @type: the type of message contents
1473 * @message: the message data
1474 *
1475 * Emitted when we receive a message from the peer.
1476 *
1477 * As a convenience, the @message data will always be null-terminated, but
1478 * the null-terminator will not be included in the length count.
1479 * This signal may emitted multiple times.
1480 */
1481 signals[MESSAGE] = g_signal_new ("message",
1482 WEB_SOCKET_TYPE_CONNECTION,
1483 G_SIGNAL_RUN_FIRST,
1484 G_STRUCT_OFFSET (WebSocketConnectionClass, message),
1485 NULL, NULL, g_cclosure_marshal_generic,
1486 G_TYPE_NONE, 2, G_TYPE_INT, G_TYPE_BYTES);
1487
1488 /**
1489 * WebSocketConnection::error:
1490 * @self: the WebSocket
1491 * @error: the error that occurred
1492 *
1493 * Emitted when an error occurred on the WebSocket. This may be fired
1494 * multiple times. Fatal errors will be followed by the #WebSocketConnection::close
1495 * signal being emitted.
1496 */
1497 signals[ERROR] = g_signal_new ("error",
1498 WEB_SOCKET_TYPE_CONNECTION,
1499 G_SIGNAL_RUN_LAST,
1500 G_STRUCT_OFFSET (WebSocketConnectionClass, error),
1501 g_signal_accumulator_true_handled, NULL,
1502 g_cclosure_marshal_generic,
1503 G_TYPE_BOOLEAN, 1, G_TYPE_ERROR);
1504
1505 /**
1506 * WebSocketConnection::closing:
1507 * @self: the WebSocket
1508 *
1509 * This signal will be emitted during an orderly close
1510 */
1511 signals[CLOSING] = g_signal_new ("closing",
1512 WEB_SOCKET_TYPE_CONNECTION,
1513 G_SIGNAL_RUN_LAST,
1514 G_STRUCT_OFFSET (WebSocketConnectionClass, closing),
1515 g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic,
1516 G_TYPE_BOOLEAN, 0);
1517
1518 klass->error = web_socket_connection_default_error;
1519 klass->closing = web_socket_connection_default_closing;
1520
1521 /**
1522 * WebSocketConnection::close:
1523 * @self: the WebSocket
1524 *
1525 * Emitted when the connection has completely closed, either due to an
1526 * orderly close from the peer, one initiated via web_socket_connection_close()
1527 * or a fatal error condition that caused a close.
1528 *
1529 * This signal will be emitted once.
1530 */
1531 signals[CLOSE] = g_signal_new ("close",
1532 WEB_SOCKET_TYPE_CONNECTION,
1533 G_SIGNAL_RUN_FIRST,
1534 G_STRUCT_OFFSET (WebSocketConnectionClass, close),
1535 NULL, NULL, g_cclosure_marshal_generic,
1536 G_TYPE_NONE, 0);
1537 }
1538
1539 /**
1540 * web_socket_connection_get_url:
1541 * @self: the WebSocket
1542 *
1543 * Get the URL of the WebSocket.
1544 *
1545 * For servers this represents the address of the WebSocket, and
1546 * for clients it is the address connected to.
1547 *
1548 * Returns: the URL
1549 */
1550 const gchar *
1551 web_socket_connection_get_url (WebSocketConnection *self)
1552 {
1553 g_return_val_if_fail (WEB_SOCKET_IS_CONNECTION (self), NULL);
1554 return GET_PRIV(self)->url;
1555 }
1556
1557 /**
1558 * web_socket_connection_get_protocol:
1559 * @self: the WebSocket
1560 *
1561 * Get the protocol chosen via negotiation with the peer.
1562 *
1563 * A list of possible protocols is provided when creating a #WebSocketClient
1564 * or #WebSocketServer, and one is negotiated during the handshake.
1565 *
1566 * This will be %NULL until the WebSocket is in the %WEB_SOCKET_STATE_OPEN
1567 * state.
1568 *
1569 * Returns: the chosen protocol or %NULL
1570 */
1571 const gchar *
1572 web_socket_connection_get_protocol (WebSocketConnection *self)
1573 {
1574 g_return_val_if_fail (WEB_SOCKET_IS_CONNECTION (self), NULL);
1575 return GET_PRIV(self)->chosen_protocol;
1576 }
1577
1578 /**
1579 * web_socket_connection_get_ready_state:
1580 * @self: the WebSocket
1581 *
1582 * Get the current state of the WebSocket.
1583 *
1584 * Returns: the state
1585 */
1586 WebSocketState
1587 web_socket_connection_get_ready_state (WebSocketConnection *self)
1588 {
1589 g_return_val_if_fail (WEB_SOCKET_IS_CONNECTION (self), 0);
1590
1591 if (GET_PRIV(self)->io_closed)
1592 return WEB_SOCKET_STATE_CLOSED;
1593 else if ((GET_PRIV(self)->io_stream && !GET_PRIV(self)->io_open) || GET_PRIV(self)->close_sent)
1594 return WEB_SOCKET_STATE_CLOSING;
1595 else if (GET_PRIV(self)->handshake_done)
1596 return WEB_SOCKET_STATE_OPEN;
1597 else
1598 return WEB_SOCKET_STATE_CONNECTING;
1599 }
1600
1601 /**
1602 * web_socket_connection_get_buffered_amount:
1603 * @self: the WebSocket
1604 *
1605 * Get the amount of buffered data not yet sent.
1606 *
1607 * This represents caller provided data passed into the
1608 * web_socket_connection_send() function.
1609 *
1610 * Returns: the amount of buffered data
1611 */
1612 gsize
1613 web_socket_connection_get_buffered_amount (WebSocketConnection *self)
1614 {
1615 gsize amount = 0;
1616 Frame *frame;
1617 GList *l;
1618
1619 g_return_val_if_fail (WEB_SOCKET_IS_CONNECTION (self), 0);
1620
1621 for (l = GET_PRIV(self)->outgoing.head; l != NULL; l = g_list_next (l))
1622 {
1623 frame = l->data;
1624 amount += frame->amount;
1625 }
1626
1627 return amount;
1628 }
1629
1630 /**
1631 * web_socket_connection_get_io_stream:
1632 * @self: the WebSocket
1633 *
1634 * Get the IO stream the WebSocket is communicating over.
1635 *
1636 * Returns: (transfer none): the amount of buffered data
1637 */
1638 GIOStream *
1639 web_socket_connection_get_io_stream (WebSocketConnection *self)
1640 {
1641 g_return_val_if_fail (WEB_SOCKET_IS_CONNECTION (self), NULL);
1642 return GET_PRIV(self)->io_stream;
1643 }
1644
1645 /**
1646 * web_socket_connection_get_close_code:
1647 * @self: the WebSocket
1648 *
1649 * Get the close code received from the WebSocket peer.
1650 *
1651 * This only becomes valid once the WebSocket is in the
1652 * %WEB_SOCKET_STATE_CLOSED state. The value will often be in the
1653 * #WebSocketCloseCodes enumeration, but may also be an application
1654 * defined close code.
1655 *
1656 * Returns: the close code or zero.
1657 */
1658 gushort
1659 web_socket_connection_get_close_code (WebSocketConnection *self)
1660 {
1661 g_return_val_if_fail (WEB_SOCKET_IS_CONNECTION (self), 0);
1662 return GET_PRIV(self)->peer_close_code;
1663 }
1664
1665 /**
1666 * web_socket_connection_get_close_data:
1667 * @self: the WebSocket
1668 *
1669 * Get the close data received from the WebSocket peer.
1670 *
1671 * This only becomes valid once the WebSocket is in the
1672 * %WEB_SOCKET_STATE_CLOSED state. The data may be freed once
1673 * the main loop is run, so copy it if you need to keep it around.
1674 *
1675 * Returns: the close data or %NULL
1676 */
1677 const gchar *
1678 web_socket_connection_get_close_data (WebSocketConnection *self)
1679 {
1680 g_return_val_if_fail (WEB_SOCKET_IS_CONNECTION (self), NULL);
1681 return GET_PRIV(self)->peer_close_data;
1682 }
1683
1684 /**
1685 * web_socket_connection_send:
1686 * @self: the WebSocket
1687 * @type: the data type of message
1688 * @prefix: (allow-none): an optional prefix prepended to the message
1689 * @message: the message contents
1690 *
1691 * Send a message to the peer.
1692 *
1693 * The @type parameter describes whether this is a binary or text message.
1694 * If a text message then the contents must be UTF-8 valid.
1695 *
1696 * The message is queued to be sent and will be sent when the main loop
1697 * is run.
1698 *
1699 * The optional @prefix can be a canned header to be prefixed to the message.
1700 * It can be specified as a separate argument for efficiency.
1701 */
1702 void
1703 web_socket_connection_send (WebSocketConnection *self,
1704 WebSocketDataType type,
1705 GBytes *prefix,
1706 GBytes *message)
1707 {
1708 gconstpointer pref = NULL;
1709 gsize prefix_len = 0;
1710 gconstpointer payload;
1711 gsize payload_len;
1712 guint8 opcode;
1713
1714 g_return_if_fail (WEB_SOCKET_IS_CONNECTION (self));
1715 g_return_if_fail (message != NULL);
1716
1717 if (web_socket_connection_get_ready_state (self) != WEB_SOCKET_STATE_OPEN)
1718 {
1719 g_critical ("Can only send messages when WebSocket is open");
1720 return;
1721 }
1722
1723 if (prefix)
1724 pref = g_bytes_get_data (prefix, &prefix_len);
1725 payload = g_bytes_get_data (message, &payload_len);
1726
1727 switch (type)
1728 {
1729 case WEB_SOCKET_DATA_TEXT:
1730 opcode = 0x01;
1731 if (!g_utf8_validate (pref, prefix_len, NULL) ||
1732 !g_utf8_validate (payload, payload_len, NULL))
1733 {
1734 g_critical ("invalid non-UTF8 @data passed as text to web_socket_connection_send()");
1735 return;
1736 }
1737 break;
1738 case WEB_SOCKET_DATA_BINARY:
1739 opcode = 0x02;
1740 break;
1741 default:
1742 g_critical ("invalid @type argument for web_socket_connection_send()");
1743 return;
1744 }
1745
1746 send_prefixed_message_rfc6455 (self, WEB_SOCKET_QUEUE_NORMAL, opcode,
1747 pref, prefix_len, payload, payload_len);
1748
1749 g_object_notify (G_OBJECT (self), "buffered-amount");
1750 }
1751
1752 /**
1753 * web_socket_connection_close:
1754 * @self: the WebSocket
1755 * @code: close code
1756 * @data: (allow-none): close data
1757 *
1758 * Close the connection in an orderly fashion.
1759 *
1760 * Note that until the #WebSocketConnection::close signal fires, the connection
1761 * is not yet completely closed. The close message is not even sent until the
1762 * main loop runs.
1763 *
1764 * The @code and @data are sent to the peer along with the close request.
1765 * Note that the @data must be UTF-8 valid.
1766 */
1767 void
1768 web_socket_connection_close (WebSocketConnection *self,
1769 gushort code,
1770 const gchar *data)
1771 {
1772 WebSocketQueueFlags flags;
1773 gboolean handled = FALSE;
1774
1775 g_return_if_fail (WEB_SOCKET_IS_CONNECTION (self));
1776 g_return_if_fail (!GET_PRIV(self)->close_sent);
1777
1778 g_signal_emit (self, signals[CLOSING], 0, &handled);
1779 if (!handled)
1780 return;
1781
1782 if (GET_PRIV(self)->close_received)
1783 g_debug ("responding to close request");
1784
1785 if (GET_PRIV(self)->handshake_done)
1786 {
1787 flags = 0;
1788 if (GET_PRIV(self)->server_side && GET_PRIV(self)->close_received)
1789 flags |= WEB_SOCKET_QUEUE_LAST;
1790 send_close_rfc6455 (self, flags, code, data);
1791 close_io_after_timeout (self);
1792 }
1793 else
1794 {
1795 close_io_stream (self);
1796 }
1797 }
1798
1799 static void
1800 on_throttle_pressure (GObject *object,
1801 gboolean throttle,
1802 gpointer user_data)
1803 {
1804 WebSocketConnection *self = WEB_SOCKET_CONNECTION (user_data);
1805 if (throttle)
1806 {
1807 if (GET_PRIV(self)->io_open && GET_PRIV(self)->input_source != NULL)
1808 {
1809 g_debug ("applying back pressure in web socket");
1810 stop_input (self);
1811 }
1812 }
1813 else
1814 {
1815 if (GET_PRIV(self)->io_open && GET_PRIV(self)->input_source == NULL)
1816 {
1817 g_debug ("relieving back pressure in web socket");
1818 start_input (self);
1819 }
1820 }
1821 }
1822
1823 static void
1824 web_socket_connection_throttle (CockpitFlow *flow,
1825 CockpitFlow *controlling)
1826 {
1827 WebSocketConnection *self = WEB_SOCKET_CONNECTION (flow);
1828
1829 if (GET_PRIV(self)->pressure)
1830 {
1831 g_signal_handler_disconnect (GET_PRIV(self)->pressure, GET_PRIV(self)->pressure_sig);
1832 g_object_remove_weak_pointer (G_OBJECT (GET_PRIV(self)->pressure), (gpointer *)&GET_PRIV(self)->pressure);
1833 GET_PRIV(self)->pressure = NULL;
1834 }
1835
1836 if (controlling)
1837 {
1838 GET_PRIV(self)->pressure = controlling;
1839 g_object_add_weak_pointer (G_OBJECT (GET_PRIV(self)->pressure), (gpointer *)&GET_PRIV(self)->pressure);
1840 GET_PRIV(self)->pressure_sig = g_signal_connect (controlling, "pressure", G_CALLBACK (on_throttle_pressure), self);
1841 }
1842 }
1843
1844 gboolean
1845 _web_socket_connection_choose_protocol (WebSocketConnection *self,
1846 const gchar **protocols,
1847 const gchar *value)
1848 {
1849 WebSocketConnectionPrivate *pv = web_socket_connection_get_instance_private (self);
1850 gboolean chosen = FALSE;
1851 gchar **values;
1852 gint i, j;
1853
1854 g_free (pv->chosen_protocol);
1855 pv->chosen_protocol = NULL;
1856
1857 /* Automatically select one */
1858 if (!value)
1859 {
1860 if (protocols)
1861 {
1862 pv->chosen_protocol = g_strdup (protocols[0]);
1863 g_debug ("automatically selected protocol: %s", pv->chosen_protocol);
1864 }
1865 g_object_notify (G_OBJECT (self), "protocol");
1866 return TRUE;
1867 }
1868
1869 /* Choose one from what client/server agree on */
1870 if (!g_str_is_ascii (value))
1871 {
1872 /* splitting into words by comma might interfere with multi-byte characters,
1873 * and they are invalid here anyway */
1874 g_message ("received invalid Sec-WebSocket-Protocol, must be ASCII: %s", value);
1875 return FALSE;
1876 }
1877 values = g_strsplit_set (value, ", ", -1);
1878
1879 /* Accept any protocol */
1880 if (!protocols)
1881 {
1882 pv->chosen_protocol = g_strdup (values[0]);
1883 g_debug ("automatically selected protocol: %s", pv->chosen_protocol);
1884 chosen = TRUE;
1885 }
1886
1887 for (j = 0; !chosen && values[j] != NULL; j++)
1888 {
1889 for (i = 0; protocols[i] != NULL; i++)
1890 {
1891 if (g_str_equal (protocols[i], values[j]))
1892 {
1893 pv->chosen_protocol = g_strdup (values[j]);
1894 g_debug ("agreed on protocol: %s", pv->chosen_protocol);
1895 chosen = TRUE;
1896 }
1897 }
1898 }
1899 g_strfreev (values);
1900
1901 if (chosen)
1902 g_object_notify (G_OBJECT (self), "protocol");
1903 else
1904 g_message ("received invalid or unsupported Sec-WebSocket-Protocol: %s", value);
1905
1906 return chosen;
1907 }
1908
1909 GMainContext *
1910 _web_socket_connection_get_main_context (WebSocketConnection *self)
1911 {
1912 g_return_val_if_fail (WEB_SOCKET_IS_CONNECTION (self), NULL);
1913 return GET_PRIV(self)->main_context;
1914 }
1915
1916 static void
1917 web_socket_connection_flow_iface_init (CockpitFlowInterface *iface)
1918 {
1919 iface->throttle = web_socket_connection_throttle;
1920 }
1921