Debian Codegraph @

src/ws/cockpitwebserver.c

raw
1 /*
2 * Copyright (C) 2013-2014 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 #include "config.h"
7
8 /* This gets logged as part of the (more verbose) protocol logging */
9 #ifdef G_LOG_DOMAIN
10 #undef G_LOG_DOMAIN
11 #endif
12 #define G_LOG_DOMAIN "cockpit-protocol"
13
14 #include "cockpitwebserver.h"
15
16 #include "common/cockpitconf.h"
17 #include "cockpithash.h"
18 #include "cockpitjson.h"
19 #include "cockpitmemfdread.h"
20 #include "common/cockpitmemory.h"
21 #include "cockpitsocket.h"
22 #include "cockpitwebresponse.h"
23
24 #include "websocket.h"
25
26 #include <sys/socket.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32
33 #include "cockpitwebrequest-private.h"
34
35 guint cockpit_webserver_request_timeout = 30;
36 const gsize cockpit_webserver_request_maximum = 8192;
37
38 struct _CockpitWebServer {
39 GObject parent_instance;
40
41 GString *ssl_exception_prefix;
42 GString *url_root;
43 gint request_timeout;
44 gint request_max;
45 CockpitWebServerFlags flags;
46
47 gchar *protocol_header;
48 gchar *forwarded_for_header;
49
50 GSocketService *socket_service;
51 GMainContext *main_context;
52 GHashTable *requests;
53 };
54
55 enum
56 {
57 PROP_0,
58 PROP_SSL_EXCEPTION_PREFIX,
59 PROP_FLAGS,
60 PROP_URL_ROOT,
61 };
62
63 static gint sig_handle_stream = 0;
64 static gint sig_handle_resource = 0;
65
66 static void cockpit_web_request_free (gpointer data);
67
68 static void cockpit_web_request_start (CockpitWebServer *web_server,
69 GIOStream *stream,
70 gboolean first);
71
72 G_DEFINE_TYPE (CockpitWebServer, cockpit_web_server, G_TYPE_OBJECT)
73
74 /* ---------------------------------------------------------------------------------------------------- */
75
76 static gboolean
77 on_incoming (GSocketService *service,
78 GSocketConnection *connection,
79 GObject *source_object,
80 gpointer user_data)
81 {
82 CockpitWebServer *self = COCKPIT_WEB_SERVER (user_data);
83 cockpit_web_request_start (self, G_IO_STREAM (connection), TRUE);
84
85 /* handled */
86 return TRUE;
87 }
88
89 static void
90 cockpit_web_server_init (CockpitWebServer *server)
91 {
92 server->requests = g_hash_table_new_full (g_direct_hash, g_direct_equal,
93 cockpit_web_request_free, NULL);
94 server->main_context = g_main_context_ref_thread_default ();
95 server->ssl_exception_prefix = g_string_new ("");
96 server->url_root = g_string_new ("");
97
98 server->socket_service = g_socket_service_new ();
99
100 /* The web server has to be explicitly started */
101 g_socket_service_stop (server->socket_service);
102
103 g_signal_connect (server->socket_service, "incoming",
104 G_CALLBACK (on_incoming), server);
105 }
106
107 static void
108 cockpit_web_server_dispose (GObject *object)
109 {
110 CockpitWebServer *self = COCKPIT_WEB_SERVER (object);
111
112 g_hash_table_remove_all (self->requests);
113
114 G_OBJECT_CLASS (cockpit_web_server_parent_class)->dispose (object);
115 }
116
117 static void
118 cockpit_web_server_finalize (GObject *object)
119 {
120 CockpitWebServer *server = COCKPIT_WEB_SERVER (object);
121
122 g_hash_table_destroy (server->requests);
123 if (server->main_context)
124 g_main_context_unref (server->main_context);
125 g_string_free (server->ssl_exception_prefix, TRUE);
126 g_string_free (server->url_root, TRUE);
127 g_clear_object (&server->socket_service);
128 g_free (server->protocol_header);
129 g_free (server->forwarded_for_header);
130
131 G_OBJECT_CLASS (cockpit_web_server_parent_class)->finalize (object);
132 }
133
134 static void
135 cockpit_web_server_get_property (GObject *object,
136 guint prop_id,
137 GValue *value,
138 GParamSpec *pspec)
139 {
140 CockpitWebServer *server = COCKPIT_WEB_SERVER (object);
141
142 switch (prop_id)
143 {
144 case PROP_SSL_EXCEPTION_PREFIX:
145 g_value_set_string (value, server->ssl_exception_prefix->str);
146 break;
147
148 case PROP_URL_ROOT:
149 if (server->url_root->len)
150 g_value_set_string (value, server->url_root->str);
151 else
152 g_value_set_string (value, NULL);
153 break;
154
155 case PROP_FLAGS:
156 g_value_set_int (value, server->flags);
157 break;
158
159 default:
160 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
161 break;
162 }
163 }
164
165 static void
166 cockpit_web_server_set_property (GObject *object,
167 guint prop_id,
168 const GValue *value,
169 GParamSpec *pspec)
170 {
171 CockpitWebServer *server = COCKPIT_WEB_SERVER (object);
172 GString *str;
173
174 switch (prop_id)
175 {
176 case PROP_SSL_EXCEPTION_PREFIX:
177 g_string_assign (server->ssl_exception_prefix, g_value_get_string (value));
178 break;
179
180 case PROP_URL_ROOT:
181 str = g_string_new (g_value_get_string (value));
182
183 while (str->str[0] == '/')
184 g_string_erase (str, 0, 1);
185
186 if (str->len)
187 {
188 while (str->str[str->len - 1] == '/')
189 g_string_truncate (str, str->len - 1);
190 }
191
192 if (str->len)
193 g_string_printf (server->url_root, "/%s", str->str);
194 else
195 g_string_assign (server->url_root, str->str);
196
197 g_string_free (str, TRUE);
198 break;
199
200 case PROP_FLAGS:
201 server->flags = g_value_get_int (value);
202 break;
203
204 default:
205 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
206 break;
207 }
208 }
209
210 static void
211 on_io_closed (GObject *stream,
212 GAsyncResult *result,
213 gpointer user_data)
214 {
215 GError *error = NULL;
216
217 if (!g_io_stream_close_finish (G_IO_STREAM (stream), result, &error))
218 {
219 if (!cockpit_web_should_suppress_output_error ("http", error))
220 g_message ("http close error: %s", error->message);
221 g_error_free (error);
222 }
223 }
224
225 static void
226 close_io_stream (GIOStream *io)
227 {
228 g_io_stream_close_async (io, G_PRIORITY_DEFAULT, NULL, on_io_closed, NULL);
229 }
230
231 static void
232 on_web_response_done (CockpitWebResponse *response,
233 gboolean reusable,
234 gpointer user_data)
235 {
236 CockpitWebServer *self = user_data;
237 GIOStream *io;
238
239 io = cockpit_web_response_get_stream (response);
240 if (reusable)
241 cockpit_web_request_start (self, io, FALSE);
242 else
243 close_io_stream (io);
244 }
245
246 static gboolean
247 cockpit_web_server_default_handle_resource (CockpitWebServer *self,
248 CockpitWebRequest *request,
249 const gchar *path,
250 GHashTable *headers,
251 CockpitWebResponse *response)
252 {
253 cockpit_web_response_error (response, 404, NULL, NULL);
254 return TRUE;
255 }
256
257 static gboolean
258 cockpit_web_server_default_handle_stream (CockpitWebServer *self,
259 CockpitWebRequest *request)
260 {
261 CockpitWebResponse *response;
262 gboolean claimed = FALSE;
263 GQuark detail = 0;
264
265 /* TODO: Correct HTTP version for response */
266 response = cockpit_web_request_respond (request);
267 g_signal_connect_data (response, "done", G_CALLBACK (on_web_response_done),
268 g_object_ref (self), (GClosureNotify)g_object_unref, 0);
269
270 /*
271 * If the path has more than one component, then we search
272 * for handlers registered under the detail like this:
273 *
274 * /component/
275 *
276 * Otherwise we search for handlers registered under detail
277 * of the entire path:
278 *
279 * /component
280 *
281 * We only bother to calculate the detail if it would have a length of
282 * less than 100: nobody is going to register a signal handler for a
283 * longer path than that.
284 */
285 g_assert (request->path[0] == '/');
286 gsize component_end = 1 + strcspn (request->path + 1, "/");
287 if (request->path[component_end] == '/')
288 component_end++;
289 if (component_end < 100)
290 {
291 gchar buffer[component_end + 1];
292 memcpy (buffer, request->path, component_end);
293 buffer[component_end] = '\0';
294 detail = g_quark_try_string (buffer);
295 }
296
297 /* See if we have any takers... */
298 g_signal_emit (self,
299 sig_handle_resource, detail,
300 request,
301 request->path,
302 request->headers,
303 response,
304 &claimed);
305
306 if (!claimed)
307 claimed = cockpit_web_server_default_handle_resource (self, request, request->path, request->headers, response);
308
309 /* TODO: Here is where we would plug keep-alive into response */
310 g_object_unref (response);
311
312 return claimed;
313 }
314
315 static void
316 cockpit_web_server_class_init (CockpitWebServerClass *klass)
317 {
318 GObjectClass *gobject_class;
319
320 gobject_class = G_OBJECT_CLASS (klass);
321 gobject_class->dispose = cockpit_web_server_dispose;
322 gobject_class->finalize = cockpit_web_server_finalize;
323 gobject_class->set_property = cockpit_web_server_set_property;
324 gobject_class->get_property = cockpit_web_server_get_property;
325
326 g_object_class_install_property (gobject_class, PROP_SSL_EXCEPTION_PREFIX,
327 g_param_spec_string ("ssl-exception-prefix", NULL, NULL, "",
328 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
329
330 g_object_class_install_property (gobject_class, PROP_URL_ROOT,
331 g_param_spec_string ("url-root", NULL, NULL, "",
332 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
333
334 g_object_class_install_property (gobject_class, PROP_FLAGS,
335 g_param_spec_int ("flags", NULL, NULL, 0, COCKPIT_WEB_SERVER_FLAGS_MAX, 0,
336 G_PARAM_READABLE |
337 G_PARAM_WRITABLE |
338 G_PARAM_CONSTRUCT_ONLY |
339 G_PARAM_STATIC_STRINGS));
340
341 sig_handle_stream = g_signal_new ("handle-stream",
342 G_OBJECT_CLASS_TYPE (klass),
343 G_SIGNAL_RUN_LAST,
344 0, /* class offset */
345 g_signal_accumulator_true_handled,
346 NULL, /* accu_data */
347 g_cclosure_marshal_generic,
348 G_TYPE_BOOLEAN,
349 1,
350 COCKPIT_TYPE_WEB_REQUEST | G_SIGNAL_TYPE_STATIC_SCOPE);
351
352 sig_handle_resource = g_signal_new ("handle-resource",
353 G_OBJECT_CLASS_TYPE (klass),
354 G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
355 0, /* class offset */
356 g_signal_accumulator_true_handled,
357 NULL, /* accu_data */
358 g_cclosure_marshal_generic,
359 G_TYPE_BOOLEAN,
360 4,
361 COCKPIT_TYPE_WEB_REQUEST | G_SIGNAL_TYPE_STATIC_SCOPE,
362 G_TYPE_STRING,
363 G_TYPE_HASH_TABLE,
364 COCKPIT_TYPE_WEB_RESPONSE);
365 }
366
367 CockpitWebServer *
368 cockpit_web_server_new (CockpitWebServerFlags flags)
369 {
370 return g_object_new (COCKPIT_TYPE_WEB_SERVER,
371 "flags", flags,
372 NULL);
373 }
374
375 /* ---------------------------------------------------------------------------------------------------- */
376
377 CockpitWebServerFlags
378 cockpit_web_server_get_flags (CockpitWebServer *self)
379 {
380 g_return_val_if_fail (COCKPIT_IS_WEB_SERVER (self), COCKPIT_WEB_SERVER_NONE);
381
382 return self->flags;
383 }
384
385 GHashTable *
386 cockpit_web_server_new_table (void)
387 {
388 return g_hash_table_new_full (cockpit_str_case_hash, cockpit_str_case_equal, g_free, g_free);
389 }
390
391 gchar *
392 cockpit_web_server_parse_cookie (GHashTable *headers,
393 const gchar *name)
394 {
395 const gchar *header;
396 const gchar *pos;
397 const gchar *value;
398 const gchar *end;
399 gboolean at_start = TRUE;
400 gchar *decoded;
401 gint diff;
402 gint offset;
403
404 header = g_hash_table_lookup (headers, "Cookie");
405 if (!header)
406 return NULL;
407
408 for (;;)
409 {
410 pos = strstr (header, name);
411 if (!pos)
412 return NULL;
413
414 if (pos != header)
415 {
416 diff = strlen (header) - strlen (pos);
417 offset = 1;
418 at_start = FALSE;
419 while (offset < diff)
420 {
421 if (!g_ascii_isspace (*(pos - offset)))
422 {
423 at_start = *(pos - offset) == ';';
424 break;
425 }
426 offset++;
427 }
428 }
429
430 pos += strlen (name);
431 if (*pos == '=' && at_start)
432 {
433 value = pos + 1;
434 end = strchr (value, ';');
435 if (end == NULL)
436 end = value + strlen (value);
437
438 decoded = g_uri_unescape_segment (value, end, NULL);
439 if (!decoded)
440 g_debug ("invalid cookie encoding");
441
442 return decoded;
443 }
444 else
445 {
446 at_start = FALSE;
447 }
448 header = pos;
449 }
450 }
451
452 typedef struct {
453 double qvalue;
454 const gchar *value;
455 } Language;
456
457 static gint
458 sort_qvalue (gconstpointer a,
459 gconstpointer b)
460 {
461 const Language *la = *((Language **)a);
462 const Language *lb = *((Language **)b);
463 if (lb->qvalue == la->qvalue)
464 return 0;
465 return lb->qvalue < la->qvalue ? -1 : 1;
466 }
467
468 gchar **
469 cockpit_web_server_parse_accept_list (const gchar *accept,
470 const gchar *defawlt)
471 {
472 g_autofree gchar *copy = g_strdup (accept);
473 gchar *walk = copy;
474
475 g_autoptr(GPtrArray) langs = g_ptr_array_new_with_free_func (g_free);
476
477 if (defawlt)
478 {
479 Language *lang = g_new0 (Language, 1);
480 lang->qvalue = 0.1;
481 lang->value = defawlt;
482 g_ptr_array_add (langs, lang);
483 }
484
485 /* First build up an array we can sort */
486 while (walk)
487 {
488 gchar *next = strchr (walk, ',');
489 if (next)
490 {
491 *next = '\0';
492 next++;
493 }
494
495 Language *lang = g_new0 (Language, 1);
496 lang->qvalue = 1;
497
498 gchar *pos = strchr (walk, ';');
499 if (pos)
500 {
501 *pos = '\0';
502 if (strncmp (pos + 1, "q=", 2) == 0)
503 {
504 lang->qvalue = g_ascii_strtod (pos + 3, NULL);
505 if (lang->qvalue < 0)
506 lang->qvalue = 0;
507 }
508 }
509
510 lang->value = walk;
511 g_ptr_array_add (langs, lang);
512 walk = next;
513 }
514
515 g_ptr_array_sort (langs, sort_qvalue);
516
517 /* Now in the right order add all the prefs */
518 GPtrArray *ret = g_ptr_array_new ();
519 for (guint i = 0; i < langs->len; i++)
520 {
521 Language *lang = langs->pdata[i];
522 if (lang->qvalue > 0)
523 {
524 gchar *value = g_strstrip (g_ascii_strdown (lang->value, -1));
525 g_ptr_array_add (ret, value);
526 }
527 }
528
529 /* Add base languages after that */
530 for (guint i = 0; i < langs->len; i++)
531 {
532 Language *lang = langs->pdata[i];
533 if (lang->qvalue > 0)
534 {
535 const gchar *dash = strchr (lang->value, '-');
536 if (dash)
537 {
538 gchar *value = g_strstrip (g_ascii_strdown (lang->value, dash - lang->value));
539 g_ptr_array_add (ret, value);
540 }
541 }
542 }
543
544 g_ptr_array_add (ret, NULL);
545 return (gchar **)g_ptr_array_free (ret, FALSE);
546 }
547
548 /* ---------------------------------------------------------------------------------------------------- */
549
550 guint16
551 cockpit_web_server_add_inet_listener (CockpitWebServer *self,
552 const gchar *address,
553 guint16 port,
554 GError **error)
555 {
556 if (address != NULL)
557 {
558 g_autoptr(GSocketAddress) socket_address = g_inet_socket_address_new_from_string (address, port);
559 if (socket_address == NULL)
560 {
561 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA,
562 "Couldn't parse IP address from `%s`", address);
563 return 0;
564 }
565
566 g_autoptr(GSocketAddress) result_address = NULL;
567 if (!g_socket_listener_add_address (G_SOCKET_LISTENER (self->socket_service), socket_address,
568 G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_DEFAULT,
569 NULL, &result_address, error))
570 return 0;
571
572 port = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (result_address));
573 g_assert (port != 0);
574
575 return port;
576 }
577
578 else if (port > 0)
579 {
580 if (g_socket_listener_add_inet_port (G_SOCKET_LISTENER (self->socket_service), port, NULL, error))
581 return port;
582 else
583 return 0;
584 }
585 else
586 return g_socket_listener_add_any_inet_port (G_SOCKET_LISTENER (self->socket_service), NULL, error);
587 }
588
589 gboolean
590 cockpit_web_server_add_fd_listener (CockpitWebServer *self,
591 int fd,
592 GError **error)
593 {
594 g_autoptr(GSocket) socket = g_socket_new_from_fd (fd, error);
595 if (socket == NULL)
596 {
597 g_prefix_error (error, "Failed to acquire passed socket %i: ", fd);
598 return FALSE;
599 }
600
601 if (!g_socket_listener_add_socket (G_SOCKET_LISTENER (self->socket_service), socket, NULL, error))
602 {
603 g_prefix_error (error, "Failed to add listener for socket %i: ", fd);
604 return FALSE;
605 }
606
607 return TRUE;
608 }
609
610 void
611 cockpit_web_server_start (CockpitWebServer *self)
612 {
613 g_return_if_fail (COCKPIT_IS_WEB_SERVER (self));
614 g_socket_service_start (self->socket_service);
615 }
616
617 /* ---------------------------------------------------------------------------------------------------- */
618
619 void
620 cockpit_web_server_set_protocol_header (CockpitWebServer *self,
621 const gchar *protocol_header)
622 {
623 g_free (self->protocol_header);
624 self->protocol_header = g_strdup (protocol_header);
625 }
626
627 void
628 cockpit_web_server_set_forwarded_for_header (CockpitWebServer *self,
629 const gchar *forwarded_for_header)
630 {
631 g_free (self->forwarded_for_header);
632 self->forwarded_for_header = g_strdup (forwarded_for_header);
633 }
634
635 /* ---------------------------------------------------------------------------------------------------- */
636
637 static CockpitWebRequest *
638 never_copy (CockpitWebRequest *self)
639 {
640 g_assert_not_reached ();
641 }
642
643 static void
644 never_free (CockpitWebRequest *self)
645 {
646 g_assert_not_reached ();
647 }
648
649 G_DEFINE_BOXED_TYPE(CockpitWebRequest, cockpit_web_request, never_copy, never_free);
650
651 static void
652 cockpit_web_request_free (gpointer data)
653 {
654 CockpitWebRequest *self = data;
655 if (self->timeout)
656 {
657 g_source_destroy (self->timeout);
658 g_source_unref (self->timeout);
659 }
660 if (self->source)
661 {
662 g_source_destroy (self->source);
663 g_source_unref (self->source);
664 }
665
666 /*
667 * Request memory is either cleared or used elsewhere, by
668 * handle-stream handlers (eg: the default handler. Don't
669 * clear it here. The buffer may still be in use.
670 */
671 g_byte_array_unref (self->buffer);
672 g_object_unref (self->io);
673 g_free (self);
674 }
675
676 static void
677 cockpit_web_request_finish (CockpitWebRequest *self)
678 {
679 g_hash_table_remove (self->web_server->requests, self);
680 }
681
682 static void
683 cockpit_web_request_process_delayed_reply (CockpitWebRequest *self,
684 const gchar *path,
685 GHashTable *headers)
686 {
687 g_assert (self->delayed_reply > 299);
688
689 g_autoptr(CockpitWebResponse) response = cockpit_web_request_respond (self);
690 g_signal_connect_data (response, "done", G_CALLBACK (on_web_response_done),
691 g_object_ref (self->web_server), (GClosureNotify)g_object_unref, 0);
692
693 if (self->delayed_reply == 301)
694 {
695 const gchar *host = g_hash_table_lookup (headers, "Host");
696 g_autofree gchar *url = g_strdup_printf ("https://%s%s", host != NULL ? host : "", path);
697 cockpit_web_response_headers (response, 301, "Moved Permanently", 0, "Location", url, NULL);
698 cockpit_web_response_complete (response);
699 }
700 else
701 {
702 cockpit_web_response_error (response, self->delayed_reply, NULL, NULL);
703 }
704 }
705
706 static gboolean
707 path_has_prefix (const gchar *path,
708 GString *prefix)
709 {
710 return prefix->len > 0 &&
711 strncmp (path, prefix->str, prefix->len) == 0 &&
712 (path[prefix->len] == '\0' || path[prefix->len] == '/');
713 }
714
715 static gboolean
716 is_localhost_connection (GSocketConnection *conn)
717 {
718 g_autoptr (GSocketAddress) addr = g_socket_connection_get_local_address (conn, NULL);
719 if (G_IS_INET_SOCKET_ADDRESS (addr))
720 {
721 GInetAddress *inet = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (addr));
722 return g_inet_address_get_is_loopback (inet);
723 }
724
725 return FALSE;
726 }
727
728 static void
729 cockpit_web_request_process (CockpitWebRequest *self,
730 const gchar *method,
731 const gchar *path,
732 const gchar *host,
733 GHashTable *headers)
734 {
735 gboolean claimed = FALSE;
736
737 if (self->web_server->url_root->len &&
738 !path_has_prefix (path, self->web_server->url_root))
739 {
740 self->delayed_reply = 404;
741 }
742
743 /* Redirect to TLS? */
744 if (!self->delayed_reply && self->check_tls_redirect)
745 {
746 self->check_tls_redirect = FALSE;
747
748 /* Certain paths don't require us to redirect */
749 if (!path_has_prefix (path, self->web_server->ssl_exception_prefix))
750 {
751 if (!is_localhost_connection (G_SOCKET_CONNECTION (self->io)))
752 {
753 g_debug ("redirecting request from Host: %s to TLS", host);
754 self->delayed_reply = 301;
755 }
756 }
757 }
758
759 self->method = method;
760
761 if (self->delayed_reply)
762 {
763 cockpit_web_request_process_delayed_reply (self, path, headers);
764 return;
765 }
766
767 g_autofree gchar *path_copy = g_strdup (path);
768
769 self->original_path = path_copy;
770 self->path = path_copy + self->web_server->url_root->len;
771 self->headers = headers;
772 self->host = host;
773
774 gchar *query = strchr (path_copy, '?');
775 if (query)
776 {
777 *query = '\0';
778 self->query = query + 1;
779 }
780 else
781 self->query = "";
782
783 /* Normalize path after URL Root is removed, exact URL Root requests yield an empty suffix */
784 if (self->path[0] == '\0')
785 self->path = "/";
786
787 /* See if we have any takers... */
788 g_signal_emit (self->web_server, sig_handle_stream, 0, self, &claimed);
789
790 if (!claimed)
791 claimed = cockpit_web_server_default_handle_stream (self->web_server, self);
792
793 self->original_path = NULL;
794 self->path = NULL;
795 self->query = NULL;
796
797 if (!claimed)
798 g_critical ("no handler responded to request: %s", self->path);
799 }
800
801 static gboolean
802 cockpit_web_request_parse_and_process (CockpitWebRequest *self)
803 {
804 gboolean again = FALSE;
805 GHashTable *headers = NULL;
806 gchar *method = NULL;
807 gchar *path = NULL;
808 const gchar *str;
809 gchar *end = NULL;
810 gssize off1;
811 gssize off2;
812 guint64 length;
813
814 /* The hard input limit, we just terminate the connection */
815 if (self->buffer->len > cockpit_webserver_request_maximum * 2)
816 {
817 g_message ("received HTTP request that was too large");
818 goto out;
819 }
820
821 off1 = web_socket_util_parse_req_line ((const gchar *)self->buffer->data,
822 self->buffer->len,
823 &method,
824 &path);
825 if (off1 == 0)
826 {
827 again = TRUE;
828 goto out;
829 }
830 if (off1 < 0)
831 {
832 g_message ("received invalid HTTP request line");
833 self->delayed_reply = 400;
834 goto out;
835 }
836 if (!path || path[0] != '/')
837 {
838 g_message ("received invalid HTTP path");
839 self->delayed_reply = 400;
840 goto out;
841 }
842
843 off2 = web_socket_util_parse_headers ((const gchar *)self->buffer->data + off1,
844 self->buffer->len - off1,
845 &headers);
846 if (off2 == 0)
847 {
848 again = TRUE;
849 goto out;
850 }
851 if (off2 < 0)
852 {
853 g_message ("received invalid HTTP request headers");
854 self->delayed_reply = 400;
855 goto out;
856 }
857
858 /* If we get a Content-Length then verify it is zero */
859 length = 0;
860 str = g_hash_table_lookup (headers, "Content-Length");
861 if (str != NULL)
862 {
863 end = NULL;
864 length = g_ascii_strtoull (str, &end, 10);
865 if (!end || end[0])
866 {
867 g_message ("received invalid Content-Length");
868 self->delayed_reply = 400;
869 goto out;
870 }
871
872 /* The soft limit, we return 413 */
873 if (length != 0)
874 {
875 g_debug ("received non-zero Content-Length");
876 self->delayed_reply = 413;
877 }
878 }
879
880 /* Not enough data yet */
881 if (self->buffer->len < off1 + off2 + length)
882 {
883 again = TRUE;
884 goto out;
885 }
886
887 if (!g_str_equal (method, "GET") && !g_str_equal (method, "HEAD"))
888 {
889 g_message ("received unsupported HTTP method");
890 self->delayed_reply = 405;
891 }
892
893 str = g_hash_table_lookup (headers, "Host");
894 if (!str || g_str_equal (str, ""))
895 {
896 g_message ("received HTTP request without Host header");
897 self->delayed_reply = 400;
898 }
899
900 g_byte_array_remove_range (self->buffer, 0, off1 + off2);
901 cockpit_web_request_process (self, method, path, str, headers);
902
903 out:
904 if (headers)
905 g_hash_table_unref (headers);
906 g_free (method);
907 g_free (path);
908 if (!again)
909 cockpit_web_request_finish (self);
910 return again;
911 }
912
913 #if !GLIB_CHECK_VERSION(2,43,2)
914 #define G_IO_ERROR_CONNECTION_CLOSED G_IO_ERROR_BROKEN_PIPE
915 #endif
916
917 static gboolean
918 should_suppress_request_error (GError *error,
919 gsize received)
920 {
921 /* If no bytes received, then don't worry about ECONNRESET and friends */
922 if (received > 0)
923 return FALSE;
924
925 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CONNECTION_CLOSED) ||
926 g_error_matches (error, G_IO_ERROR, G_IO_ERROR_BROKEN_PIPE))
927 {
928 g_debug ("request error: %s", error->message);
929 return TRUE;
930 }
931
932 #if !GLIB_CHECK_VERSION(2,43,2)
933 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_FAILED) &&
934 strstr (error->message, g_strerror (ECONNRESET)))
935 {
936 g_debug ("request error: %s", error->message);
937 return TRUE;
938 }
939 #endif
940
941 return FALSE;
942 }
943
944 static gboolean
945 cockpit_web_request_on_input (GObject *pollable_input,
946 gpointer user_data)
947 {
948 GPollableInputStream *input = (GPollableInputStream *)pollable_input;
949 CockpitWebRequest *self = user_data;
950 GError *error = NULL;
951 gsize length;
952 gssize count;
953
954 length = self->buffer->len;
955
956 /* With a GTlsServerConnection, the GSource callback is not called again if
957 * there is still pending data in GnuTLS'es buffer.
958 * (https://gitlab.gnome.org/GNOME/glib-networking/issues/20). Thus read up
959 * to our allowed maximum size to ensure we got everything that's pending.
960 * Add one extra byte so that cockpit_web_request_parse_and_process()
961 * correctly rejects requests that are > maximum, instead of hanging.
962 *
963 * FIXME: This may still hang for several large requests that are pipelined;
964 * for these this needs to be changed into a loop.
965 */
966 g_byte_array_set_size (self->buffer, length + cockpit_webserver_request_maximum + 1);
967
968 count = g_pollable_input_stream_read_nonblocking (input, self->buffer->data + length,
969 cockpit_webserver_request_maximum + 1, NULL, &error);
970 if (count < 0)
971 {
972 g_byte_array_set_size (self->buffer, length);
973
974 /* Just wait and try again */
975 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
976 {
977 g_error_free (error);
978 return TRUE;
979 }
980
981 if (!should_suppress_request_error (error, length))
982 g_message ("couldn't read from connection: %s", error->message);
983
984 cockpit_web_request_finish (self);
985 g_error_free (error);
986 return FALSE;
987 }
988
989 g_byte_array_set_size (self->buffer, length + count);
990
991 if (count == 0)
992 {
993 if (self->eof_okay)
994 close_io_stream (self->io);
995 else
996 g_debug ("caller closed connection early");
997 cockpit_web_request_finish (self);
998 return FALSE;
999 }
1000
1001 /* Once we receive data EOF is unexpected (until possible next request) */
1002 self->eof_okay = FALSE;
1003
1004 return cockpit_web_request_parse_and_process (self);
1005 }
1006
1007 static void
1008 cockpit_web_request_start_input (CockpitWebRequest *self)
1009 {
1010 GPollableInputStream *poll_in;
1011 GInputStream *in;
1012
1013 /* Both GSocketConnection and GTlsServerConnection are pollable */
1014 in = g_io_stream_get_input_stream (self->io);
1015 poll_in = NULL;
1016 if (G_IS_POLLABLE_INPUT_STREAM (in))
1017 poll_in = (GPollableInputStream *)in;
1018
1019 if (!poll_in || !g_pollable_input_stream_can_poll (poll_in))
1020 {
1021 if (in)
1022 g_critical ("cannot use a non-pollable input stream: %s", G_OBJECT_TYPE_NAME (in));
1023 else
1024 g_critical ("no input stream available");
1025
1026 cockpit_web_request_finish (self);
1027 return;
1028 }
1029
1030 /* Replace with a new source */
1031 if (self->source)
1032 {
1033 g_source_destroy (self->source);
1034 g_source_unref (self->source);
1035 }
1036
1037 self->source = g_pollable_input_stream_create_source (poll_in, NULL);
1038 g_source_set_callback (self->source, (GSourceFunc)cockpit_web_request_on_input, self, NULL);
1039 g_source_attach (self->source, self->web_server->main_context);
1040 }
1041
1042 static gboolean
1043 cockpit_web_request_on_socket_input (GSocket *socket,
1044 GIOCondition condition,
1045 gpointer user_data)
1046 {
1047 CockpitWebRequest *self = user_data;
1048 guchar first_byte;
1049 GInputVector vector[1] = { { &first_byte, 1 } };
1050 gint flags = G_SOCKET_MSG_PEEK;
1051 GError *error = NULL;
1052 gssize num_read;
1053 g_auto(CockpitControlMessages) ccm = COCKPIT_CONTROL_MESSAGES_INIT;
1054
1055 num_read = g_socket_receive_message (socket,
1056 NULL, /* out GSocketAddress */
1057 vector,
1058 1,
1059 &ccm.messages,
1060 &ccm.n_messages,
1061 &flags,
1062 NULL, /* GCancellable* */
1063 &error);
1064
1065 if (num_read < 0)
1066 {
1067 /* Just wait and try again */
1068 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
1069 {
1070 g_error_free (error);
1071 return TRUE;
1072 }
1073
1074 if (!should_suppress_request_error (error, 0))
1075 g_message ("couldn't read from socket: %s", error->message);
1076
1077 cockpit_web_request_finish (self);
1078 g_error_free (error);
1079 return FALSE;
1080 }
1081
1082 JsonObject *metadata = cockpit_memfd_read_json_from_control_messages (&ccm, &error);
1083 if (metadata)
1084 {
1085 g_assert (G_IS_SOCKET_CONNECTION (self->io));
1086 g_object_set_qdata_full (G_OBJECT (self->io),
1087 g_quark_from_static_string ("metadata"),
1088 metadata, (GDestroyNotify) json_object_unref);
1089 }
1090 else if (error != NULL)
1091 {
1092 g_warning ("Failed while reading metadata from new connection: %s", error->message);
1093 g_clear_error (&error);
1094 }
1095
1096 /*
1097 * TLS streams are guaranteed to start with octet 22.. this way we can distinguish them
1098 * from regular HTTP requests. cockpit-ws no longer handles TLS.
1099 */
1100 if (num_read && (first_byte == 22 || first_byte == 0x80))
1101 {
1102 g_warning ("Received unexpected TLS connection; use cockpit-tls for TLS termination");
1103 cockpit_web_request_finish (self);
1104 return FALSE;
1105 }
1106
1107 /* Defer redirection check until after header parsing */
1108 if (cockpit_web_server_get_flags (self->web_server) & COCKPIT_WEB_SERVER_REDIRECT_TLS)
1109 self->check_tls_redirect = TRUE;
1110
1111 cockpit_web_request_start_input (self);
1112
1113 /* No longer run *this* source */
1114 return FALSE;
1115 }
1116
1117 static gboolean
1118 cockpit_web_request_on_timeout (gpointer data)
1119 {
1120 CockpitWebRequest *self = data;
1121 if (self->eof_okay)
1122 g_debug ("request timed out, closing");
1123 else
1124 g_message ("request timed out, closing");
1125 cockpit_web_request_finish (self);
1126 return FALSE;
1127 }
1128
1129 static void
1130 cockpit_web_request_start (CockpitWebServer *web_server,
1131 GIOStream *io,
1132 gboolean first)
1133 {
1134 GSocketConnection *connection;
1135 GSocket *socket;
1136
1137 CockpitWebRequest *self = g_new0 (CockpitWebRequest, 1);
1138 self->web_server = web_server;
1139 self->io = g_object_ref (io);
1140 self->buffer = g_byte_array_new ();
1141
1142 /* Right before a request, EOF is not unexpected */
1143 self->eof_okay = TRUE;
1144
1145 self->timeout = g_timeout_source_new_seconds (cockpit_webserver_request_timeout);
1146 g_source_set_callback (self->timeout, cockpit_web_request_on_timeout, self, NULL);
1147 g_source_attach (self->timeout, web_server->main_context);
1148
1149 if (first)
1150 {
1151 connection = G_SOCKET_CONNECTION (io);
1152 socket = g_socket_connection_get_socket (connection);
1153 g_socket_set_blocking (socket, FALSE);
1154
1155 self->source = g_socket_create_source (g_socket_connection_get_socket (connection),
1156 G_IO_IN, NULL);
1157 g_source_set_callback (self->source, (GSourceFunc)cockpit_web_request_on_socket_input, self, NULL);
1158 g_source_attach (self->source, web_server->main_context);
1159 }
1160 else
1161 cockpit_web_request_start_input (self);
1162
1163 /* Owns the request */
1164 g_hash_table_add (web_server->requests, self);
1165 }
1166
1167 CockpitWebResponse *
1168 cockpit_web_request_respond (CockpitWebRequest *self)
1169 {
1170 return cockpit_web_response_new (self->io, self->original_path, self->path, self->headers,
1171 self->method, cockpit_web_request_get_protocol (self));
1172 }
1173
1174 const gchar *
1175 cockpit_web_request_get_path (CockpitWebRequest *self)
1176 {
1177 return self->path;
1178 }
1179
1180 const gchar *
1181 cockpit_web_request_get_query (CockpitWebRequest *self)
1182 {
1183 return self->query;
1184 }
1185
1186 const gchar *
1187 cockpit_web_request_get_method (CockpitWebRequest *self)
1188 {
1189 return self->method;
1190 }
1191
1192 GByteArray *
1193 cockpit_web_request_get_buffer (CockpitWebRequest *self)
1194 {
1195 return self->buffer;
1196 }
1197
1198 GHashTable *
1199 cockpit_web_request_get_headers (CockpitWebRequest *self)
1200 {
1201 return self->headers;
1202 }
1203
1204 const gchar *
1205 cockpit_web_request_lookup_header (CockpitWebRequest *self,
1206 const gchar *header)
1207 {
1208 if (!self->headers)
1209 return NULL;
1210
1211 return g_hash_table_lookup (self->headers, header);
1212 }
1213
1214 gchar *
1215 cockpit_web_request_parse_cookie (CockpitWebRequest *self,
1216 const gchar *name)
1217 {
1218 if (!self->headers)
1219 return NULL;
1220
1221 return cockpit_web_server_parse_cookie (self->headers, name);
1222 }
1223
1224 GIOStream *
1225 cockpit_web_request_get_io_stream (CockpitWebRequest *self)
1226 {
1227 return self->io;
1228 }
1229
1230 const gchar *
1231 cockpit_web_request_get_host (CockpitWebRequest *self)
1232 {
1233 return self->host;
1234 }
1235
1236 const gchar *
1237 cockpit_web_request_get_protocol (CockpitWebRequest *self)
1238 {
1239 if (self->web_server && self->web_server->flags & COCKPIT_WEB_SERVER_FOR_TLS_PROXY)
1240 return "https";
1241
1242 if (self->web_server && self->web_server->protocol_header)
1243 {
1244 const gchar *protocol = g_hash_table_lookup (self->headers, self->web_server->protocol_header);
1245 if (protocol)
1246 return protocol;
1247 }
1248
1249 return "http";
1250 }
1251
1252 gchar *
1253 cockpit_web_request_get_remote_address (CockpitWebRequest *self)
1254 {
1255 if (self->web_server && self->web_server->forwarded_for_header)
1256 {
1257 const gchar *forwarded_header = g_hash_table_lookup (self->headers, self->web_server->forwarded_for_header);
1258 if (forwarded_header && forwarded_header[0])
1259 {
1260 /* This isn't really standardised, but in practice, it's a
1261 * space separated list and the last item is from the
1262 * immediately upstream server.
1263 */
1264 const gchar *last_space = strrchr (forwarded_header, ' ');
1265 if (last_space)
1266 return g_strdup (last_space + 1);
1267 else
1268 return g_strdup (forwarded_header);
1269 }
1270 }
1271
1272 if (self->io == NULL)
1273 return NULL;
1274
1275 JsonObject *metadata = g_object_get_qdata (G_OBJECT (self->io), g_quark_from_static_string ("metadata"));
1276 if (metadata)
1277 {
1278 const gchar *tmp;
1279 if (cockpit_json_get_string (metadata, "origin-ip", NULL, &tmp))
1280 return g_strdup (tmp);
1281 }
1282
1283 /* This is definitely a socket */
1284 g_return_val_if_fail (G_IS_SOCKET_CONNECTION (self->io), NULL);
1285
1286 /* ...but it might be a unix socket. NB: GInetSocketAddress includes IPv6. */
1287 g_autoptr(GSocketAddress) remote = g_socket_connection_get_remote_address (G_SOCKET_CONNECTION (self->io), NULL);
1288 if (remote && G_IS_INET_SOCKET_ADDRESS (remote))
1289 return g_inet_address_to_string (g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (remote)));
1290
1291 return NULL;
1292 }
1293
1294 const gchar *
1295 cockpit_web_request_get_client_certificate (CockpitWebRequest *self)
1296 {
1297 if (self->io == NULL)
1298 return NULL;
1299
1300 JsonObject *metadata = g_object_get_qdata (G_OBJECT (self->io), g_quark_from_static_string ("metadata"));
1301 if (metadata == NULL)
1302 return NULL;
1303
1304 const gchar *client_certificate = NULL;
1305 cockpit_json_get_string (metadata, "client-certificate", NULL, &client_certificate);
1306 return client_certificate;
1307 }