MythTV master
mythhttpencoding.cpp
Go to the documentation of this file.
1// C++ headers
2#include <algorithm>
3
4// MythTV
5#include "mythlogging.h"
6#include "unziputil.h"
8#include "http/mythhttpdata.h"
9#include "http/mythhttpfile.h"
12
13// Qt
14#include <QDomDocument>
15#include <QJsonDocument>
16#include <QJsonObject>
17#include <QJsonValue>
18
19#define LOC QString("HTTPEnc: ")
20
32using MimePair = std::pair<float,QString>;
33QStringList MythHTTPEncoding::GetMimeTypes(const QString &Accept)
34{
35 // Split out mime types
36 auto types = Accept.split(",", Qt::SkipEmptyParts);
37
38 std::vector<MimePair> weightings;
39 for (const auto & type : std::as_const(types))
40 {
41 QString mime = type.trimmed();
42 auto quality = 1.0F;
43 // Find any quality value (defaults to 1)
44 if (auto index = type.lastIndexOf(";"); index > -1)
45 {
46 mime = type.mid(0, index).trimmed().toLower();
47 auto qual = type.mid(index + 1).trimmed();
48 if (auto index2 = qual.lastIndexOf("="); index2 > -1)
49 {
50 bool ok = false;
51 auto newquality = qual.mid(index2 + 1).toFloat(&ok);
52 if (ok)
53 quality = newquality;
54 }
55 }
56 weightings.emplace_back(quality, mime);
57 }
58
59 // Sort the list
60 auto comp = [](const MimePair& First, const MimePair& Second) { return First.first > Second.first; };
61 std::ranges::sort(weightings, comp);
62
63 // Build the final result. This will pass through invalid types - which should
64 // be handled by the consumer (e.g. wildcard specifiers are not handled).
65 QStringList result;
66 for (const auto & weight : weightings)
67 result.append(weight.second);
68
69 // Default to xml
70 if (result.empty())
71 result.append("application/xml");
72 return result;
73}
74
78{
79 if (!Request || !Request->m_content.get())
80 return;
81
82 auto contenttype = MythHTTP::GetHeader(Request->m_headers, "content-type");
83
84 // type is e.g. text/html; charset=UTF-8 or multipart/form-data; boundary=something
85 auto types = contenttype.split(";", Qt::SkipEmptyParts);
86 if (types.isEmpty())
87 return;
88
89 // Note: This can produce an invalid mime type but there is no sensible fallback
90 if (auto mime = MythMimeDatabase::MimeTypeForName(types[0].trimmed().toLower()); mime.IsValid())
91 {
92 Request->m_content->m_mimeType = mime;
93 if (mime.Name() == "application/x-www-form-urlencoded")
95 else if (mime.Name() == "text/xml" || mime.Name() == "application/xml" ||
96 mime.Name() == "application/soap+xml")
98 else if (mime.Name() == "application/json")
100 else
101 LOG(VB_HTTP, LOG_ERR, QString("Don't know how to get the parameters for MIME type: '%1'").arg(mime.Name()));
102 }
103 else
104 {
105 LOG(VB_HTTP, LOG_ERR, QString("Unknown MIME type: '%1'").arg(types[0]));
106 }
107
108}
109
111{
112 if (!Request || !Request->m_content.get())
113 return;
114
115 auto payload = QString::fromUtf8(Request->m_content->constData(), Request->m_content->size());
116
117 // This looks odd, but it is here to cope with stupid UPnP clients that
118 // forget to de-escape the URLs. We can't map %26 here as well, as that
119 // breaks anything that is trying to pass & as part of a name or value.
120 payload.replace("&amp;", "&");
121 if (!payload.isEmpty())
122 {
123 QStringList params = payload.split('&', Qt::SkipEmptyParts);
124 for (const auto & param : std::as_const(params))
125 {
126 QString name = param.section('=', 0, 0);
127 QString value = param.section('=', 1);
128 value.replace("+", " ");
129 if (!name.isEmpty())
130 {
131 name = QUrl::fromPercentEncoding(name.toUtf8());
132 value = QUrl::fromPercentEncoding(value.toUtf8());
133 Request->m_queries.insert(name.trimmed().toLower(), value);
134 }
135 }
136 }
137}
138
140{
141 LOG(VB_HTTP, LOG_DEBUG, "Inspecting XML payload");
142
143 if (!Request || !Request->m_content.get())
144 return;
145
146 // soapaction is formatted like "\"http://mythtv.org/Dvr/GetRecordedList\""
147 QString soapaction = Request->m_headers->value("soapaction");
148 soapaction.remove('"');
149 int lastSlashPos= soapaction.lastIndexOf('/');
150 if (lastSlashPos < 0)
151 return;
152 if (Request->m_path == "/")
153 Request->m_path.append(Request->m_fileName).append("/");
154 Request->m_fileName = soapaction.right(soapaction.size()-lastSlashPos-1);
155 LOG(VB_HTTP, LOG_DEBUG, QString("Found method call (%1)").arg(Request->m_fileName));
156
157 auto payload = QDomDocument();
158#if QT_VERSION < QT_VERSION_CHECK(6,5,0)
159 QString err_msg;
160 int err_line {-1};
161 int err_col {-1};
162 if (!payload.setContent(static_cast<QByteArray>(Request->m_content->constData()),
163 true, &err_msg, &err_line, &err_col))
164 {
165 LOG(VB_HTTP, LOG_WARNING, "Unable to parse XML request body");
166 LOG(VB_HTTP, LOG_WARNING, QString("- Error at line %1, column %2, msg: %3")
167 .arg(err_line).arg(err_col).arg(err_msg));
168 return;
169 }
170#else
171 auto parseresult = payload.setContent(Request->m_content->constData(),
172 QDomDocument::ParseOption::UseNamespaceProcessing);
173 if (!parseresult)
174 {
175 LOG(VB_HTTP, LOG_WARNING, "Unable to parse XML request body");
176 LOG(VB_HTTP, LOG_WARNING, QString("- Error at line %1, column %2, msg: %3")
177 .arg(parseresult.errorLine).arg(parseresult.errorColumn)
178 .arg(parseresult.errorMessage));
179 return;
180 }
181#endif
182 QString doc_name = payload.documentElement().localName();
183 if (doc_name.compare("envelope", Qt::CaseInsensitive) == 0)
184 {
185 LOG(VB_HTTP, LOG_DEBUG, "Found SOAP XML message envelope");
186 auto doc_body = payload.documentElement().namedItem("Body");
187 if (doc_body.isNull() || !doc_body.hasChildNodes()) // None or empty body
188 {
189 LOG(VB_HTTP, LOG_DEBUG, "Missing or empty SOAP body");
190 return;
191 }
192 auto body_contents = doc_body.firstChild();
193 if (body_contents.hasChildNodes()) // params for the method
194 {
195 for (QDomNode node = body_contents.firstChild(); !node.isNull(); node = node.nextSibling())
196 {
197 QString name = node.localName();
198 QString value = node.toElement().text();
199 if (!name.isEmpty())
200 {
201 // TODO: html decode entities if required
202 Request->m_queries.insert(name.trimmed().toLower(), value);
203 LOG(VB_HTTP, LOG_DEBUG, QString("Found URL param (%1=%2)").arg(name, value));
204 }
205 }
206 }
207 }
208}
209
211{
212 LOG(VB_HTTP, LOG_DEBUG, "Inspecting JSON payload");
213
214 if (!Request || !Request->m_content.get())
215 return;
216
217 QByteArray jstr = static_cast<QByteArray>(Request->m_content->constData());
218 QJsonParseError parseError {};
219 QJsonDocument doc = QJsonDocument::fromJson(jstr, &parseError);
220 if (parseError.error != QJsonParseError::NoError)
221 {
222 LOG(VB_HTTP, LOG_WARNING,
223 QString("Unable to parse JSON request body - Error at position %1, msg: %2")
224 .arg(parseError.offset).arg(parseError.errorString()));
225 return;
226 }
227
228 QJsonObject json = doc.object();
229 QStringList keys = json.keys();
230 for (const QString& key : std::as_const(keys))
231 {
232 if (!key.isEmpty())
233 {
234 QString value;
235 if (json.value(key).isObject())
236 {
237 QJsonDocument vd(json.value(key).toObject());
238 value = vd.toJson(QJsonDocument::Compact);
239 }
240 else
241 {
242 value = json.value(key).toVariant().toString();
243
244 if (value.isEmpty())
245 {
246 LOG(VB_HTTP, LOG_WARNING,
247 QString("Failed to parse value for key '%1' from %2")
248 .arg(key, QString(jstr)));
249 }
250 }
251
252 Request->m_queries.insert(key.trimmed().toLower(), value);
253 LOG(VB_HTTP, LOG_DEBUG,
254 QString("Found URL param (%1=%2)").arg(key, value));
255 }
256 }
257}
258
262{
263 auto * data = std::get_if<HTTPData>(&Content);
264 auto * file = std::get_if<HTTPFile>(&Content);
265 if (!(data || file))
266 return {};
267
268 QString filename;
269 if (data)
270 filename = (*data)->m_fileName;
271 else if (file)
272 filename = (*file)->m_fileName;
273
274 // Look for unambiguous mime type
276 if (types.size() == 1)
277 return types.front();
278
279 // Look for an override. QMimeDatabase gets it wrong sometimes when the result
280 // is ambiguous and it resorts to probing. Add to this list as necessary
281 static const std::map<QString,QString> s_mimeOverrides =
282 {
283 { "ts", "video/mp2t"}
284 };
285
287 for (const auto & type : s_mimeOverrides)
288 if (suffix.compare(type.first, Qt::CaseInsensitive) == 0)
290
291 // Try interrogating content as well
292 if (data)
293 if (auto mime = MythMimeDatabase::MimeTypeForFileNameAndData(filename, **data); mime.IsValid())
294 return mime;
295 if (file)
296 if (auto mime = MythMimeDatabase::MimeTypeForFileNameAndData(filename, (*file).get()); mime.IsValid())
297 return mime;
298
299 // Default to text/plain (possibly use application/octet-stream as well?)
300 return MythMimeDatabase::MimeTypeForName("text/plain");
301}
302
311{
312 auto result = HTTPNoEncode;
313 if (!Response || !Response->m_requestHeaders)
314 return result;
315
316 // We need something to compress/chunk
317 auto * data = std::get_if<HTTPData>(&Response->m_response);
318 auto * file = std::get_if<HTTPFile>(&Response->m_response);
319 if (!(data || file))
320 return result;
321
322 // Don't touch range requests. They do not work with compression and there
323 // is no point in chunking gzipped content as the client still has to wait
324 // for the entire payload before unzipping
325 // Note: It is permissible to chunk a range request - but ignore for the
326 // timebeing to keep the code simple.
327 if ((data && !(*data)->m_ranges.empty()) || (file && !(*file)->m_ranges.empty()))
328 return result;
329
330 // Has the client actually requested compression
331 bool wantgzip = MythHTTP::GetHeader(Response->m_requestHeaders, "accept-encoding").toLower().contains("gzip");
332
333 // Chunking is HTTP/1.1 only - and must be supported
334 bool chunkable = Response->m_version == HTTPOneDotOne;
335
336 // Has the client requested no chunking by specifying identity?
337 bool allowchunk = ! MythHTTP::GetHeader(Response->m_requestHeaders, "accept-encoding").toLower().contains("identity");
338
339 // and restrict to 'chunky' files
340 bool chunky = Size > 102400; // 100KB
341
342 // Don't compress anything that is too large. Under normal circumstances this
343 // should not be a problem as we only compress text based data - but avoid
344 // potentially memory hungry compression operations.
345 // On the flip side, don't compress trivial amounts of data
346 bool gzipsize = Size > 512 && !chunky; // 0.5KB <-> 100KB
347
348 // Only consider compressing text based content. No point in compressing audio,
349 // video and images.
350 bool compressable = (data ? (*data)->m_mimeType : (*file)->m_mimeType).Inherits("text/plain");
351
352 // Decision time
353 bool gzip = wantgzip && gzipsize && compressable;
354 bool chunk = chunkable && chunky && allowchunk;
355
356 if (!gzip)
357 {
358 // Chunking happens as we write to the socket, so flag it as required
359 if (chunk)
360 {
361 result = HTTPChunked;
362 if (data) (*data)->m_encoding = result;
363 if (file) (*file)->m_encoding = result;
364 }
365 return result;
366 }
367
368 // As far as I can tell, Qt's implicit sharing of data should ensure we aren't
369 // copying data unnecessarily here - but I can't be sure. We could definitely
370 // improve compressing files by avoiding the copy into a temporary buffer.
371 HTTPData buffer = MythHTTPData::Create(data ? gzipCompress(**data) : gzipCompress((*file)->readAll()));
372
373 // Add the required header
374 Response->AddHeader("Content-Encoding", "gzip");
375
376 LOG(VB_HTTP, LOG_INFO, LOC + QString("'%1' compressed from %2 to %3 bytes")
377 .arg(data ? (*data)->m_fileName : (*file)->fileName())
378 .arg(Size).arg(buffer->size()));
379
380 // Copy the filename and last modified, set the new buffer and set the content size
381 buffer->m_lastModified = data ? (*data)->m_lastModified : (*file)->m_lastModified;
382 buffer->m_etag = data ? (*data)->m_etag : (*file)->m_etag;
383 buffer->m_fileName = data ? (*data)->m_fileName : (*file)->m_fileName;
384 buffer->m_cacheType = data ? (*data)->m_cacheType : (*file)->m_cacheType;
385 buffer->m_encoding = HTTPGzip;
386 Response->m_response = buffer;
387 Size = buffer->size();
388 return HTTPGzip;
389}
static HTTPData Create()
Definition: mythhttpdata.cpp:4
static MythHTTPEncode Compress(MythHTTPResponse *Response, int64_t &Size)
Compress the response content under certain circumstances or mark the content as 'chunkable'.
static void GetURLEncodedParameters(MythHTTPRequest *Request)
static void GetContentType(MythHTTPRequest *Request)
Parse the incoming Content-Type header for POST/PUT content.
static QStringList GetMimeTypes(const QString &Accept)
static void GetJSONEncodedParameters(MythHTTPRequest *Request)
static MythMimeType GetMimeType(HTTPVariant Content)
Return a QMimeType that represents Content.
static void GetXMLEncodedParameters(MythHTTPRequest *Request)
Limited parsing of HTTP method and some headers to determine validity of request.
HTTPVariant m_response
MythHTTPVersion m_version
void AddHeader(const QString &key, const T &val)
HTTPHeaders m_requestHeaders
static QString GetHeader(const HTTPHeaders &Headers, const QString &Value, const QString &Default="")
static MythMimeTypes MimeTypesForFileName(const QString &FileName)
Return a vector of mime types that match the given filename.
static QString SuffixForFileName(const QString &FileName)
Return the preferred suffix for the given filename.
static MythMimeType MimeTypeForName(const QString &Name)
Return a mime type that matches the given name.
static MythMimeType MimeTypeForFileNameAndData(const QString &FileName, const QByteArray &Data)
Return a mime type for the given FileName and data.
bool IsValid() const
static const struct wl_interface * types[]
#define LOC
std::pair< float, QString > MimePair
Parse the incoming HTTP 'Accept' header and return an ordered list of preferences.
MythHTTPEncode
@ HTTPNoEncode
@ HTTPChunked
@ HTTPGzip
std::shared_ptr< MythHTTPData > HTTPData
Definition: mythhttptypes.h:37
@ HTTPOneDotOne
Definition: mythhttptypes.h:87
std::variant< std::monostate, HTTPData, HTTPFile > HTTPVariant
Definition: mythhttptypes.h:42
#define LOG(_MASK_, _LEVEL_, _QSTRING_)
Definition: mythlogging.h:39
QByteArray gzipCompress(const QByteArray &data)
Definition: unziputil.cpp:93