Debian Codegraph @

crt/aws-c-http/source/websocket_bootstrap.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/cal/hash.h>
7 #include <aws/common/encoding.h>
8 #include <aws/common/logging.h>
9 #include <aws/common/string.h>
10 #include <aws/http/connection.h>
11 #include <aws/http/private/http_impl.h>
12 #include <aws/http/private/strutil.h>
13 #include <aws/http/private/websocket_impl.h>
14 #include <aws/http/request_response.h>
15 #include <aws/http/status_code.h>
16 #include <aws/io/uri.h>
17
18 #include <inttypes.h>
19
20 #ifdef _MSC_VER
21 # pragma warning(disable : 4204) /* non-constant aggregate initializer */
22 #endif
23
24 /**
25 * Allow unit-tests to mock interactions with external systems.
26 */
27 static const struct aws_websocket_client_bootstrap_system_vtable s_default_system_vtable = {
28 .aws_http_client_connect = aws_http_client_connect,
29 .aws_http_connection_release = aws_http_connection_release,
30 .aws_http_connection_close = aws_http_connection_close,
31 .aws_http_connection_get_channel = aws_http_connection_get_channel,
32 .aws_http_connection_make_request = aws_http_connection_make_request,
33 .aws_http_stream_activate = aws_http_stream_activate,
34 .aws_http_stream_release = aws_http_stream_release,
35 .aws_http_stream_get_connection = aws_http_stream_get_connection,
36 .aws_http_stream_update_window = aws_http_stream_update_window,
37 .aws_http_stream_get_incoming_response_status = aws_http_stream_get_incoming_response_status,
38 .aws_websocket_handler_new = aws_websocket_handler_new,
39 };
40
41 static const struct aws_websocket_client_bootstrap_system_vtable *s_system_vtable = &s_default_system_vtable;
42
43 void aws_websocket_client_bootstrap_set_system_vtable(
44 const struct aws_websocket_client_bootstrap_system_vtable *system_vtable) {
45
46 s_system_vtable = system_vtable;
47 }
48
49 /**
50 * The websocket bootstrap brings a websocket connection into this world, and sees it out again.
51 * Spins up an HTTP client, performs the opening handshake (HTTP Upgrade request),
52 * creates the websocket handler, and inserts it into the channel.
53 * The bootstrap is responsible for firing the on_connection_setup and on_connection_shutdown callbacks.
54 */
55 struct aws_websocket_client_bootstrap {
56 /* Settings copied in from aws_websocket_client_connection_options */
57 struct aws_allocator *alloc;
58 size_t initial_window_size;
59 bool manual_window_update;
60 void *user_data;
61 /* Setup callback will be set NULL once it's invoked.
62 * This is used to determine whether setup or shutdown should be invoked
63 * from the HTTP-shutdown callback. */
64 aws_websocket_on_connection_setup_fn *websocket_setup_callback;
65 aws_websocket_on_connection_shutdown_fn *websocket_shutdown_callback;
66 aws_websocket_on_incoming_frame_begin_fn *websocket_frame_begin_callback;
67 aws_websocket_on_incoming_frame_payload_fn *websocket_frame_payload_callback;
68 aws_websocket_on_incoming_frame_complete_fn *websocket_frame_complete_callback;
69
70 /* Handshake request data */
71 struct aws_http_message *handshake_request;
72
73 /* Given the "Sec-WebSocket-Key" from the request,
74 * this is what we expect the response's "Sec-WebSocket-Accept" to be */
75 struct aws_byte_buf expected_sec_websocket_accept;
76
77 /* Comma-separated values from the request's "Sec-WebSocket-Protocol" (or NULL if none) */
78 struct aws_string *expected_sec_websocket_protocols;
79
80 /* Handshake response data */
81 int response_status;
82 struct aws_http_headers *response_headers;
83 bool got_full_response_headers;
84 struct aws_byte_buf response_body;
85 bool got_full_response_body;
86
87 int setup_error_code;
88 struct aws_websocket *websocket;
89 };
90
91 static void s_ws_bootstrap_destroy(struct aws_websocket_client_bootstrap *ws_bootstrap);
92 static int s_ws_bootstrap_calculate_sec_websocket_accept(
93 struct aws_byte_cursor sec_websocket_key,
94 struct aws_byte_buf *out_buf,
95 struct aws_allocator *alloc);
96 static void s_ws_bootstrap_cancel_setup_due_to_err(
97 struct aws_websocket_client_bootstrap *ws_bootstrap,
98 struct aws_http_connection *http_connection,
99 int error_code);
100 static void s_ws_bootstrap_on_http_setup(struct aws_http_connection *http_connection, int error_code, void *user_data);
101 static void s_ws_bootstrap_on_http_shutdown(
102 struct aws_http_connection *http_connection,
103 int error_code,
104 void *user_data);
105 static int s_ws_bootstrap_on_handshake_response_headers(
106 struct aws_http_stream *stream,
107 enum aws_http_header_block header_block,
108 const struct aws_http_header *header_array,
109 size_t num_headers,
110 void *user_data);
111 static int s_ws_bootstrap_on_handshake_response_header_block_done(
112 struct aws_http_stream *stream,
113 enum aws_http_header_block header_block,
114 void *user_data);
115 static int s_ws_bootstrap_on_handshake_response_body(
116 struct aws_http_stream *stream,
117 const struct aws_byte_cursor *data,
118 void *user_data);
119 static void s_ws_bootstrap_on_stream_complete(struct aws_http_stream *stream, int error_code, void *user_data);
120
121 int aws_websocket_client_connect(const struct aws_websocket_client_connection_options *options) {
122 aws_http_fatal_assert_library_initialized();
123 AWS_ASSERT(options);
124
125 /* Validate options */
126 struct aws_byte_cursor path;
127 aws_http_message_get_request_path(options->handshake_request, &path);
128 if (!options->allocator || !options->bootstrap || !options->socket_options || !options->host.len || !path.len ||
129 !options->on_connection_setup) {
130
131 AWS_LOGF_ERROR(AWS_LS_HTTP_WEBSOCKET_SETUP, "id=static: Missing required websocket connection options.");
132 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
133 }
134
135 struct aws_byte_cursor method;
136 aws_http_message_get_request_method(options->handshake_request, &method);
137 if (aws_http_str_to_method(method) != AWS_HTTP_METHOD_GET) {
138
139 AWS_LOGF_ERROR(AWS_LS_HTTP_WEBSOCKET_SETUP, "id=static: Websocket request must have method be 'GET'.");
140 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
141 }
142
143 if (!options->handshake_request) {
144 AWS_LOGF_ERROR(
145 AWS_LS_HTTP_WEBSOCKET_SETUP,
146 "id=static: Invalid connection options, missing required request for websocket client handshake.");
147 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
148 }
149
150 const struct aws_http_headers *request_headers = aws_http_message_get_headers(options->handshake_request);
151 struct aws_byte_cursor sec_websocket_key;
152 if (aws_http_headers_get(request_headers, aws_byte_cursor_from_c_str("Sec-WebSocket-Key"), &sec_websocket_key)) {
153 AWS_LOGF_ERROR(
154 AWS_LS_HTTP_WEBSOCKET_SETUP,
155 "id=static: Websocket handshake request is missing required 'Sec-WebSocket-Key' header");
156 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
157 }
158
159 /* Extensions are not currently supported */
160 if (aws_http_headers_has(request_headers, aws_byte_cursor_from_c_str("Sec-WebSocket-Extensions"))) {
161 AWS_LOGF_ERROR(
162 AWS_LS_HTTP_WEBSOCKET_SETUP, "id=static: 'Sec-WebSocket-Extensions' are not currently supported");
163 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
164 }
165
166 /* Create bootstrap */
167 struct aws_websocket_client_bootstrap *ws_bootstrap =
168 aws_mem_calloc(options->allocator, 1, sizeof(struct aws_websocket_client_bootstrap));
169
170 ws_bootstrap->alloc = options->allocator;
171 ws_bootstrap->initial_window_size = options->initial_window_size;
172 ws_bootstrap->manual_window_update = options->manual_window_management;
173 ws_bootstrap->user_data = options->user_data;
174 ws_bootstrap->websocket_setup_callback = options->on_connection_setup;
175 ws_bootstrap->websocket_shutdown_callback = options->on_connection_shutdown;
176 ws_bootstrap->websocket_frame_begin_callback = options->on_incoming_frame_begin;
177 ws_bootstrap->websocket_frame_payload_callback = options->on_incoming_frame_payload;
178 ws_bootstrap->websocket_frame_complete_callback = options->on_incoming_frame_complete;
179 ws_bootstrap->handshake_request = aws_http_message_acquire(options->handshake_request);
180 ws_bootstrap->response_status = AWS_HTTP_STATUS_CODE_UNKNOWN;
181 ws_bootstrap->response_headers = aws_http_headers_new(ws_bootstrap->alloc);
182 aws_byte_buf_init(&ws_bootstrap->response_body, ws_bootstrap->alloc, 0);
183
184 if (s_ws_bootstrap_calculate_sec_websocket_accept(
185 sec_websocket_key, &ws_bootstrap->expected_sec_websocket_accept, ws_bootstrap->alloc)) {
186 goto error;
187 }
188
189 ws_bootstrap->expected_sec_websocket_protocols =
190 aws_http_headers_get_all(request_headers, aws_byte_cursor_from_c_str("Sec-WebSocket-Protocol"));
191
192 /* Initiate HTTP connection */
193 struct aws_http_client_connection_options http_options = AWS_HTTP_CLIENT_CONNECTION_OPTIONS_INIT;
194 http_options.allocator = ws_bootstrap->alloc;
195 http_options.bootstrap = options->bootstrap;
196 http_options.host_name = options->host;
197 http_options.socket_options = options->socket_options;
198 http_options.tls_options = options->tls_options;
199 http_options.proxy_options = options->proxy_options;
200
201 if (options->manual_window_management) {
202 http_options.manual_window_management = true;
203
204 /* Give HTTP handler enough window to comfortably receive the handshake response.
205 *
206 * If the upgrade is unsuccessful, the HTTP window will shrink as the response body is received.
207 * In this case, we'll keep incrementing the window back to its original size so data keeps arriving.
208 *
209 * If the upgrade is successful, then the websocket handler is installed, and
210 * the HTTP handler will take over its own window management. */
211 http_options.initial_window_size = 1024;
212 }
213
214 http_options.user_data = ws_bootstrap;
215 http_options.on_setup = s_ws_bootstrap_on_http_setup;
216 http_options.on_shutdown = s_ws_bootstrap_on_http_shutdown;
217 http_options.requested_event_loop = options->requested_event_loop;
218 http_options.host_resolution_config = options->host_resolution_config;
219
220 /* Infer port, if not explicitly specified in URI */
221 http_options.port = options->port;
222 if (!http_options.port) {
223 http_options.port = options->tls_options ? 443 : 80;
224 }
225
226 if (s_system_vtable->aws_http_client_connect(&http_options)) {
227 AWS_LOGF_ERROR(
228 AWS_LS_HTTP_WEBSOCKET_SETUP,
229 "id=static: Websocket failed to initiate HTTP connection, error %d (%s)",
230 aws_last_error(),
231 aws_error_name(aws_last_error()));
232 goto error;
233 }
234
235 /* Success! (so far) */
236 AWS_LOGF_TRACE(
237 AWS_LS_HTTP_WEBSOCKET_SETUP,
238 "id=%p: Websocket setup begun, connecting to " PRInSTR ":%" PRIu32 PRInSTR,
239 (void *)ws_bootstrap,
240 AWS_BYTE_CURSOR_PRI(options->host),
241 options->port,
242 AWS_BYTE_CURSOR_PRI(path));
243
244 return AWS_OP_SUCCESS;
245
246 error:
247 s_ws_bootstrap_destroy(ws_bootstrap);
248 return AWS_OP_ERR;
249 }
250
251 static void s_ws_bootstrap_destroy(struct aws_websocket_client_bootstrap *ws_bootstrap) {
252 if (!ws_bootstrap) {
253 return;
254 }
255
256 aws_http_message_release(ws_bootstrap->handshake_request);
257 aws_http_headers_release(ws_bootstrap->response_headers);
258 aws_byte_buf_clean_up(&ws_bootstrap->expected_sec_websocket_accept);
259 aws_string_destroy(ws_bootstrap->expected_sec_websocket_protocols);
260 aws_byte_buf_clean_up(&ws_bootstrap->response_body);
261
262 aws_mem_release(ws_bootstrap->alloc, ws_bootstrap);
263 }
264
265 /* Given the handshake request's "Sec-WebSocket-Key" value,
266 * calculate the expected value for the response's "Sec-WebSocket-Accept".
267 * RFC-6455 Section 4.1:
268 * base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-Key|
269 * (as a string, not base64-decoded) with the string
270 * "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
271 * trailing whitespace
272 */
273 static int s_ws_bootstrap_calculate_sec_websocket_accept(
274 struct aws_byte_cursor sec_websocket_key,
275 struct aws_byte_buf *out_buf,
276 struct aws_allocator *alloc) {
277
278 AWS_ASSERT(out_buf && !out_buf->allocator && out_buf->len == 0); /* expect buf to be uninitialized */
279
280 /* note: leading and trailing whitespace was already trimmed by aws_http_headers */
281
282 /* optimization: skip concatenating Sec-WebSocket-Key and the magic string.
283 * just run the SHA1 over the first string, and then the 2nd. */
284
285 bool success = false;
286 struct aws_byte_cursor magic_string = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
287
288 /* SHA-1 */
289 struct aws_hash *sha1 = aws_sha1_new(alloc);
290 if (!sha1) {
291 AWS_LOGF_ERROR(
292 AWS_LS_HTTP_WEBSOCKET_SETUP,
293 "id=static: Failed to initiate SHA1, error %d (%s)",
294 aws_last_error(),
295 aws_error_name(aws_last_error()));
296 goto cleanup;
297 }
298
299 if (aws_hash_update(sha1, &sec_websocket_key) || aws_hash_update(sha1, &magic_string)) {
300 AWS_LOGF_ERROR(
301 AWS_LS_HTTP_WEBSOCKET_SETUP,
302 "id=static: Failed to update SHA1, error %d (%s)",
303 aws_last_error(),
304 aws_error_name(aws_last_error()));
305 goto cleanup;
306 }
307
308 uint8_t sha1_storage[AWS_SHA1_LEN];
309 struct aws_byte_buf sha1_buf = aws_byte_buf_from_empty_array(sha1_storage, sizeof(sha1_storage));
310 if (aws_hash_finalize(sha1, &sha1_buf, 0)) {
311 AWS_LOGF_ERROR(
312 AWS_LS_HTTP_WEBSOCKET_SETUP,
313 "id=static: Failed to finalize SHA1, error %d (%s)",
314 aws_last_error(),
315 aws_error_name(aws_last_error()));
316 goto cleanup;
317 }
318
319 /* base64-encoded SHA-1 (clear out_buf, and write to it again) */
320 size_t base64_encode_sha1_len;
321 if (aws_base64_compute_encoded_len(sha1_buf.len, &base64_encode_sha1_len)) {
322 AWS_LOGF_ERROR(
323 AWS_LS_HTTP_WEBSOCKET_SETUP,
324 "id=static: Failed to determine Base64-encoded length, error %d (%s)",
325 aws_last_error(),
326 aws_error_name(aws_last_error()));
327 goto cleanup;
328 }
329 aws_byte_buf_init(out_buf, alloc, base64_encode_sha1_len);
330
331 struct aws_byte_cursor sha1_cursor = aws_byte_cursor_from_buf(&sha1_buf);
332 if (aws_base64_encode(&sha1_cursor, out_buf)) {
333 AWS_LOGF_ERROR(
334 AWS_LS_HTTP_WEBSOCKET_SETUP,
335 "id=static: Failed to Base64-encode, error %d (%s)",
336 aws_last_error(),
337 aws_error_name(aws_last_error()));
338 goto cleanup;
339 }
340
341 success = true;
342 cleanup:
343 if (sha1) {
344 aws_hash_destroy(sha1);
345 }
346 return success ? AWS_OP_SUCCESS : AWS_OP_ERR;
347 }
348
349 /* Called if something goes wrong after an HTTP connection is established.
350 * The HTTP connection is closed.
351 * We must wait for its shutdown to complete before informing user of the failed websocket setup. */
352 static void s_ws_bootstrap_cancel_setup_due_to_err(
353 struct aws_websocket_client_bootstrap *ws_bootstrap,
354 struct aws_http_connection *http_connection,
355 int error_code) {
356
357 AWS_ASSERT(error_code);
358 AWS_ASSERT(http_connection);
359
360 if (!ws_bootstrap->setup_error_code) {
361 AWS_LOGF_ERROR(
362 AWS_LS_HTTP_WEBSOCKET_SETUP,
363 "id=%p: Canceling websocket setup due to error %d (%s).",
364 (void *)ws_bootstrap,
365 error_code,
366 aws_error_name(error_code));
367
368 ws_bootstrap->setup_error_code = error_code;
369
370 s_system_vtable->aws_http_connection_close(http_connection);
371 }
372 }
373
374 static void s_ws_bootstrap_invoke_setup_callback(struct aws_websocket_client_bootstrap *ws_bootstrap, int error_code) {
375
376 /* sanity check: websocket XOR error_code is set. both cannot be set. both cannot be unset */
377 AWS_FATAL_ASSERT((error_code != 0) ^ (ws_bootstrap->websocket != NULL));
378
379 /* Report things about the response, if we received them */
380 int *response_status_ptr = NULL;
381 struct aws_http_header *response_header_array = NULL;
382 size_t num_response_headers = 0;
383 struct aws_byte_cursor *response_body_ptr = NULL;
384 struct aws_byte_cursor response_body_cursor = {.len = 0};
385
386 if (ws_bootstrap->got_full_response_headers) {
387 response_status_ptr = &ws_bootstrap->response_status;
388
389 num_response_headers = aws_http_headers_count(ws_bootstrap->response_headers);
390
391 response_header_array =
392 aws_mem_calloc(ws_bootstrap->alloc, aws_max_size(1, num_response_headers), sizeof(struct aws_http_header));
393
394 for (size_t i = 0; i < num_response_headers; ++i) {
395 aws_http_headers_get_index(ws_bootstrap->response_headers, i, &response_header_array[i]);
396 }
397
398 if (ws_bootstrap->got_full_response_body) {
399 response_body_cursor = aws_byte_cursor_from_buf(&ws_bootstrap->response_body);
400 response_body_ptr = &response_body_cursor;
401 }
402 }
403
404 struct aws_websocket_on_connection_setup_data setup_data = {
405 .error_code = error_code,
406 .websocket = ws_bootstrap->websocket,
407 .handshake_response_status = response_status_ptr,
408 .handshake_response_header_array = response_header_array,
409 .num_handshake_response_headers = num_response_headers,
410 .handshake_response_body = response_body_ptr,
411 };
412
413 ws_bootstrap->websocket_setup_callback(&setup_data, ws_bootstrap->user_data);
414
415 /* Clear setup callback so that we know that it's been invoked. */
416 ws_bootstrap->websocket_setup_callback = NULL;
417
418 if (response_header_array) {
419 aws_mem_release(ws_bootstrap->alloc, response_header_array);
420 }
421 }
422
423 /* Invoked when HTTP connection has been established (or failed to be established) */
424 static void s_ws_bootstrap_on_http_setup(struct aws_http_connection *http_connection, int error_code, void *user_data) {
425
426 struct aws_websocket_client_bootstrap *ws_bootstrap = user_data;
427
428 /* Setup callback contract is: if error_code is non-zero then connection is NULL. */
429 AWS_FATAL_ASSERT((error_code != 0) == (http_connection == NULL));
430
431 /* If http connection failed, inform the user immediately and clean up the websocket bootstrapper. */
432 if (error_code) {
433 AWS_LOGF_ERROR(
434 AWS_LS_HTTP_WEBSOCKET_SETUP,
435 "id=%p: Websocket setup failed to establish HTTP connection, error %d (%s).",
436 (void *)ws_bootstrap,
437 error_code,
438 aws_error_name(error_code));
439
440 s_ws_bootstrap_invoke_setup_callback(ws_bootstrap, error_code);
441
442 s_ws_bootstrap_destroy(ws_bootstrap);
443 return;
444 }
445
446 /* Connection exists!
447 * Note that if anything goes wrong with websocket setup from hereon out, we must close the http connection
448 * first and wait for shutdown to complete before informing the user of setup failure. */
449
450 /* Send the handshake request */
451 struct aws_http_make_request_options options = {
452 .self_size = sizeof(options),
453 .request = ws_bootstrap->handshake_request,
454 .user_data = ws_bootstrap,
455 .on_response_headers = s_ws_bootstrap_on_handshake_response_headers,
456 .on_response_header_block_done = s_ws_bootstrap_on_handshake_response_header_block_done,
457 .on_response_body = s_ws_bootstrap_on_handshake_response_body,
458 .on_complete = s_ws_bootstrap_on_stream_complete,
459 };
460
461 struct aws_http_stream *handshake_stream =
462 s_system_vtable->aws_http_connection_make_request(http_connection, &options);
463
464 if (!handshake_stream) {
465 AWS_LOGF_ERROR(
466 AWS_LS_HTTP_WEBSOCKET_SETUP,
467 "id=%p: Failed to make websocket upgrade request, error %d (%s).",
468 (void *)ws_bootstrap,
469 aws_last_error(),
470 aws_error_name(aws_last_error()));
471 goto error;
472 }
473
474 if (s_system_vtable->aws_http_stream_activate(handshake_stream)) {
475 AWS_LOGF_ERROR(
476 AWS_LS_HTTP_WEBSOCKET_SETUP,
477 "id=%p: Failed to activate websocket upgrade request, error %d (%s).",
478 (void *)ws_bootstrap,
479 aws_last_error(),
480 aws_error_name(aws_last_error()));
481 goto error;
482 }
483
484 /* Success! (so far) */
485 AWS_LOGF_TRACE(
486 AWS_LS_HTTP_WEBSOCKET_SETUP,
487 "id=%p: HTTP connection established, sending websocket upgrade request.",
488 (void *)ws_bootstrap);
489 return;
490
491 error:
492 s_system_vtable->aws_http_stream_release(handshake_stream);
493 s_ws_bootstrap_cancel_setup_due_to_err(ws_bootstrap, http_connection, aws_last_error());
494 }
495
496 /* Invoked when the HTTP connection has shut down.
497 * This is never called if the HTTP connection failed its setup */
498 static void s_ws_bootstrap_on_http_shutdown(
499 struct aws_http_connection *http_connection,
500 int error_code,
501 void *user_data) {
502
503 struct aws_websocket_client_bootstrap *ws_bootstrap = user_data;
504
505 /* Inform user that connection has completely shut down.
506 * If setup callback still hasn't fired, invoke it now and indicate failure.
507 * Otherwise, invoke shutdown callback. */
508 if (ws_bootstrap->websocket_setup_callback) {
509 AWS_ASSERT(!ws_bootstrap->websocket);
510
511 /* If there's already a setup_error_code, use that */
512 if (ws_bootstrap->setup_error_code) {
513 error_code = ws_bootstrap->setup_error_code;
514 }
515
516 /* Ensure non-zero error_code is passed */
517 if (!error_code) {
518 error_code = AWS_ERROR_UNKNOWN;
519 }
520
521 AWS_LOGF_ERROR(
522 AWS_LS_HTTP_WEBSOCKET_SETUP,
523 "id=%p: Websocket setup failed, error %d (%s).",
524 (void *)ws_bootstrap,
525 error_code,
526 aws_error_name(error_code));
527
528 s_ws_bootstrap_invoke_setup_callback(ws_bootstrap, error_code);
529
530 } else if (ws_bootstrap->websocket_shutdown_callback) {
531 AWS_ASSERT(ws_bootstrap->websocket);
532
533 AWS_LOGF_DEBUG(
534 AWS_LS_HTTP_WEBSOCKET,
535 "id=%p: Websocket client connection shut down with error %d (%s).",
536 (void *)ws_bootstrap->websocket,
537 error_code,
538 aws_error_name(error_code));
539
540 ws_bootstrap->websocket_shutdown_callback(ws_bootstrap->websocket, error_code, ws_bootstrap->user_data);
541 }
542
543 /* Clean up HTTP connection and websocket-bootstrap.
544 * It's still up to the user to release the websocket itself. */
545 s_system_vtable->aws_http_connection_release(http_connection);
546
547 s_ws_bootstrap_destroy(ws_bootstrap);
548 }
549
550 /* Invoked repeatedly as handshake response headers arrive */
551 static int s_ws_bootstrap_on_handshake_response_headers(
552 struct aws_http_stream *stream,
553 enum aws_http_header_block header_block,
554 const struct aws_http_header *header_array,
555 size_t num_headers,
556 void *user_data) {
557
558 (void)stream;
559 (void)header_block;
560
561 struct aws_websocket_client_bootstrap *ws_bootstrap = user_data;
562
563 /* Deep-copy headers into ws_bootstrap */
564 aws_http_headers_add_array(ws_bootstrap->response_headers, header_array, num_headers);
565
566 /* Don't report a partially-received response */
567 ws_bootstrap->got_full_response_headers = false;
568
569 return AWS_OP_SUCCESS;
570 }
571
572 static int s_ws_bootstrap_validate_header(
573 struct aws_websocket_client_bootstrap *ws_bootstrap,
574 const char *name,
575 struct aws_byte_cursor expected_value,
576 bool case_sensitive) {
577
578 struct aws_byte_cursor actual_value;
579 if (aws_http_headers_get(ws_bootstrap->response_headers, aws_byte_cursor_from_c_str(name), &actual_value)) {
580 AWS_LOGF_ERROR(
581 AWS_LS_HTTP_WEBSOCKET_SETUP, "id=%p: Response lacks required '%s' header", (void *)ws_bootstrap, name);
582 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_UPGRADE_FAILURE);
583 }
584
585 bool matches = case_sensitive ? aws_byte_cursor_eq(&expected_value, &actual_value)
586 : aws_byte_cursor_eq_ignore_case(&expected_value, &actual_value);
587 if (!matches) {
588 AWS_LOGF_ERROR(
589 AWS_LS_HTTP_WEBSOCKET_SETUP,
590 "id=%p: Response '%s' header has wrong value. Expected '" PRInSTR "'. Received '" PRInSTR "'",
591 (void *)ws_bootstrap,
592 name,
593 AWS_BYTE_CURSOR_PRI(expected_value),
594 AWS_BYTE_CURSOR_PRI(actual_value));
595 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_UPGRADE_FAILURE);
596 }
597
598 return AWS_OP_SUCCESS;
599 }
600
601 static int s_ws_bootstrap_validate_sec_websocket_protocol(const struct aws_websocket_client_bootstrap *ws_bootstrap) {
602 /* First handle the easy case:
603 * If client requested no protocols, then the response should not pick any */
604 if (ws_bootstrap->expected_sec_websocket_protocols == NULL) {
605 if (aws_http_headers_has(
606 ws_bootstrap->response_headers, aws_byte_cursor_from_c_str("Sec-WebSocket-Protocol"))) {
607
608 AWS_LOGF_ERROR(
609 AWS_LS_HTTP_WEBSOCKET_SETUP,
610 "id=%p: Response has 'Sec-WebSocket-Protocol' header, no protocol was requested",
611 (void *)ws_bootstrap);
612 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_UPGRADE_FAILURE);
613 } else {
614 return AWS_OP_SUCCESS;
615 }
616 }
617
618 /* Check that server has picked one of the protocols listed in the request */
619 struct aws_byte_cursor response_protocol;
620 if (aws_http_headers_get(
621 ws_bootstrap->response_headers, aws_byte_cursor_from_c_str("Sec-WebSocket-Protocol"), &response_protocol)) {
622 AWS_LOGF_ERROR(
623 AWS_LS_HTTP_WEBSOCKET_SETUP,
624 "id=%p: Response lacks required 'Sec-WebSocket-Protocol' header",
625 (void *)ws_bootstrap);
626 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_UPGRADE_FAILURE);
627 }
628
629 struct aws_byte_cursor request_protocols =
630 aws_byte_cursor_from_string(ws_bootstrap->expected_sec_websocket_protocols);
631 struct aws_byte_cursor request_protocol_i;
632 AWS_ZERO_STRUCT(request_protocol_i);
633 while (aws_byte_cursor_next_split(&request_protocols, ',', &request_protocol_i)) {
634 struct aws_byte_cursor request_protocol = aws_strutil_trim_http_whitespace(request_protocol_i);
635 if (aws_byte_cursor_eq(&response_protocol, &request_protocol)) {
636 /* Success! */
637 AWS_LOGF_DEBUG(
638 AWS_LS_HTTP_WEBSOCKET_SETUP,
639 "id=%p: Server selected Sec-WebSocket-Protocol: " PRInSTR,
640 (void *)ws_bootstrap,
641 AWS_BYTE_CURSOR_PRI(response_protocol));
642 return AWS_OP_SUCCESS;
643 }
644 }
645
646 AWS_LOGF_ERROR(
647 AWS_LS_HTTP_WEBSOCKET_SETUP,
648 "id=%p: Response 'Sec-WebSocket-Protocol' header has wrong value. Received '" PRInSTR
649 "'. Expected one of '" PRInSTR "'",
650 (void *)ws_bootstrap,
651 AWS_BYTE_CURSOR_PRI(response_protocol),
652 AWS_BYTE_CURSOR_PRI(request_protocols));
653 return aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_UPGRADE_FAILURE);
654 }
655
656 /* OK, we've got all the headers for the 101 Switching Protocols response.
657 * Validate the handshake response, install the websocket handler into the channel,
658 * and invoke the on_connection_setup callback. */
659 static int s_ws_bootstrap_validate_response_and_install_websocket_handler(
660 struct aws_websocket_client_bootstrap *ws_bootstrap,
661 struct aws_http_connection *http_connection) {
662
663 /* RFC-6455 Section 4.1 - The client MUST validate the server's response as follows... */
664
665 /* (we already checked step 1, that status code is 101) */
666 AWS_FATAL_ASSERT(ws_bootstrap->response_status == AWS_HTTP_STATUS_CODE_101_SWITCHING_PROTOCOLS);
667
668 /* 2. If the response lacks an |Upgrade| header field or the |Upgrade|
669 * header field contains a value that is not an ASCII case-
670 * insensitive match for the value "websocket", the client MUST
671 * _Fail the WebSocket Connection_. */
672 if (s_ws_bootstrap_validate_header(
673 ws_bootstrap, "Upgrade", aws_byte_cursor_from_c_str("websocket"), false /*case_sensitive*/)) {
674 goto error;
675 }
676
677 /* 3. If the response lacks a |Connection| header field or the
678 * |Connection| header field doesn't contain a token that is an
679 * ASCII case-insensitive match for the value "Upgrade", the client
680 * MUST _Fail the WebSocket Connection_. */
681 if (s_ws_bootstrap_validate_header(
682 ws_bootstrap, "Connection", aws_byte_cursor_from_c_str("Upgrade"), false /*case_sensitive*/)) {
683 goto error;
684 }
685
686 /* 4. If the response lacks a |Sec-WebSocket-Accept| header field or
687 * the |Sec-WebSocket-Accept| contains a value other than the
688 * base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
689 * Key| (as a string, not base64-decoded) with the string "258EAFA5-
690 * E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
691 * trailing whitespace, the client MUST _Fail the WebSocket
692 * Connection_. */
693 if (s_ws_bootstrap_validate_header(
694 ws_bootstrap,
695 "Sec-WebSocket-Accept",
696 aws_byte_cursor_from_buf(&ws_bootstrap->expected_sec_websocket_accept),
697 true /*case_sensitive*/)) {
698 goto error;
699 }
700
701 /* (step 5 is about validating Sec-WebSocket-Extensions, but we don't support extensions) */
702 if (aws_http_headers_has(ws_bootstrap->response_headers, aws_byte_cursor_from_c_str("Sec-WebSocket-Extensions"))) {
703 AWS_LOGF_ERROR(
704 AWS_LS_HTTP_WEBSOCKET_SETUP,
705 "id=%p: Response has 'Sec-WebSocket-Extensions' header, but client does not support extensions.",
706 (void *)ws_bootstrap);
707 aws_raise_error(AWS_ERROR_HTTP_WEBSOCKET_UPGRADE_FAILURE);
708 goto error;
709 }
710
711 /* 6. If the response includes a |Sec-WebSocket-Protocol| header field
712 * and this header field indicates the use of a subprotocol that was
713 * not present in the client's handshake (the server has indicated a
714 * subprotocol not requested by the client), the client MUST _Fail
715 * the WebSocket Connection_. */
716 if (s_ws_bootstrap_validate_sec_websocket_protocol(ws_bootstrap)) {
717 goto error;
718 }
719
720 /* Insert websocket handler into channel */
721 struct aws_channel *channel = s_system_vtable->aws_http_connection_get_channel(http_connection);
722 AWS_ASSERT(channel);
723
724 struct aws_websocket_handler_options ws_options = {
725 .allocator = ws_bootstrap->alloc,
726 .channel = channel,
727 .initial_window_size = ws_bootstrap->initial_window_size,
728 .user_data = ws_bootstrap->user_data,
729 .on_incoming_frame_begin = ws_bootstrap->websocket_frame_begin_callback,
730 .on_incoming_frame_payload = ws_bootstrap->websocket_frame_payload_callback,
731 .on_incoming_frame_complete = ws_bootstrap->websocket_frame_complete_callback,
732 .is_server = false,
733 .manual_window_update = ws_bootstrap->manual_window_update,
734 };
735
736 ws_bootstrap->websocket = s_system_vtable->aws_websocket_handler_new(&ws_options);
737 if (!ws_bootstrap->websocket) {
738 AWS_LOGF_ERROR(
739 AWS_LS_HTTP_WEBSOCKET_SETUP,
740 "id=%p: Failed to create websocket handler, error %d (%s)",
741 (void *)ws_bootstrap,
742 aws_last_error(),
743 aws_error_name(aws_last_error()));
744
745 goto error;
746 }
747
748 /* Success! Setup complete! */
749 AWS_LOGF_TRACE(/* Log for tracing setup id to websocket id. */
750 AWS_LS_HTTP_WEBSOCKET_SETUP,
751 "id=%p: Setup success, created websocket=%p",
752 (void *)ws_bootstrap,
753 (void *)ws_bootstrap->websocket);
754
755 AWS_LOGF_DEBUG(/* Debug log about creation of websocket. */
756 AWS_LS_HTTP_WEBSOCKET,
757 "id=%p: Websocket client connection established.",
758 (void *)ws_bootstrap->websocket);
759
760 s_ws_bootstrap_invoke_setup_callback(ws_bootstrap, 0 /*error_code*/);
761 return AWS_OP_SUCCESS;
762
763 error:
764 s_ws_bootstrap_cancel_setup_due_to_err(ws_bootstrap, http_connection, aws_last_error());
765 /* Returning error stops HTTP from processing any further data */
766 return AWS_OP_ERR;
767 }
768
769 /**
770 * Invoked each time we reach the end of a block of response headers.
771 * If we got a valid 101 Switching Protocols response, we insert the websocket handler.
772 * Note:
773 * In HTTP, 1xx responses are "interim" responses. So a 101 Switching Protocols
774 * response does not "complete" the stream. Once the connection has switched
775 * protocols, the stream does not end until the whole connection is closed.
776 */
777 static int s_ws_bootstrap_on_handshake_response_header_block_done(
778 struct aws_http_stream *stream,
779 enum aws_http_header_block header_block,
780 void *user_data) {
781
782 struct aws_websocket_client_bootstrap *ws_bootstrap = user_data;
783 struct aws_http_connection *http_connection = s_system_vtable->aws_http_stream_get_connection(stream);
784 AWS_ASSERT(http_connection);
785
786 /* Get status code from stream */
787 s_system_vtable->aws_http_stream_get_incoming_response_status(stream, &ws_bootstrap->response_status);
788
789 ws_bootstrap->got_full_response_headers = true;
790
791 if (header_block == AWS_HTTP_HEADER_BLOCK_INFORMATIONAL) {
792 if (ws_bootstrap->response_status == AWS_HTTP_STATUS_CODE_101_SWITCHING_PROTOCOLS) {
793 /* OK, got 101 response, proceed with upgrade! */
794 return s_ws_bootstrap_validate_response_and_install_websocket_handler(ws_bootstrap, http_connection);
795
796 } else {
797 /* It would be weird to get any other kind of 1xx response, but anything is possible.
798 * Another response should come eventually. Just ignore the headers from this one... */
799 AWS_LOGF_DEBUG(
800 AWS_LS_HTTP_WEBSOCKET_SETUP,
801 "id=%p: Server sent interim response with status code %d",
802 (void *)ws_bootstrap,
803 ws_bootstrap->response_status);
804
805 aws_http_headers_clear(ws_bootstrap->response_headers);
806 ws_bootstrap->got_full_response_headers = false;
807 return AWS_OP_SUCCESS;
808 }
809 }
810
811 /* Otherwise, we got normal headers (from a non-1xx response), or trailing headers.
812 * This can only happen if the handshake did not succeed. Keep the connection going.
813 * We'll report failed setup to the user after we've received the complete response */
814 ws_bootstrap->setup_error_code = AWS_ERROR_HTTP_WEBSOCKET_UPGRADE_FAILURE;
815 return AWS_OP_SUCCESS;
816 }
817
818 /**
819 * Invoked as we receive the body of a failed response.
820 * This is never invoked if the handshake succeeds.
821 */
822 static int s_ws_bootstrap_on_handshake_response_body(
823 struct aws_http_stream *stream,
824 const struct aws_byte_cursor *data,
825 void *user_data) {
826
827 struct aws_websocket_client_bootstrap *ws_bootstrap = user_data;
828
829 aws_byte_buf_append_dynamic(&ws_bootstrap->response_body, data);
830
831 /* If we're managing the read window...
832 * bump the HTTP window back to its starting size, so that we keep receiving the whole response. */
833 if (ws_bootstrap->manual_window_update) {
834 s_system_vtable->aws_http_stream_update_window(stream, data->len);
835 }
836
837 return AWS_OP_SUCCESS;
838 }
839
840 /**
841 * Invoked when the stream completes.
842 *
843 * If the handshake succeeded and the websocket was installed,
844 * then this is invoked at the end of the websocket connection.
845 *
846 * If the handshake response was not 101, then this is invoked
847 * after we've received the whole response.
848 *
849 * Or this is invoked because the connection failed unexpectedly before the handshake could complete,
850 * (or we killed the connection because the 101 response didn't pass validation).
851 */
852 static void s_ws_bootstrap_on_stream_complete(struct aws_http_stream *stream, int error_code, void *user_data) {
853 struct aws_websocket_client_bootstrap *ws_bootstrap = user_data;
854 struct aws_http_connection *http_connection = s_system_vtable->aws_http_stream_get_connection(stream);
855
856 /* Only report the body if we received a complete response */
857 if (error_code == 0) {
858 ws_bootstrap->got_full_response_body = true;
859 }
860
861 /* Make sure the connection closes.
862 * We'll deal with finishing setup or shutdown from the http-shutdown callback */
863 s_system_vtable->aws_http_connection_close(http_connection);
864
865 /* Done with stream, let it be cleaned up */
866 s_system_vtable->aws_http_stream_release(stream);
867 }