Debian Codegraph @

src/ws/websocketclient.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 "websocketclient.h"
14 #include "websocketprivate.h"
15
16 #include <string.h>
17
18 enum {
19 PROP_0,
20 PROP_ORIGIN,
21 PROP_PROTOCOLS,
22 };
23
24 struct _WebSocketClient
25 {
26 WebSocketConnection parent;
27
28 gboolean handshake_started;
29 gchar *origin;
30 gchar **possible_protocols;
31 gpointer accept_key;
32 GHashTable *include_headers;
33 GHashTable *response_headers;
34 GCancellable *cancellable;
35 GSource *idle_start;
36 };
37
38 struct _WebSocketClientClass
39 {
40 WebSocketConnectionClass parent;
41 };
42
43 G_DEFINE_TYPE (WebSocketClient, web_socket_client, WEB_SOCKET_TYPE_CONNECTION);
44
45 static void
46 web_socket_client_init (WebSocketClient *self)
47 {
48
49 }
50
51 static void
52 protocol_error_and_close (WebSocketConnection *conn)
53 {
54 GError *error = g_error_new_literal (WEB_SOCKET_ERROR,
55 WEB_SOCKET_CLOSE_PROTOCOL,
56 "Received invalid WebSocket handshake from the server");
57 _web_socket_connection_error_and_close (conn, error, TRUE);
58 }
59
60 static gboolean
61 verify_handshake_rfc6455 (WebSocketClient *self,
62 WebSocketConnection *conn,
63 GHashTable *headers)
64 {
65 const gchar *value;
66
67 /*
68 * This is a client verifying a handshake response it's received
69 * from the server.
70 */
71
72 if (!_web_socket_util_header_equals (headers, "Upgrade", "websocket") ||
73 !_web_socket_util_header_contains (headers, "Connection", "upgrade") ||
74 !_web_socket_connection_choose_protocol (conn, (const gchar **)self->possible_protocols,
75 g_hash_table_lookup (headers, "Sec-Websocket-Protocol")) ||
76 !_web_socket_util_header_empty (headers, "Sec-WebSocket-Extensions"))
77 {
78 protocol_error_and_close (conn);
79 return FALSE;
80 }
81
82 /*
83 * We filled in accept_key when we did a handshake request
84 * earlier in request_handshake_rfc6455().
85 */
86 value = g_hash_table_lookup (headers, "Sec-WebSocket-Accept");
87 if (value == NULL || self->accept_key == NULL ||
88 g_ascii_strcasecmp (self->accept_key, value))
89 {
90 g_message ("received invalid or missing Sec-WebSocket-Accept header: %s", value);
91 protocol_error_and_close (conn);
92 return FALSE;
93 }
94
95 g_debug ("verified rfc6455 handshake");
96 return TRUE;
97 }
98
99 static gboolean
100 parse_handshake_response (WebSocketClient *self,
101 WebSocketConnection *conn,
102 GByteArray *incoming)
103 {
104 GHashTable *headers;
105 gchar *reason;
106 gboolean verified;
107 guint status;
108 GError *error = NULL;
109 gssize in1, in2;
110 gssize consumed;
111
112 /* Parse the handshake response received from the server */
113 in1 = web_socket_util_parse_status_line ((const gchar *)incoming->data,
114 incoming->len, NULL, &status, &reason);
115 if (in1 < 0)
116 {
117 g_message ("received invalid status line");
118 protocol_error_and_close (conn);
119 }
120 else if (in1 == 0)
121 g_debug ("waiting for more handshake data");
122 if (in1 <= 0)
123 return FALSE;
124
125 in2 = web_socket_util_parse_headers ((const gchar *)incoming->data + in1,
126 incoming->len - in1, &headers);
127 if (in2 < 0)
128 {
129 g_message ("received invalid response headers");
130 protocol_error_and_close (conn);
131 }
132 else if (in2 == 0)
133 g_debug ("waiting for more handshake data");
134 if (in2 <= 0)
135 {
136 g_free (reason);
137 return FALSE;
138 }
139
140 consumed = in1 + in2;
141
142 if (self->response_headers)
143 g_hash_table_unref (self->response_headers);
144 self->response_headers = headers;
145
146 /*
147 * TODO: We could handle the following codes here:
148 * 401: authentication
149 * 3xx: redirect
150 */
151
152 if (status == 101)
153 {
154 verified = verify_handshake_rfc6455 (self, conn, headers);
155 if (verified)
156 {
157 /* Handshake is successful */
158 g_debug ("open: handshake completed");
159 }
160 }
161 else
162 {
163 verified = FALSE;
164 g_message ("received unexpected status: %d %s", status, reason);
165 if (reason == NULL)
166 error = g_error_new (WEB_SOCKET_ERROR,
167 WEB_SOCKET_CLOSE_PROTOCOL,
168 "Handshake failed: %u", status);
169 else
170 error = g_error_new (WEB_SOCKET_ERROR,
171 WEB_SOCKET_CLOSE_PROTOCOL,
172 "%s", reason);
173 _web_socket_connection_error_and_close (conn, error, FALSE);
174 }
175
176 g_free (reason);
177 if (consumed > 0)
178 g_byte_array_remove_range (incoming, 0, consumed);
179 return verified;
180 }
181
182 static void
183 include_custom_headers (WebSocketClient *self,
184 GString *handshake)
185 {
186 GHashTableIter iter;
187 gpointer name;
188 gpointer value;
189
190 if (!self->include_headers)
191 return;
192
193 g_hash_table_iter_init (&iter, self->include_headers);
194 while (g_hash_table_iter_next (&iter, &name, &value))
195 {
196 if (value == NULL)
197 continue;
198 g_debug ("including custom header: %s: %s", (gchar *)name, (gchar *)value);
199 g_string_append_printf (handshake, "%s: %s\r\n",
200 (gchar *)name, (gchar *)value);
201 }
202 }
203
204 static void
205 request_handshake_rfc6455 (WebSocketClient *self,
206 WebSocketConnection *conn,
207 const gchar *host,
208 const gchar *path)
209 {
210 gchar *key;
211 gchar *protocols;
212 GString *handshake;
213 guint32 raw[4];
214 gsize len;
215
216 raw[0] = g_random_int ();
217 raw[1] = g_random_int ();
218 raw[2] = g_random_int ();
219 raw[3] = g_random_int ();
220 G_STATIC_ASSERT (sizeof (raw) == 16);
221 key = g_base64_encode ((const guchar *)raw, sizeof (raw));
222
223 /* Save this for verify_handshake_rfc6455() */
224 g_free (self->accept_key);
225 self->accept_key = _web_socket_complete_accept_key_rfc6455 (key);
226
227 handshake = g_string_new ("");
228 g_string_printf (handshake, "GET %s HTTP/1.1\r\n"
229 "Host: %s\r\n"
230 "Upgrade: websocket\r\n"
231 "Connection: Upgrade\r\n"
232 "Sec-WebSocket-Key: %s\r\n"
233 "Sec-WebSocket-Version: 13\r\n",
234 path, host, key);
235
236 /* RFC 6454 talks about 'null' */
237 g_string_append_printf (handshake, "Origin: %s\r\n", self->origin ? self->origin : "null");
238
239 if (self->possible_protocols)
240 {
241 protocols = g_strjoinv (", ", self->possible_protocols);
242 g_string_append_printf (handshake, "Sec-WebSocket-Protocol: %s\r\n", protocols);
243 g_free (protocols);
244 }
245
246 include_custom_headers (self, handshake);
247 g_string_append (handshake, "\r\n");
248
249 g_free (key);
250
251 len = handshake->len;
252 _web_socket_connection_queue (conn, WEB_SOCKET_QUEUE_URGENT,
253 g_string_free (handshake, FALSE), len, 0);
254 g_debug ("queued rfc6455 handshake request");
255 }
256
257 static void
258 request_handshake (WebSocketClient *self,
259 WebSocketConnection *conn)
260 {
261 GError *error = NULL;
262 const gchar *url;
263 gchar *host;
264 gchar *path;
265
266 self->handshake_started = TRUE;
267
268 url = web_socket_connection_get_url (conn);
269 if (!_web_socket_util_parse_url (url, NULL, &host, &path, &error))
270 {
271 _web_socket_connection_error_and_close (conn, error, TRUE);
272 return;
273 }
274
275 request_handshake_rfc6455 (self, conn, host, path);
276
277 g_free (host);
278 g_free (path);
279 }
280
281 static gpointer
282 on_idle_do_handshake (gpointer user_data)
283 {
284 WebSocketClient *self = WEB_SOCKET_CLIENT (user_data);
285 WebSocketConnection *conn = WEB_SOCKET_CONNECTION (user_data);
286 g_source_unref (self->idle_start);
287 self->idle_start = NULL;
288 request_handshake (self, conn);
289 return FALSE;
290 }
291
292 static void
293 on_connect_to_uri (GObject *source,
294 GAsyncResult *result,
295 gpointer user_data)
296 {
297 WebSocketClient *self = WEB_SOCKET_CLIENT (user_data);
298 WebSocketConnection *conn = WEB_SOCKET_CONNECTION (user_data);
299 GSocketConnection *connection;
300 GError *error = NULL;
301
302 connection = g_socket_client_connect_to_uri_finish (G_SOCKET_CLIENT (source),
303 result, &error);
304
305 if (error == NULL)
306 {
307 _web_socket_connection_take_io_stream (conn, G_IO_STREAM (connection));
308 request_handshake (self, conn);
309 }
310 else if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
311 {
312 g_error_free (error);
313 }
314 else
315 {
316 _web_socket_connection_error_and_close (conn, error, TRUE);
317 }
318
319 g_object_unref (self);
320 }
321
322 static void
323 web_socket_client_constructed (GObject *object)
324 {
325 WebSocketClient *self = WEB_SOCKET_CLIENT (object);
326 WebSocketConnection *conn = WEB_SOCKET_CONNECTION (object);
327 GSocketClient *client;
328 const gchar *url;
329 guint16 default_port;
330 gchar *scheme;
331
332 G_OBJECT_CLASS (web_socket_client_parent_class)->constructed (object);
333
334 if (web_socket_connection_get_io_stream (conn))
335 {
336 /* Start handshake from the main context */
337 self->idle_start = g_idle_source_new ();
338 g_source_set_priority (self->idle_start, G_PRIORITY_HIGH);
339 g_source_set_callback (self->idle_start, (GSourceFunc)on_idle_do_handshake,
340 self, NULL);
341 g_source_attach (self->idle_start, _web_socket_connection_get_main_context (conn));
342 }
343 else
344 {
345 client = g_socket_client_new ();
346 self->cancellable = g_cancellable_new ();
347
348 url = web_socket_connection_get_url (WEB_SOCKET_CONNECTION (self));
349 scheme = g_uri_parse_scheme (url);
350 if (scheme && (g_str_equal (scheme, "wss") || g_str_equal (scheme, "https")))
351 {
352 g_socket_client_set_tls (client, TRUE);
353 default_port = 443;
354 }
355 else
356 {
357 default_port = 80;
358 }
359 g_free (scheme);
360
361 g_socket_client_connect_to_uri_async (client, url, default_port,
362 self->cancellable, on_connect_to_uri,
363 g_object_ref (self));
364 g_object_unref (client);
365 }
366 }
367
368 static gboolean
369 web_socket_client_handshake (WebSocketConnection *conn,
370 GByteArray *incoming)
371 {
372 WebSocketClient *self = WEB_SOCKET_CLIENT (conn);
373 return parse_handshake_response (self, conn, incoming);
374 }
375
376 static void
377 web_socket_client_set_property (GObject *object,
378 guint prop_id,
379 const GValue *value,
380 GParamSpec *pspec)
381 {
382 WebSocketClient *self = WEB_SOCKET_CLIENT (object);
383
384 switch (prop_id)
385 {
386 case PROP_ORIGIN:
387 g_return_if_fail (self->origin == NULL);
388 self->origin = g_value_dup_string (value);
389 break;
390
391 case PROP_PROTOCOLS:
392 g_return_if_fail (self->handshake_started == FALSE);
393 g_strfreev (self->possible_protocols);
394 self->possible_protocols = g_value_dup_boxed (value);
395 break;
396
397 default:
398 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
399 break;
400 }
401 }
402
403 static void
404 web_socket_client_close (WebSocketConnection *conn)
405 {
406 WebSocketClient *self = WEB_SOCKET_CLIENT (conn);
407
408 if (self->cancellable)
409 g_cancellable_cancel (self->cancellable);
410 if (self->idle_start)
411 {
412 g_source_destroy (self->idle_start);
413 g_source_unref (self->idle_start);
414 }
415 }
416
417 static void
418 web_socket_client_finalize (GObject *object)
419 {
420 WebSocketClient *self = WEB_SOCKET_CLIENT (object);
421
422 g_strfreev (self->possible_protocols);
423 g_free (self->origin);
424 g_free (self->accept_key);
425 if (self->include_headers)
426 g_hash_table_unref (self->include_headers);
427 if (self->response_headers)
428 g_hash_table_unref (self->response_headers);
429 if (self->cancellable)
430 g_object_unref (self->cancellable);
431 g_assert (self->idle_start == NULL);
432
433 G_OBJECT_CLASS (web_socket_client_parent_class)->finalize (object);
434 }
435
436 static void
437 web_socket_client_class_init (WebSocketClientClass *klass)
438 {
439 WebSocketConnectionClass *conn_class = WEB_SOCKET_CONNECTION_CLASS (klass);
440 GObjectClass *object_class = G_OBJECT_CLASS (klass);
441
442 object_class->constructed = web_socket_client_constructed;
443 object_class->set_property = web_socket_client_set_property;
444 object_class->finalize = web_socket_client_finalize;
445
446 conn_class->server_behavior = FALSE;
447 conn_class->handshake = web_socket_client_handshake;
448 conn_class->close = web_socket_client_close;
449
450 /**
451 * WebSocketClient:origin:
452 *
453 * The WebSocket origin. Client WebSockets will send this to the server. If
454 * set on a server, then only clients with the matching origin will be accepted.
455 */
456 g_object_class_install_property (object_class, PROP_ORIGIN,
457 g_param_spec_string ("origin", "Origin", "The WebSocket origin", NULL,
458 G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
459
460 /**
461 * WebSocketClient:protocols:
462 *
463 * The possible protocols to negotiate with the peer.
464 */
465 g_object_class_install_property (object_class, PROP_PROTOCOLS,
466 g_param_spec_boxed ("protocols", "Protocol", "The desired WebSocket protocols", G_TYPE_STRV,
467 G_PARAM_WRITABLE | G_PARAM_STATIC_STRINGS));
468 }
469
470 /**
471 * web_socket_client_new:
472 * @url: the url address of the WebSocket
473 * @origin: (allow-none): the origin to report to server
474 * @protocols: (allow-none): possible protocols to negotiate
475 *
476 * Create a new client side WebSocket connection to communicate with a server.
477 *
478 * The WebSocket will establish a connection to the server using HTTP
479 * or HTTPS at the address specified in the @url.
480 *
481 * If @protocols are specified then these are used to negotiate a protocol
482 * with the client.
483 *
484 * Returns: (transfer full): a new WebSocket
485 */
486 WebSocketConnection *
487 web_socket_client_new (const gchar *url,
488 const gchar *origin,
489 const gchar **protocols)
490 {
491 return g_object_new (WEB_SOCKET_TYPE_CLIENT,
492 "url", url,
493 "origin", origin,
494 "protocols", protocols,
495 NULL);
496 }
497
498 /**
499 * web_socket_client_new_for_stream:
500 * @url: the url address of the WebSocket
501 * @origin: (allow-none): the origin to report to server
502 * @protocols: (allow-none): possible protocols to negotiate
503 * @io_stream: the IO stream to communicate over
504 *
505 * Create a new client side WebSocket connection to communicate with a server.
506 *
507 * Use this function if you've already opened up a IO stream to the server
508 * and now wish to communicate over it. The input and output streams of the
509 * @io_stream must be pollable.
510 *
511 * If @protocols are specified then these are used to negotiate a protocol
512 * with the client.
513 *
514 * Returns: (transfer full): a new WebSocket
515 */
516 WebSocketConnection *
517 web_socket_client_new_for_stream (const gchar *url,
518 const gchar *origin,
519 const gchar **protocols,
520 GIOStream *io_stream)
521 {
522 return g_object_new (WEB_SOCKET_TYPE_CLIENT,
523 "url", url,
524 "origin", origin,
525 "protocols", protocols,
526 "io-stream", io_stream,
527 NULL);
528 }
529
530 /**
531 * web_socket_client_include_header:
532 * @self: the client
533 * @name: the header name
534 * @value: the header value
535 *
536 * Add an HTTP header (eg: for authentication) to the
537 * HTTP request.
538 */
539 void
540 web_socket_client_include_header (WebSocketClient *self,
541 const gchar *name,
542 const gchar *value)
543 {
544 g_return_if_fail (WEB_SOCKET_IS_CLIENT (self));
545 g_return_if_fail (self->handshake_started == FALSE);
546
547 if (!self->include_headers)
548 self->include_headers = web_socket_util_new_headers ();
549 g_hash_table_insert (self->include_headers,
550 g_strdup (name), g_strdup (value));
551 }
552
553 GHashTable *
554 web_socket_client_get_headers (WebSocketClient *self)
555 {
556 g_return_val_if_fail (WEB_SOCKET_IS_CLIENT (self), NULL);
557 return self->response_headers;
558 }