/* * Copyright (C) 2014 Red Hat, Inc. * SPDX-License-Identifier: LGPL-2.1-or-later */ #include "config.h" /* This gets logged as part of the (more verbose) protocol logging */ #ifdef G_LOG_DOMAIN #undef G_LOG_DOMAIN #endif #define G_LOG_DOMAIN "cockpit-protocol" #include "cockpitwebresponse.h" #include "cockpitwebfilter.h" #include "common/cockpitconf.h" #include "cockpiterror.h" #include "cockpitflow.h" #include "cockpitlocale.h" #include "cockpittemplate.h" #include #include #include /** * CockpitWebResponse: * * A response sent back to an HTTP client. You can use the high level one * shot APIs, like cockpit_web_response_content() and * cockpit_web_response_error() * or low level builder APIs: * * cockpit_web_response_headers() send the headers * cockpit_web_response_queue() send a block of data. * cockpit_web_response_complete() finish. */ struct _CockpitWebResponse { GObject parent; GIOStream *io; const gchar *logname; const gchar *path; gchar *full_path; gchar *url_root; gchar *method; gchar *origin; gchar *protocol; CockpitCacheType cache_type; /* The output queue */ GPollableOutputStream *out; GQueue *queue; gsize out_queued; gsize out_queueable; gsize partial_offset; GSource *source; /* Status flags */ guint count; gboolean complete; gboolean failed; gboolean done; gboolean chunked; gboolean keep_alive; GList *filters; }; /* A megabyte is when we start to consider queue full enough */ #define QUEUE_PRESSURE 1024UL * 1024UL static guint signal__done; static void cockpit_web_response_flow_iface_init (CockpitFlowInterface *iface); G_DEFINE_TYPE_WITH_CODE (CockpitWebResponse, cockpit_web_response, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE (COCKPIT_TYPE_FLOW, cockpit_web_response_flow_iface_init)); static void cockpit_web_response_init (CockpitWebResponse *self) { self->queue = g_queue_new (); self->out_queueable = G_MAXSIZE; self->cache_type = COCKPIT_WEB_RESPONSE_CACHE_UNSET; } static void cockpit_web_response_done (CockpitWebResponse *self) { gboolean reusable = FALSE; g_object_ref (self); g_assert (!self->done); self->done = TRUE; if (self->source) { g_source_destroy (self->source); g_source_unref (self->source); self->source = NULL; } if (self->complete) { reusable = !self->failed && self->keep_alive; g_object_unref (self); } else if (!self->failed) { g_critical ("A CockpitWebResponse was freed without being completed properly. " "This is a programming error."); } g_signal_emit (self, signal__done, 0, reusable); g_object_unref (self->io); self->io = NULL; self->out = NULL; g_object_unref (self); } static void cockpit_web_response_dispose (GObject *object) { CockpitWebResponse *self = COCKPIT_WEB_RESPONSE (object); if (!self->done) cockpit_web_response_done (self); g_list_free_full (self->filters, g_object_unref); self->filters = NULL; G_OBJECT_CLASS (cockpit_web_response_parent_class)->dispose (object); } static void cockpit_web_response_finalize (GObject *object) { CockpitWebResponse *self = COCKPIT_WEB_RESPONSE (object); g_free (self->protocol); g_free (self->full_path); g_free (self->url_root); g_free (self->method); g_free (self->origin); g_assert (self->io == NULL); g_assert (self->out == NULL); g_queue_free_full (self->queue, (GDestroyNotify)g_bytes_unref); self->out_queued = 0; G_OBJECT_CLASS (cockpit_web_response_parent_class)->finalize (object); } static void cockpit_web_response_class_init (CockpitWebResponseClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gobject_class->dispose = cockpit_web_response_dispose; gobject_class->finalize = cockpit_web_response_finalize; signal__done = g_signal_new ("done", COCKPIT_TYPE_WEB_RESPONSE, G_SIGNAL_RUN_LAST, 0, NULL, NULL, NULL, G_TYPE_NONE, 1, G_TYPE_BOOLEAN); } /** * cockpit_web_response_new: * @io: the stream to send on * @path: the path resource or NULL * @in_headers: input headers or NULL * @flags: in #COCKPIT_WEB_RESPONSE_FOR_TLS_PROXY mode, the origin is assumed to * be https:// even for a non-HTTPS connection. * * Create a new web response. * * The returned reference belongs to the caller. Additionally * once cockpit_web_response_complete() is called, an additional * reference is held until the response is sent and flushed. * * Returns: (transfer full): the new response, unref when done with it */ CockpitWebResponse * cockpit_web_response_new (GIOStream *io, const gchar *original_path, const gchar *path, GHashTable *in_headers, const gchar *method, const gchar *protocol) { CockpitWebResponse *self; GOutputStream *out; const gchar *connection; const gchar *host = NULL; gint offset; /* Trying to be a somewhat performant here, avoiding properties */ self = g_object_new (COCKPIT_TYPE_WEB_RESPONSE, NULL); self->io = g_object_ref (io); out = g_io_stream_get_output_stream (io); if (G_IS_POLLABLE_OUTPUT_STREAM (out)) { self->out = (GPollableOutputStream *)out; } else if (out) { g_critical ("Cannot send web response over non-pollable output stream: %s", G_OBJECT_TYPE_NAME (out)); } else { g_critical ("Cannot send web response: no output stream available"); } self->url_root = NULL; self->full_path = g_strdup (path); self->path = self->full_path; g_assert (method != NULL); self->method = g_strdup (method); if (path && original_path) { offset = strlen (original_path) - strlen (path); if (offset > 0 && g_strcmp0 (original_path + offset, path) == 0) self->url_root = g_strndup (original_path, offset); } if (self->path) self->logname = self->path; else self->logname = "response"; self->keep_alive = TRUE; if (in_headers) { connection = g_hash_table_lookup (in_headers, "Connection"); if (connection) self->keep_alive = g_str_equal (connection, "keep-alive"); host = g_hash_table_lookup (in_headers, "Host"); } self->protocol = g_strdup (protocol ?: "http"); if (host) self->origin = g_strdup_printf ("%s://%s", self->protocol, host); return self; } /** * cockpit_web_response_get_path: * @self: the response * * Returns: the resource path for response */ const gchar * cockpit_web_response_get_path (CockpitWebResponse *self) { g_return_val_if_fail (COCKPIT_IS_WEB_RESPONSE (self), NULL); return self->path; } /** * cockpit_web_response_get_url_root: * @self: the response * * Returns: The url root portion of the original path that was removed */ const gchar * cockpit_web_response_get_url_root (CockpitWebResponse *self) { return self->url_root; } /** * cockpit_web_response_get_stream: * @self: the response * * Returns: the stream we're sending on */ GIOStream * cockpit_web_response_get_stream (CockpitWebResponse *self) { g_return_val_if_fail (COCKPIT_IS_WEB_RESPONSE (self), NULL); return self->io; } #if !GLIB_CHECK_VERSION(2,43,2) #define G_IO_ERROR_CONNECTION_CLOSED G_IO_ERROR_BROKEN_PIPE #endif gboolean cockpit_web_should_suppress_output_error (const gchar *logname, GError *error) { if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CONNECTION_CLOSED) || g_error_matches (error, G_IO_ERROR, G_IO_ERROR_BROKEN_PIPE)) { g_debug ("%s: output error: %s", logname, error->message); return TRUE; } #if !GLIB_CHECK_VERSION(2,43,2) if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_FAILED) && strstr (error->message, g_strerror (ECONNRESET))) { g_debug ("%s: output error: %s", logname, error->message); return TRUE; } #endif return FALSE; } static void on_output_flushed (GObject *stream, GAsyncResult *result, gpointer user_data) { CockpitWebResponse *self = COCKPIT_WEB_RESPONSE (user_data); GOutputStream *output = G_OUTPUT_STREAM (stream); GError *error = NULL; if (g_output_stream_flush_finish (output, result, &error)) { g_debug ("%s: flushed output", self->logname); } else { if (!cockpit_web_should_suppress_output_error (self->logname, error)) g_message ("%s: couldn't flush web output: %s", self->logname, error->message); self->failed = TRUE; g_error_free (error); } cockpit_web_response_done (self); g_object_unref (self); } static gboolean on_response_output (GObject *pollable, gpointer user_data) { CockpitWebResponse *self = user_data; GError *error = NULL; const guint8 *data; GBytes *block; gssize count; gsize before, size, len; block = g_queue_peek_head (self->queue); if (block) { data = g_bytes_get_data (block, &len); g_assert (len == 0 || self->partial_offset < len); data += self->partial_offset; len -= self->partial_offset; before = self->out_queued; if (len > 0) { count = g_pollable_output_stream_write_nonblocking (self->out, data, len, NULL, &error); } else { count = 0; } if (count < 0) { if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) { g_error_free (error); return TRUE; } if (!cockpit_web_should_suppress_output_error (self->logname, error)) g_message ("%s: couldn't write web output: %s", self->logname, error->message); self->failed = TRUE; cockpit_web_response_done (self); g_error_free (error); return FALSE; } if (count == len) { g_debug ("%s: sent %d bytes", self->logname, (int)len); self->partial_offset = 0; block = g_queue_pop_head (self->queue); size = g_bytes_get_size (block); g_assert (size <= self->out_queued); self->out_queued -= size; g_bytes_unref (block); } else { g_debug ("%s: sent %d partial", self->logname, (int)count); g_assert (count < len); self->partial_offset += count; } /* * If we're controlling another flow, turn it on again when our output * buffer size becomes less than the low mark. */ if (before >= QUEUE_PRESSURE && self->out_queued < QUEUE_PRESSURE) cockpit_flow_emit_pressure (COCKPIT_FLOW (self), FALSE); return TRUE; } else { g_source_destroy (self->source); g_source_unref (self->source); self->source = NULL; if (self->complete) { g_debug ("%s: complete flushing output", self->logname); g_output_stream_flush_async (G_OUTPUT_STREAM (self->out), G_PRIORITY_DEFAULT, NULL, on_output_flushed, g_object_ref (self)); } return FALSE; } } static void queue_bytes (CockpitWebResponse *self, GBytes *block) { gsize size, before; size = g_bytes_get_size (block); before = self->out_queued; g_return_if_fail (G_MAXSIZE - size > self->out_queued); self->out_queued += size; g_queue_push_tail (self->queue, g_bytes_ref (block)); self->count++; if (!self->source) { self->source = g_pollable_output_stream_create_source (self->out, NULL); g_source_set_callback (self->source, (GSourceFunc)on_response_output, self, NULL); g_source_attach (self->source, NULL); } if (before < QUEUE_PRESSURE && self->out_queued >= QUEUE_PRESSURE) cockpit_flow_emit_pressure (COCKPIT_FLOW (self), TRUE); } static void queue_block (CockpitWebResponse *self, GBytes *block) { gsize length = g_bytes_get_size (block); GBytes *bytes; gchar *data; /* * We cannot queue chunks of length zero. Besides being silly, this * messes with chunked encoding. The 0 length block means end of * response. */ if (length == 0) return; if (self->out_queueable < length) { g_critical ("Too much data queuing in HTTP response. This is a programmer error."); return; } self->out_queueable -= length; g_debug ("%s: queued %d bytes", self->logname, (int)length); if (!self->chunked) { queue_bytes (self, block); } else { /* Required for chunked transfer encoding. */ data = g_strdup_printf ("%x\r\n", (unsigned int)length); bytes = g_bytes_new_take (data, strlen (data)); queue_bytes (self, bytes); g_bytes_unref (bytes); queue_bytes (self, block); bytes = g_bytes_new_static ("\r\n", 2); queue_bytes (self, bytes); g_bytes_unref (bytes); } } typedef struct { CockpitWebResponse *response; GList *filters; } QueueStep; static void queue_filter (gpointer data, GBytes *bytes) { QueueStep *qs = data; QueueStep qn = { .response = qs->response }; g_return_if_fail (bytes != NULL); if (qs->filters) { qn.filters = qs->filters->next; cockpit_web_filter_push (qs->filters->data, bytes, queue_filter, &qn); } else { queue_block (qs->response, bytes); } } /** * cockpit_web_response_queue: * @self: the response * @block: the block of data to queue * * Queue a single block of data on the response. Will be sent * during the main loop. * * See cockpit_web_response_content() for a simple way to * avoid queueing individual blocks. * * If this function returns %FALSE, then the response has failed * or has been completed elsewhere. The block was ignored and * queuing more blocks doesn't makes sense. * * After done queuing all your blocks call * cockpit_web_response_complete(). * * Returns: Whether queuing more blocks makes sense */ gboolean cockpit_web_response_queue (CockpitWebResponse *self, GBytes *block) { QueueStep qn = { .response = self }; g_return_val_if_fail (COCKPIT_IS_WEB_RESPONSE (self), FALSE); g_return_val_if_fail (block != NULL, FALSE); g_return_val_if_fail (self->complete == FALSE, FALSE); if (self->failed) { g_debug ("%s: ignoring queued block after failure", self->logname); return FALSE; } if (g_str_equal (self->method, "HEAD")) { g_debug ("%s: ignoring queued block for method HEAD", self->logname); return TRUE; } qn.filters = self->filters; queue_filter (&qn, block); return TRUE; } /** * cockpit_web_response_complete: * @self: the response * * See cockpit_web_response_content() for easy to use stuff. * * Tell the response that all the data has been queued. * The response will hold a reference to itself until the * data is actually sent, so you can unref it. */ void cockpit_web_response_complete (CockpitWebResponse *self) { GBytes *bytes; g_return_if_fail (COCKPIT_IS_WEB_RESPONSE (self)); g_return_if_fail (self->complete == FALSE); if (self->failed) return; /* Hold a reference until cockpit_web_response_done() */ g_object_ref (self); self->complete = TRUE; if (self->chunked && !g_str_equal(self->method, "HEAD")) { bytes = g_bytes_new_static ("0\r\n\r\n", 5); queue_bytes (self, bytes); g_bytes_unref (bytes); } if (self->source) { g_debug ("%s: queueing complete", self->logname); } else { g_debug ("%s: complete closing io", self->logname); g_output_stream_flush_async (G_OUTPUT_STREAM (self->out), G_PRIORITY_DEFAULT, NULL, on_output_flushed, g_object_ref (self)); } } /** * cockpit_web_response_abort: * @self: the response * * This function is used when streaming content, and at * some point we can't provide the remainder of the content * * This completes the response and terminates the connection. */ void cockpit_web_response_abort (CockpitWebResponse *self) { g_return_if_fail (COCKPIT_IS_WEB_RESPONSE (self)); g_return_if_fail (self->complete == FALSE); if (self->failed) return; /* Hold a reference until cockpit_web_response_done() */ g_object_ref (self); self->complete = TRUE; self->failed = TRUE; g_debug ("%s: aborted", self->logname); cockpit_web_response_done (self); } /** * CockpitWebResponding: * @COCKPIT_WEB_RESPONSE_READY: nothing queued or sent yet * @COCKPIT_WEB_RESPONSE_QUEUING: started and still queuing data on response * @COCKPIT_WEB_RESPONSE_COMPLETE: all data is queued or aborted * @COCKPIT_WEB_RESPONSE_SENT: data is completely sent * * Various states of the web response. */ /** * cockpit_web_response_get_state: * @self: the web response * * Return the state of the web response. */ CockpitWebResponding cockpit_web_response_get_state (CockpitWebResponse *self) { g_return_val_if_fail (COCKPIT_IS_WEB_RESPONSE (self), 0); if (self->done) return COCKPIT_WEB_RESPONSE_SENT; else if (self->complete) return COCKPIT_WEB_RESPONSE_COMPLETE; else if (self->count == 0) return COCKPIT_WEB_RESPONSE_READY; else return COCKPIT_WEB_RESPONSE_QUEUING; } static gboolean cockpit_web_response_is_simple_token (const gchar *string) { string += strcspn (string, " \t\r\n\v"); return string[0] == '\0'; } gboolean cockpit_web_response_is_header_value (const gchar *string) { string += strcspn (string, "\r\n\v"); return string[0] == '\0'; } enum { HEADER_CONTENT_TYPE = 1 << 0, HEADER_CONTENT_ENCODING = 1 << 1, HEADER_VARY = 1 << 2, HEADER_CACHE_CONTROL = 1 << 3, HEADER_DNS_PREFETCH_CONTROL = 1 << 4, HEADER_REFERRER_POLICY = 1 << 5, HEADER_CONTENT_TYPE_OPTIONS = 1 << 6, HEADER_CROSS_ORIGIN_RESOURCE_POLICY = 1 << 7, HEADER_X_FRAME_OPTIONS = 1 << 8, }; static GString * begin_headers (CockpitWebResponse *response, guint status, const gchar *reason) { GString *string; string = g_string_sized_new (1024); g_string_printf (string, "HTTP/1.1 %d %s\r\n", status, reason); return string; } static guint append_header (GString *string, const gchar *name, const gchar *value) { if (value) { g_return_val_if_fail (cockpit_web_response_is_simple_token (name), 0); g_return_val_if_fail (cockpit_web_response_is_header_value (value), 0); g_string_append_printf (string, "%s: %s\r\n", name, value); } if (g_ascii_strcasecmp ("Content-Type", name) == 0) return HEADER_CONTENT_TYPE; if (g_ascii_strcasecmp ("Cache-Control", name) == 0) return HEADER_CACHE_CONTROL; if (g_ascii_strcasecmp ("Vary", name) == 0) return HEADER_VARY; if (g_ascii_strcasecmp ("Content-Encoding", name) == 0) return HEADER_CONTENT_ENCODING; if (g_ascii_strcasecmp ("X-DNS-Prefetch-Control", name) == 0) return HEADER_DNS_PREFETCH_CONTROL; if (g_ascii_strcasecmp ("Referrer-Policy", name) == 0) return HEADER_REFERRER_POLICY; if (g_ascii_strcasecmp ("X-Content-Type-Options", name) == 0) return HEADER_CONTENT_TYPE_OPTIONS; if (g_ascii_strcasecmp ("Cross-Origin-Resource-Policy", name) == 0) return HEADER_CROSS_ORIGIN_RESOURCE_POLICY; if (g_ascii_strcasecmp ("X-Frame-Options", name) == 0) return HEADER_X_FRAME_OPTIONS; if (g_ascii_strcasecmp ("Content-Length", name) == 0 || g_ascii_strcasecmp ("Transfer-Encoding", name) == 0 || g_ascii_strcasecmp ("Connection", name) == 0) { g_critical ("Don't set %s header manually. This is a programmer error.", name); } return 0; } static guint append_table (GString *string, GHashTable *headers) { GHashTableIter iter; gpointer key; gpointer value; guint seen = 0; if (headers) { g_hash_table_iter_init (&iter, headers); while (g_hash_table_iter_next (&iter, &key, &value)) seen |= append_header (string, key, value); } return seen; } static guint append_va (GString *string, va_list va) { const gchar *name; const gchar *value; guint seen = 0; for (;;) { name = va_arg (va, const gchar *); if (!name) break; value = va_arg (va, const gchar *); seen |= append_header (string, name, value); } return seen; } static GBytes * finish_headers (CockpitWebResponse *self, GString *string, gssize length, gint status, guint seen) { const gchar *content_type; /* Automatically figure out content type */ if ((seen & HEADER_CONTENT_TYPE) == 0 && self->full_path != NULL && status >= 200 && status <= 299) { content_type = cockpit_web_response_content_type (self->full_path); if (content_type) g_string_append_printf (string, "Content-Type: %s\r\n", content_type); } if (status != 304) { if (length < 0 || seen & HEADER_CONTENT_ENCODING || self->filters) { self->chunked = TRUE; g_string_append_printf (string, "Transfer-Encoding: chunked\r\n"); } else { self->chunked = FALSE; g_string_append_printf (string, "Content-Length: %" G_GSSIZE_FORMAT "\r\n", length); self->out_queueable = length; } } if ((seen & HEADER_CACHE_CONTROL) == 0 && status >= 200 && status <= 299) { if (self->cache_type == COCKPIT_WEB_RESPONSE_NO_CACHE) g_string_append (string, "Cache-Control: no-cache, no-store\r\n"); else if (self->cache_type == COCKPIT_WEB_RESPONSE_CACHE) g_string_append (string, "Cache-Control: max-age=86400, private\r\n"); } if ((seen & HEADER_VARY) == 0 && status >= 200 && status <= 299 && self->cache_type == COCKPIT_WEB_RESPONSE_CACHE) { g_string_append (string, "Vary: Cookie\r\n"); } if (!self->keep_alive) g_string_append (string, "Connection: close\r\n"); /* Some blanket security headers */ if ((seen & HEADER_DNS_PREFETCH_CONTROL) == 0) g_string_append (string, "X-DNS-Prefetch-Control: off\r\n"); if ((seen & HEADER_REFERRER_POLICY) == 0) g_string_append (string, "Referrer-Policy: no-referrer\r\n"); if ((seen & HEADER_CONTENT_TYPE_OPTIONS) == 0) g_string_append (string, "X-Content-Type-Options: nosniff\r\n"); /* Be very strict here -- there is no reason that external web sites should * be able to read any resource. This does *not* affect embedding with