1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include "qplatformdefs.h"
5#include "qurl.h"
6#include "private/qdataurl_p.h"
7
8QT_BEGIN_NAMESPACE
9
10using namespace Qt::Literals;
11
12/*!
13 \internal
14
15 Decode a data: URL into its mimetype and payload. Returns a null string if
16 the URL could not be decoded.
17*/
18Q_CORE_EXPORT bool qDecodeDataUrl(const QUrl &uri, QString &mimeType, QByteArray &payload)
19{
20 if (uri.scheme() != "data"_L1 || !uri.host().isEmpty())
21 return false;
22
23 mimeType = QStringLiteral("text/plain;charset=US-ASCII");
24
25 // the following would have been the correct thing, but
26 // reality often differs from the specification. People have
27 // data: URIs with ? and #
28 //QByteArray data = QByteArray::fromPercentEncoding(uri.path(QUrl::FullyEncoded).toLatin1());
29 QByteArray data = QByteArray::fromPercentEncoding(pctEncoded: uri.url(options: QUrl::FullyEncoded | QUrl::RemoveScheme).toLatin1());
30
31 // parse it:
32 const qsizetype pos = data.indexOf(c: ',');
33 if (pos != -1) {
34 payload = data.mid(index: pos + 1);
35 data.truncate(pos);
36 data = data.trimmed();
37
38 // find out if the payload is encoded in Base64
39 if (QLatin1StringView{data}.endsWith(s: ";base64"_L1, cs: Qt::CaseInsensitive)) {
40 payload = QByteArray::fromBase64(base64: payload);
41 data.chop(n: 7);
42 }
43
44 if (QLatin1StringView{data}.startsWith(s: "charset"_L1, cs: Qt::CaseInsensitive)) {
45 qsizetype i = 7; // strlen("charset")
46 while (data.at(i) == ' ')
47 ++i;
48 if (data.at(i) == '=')
49 data.prepend(s: "text/plain;");
50 }
51
52 if (!data.isEmpty())
53 mimeType = QString::fromLatin1(ba: data.trimmed());
54
55 }
56
57 return true;
58}
59
60QT_END_NAMESPACE
61

source code of qtbase/src/corelib/io/qdataurl.cpp