1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Copyright (C) 2016 Intel Corporation.
5** Contact: https://www.qt.io/licensing/
6**
7** This file is part of the QtCore module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial License Usage
11** Licensees holding valid commercial Qt licenses may use this file in
12** accordance with the commercial license agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and The Qt Company. For licensing terms
15** and conditions see https://www.qt.io/terms-conditions. For further
16** information use the contact form at https://www.qt.io/contact-us.
17**
18** GNU Lesser General Public License Usage
19** Alternatively, this file may be used under the terms of the GNU Lesser
20** General Public License version 3 as published by the Free Software
21** Foundation and appearing in the file LICENSE.LGPL3 included in the
22** packaging of this file. Please review the following information to
23** ensure the GNU Lesser General Public License version 3 requirements
24** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25**
26** GNU General Public License Usage
27** Alternatively, this file may be used under the terms of the GNU
28** General Public License version 2.0 or (at your option) the GNU General
29** Public license version 3 or any later version approved by the KDE Free
30** Qt Foundation. The licenses are as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32** included in the packaging of this file. Please review the following
33** information to ensure the GNU General Public License requirements will
34** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35** https://www.gnu.org/licenses/gpl-3.0.html.
36**
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41/*!
42 \class QUrl
43 \inmodule QtCore
44
45 \brief The QUrl class provides a convenient interface for working
46 with URLs.
47
48 \reentrant
49 \ingroup io
50 \ingroup network
51 \ingroup shared
52
53
54 It can parse and construct URLs in both encoded and unencoded
55 form. QUrl also has support for internationalized domain names
56 (IDNs).
57
58 The most common way to use QUrl is to initialize it via the
59 constructor by passing a QString. Otherwise, setUrl() can also
60 be used.
61
62 URLs can be represented in two forms: encoded or unencoded. The
63 unencoded representation is suitable for showing to users, but
64 the encoded representation is typically what you would send to
65 a web server. For example, the unencoded URL
66 "http://b├╝hler.example.com/List of applicants.xml"
67 would be sent to the server as
68 "http://xn--bhler-kva.example.com/List%20of%20applicants.xml".
69
70 A URL can also be constructed piece by piece by calling
71 setScheme(), setUserName(), setPassword(), setHost(), setPort(),
72 setPath(), setQuery() and setFragment(). Some convenience
73 functions are also available: setAuthority() sets the user name,
74 password, host and port. setUserInfo() sets the user name and
75 password at once.
76
77 Call isValid() to check if the URL is valid. This can be done at any point
78 during the constructing of a URL. If isValid() returns \c false, you should
79 clear() the URL before proceeding, or start over by parsing a new URL with
80 setUrl().
81
82 Constructing a query is particularly convenient through the use of the \l
83 QUrlQuery class and its methods QUrlQuery::setQueryItems(),
84 QUrlQuery::addQueryItem() and QUrlQuery::removeQueryItem(). Use
85 QUrlQuery::setQueryDelimiters() to customize the delimiters used for
86 generating the query string.
87
88 For the convenience of generating encoded URL strings or query
89 strings, there are two static functions called
90 fromPercentEncoding() and toPercentEncoding() which deal with
91 percent encoding and decoding of QString objects.
92
93 fromLocalFile() constructs a QUrl by parsing a local
94 file path. toLocalFile() converts a URL to a local file path.
95
96 The human readable representation of the URL is fetched with
97 toString(). This representation is appropriate for displaying a
98 URL to a user in unencoded form. The encoded form however, as
99 returned by toEncoded(), is for internal use, passing to web
100 servers, mail clients and so on. Both forms are technically correct
101 and represent the same URL unambiguously -- in fact, passing either
102 form to QUrl's constructor or to setUrl() will yield the same QUrl
103 object.
104
105 QUrl conforms to the URI specification from
106 \l{RFC 3986} (Uniform Resource Identifier: Generic Syntax), and includes
107 scheme extensions from \l{RFC 1738} (Uniform Resource Locators). Case
108 folding rules in QUrl conform to \l{RFC 3491} (Nameprep: A Stringprep
109 Profile for Internationalized Domain Names (IDN)). It is also compatible with the
110 \l{http://freedesktop.org/wiki/Specifications/file-uri-spec/}{file URI specification}
111 from freedesktop.org, provided that the locale encodes file names using
112 UTF-8 (required by IDN).
113
114 \section2 Relative URLs vs Relative Paths
115
116 Calling isRelative() will return whether or not the URL is relative.
117 A relative URL has no \l {scheme}. For example:
118
119 \snippet code/src_corelib_io_qurl.cpp 8
120
121 Notice that a URL can be absolute while containing a relative path, and
122 vice versa:
123
124 \snippet code/src_corelib_io_qurl.cpp 9
125
126 A relative URL can be resolved by passing it as an argument to resolved(),
127 which returns an absolute URL. isParentOf() is used for determining whether
128 one URL is a parent of another.
129
130 \section2 Error checking
131
132 QUrl is capable of detecting many errors in URLs while parsing it or when
133 components of the URL are set with individual setter methods (like
134 setScheme(), setHost() or setPath()). If the parsing or setter function is
135 successful, any previously recorded error conditions will be discarded.
136
137 By default, QUrl setter methods operate in QUrl::TolerantMode, which means
138 they accept some common mistakes and mis-representation of data. An
139 alternate method of parsing is QUrl::StrictMode, which applies further
140 checks. See QUrl::ParsingMode for a description of the difference of the
141 parsing modes.
142
143 QUrl only checks for conformance with the URL specification. It does not
144 try to verify that high-level protocol URLs are in the format they are
145 expected to be by handlers elsewhere. For example, the following URIs are
146 all considered valid by QUrl, even if they do not make sense when used:
147
148 \list
149 \li "http:/filename.html"
150 \li "mailto://example.com"
151 \endlist
152
153 When the parser encounters an error, it signals the event by making
154 isValid() return false and toString() / toEncoded() return an empty string.
155 If it is necessary to show the user the reason why the URL failed to parse,
156 the error condition can be obtained from QUrl by calling errorString().
157 Note that this message is highly technical and may not make sense to
158 end-users.
159
160 QUrl is capable of recording only one error condition. If more than one
161 error is found, it is undefined which error is reported.
162
163 \section2 Character Conversions
164
165 Follow these rules to avoid erroneous character conversion when
166 dealing with URLs and strings:
167
168 \list
169 \li When creating a QString to contain a URL from a QByteArray or a
170 char*, always use QString::fromUtf8().
171 \endlist
172*/
173
174/*!
175 \enum QUrl::ParsingMode
176
177 The parsing mode controls the way QUrl parses strings.
178
179 \value TolerantMode QUrl will try to correct some common errors in URLs.
180 This mode is useful for parsing URLs coming from sources
181 not known to be strictly standards-conforming.
182
183 \value StrictMode Only valid URLs are accepted. This mode is useful for
184 general URL validation.
185
186 \value DecodedMode QUrl will interpret the URL component in the fully-decoded form,
187 where percent characters stand for themselves, not as the beginning
188 of a percent-encoded sequence. This mode is only valid for the
189 setters setting components of a URL; it is not permitted in
190 the QUrl constructor, in fromEncoded() or in setUrl().
191 For more information on this mode, see the documentation for
192 \l {QUrl::ComponentFormattingOption}{QUrl::FullyDecoded}.
193
194 In TolerantMode, the parser has the following behaviour:
195
196 \list
197
198 \li Spaces and "%20": unencoded space characters will be accepted and will
199 be treated as equivalent to "%20".
200
201 \li Single "%" characters: Any occurrences of a percent character "%" not
202 followed by exactly two hexadecimal characters (e.g., "13% coverage.html")
203 will be replaced by "%25". Note that one lone "%" character will trigger
204 the correction mode for all percent characters.
205
206 \li Reserved and unreserved characters: An encoded URL should only
207 contain a few characters as literals; all other characters should
208 be percent-encoded. In TolerantMode, these characters will be
209 accepted if they are found in the URL:
210 space / double-quote / "<" / ">" / "\" /
211 "^" / "`" / "{" / "|" / "}"
212 Those same characters can be decoded again by passing QUrl::DecodeReserved
213 to toString() or toEncoded(). In the getters of individual components,
214 those characters are often returned in decoded form.
215
216 \endlist
217
218 When in StrictMode, if a parsing error is found, isValid() will return \c
219 false and errorString() will return a message describing the error.
220 If more than one error is detected, it is undefined which error gets
221 reported.
222
223 Note that TolerantMode is not usually enough for parsing user input, which
224 often contains more errors and expectations than the parser can deal with.
225 When dealing with data coming directly from the user -- as opposed to data
226 coming from data-transfer sources, such as other programs -- it is
227 recommended to use fromUserInput().
228
229 \sa fromUserInput(), setUrl(), toString(), toEncoded(), QUrl::FormattingOptions
230*/
231
232/*!
233 \enum QUrl::UrlFormattingOption
234
235 The formatting options define how the URL is formatted when written out
236 as text.
237
238 \value None The format of the URL is unchanged.
239 \value RemoveScheme The scheme is removed from the URL.
240 \value RemovePassword Any password in the URL is removed.
241 \value RemoveUserInfo Any user information in the URL is removed.
242 \value RemovePort Any specified port is removed from the URL.
243 \value RemoveAuthority
244 \value RemovePath The URL's path is removed, leaving only the scheme,
245 host address, and port (if present).
246 \value RemoveQuery The query part of the URL (following a '?' character)
247 is removed.
248 \value RemoveFragment
249 \value RemoveFilename The filename (i.e. everything after the last '/' in the path) is removed.
250 The trailing '/' is kept, unless StripTrailingSlash is set.
251 Only valid if RemovePath is not set.
252 \value PreferLocalFile If the URL is a local file according to isLocalFile()
253 and contains no query or fragment, a local file path is returned.
254 \value StripTrailingSlash The trailing slash is removed from the path, if one is present.
255 \value NormalizePathSegments Modifies the path to remove redundant directory separators,
256 and to resolve "."s and ".."s (as far as possible). For non-local paths, adjacent
257 slashes are preserved.
258
259 Note that the case folding rules in \l{RFC 3491}{Nameprep}, which QUrl
260 conforms to, require host names to always be converted to lower case,
261 regardless of the Qt::FormattingOptions used.
262
263 The options from QUrl::ComponentFormattingOptions are also possible.
264
265 \sa QUrl::ComponentFormattingOptions
266*/
267
268/*!
269 \enum QUrl::ComponentFormattingOption
270 \since 5.0
271
272 The component formatting options define how the components of an URL will
273 be formatted when written out as text. They can be combined with the
274 options from QUrl::FormattingOptions when used in toString() and
275 toEncoded().
276
277 \value PrettyDecoded The component is returned in a "pretty form", with
278 most percent-encoded characters decoded. The exact
279 behavior of PrettyDecoded varies from component to
280 component and may also change from Qt release to Qt
281 release. This is the default.
282
283 \value EncodeSpaces Leave space characters in their encoded form ("%20").
284
285 \value EncodeUnicode Leave non-US-ASCII characters encoded in their UTF-8
286 percent-encoded form (e.g., "%C3%A9" for the U+00E9
287 codepoint, LATIN SMALL LETTER E WITH ACUTE).
288
289 \value EncodeDelimiters Leave certain delimiters in their encoded form, as
290 would appear in the URL when the full URL is
291 represented as text. The delimiters are affected
292 by this option change from component to component.
293 This flag has no effect in toString() or toEncoded().
294
295 \value EncodeReserved Leave US-ASCII characters not permitted in the URL by
296 the specification in their encoded form. This is the
297 default on toString() and toEncoded().
298
299 \value DecodeReserved Decode the US-ASCII characters that the URL specification
300 does not allow to appear in the URL. This is the
301 default on the getters of individual components.
302
303 \value FullyEncoded Leave all characters in their properly-encoded form,
304 as this component would appear as part of a URL. When
305 used with toString(), this produces a fully-compliant
306 URL in QString form, exactly equal to the result of
307 toEncoded()
308
309 \value FullyDecoded Attempt to decode as much as possible. For individual
310 components of the URL, this decodes every percent
311 encoding sequence, including control characters (U+0000
312 to U+001F) and UTF-8 sequences found in percent-encoded form.
313 Use of this mode may cause data loss, see below for more information.
314
315 The values of EncodeReserved and DecodeReserved should not be used together
316 in one call. The behavior is undefined if that happens. They are provided
317 as separate values because the behavior of the "pretty mode" with regards
318 to reserved characters is different on certain components and specially on
319 the full URL.
320
321 \section2 Full decoding
322
323 The FullyDecoded mode is similar to the behavior of the functions returning
324 QString in Qt 4.x, in that every character represents itself and never has
325 any special meaning. This is true even for the percent character ('%'),
326 which should be interpreted to mean a literal percent, not the beginning of
327 a percent-encoded sequence. The same actual character, in all other
328 decoding modes, is represented by the sequence "%25".
329
330 Whenever re-applying data obtained with QUrl::FullyDecoded into a QUrl,
331 care must be taken to use the QUrl::DecodedMode parameter to the setters
332 (like setPath() and setUserName()). Failure to do so may cause
333 re-interpretation of the percent character ('%') as the beginning of a
334 percent-encoded sequence.
335
336 This mode is quite useful when portions of a URL are used in a non-URL
337 context. For example, to extract the username, password or file paths in an
338 FTP client application, the FullyDecoded mode should be used.
339
340 This mode should be used with care, since there are two conditions that
341 cannot be reliably represented in the returned QString. They are:
342
343 \list
344 \li \b{Non-UTF-8 sequences:} URLs may contain sequences of
345 percent-encoded characters that do not form valid UTF-8 sequences. Since
346 URLs need to be decoded using UTF-8, any decoder failure will result in
347 the QString containing one or more replacement characters where the
348 sequence existed.
349
350 \li \b{Encoded delimiters:} URLs are also allowed to make a distinction
351 between a delimiter found in its literal form and its equivalent in
352 percent-encoded form. This is most commonly found in the query, but is
353 permitted in most parts of the URL.
354 \endlist
355
356 The following example illustrates the problem:
357
358 \snippet code/src_corelib_io_qurl.cpp 10
359
360 If the two URLs were used via HTTP GET, the interpretation by the web
361 server would probably be different. In the first case, it would interpret
362 as one parameter, with a key of "q" and value "a+=b&c". In the second
363 case, it would probably interpret as two parameters, one with a key of "q"
364 and value "a =b", and the second with a key "c" and no value.
365
366 \sa QUrl::FormattingOptions
367*/
368
369/*!
370 \enum QUrl::UserInputResolutionOption
371 \since 5.4
372
373 The user input resolution options define how fromUserInput() should
374 interpret strings that could either be a relative path or the short
375 form of a HTTP URL. For instance \c{file.pl} can be either a local file
376 or the URL \c{http://file.pl}.
377
378 \value DefaultResolution The default resolution mechanism is to check
379 whether a local file exists, in the working
380 directory given to fromUserInput, and only
381 return a local path in that case. Otherwise a URL
382 is assumed.
383 \value AssumeLocalFile This option makes fromUserInput() always return
384 a local path unless the input contains a scheme, such as
385 \c{http://file.pl}. This is useful for applications
386 such as text editors, which are able to create
387 the file if it doesn't exist.
388
389 \sa fromUserInput()
390*/
391
392/*!
393 \fn QUrl::QUrl(QUrl &&other)
394
395 Move-constructs a QUrl instance, making it point at the same
396 object that \a other was pointing to.
397
398 \since 5.2
399*/
400
401/*!
402 \fn QUrl &QUrl::operator=(QUrl &&other)
403
404 Move-assigns \a other to this QUrl instance.
405
406 \since 5.2
407*/
408
409#include "qurl.h"
410#include "qurl_p.h"
411#include "qplatformdefs.h"
412#include "qstring.h"
413#include "qstringlist.h"
414#include "qdebug.h"
415#include "qhash.h"
416#include "qdir.h" // for QDir::fromNativeSeparators
417#include "qdatastream.h"
418#if QT_CONFIG(topleveldomain) // ### Qt6: Remove section
419#include "qtldurl_p.h"
420#endif
421#include "private/qipaddress_p.h"
422#include "qurlquery.h"
423#include "private/qdir_p.h"
424#include <private/qmemory_p.h>
425
426QT_BEGIN_NAMESPACE
427
428inline static bool isHex(char c)
429{
430 c |= 0x20;
431 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
432}
433
434static inline QString ftpScheme()
435{
436 return QStringLiteral("ftp");
437}
438
439static inline QString fileScheme()
440{
441 return QStringLiteral("file");
442}
443
444static inline QString webDavScheme()
445{
446 return QStringLiteral("webdavs");
447}
448
449static inline QString webDavSslTag()
450{
451 return QStringLiteral("@SSL");
452}
453
454class QUrlPrivate
455{
456public:
457 enum Section : uchar {
458 Scheme = 0x01,
459 UserName = 0x02,
460 Password = 0x04,
461 UserInfo = UserName | Password,
462 Host = 0x08,
463 Port = 0x10,
464 Authority = UserInfo | Host | Port,
465 Path = 0x20,
466 Hierarchy = Authority | Path,
467 Query = 0x40,
468 Fragment = 0x80,
469 FullUrl = 0xff
470 };
471
472 enum Flags : uchar {
473 IsLocalFile = 0x01
474 };
475
476 enum ErrorCode {
477 // the high byte of the error code matches the Section
478 // the first item in each value must be the generic "Invalid xxx Error"
479 InvalidSchemeError = Scheme << 8,
480
481 InvalidUserNameError = UserName << 8,
482
483 InvalidPasswordError = Password << 8,
484
485 InvalidRegNameError = Host << 8,
486 InvalidIPv4AddressError,
487 InvalidIPv6AddressError,
488 InvalidCharacterInIPv6Error,
489 InvalidIPvFutureError,
490 HostMissingEndBracket,
491
492 InvalidPortError = Port << 8,
493 PortEmptyError,
494
495 InvalidPathError = Path << 8,
496
497 InvalidQueryError = Query << 8,
498
499 InvalidFragmentError = Fragment << 8,
500
501 // the following three cases are only possible in combination with
502 // presence/absence of the path, authority and scheme. See validityError().
503 AuthorityPresentAndPathIsRelative = Authority << 8 | Path << 8 | 0x10000,
504 AuthorityAbsentAndPathIsDoubleSlash,
505 RelativeUrlPathContainsColonBeforeSlash = Scheme << 8 | Authority << 8 | Path << 8 | 0x10000,
506
507 NoError = 0
508 };
509
510 struct Error {
511 QString source;
512 ErrorCode code;
513 int position;
514 };
515
516 QUrlPrivate();
517 QUrlPrivate(const QUrlPrivate &copy);
518 ~QUrlPrivate();
519
520 void parse(const QString &url, QUrl::ParsingMode parsingMode);
521 bool isEmpty() const
522 { return sectionIsPresent == 0 && port == -1 && path.isEmpty(); }
523
524 std::unique_ptr<Error> cloneError() const;
525 void clearError();
526 void setError(ErrorCode errorCode, const QString &source, int supplement = -1);
527 ErrorCode validityError(QString *source = nullptr, int *position = nullptr) const;
528 bool validateComponent(Section section, const QString &input, int begin, int end);
529 bool validateComponent(Section section, const QString &input)
530 { return validateComponent(section, input, 0, uint(input.length())); }
531
532 // no QString scheme() const;
533 void appendAuthority(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const;
534 void appendUserInfo(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const;
535 void appendUserName(QString &appendTo, QUrl::FormattingOptions options) const;
536 void appendPassword(QString &appendTo, QUrl::FormattingOptions options) const;
537 void appendHost(QString &appendTo, QUrl::FormattingOptions options) const;
538 void appendPath(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const;
539 void appendQuery(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const;
540 void appendFragment(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const;
541
542 // the "end" parameters are like STL iterators: they point to one past the last valid element
543 bool setScheme(const QString &value, int len, bool doSetError);
544 void setAuthority(const QString &auth, int from, int end, QUrl::ParsingMode mode);
545 void setUserInfo(const QString &userInfo, int from, int end);
546 void setUserName(const QString &value, int from, int end);
547 void setPassword(const QString &value, int from, int end);
548 bool setHost(const QString &value, int from, int end, QUrl::ParsingMode mode);
549 void setPath(const QString &value, int from, int end);
550 void setQuery(const QString &value, int from, int end);
551 void setFragment(const QString &value, int from, int end);
552
553 inline bool hasScheme() const { return sectionIsPresent & Scheme; }
554 inline bool hasAuthority() const { return sectionIsPresent & Authority; }
555 inline bool hasUserInfo() const { return sectionIsPresent & UserInfo; }
556 inline bool hasUserName() const { return sectionIsPresent & UserName; }
557 inline bool hasPassword() const { return sectionIsPresent & Password; }
558 inline bool hasHost() const { return sectionIsPresent & Host; }
559 inline bool hasPort() const { return port != -1; }
560 inline bool hasPath() const { return !path.isEmpty(); }
561 inline bool hasQuery() const { return sectionIsPresent & Query; }
562 inline bool hasFragment() const { return sectionIsPresent & Fragment; }
563
564 inline bool isLocalFile() const { return flags & IsLocalFile; }
565 QString toLocalFile(QUrl::FormattingOptions options) const;
566
567 QString mergePaths(const QString &relativePath) const;
568
569 QAtomicInt ref;
570 int port;
571
572 QString scheme;
573 QString userName;
574 QString password;
575 QString host;
576 QString path;
577 QString query;
578 QString fragment;
579
580 std::unique_ptr<Error> error;
581
582 // not used for:
583 // - Port (port == -1 means absence)
584 // - Path (there's no path delimiter, so we optimize its use out of existence)
585 // Schemes are never supposed to be empty, but we keep the flag anyway
586 uchar sectionIsPresent;
587 uchar flags;
588
589 // 32-bit: 2 bytes tail padding available
590 // 64-bit: 6 bytes tail padding available
591};
592
593inline QUrlPrivate::QUrlPrivate()
594 : ref(1), port(-1),
595 sectionIsPresent(0),
596 flags(0)
597{
598}
599
600inline QUrlPrivate::QUrlPrivate(const QUrlPrivate &copy)
601 : ref(1), port(copy.port),
602 scheme(copy.scheme),
603 userName(copy.userName),
604 password(copy.password),
605 host(copy.host),
606 path(copy.path),
607 query(copy.query),
608 fragment(copy.fragment),
609 error(copy.cloneError()),
610 sectionIsPresent(copy.sectionIsPresent),
611 flags(copy.flags)
612{
613}
614
615inline QUrlPrivate::~QUrlPrivate()
616 = default;
617
618std::unique_ptr<QUrlPrivate::Error> QUrlPrivate::cloneError() const
619{
620 return error ? qt_make_unique<Error>(*error) : nullptr;
621}
622
623inline void QUrlPrivate::clearError()
624{
625 error.reset();
626}
627
628inline void QUrlPrivate::setError(ErrorCode errorCode, const QString &source, int supplement)
629{
630 if (error) {
631 // don't overwrite an error set in a previous section during parsing
632 return;
633 }
634 error = qt_make_unique<Error>();
635 error->code = errorCode;
636 error->source = source;
637 error->position = supplement;
638}
639
640// From RFC 3986, Appendix A Collected ABNF for URI
641// URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
642//[...]
643// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
644//
645// authority = [ userinfo "@" ] host [ ":" port ]
646// userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
647// host = IP-literal / IPv4address / reg-name
648// port = *DIGIT
649//[...]
650// reg-name = *( unreserved / pct-encoded / sub-delims )
651//[..]
652// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
653//
654// query = *( pchar / "/" / "?" )
655//
656// fragment = *( pchar / "/" / "?" )
657//
658// pct-encoded = "%" HEXDIG HEXDIG
659//
660// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
661// reserved = gen-delims / sub-delims
662// gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
663// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
664// / "*" / "+" / "," / ";" / "="
665// the path component has a complex ABNF that basically boils down to
666// slash-separated segments of "pchar"
667
668// The above is the strict definition of the URL components and we mostly
669// adhere to it, with few exceptions. QUrl obeys the following behavior:
670// - percent-encoding sequences always use uppercase HEXDIG;
671// - unreserved characters are *always* decoded, no exceptions;
672// - the space character and bytes with the high bit set are controlled by
673// the EncodeSpaces and EncodeUnicode bits;
674// - control characters, the percent sign itself, and bytes with the high
675// bit set that don't form valid UTF-8 sequences are always encoded,
676// except in FullyDecoded mode;
677// - sub-delims are always left alone, except in FullyDecoded mode;
678// - gen-delim change behavior depending on which section of the URL (or
679// the entire URL) we're looking at; see below;
680// - characters not mentioned above, like "<", and ">", are usually
681// decoded in individual sections of the URL, but encoded when the full
682// URL is put together (we can change on subjective definition of
683// "pretty").
684//
685// The behavior for the delimiters bears some explanation. The spec says in
686// section 2.2:
687// URIs that differ in the replacement of a reserved character with its
688// corresponding percent-encoded octet are not equivalent.
689// (note: QUrl API mistakenly uses the "reserved" term, so we will refer to
690// them here as "delimiters").
691//
692// For that reason, we cannot encode delimiters found in decoded form and we
693// cannot decode the ones found in encoded form if that would change the
694// interpretation. Conversely, we *can* perform the transformation if it would
695// not change the interpretation. From the last component of a URL to the first,
696// here are the gen-delims we can unambiguously transform when the field is
697// taken in isolation:
698// - fragment: none, since it's the last
699// - query: "#" is unambiguous
700// - path: "#" and "?" are unambiguous
701// - host: completely special but never ambiguous, see setHost() below.
702// - password: the "#", "?", "/", "[", "]" and "@" characters are unambiguous
703// - username: the "#", "?", "/", "[", "]", "@", and ":" characters are unambiguous
704// - scheme: doesn't accept any delimiter, see setScheme() below.
705//
706// Internally, QUrl stores each component in the format that corresponds to the
707// default mode (PrettyDecoded). It deviates from the "strict" FullyEncoded
708// mode in the following way:
709// - spaces are decoded
710// - valid UTF-8 sequences are decoded
711// - gen-delims that can be unambiguously transformed are decoded
712// - characters controlled by DecodeReserved are often decoded, though this behavior
713// can change depending on the subjective definition of "pretty"
714//
715// Note that the list of gen-delims that we can transform is different for the
716// user info (user name + password) and the authority (user info + host +
717// port).
718
719
720// list the recoding table modifications to be used with the recodeFromUser and
721// appendToUser functions, according to the rules above. Spaces and UTF-8
722// sequences are handled outside the tables.
723
724// the encodedXXX tables are run with the delimiters set to "leave" by default;
725// the decodedXXX tables are run with the delimiters set to "decode" by default
726// (except for the query, which doesn't use these functions)
727
728#define decode(x) ushort(x)
729#define leave(x) ushort(0x100 | (x))
730#define encode(x) ushort(0x200 | (x))
731
732static const ushort userNameInIsolation[] = {
733 decode(':'), // 0
734 decode('@'), // 1
735 decode(']'), // 2
736 decode('['), // 3
737 decode('/'), // 4
738 decode('?'), // 5
739 decode('#'), // 6
740
741 decode('"'), // 7
742 decode('<'),
743 decode('>'),
744 decode('^'),
745 decode('\\'),
746 decode('|'),
747 decode('{'),
748 decode('}'),
749 0
750};
751static const ushort * const passwordInIsolation = userNameInIsolation + 1;
752static const ushort * const pathInIsolation = userNameInIsolation + 5;
753static const ushort * const queryInIsolation = userNameInIsolation + 6;
754static const ushort * const fragmentInIsolation = userNameInIsolation + 7;
755
756static const ushort userNameInUserInfo[] = {
757 encode(':'), // 0
758 decode('@'), // 1
759 decode(']'), // 2
760 decode('['), // 3
761 decode('/'), // 4
762 decode('?'), // 5
763 decode('#'), // 6
764
765 decode('"'), // 7
766 decode('<'),
767 decode('>'),
768 decode('^'),
769 decode('\\'),
770 decode('|'),
771 decode('{'),
772 decode('}'),
773 0
774};
775static const ushort * const passwordInUserInfo = userNameInUserInfo + 1;
776
777static const ushort userNameInAuthority[] = {
778 encode(':'), // 0
779 encode('@'), // 1
780 encode(']'), // 2
781 encode('['), // 3
782 decode('/'), // 4
783 decode('?'), // 5
784 decode('#'), // 6
785
786 decode('"'), // 7
787 decode('<'),
788 decode('>'),
789 decode('^'),
790 decode('\\'),
791 decode('|'),
792 decode('{'),
793 decode('}'),
794 0
795};
796static const ushort * const passwordInAuthority = userNameInAuthority + 1;
797
798static const ushort userNameInUrl[] = {
799 encode(':'), // 0
800 encode('@'), // 1
801 encode(']'), // 2
802 encode('['), // 3
803 encode('/'), // 4
804 encode('?'), // 5
805 encode('#'), // 6
806
807 // no need to list encode(x) for the other characters
808 0
809};
810static const ushort * const passwordInUrl = userNameInUrl + 1;
811static const ushort * const pathInUrl = userNameInUrl + 5;
812static const ushort * const queryInUrl = userNameInUrl + 6;
813static const ushort * const fragmentInUrl = userNameInUrl + 6;
814
815static inline void parseDecodedComponent(QString &data)
816{
817 data.replace(QLatin1Char('%'), QLatin1String("%25"));
818}
819
820static inline QString
821recodeFromUser(const QString &input, const ushort *actions, int from, int to)
822{
823 QString output;
824 const QChar *begin = input.constData() + from;
825 const QChar *end = input.constData() + to;
826 if (qt_urlRecode(output, begin, end, {}, actions))
827 return output;
828
829 return input.mid(from, to - from);
830}
831
832// appendXXXX functions: copy from the internal form to the external, user form.
833// the internal value is stored in its PrettyDecoded form, so that case is easy.
834static inline void appendToUser(QString &appendTo, const QStringRef &value, QUrl::FormattingOptions options,
835 const ushort *actions)
836{
837 // Test ComponentFormattingOptions, ignore FormattingOptions.
838 if ((options & 0xFFFF0000) == QUrl::PrettyDecoded) {
839 appendTo += value;
840 return;
841 }
842
843 if (!qt_urlRecode(appendTo, value.data(), value.end(), options, actions))
844 appendTo += value;
845}
846
847static inline void appendToUser(QString &appendTo, const QString &value, QUrl::FormattingOptions options,
848 const ushort *actions)
849{
850 appendToUser(appendTo, QStringRef(&value), options, actions);
851}
852
853
854inline void QUrlPrivate::appendAuthority(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const
855{
856 if ((options & QUrl::RemoveUserInfo) != QUrl::RemoveUserInfo) {
857 appendUserInfo(appendTo, options, appendingTo);
858
859 // add '@' only if we added anything
860 if (hasUserName() || (hasPassword() && (options & QUrl::RemovePassword) == 0))
861 appendTo += QLatin1Char('@');
862 }
863 appendHost(appendTo, options);
864 if (!(options & QUrl::RemovePort) && port != -1)
865 appendTo += QLatin1Char(':') + QString::number(port);
866}
867
868inline void QUrlPrivate::appendUserInfo(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const
869{
870 if (Q_LIKELY(!hasUserInfo()))
871 return;
872
873 const ushort *userNameActions;
874 const ushort *passwordActions;
875 if (options & QUrl::EncodeDelimiters) {
876 userNameActions = userNameInUrl;
877 passwordActions = passwordInUrl;
878 } else {
879 switch (appendingTo) {
880 case UserInfo:
881 userNameActions = userNameInUserInfo;
882 passwordActions = passwordInUserInfo;
883 break;
884
885 case Authority:
886 userNameActions = userNameInAuthority;
887 passwordActions = passwordInAuthority;
888 break;
889
890 case FullUrl:
891 userNameActions = userNameInUrl;
892 passwordActions = passwordInUrl;
893 break;
894
895 default:
896 // can't happen
897 Q_UNREACHABLE();
898 break;
899 }
900 }
901
902 if (!qt_urlRecode(appendTo, userName.constData(), userName.constEnd(), options, userNameActions))
903 appendTo += userName;
904 if (options & QUrl::RemovePassword || !hasPassword()) {
905 return;
906 } else {
907 appendTo += QLatin1Char(':');
908 if (!qt_urlRecode(appendTo, password.constData(), password.constEnd(), options, passwordActions))
909 appendTo += password;
910 }
911}
912
913inline void QUrlPrivate::appendUserName(QString &appendTo, QUrl::FormattingOptions options) const
914{
915 // only called from QUrl::userName()
916 appendToUser(appendTo, userName, options,
917 options & QUrl::EncodeDelimiters ? userNameInUrl : userNameInIsolation);
918}
919
920inline void QUrlPrivate::appendPassword(QString &appendTo, QUrl::FormattingOptions options) const
921{
922 // only called from QUrl::password()
923 appendToUser(appendTo, password, options,
924 options & QUrl::EncodeDelimiters ? passwordInUrl : passwordInIsolation);
925}
926
927inline void QUrlPrivate::appendPath(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const
928{
929 QString thePath = path;
930 if (options & QUrl::NormalizePathSegments) {
931 thePath = qt_normalizePathSegments(path, isLocalFile() ? QDirPrivate::DefaultNormalization : QDirPrivate::RemotePath);
932 }
933
934 QStringRef thePathRef(&thePath);
935 if (options & QUrl::RemoveFilename) {
936 const int slash = path.lastIndexOf(QLatin1Char('/'));
937 if (slash == -1)
938 return;
939 thePathRef = path.leftRef(slash + 1);
940 }
941 // check if we need to remove trailing slashes
942 if (options & QUrl::StripTrailingSlash) {
943 while (thePathRef.length() > 1 && thePathRef.endsWith(QLatin1Char('/')))
944 thePathRef.chop(1);
945 }
946
947 appendToUser(appendTo, thePathRef, options,
948 appendingTo == FullUrl || options & QUrl::EncodeDelimiters ? pathInUrl : pathInIsolation);
949}
950
951inline void QUrlPrivate::appendFragment(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const
952{
953 appendToUser(appendTo, fragment, options,
954 options & QUrl::EncodeDelimiters ? fragmentInUrl :
955 appendingTo == FullUrl ? nullptr : fragmentInIsolation);
956}
957
958inline void QUrlPrivate::appendQuery(QString &appendTo, QUrl::FormattingOptions options, Section appendingTo) const
959{
960 appendToUser(appendTo, query, options,
961 appendingTo == FullUrl || options & QUrl::EncodeDelimiters ? queryInUrl : queryInIsolation);
962}
963
964// setXXX functions
965
966inline bool QUrlPrivate::setScheme(const QString &value, int len, bool doSetError)
967{
968 // schemes are strictly RFC-compliant:
969 // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
970 // we also lowercase the scheme
971
972 // schemes in URLs are not allowed to be empty, but they can be in
973 // "Relative URIs" which QUrl also supports. QUrl::setScheme does
974 // not call us with len == 0, so this can only be from parse()
975 scheme.clear();
976 if (len == 0)
977 return false;
978
979 sectionIsPresent |= Scheme;
980
981 // validate it:
982 int needsLowercasing = -1;
983 const ushort *p = reinterpret_cast<const ushort *>(value.constData());
984 for (int i = 0; i < len; ++i) {
985 if (p[i] >= 'a' && p[i] <= 'z')
986 continue;
987 if (p[i] >= 'A' && p[i] <= 'Z') {
988 needsLowercasing = i;
989 continue;
990 }
991 if (i) {
992 if (p[i] >= '0' && p[i] <= '9')
993 continue;
994 if (p[i] == '+' || p[i] == '-' || p[i] == '.')
995 continue;
996 }
997
998 // found something else
999 // don't call setError needlessly:
1000 // if we've been called from parse(), it will try to recover
1001 if (doSetError)
1002 setError(InvalidSchemeError, value, i);
1003 return false;
1004 }
1005
1006 scheme = value.left(len);
1007
1008 if (needsLowercasing != -1) {
1009 // schemes are ASCII only, so we don't need the full Unicode toLower
1010 QChar *schemeData = scheme.data(); // force detaching here
1011 for (int i = needsLowercasing; i >= 0; --i) {
1012 ushort c = schemeData[i].unicode();
1013 if (c >= 'A' && c <= 'Z')
1014 schemeData[i] = QChar(c + 0x20);
1015 }
1016 }
1017
1018 // did we set to the file protocol?
1019 if (scheme == fileScheme()
1020#ifdef Q_OS_WIN
1021 || scheme == webDavScheme()
1022#endif
1023 ) {
1024 flags |= IsLocalFile;
1025 } else {
1026 flags &= ~IsLocalFile;
1027 }
1028 return true;
1029}
1030
1031inline void QUrlPrivate::setAuthority(const QString &auth, int from, int end, QUrl::ParsingMode mode)
1032{
1033 sectionIsPresent &= ~Authority;
1034 sectionIsPresent |= Host;
1035 port = -1;
1036
1037 // we never actually _loop_
1038 while (from != end) {
1039 int userInfoIndex = auth.indexOf(QLatin1Char('@'), from);
1040 if (uint(userInfoIndex) < uint(end)) {
1041 setUserInfo(auth, from, userInfoIndex);
1042 if (mode == QUrl::StrictMode && !validateComponent(UserInfo, auth, from, userInfoIndex))
1043 break;
1044 from = userInfoIndex + 1;
1045 }
1046
1047 int colonIndex = auth.lastIndexOf(QLatin1Char(':'), end - 1);
1048 if (colonIndex < from)
1049 colonIndex = -1;
1050
1051 if (uint(colonIndex) < uint(end)) {
1052 if (auth.at(from).unicode() == '[') {
1053 // check if colonIndex isn't inside the "[...]" part
1054 int closingBracket = auth.indexOf(QLatin1Char(']'), from);
1055 if (uint(closingBracket) > uint(colonIndex))
1056 colonIndex = -1;
1057 }
1058 }
1059
1060 if (uint(colonIndex) < uint(end) - 1) {
1061 // found a colon with digits after it
1062 unsigned long x = 0;
1063 for (int i = colonIndex + 1; i < end; ++i) {
1064 ushort c = auth.at(i).unicode();
1065 if (c >= '0' && c <= '9') {
1066 x *= 10;
1067 x += c - '0';
1068 } else {
1069 x = ulong(-1); // x != ushort(x)
1070 break;
1071 }
1072 }
1073 if (x == ushort(x)) {
1074 port = ushort(x);
1075 } else {
1076 setError(InvalidPortError, auth, colonIndex + 1);
1077 if (mode == QUrl::StrictMode)
1078 break;
1079 }
1080 }
1081
1082 setHost(auth, from, qMin<uint>(end, colonIndex), mode);
1083 if (mode == QUrl::StrictMode && !validateComponent(Host, auth, from, qMin<uint>(end, colonIndex))) {
1084 // clear host too
1085 sectionIsPresent &= ~Authority;
1086 break;
1087 }
1088
1089 // success
1090 return;
1091 }
1092 // clear all sections but host
1093 sectionIsPresent &= ~Authority | Host;
1094 userName.clear();
1095 password.clear();
1096 host.clear();
1097 port = -1;
1098}
1099
1100inline void QUrlPrivate::setUserInfo(const QString &userInfo, int from, int end)
1101{
1102 int delimIndex = userInfo.indexOf(QLatin1Char(':'), from);
1103 setUserName(userInfo, from, qMin<uint>(delimIndex, end));
1104
1105 if (uint(delimIndex) >= uint(end)) {
1106 password.clear();
1107 sectionIsPresent &= ~Password;
1108 } else {
1109 setPassword(userInfo, delimIndex + 1, end);
1110 }
1111}
1112
1113inline void QUrlPrivate::setUserName(const QString &value, int from, int end)
1114{
1115 sectionIsPresent |= UserName;
1116 userName = recodeFromUser(value, userNameInIsolation, from, end);
1117}
1118
1119inline void QUrlPrivate::setPassword(const QString &value, int from, int end)
1120{
1121 sectionIsPresent |= Password;
1122 password = recodeFromUser(value, passwordInIsolation, from, end);
1123}
1124
1125inline void QUrlPrivate::setPath(const QString &value, int from, int end)
1126{
1127 // sectionIsPresent |= Path; // not used, save some cycles
1128 path = recodeFromUser(value, pathInIsolation, from, end);
1129}
1130
1131inline void QUrlPrivate::setFragment(const QString &value, int from, int end)
1132{
1133 sectionIsPresent |= Fragment;
1134 fragment = recodeFromUser(value, fragmentInIsolation, from, end);
1135}
1136
1137inline void QUrlPrivate::setQuery(const QString &value, int from, int iend)
1138{
1139 sectionIsPresent |= Query;
1140 query = recodeFromUser(value, queryInIsolation, from, iend);
1141}
1142
1143// Host handling
1144// The RFC says the host is:
1145// host = IP-literal / IPv4address / reg-name
1146// IP-literal = "[" ( IPv6address / IPvFuture ) "]"
1147// IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
1148// [a strict definition of IPv6Address and IPv4Address]
1149// reg-name = *( unreserved / pct-encoded / sub-delims )
1150//
1151// We deviate from the standard in all but IPvFuture. For IPvFuture we accept
1152// and store only exactly what the RFC says we should. No percent-encoding is
1153// permitted in this field, so Unicode characters and space aren't either.
1154//
1155// For IPv4 addresses, we accept broken addresses like inet_aton does (that is,
1156// less than three dots). However, we correct the address to the proper form
1157// and store the corrected address. After correction, we comply to the RFC and
1158// it's exclusively composed of unreserved characters.
1159//
1160// For IPv6 addresses, we accept addresses including trailing (embedded) IPv4
1161// addresses, the so-called v4-compat and v4-mapped addresses. We also store
1162// those addresses like that in the hostname field, which violates the spec.
1163// IPv6 hosts are stored with the square brackets in the QString. It also
1164// requires no transformation in any way.
1165//
1166// As for registered names, it's the other way around: we accept only valid
1167// hostnames as specified by STD 3 and IDNA. That means everything we accept is
1168// valid in the RFC definition above, but there are many valid reg-names
1169// according to the RFC that we do not accept in the name of security. Since we
1170// do accept IDNA, reg-names are subject to ACE encoding and decoding, which is
1171// specified by the DecodeUnicode flag. The hostname is stored in its Unicode form.
1172
1173inline void QUrlPrivate::appendHost(QString &appendTo, QUrl::FormattingOptions options) const
1174{
1175 if (host.isEmpty())
1176 return;
1177 if (host.at(0).unicode() == '[') {
1178 // IPv6 addresses might contain a zone-id which needs to be recoded
1179 if (options != 0)
1180 if (qt_urlRecode(appendTo, host.constBegin(), host.constEnd(), options, nullptr))
1181 return;
1182 appendTo += host;
1183 } else {
1184 // this is either an IPv4Address or a reg-name
1185 // if it is a reg-name, it is already stored in Unicode form
1186 if (options & QUrl::EncodeUnicode && !(options & 0x4000000))
1187 appendTo += qt_ACE_do(host, ToAceOnly, AllowLeadingDot);
1188 else
1189 appendTo += host;
1190 }
1191}
1192
1193// the whole IPvFuture is passed and parsed here, including brackets;
1194// returns null if the parsing was successful, or the QChar of the first failure
1195static const QChar *parseIpFuture(QString &host, const QChar *begin, const QChar *end, QUrl::ParsingMode mode)
1196{
1197 // IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
1198 static const char acceptable[] =
1199 "!$&'()*+,;=" // sub-delims
1200 ":" // ":"
1201 "-._~"; // unreserved
1202
1203 // the brackets and the "v" have been checked
1204 const QChar *const origBegin = begin;
1205 if (begin[3].unicode() != '.')
1206 return &begin[3];
1207 if ((begin[2].unicode() >= 'A' && begin[2].unicode() <= 'F') ||
1208 (begin[2].unicode() >= 'a' && begin[2].unicode() <= 'f') ||
1209 (begin[2].unicode() >= '0' && begin[2].unicode() <= '9')) {
1210 // this is so unlikely that we'll just go down the slow path
1211 // decode the whole string, skipping the "[vH." and "]" which we already know to be there
1212 host += QString::fromRawData(begin, 4);
1213
1214 // uppercase the version, if necessary
1215 if (begin[2].unicode() >= 'a')
1216 host[host.length() - 2] = begin[2].unicode() - 0x20;
1217
1218 begin += 4;
1219 --end;
1220
1221 QString decoded;
1222 if (mode == QUrl::TolerantMode && qt_urlRecode(decoded, begin, end, QUrl::FullyDecoded, nullptr)) {
1223 begin = decoded.constBegin();
1224 end = decoded.constEnd();
1225 }
1226
1227 for ( ; begin != end; ++begin) {
1228 if (begin->unicode() >= 'A' && begin->unicode() <= 'Z')
1229 host += *begin;
1230 else if (begin->unicode() >= 'a' && begin->unicode() <= 'z')
1231 host += *begin;
1232 else if (begin->unicode() >= '0' && begin->unicode() <= '9')
1233 host += *begin;
1234 else if (begin->unicode() < 0x80 && strchr(acceptable, begin->unicode()) != nullptr)
1235 host += *begin;
1236 else
1237 return decoded.isEmpty() ? begin : &origBegin[2];
1238 }
1239 host += QLatin1Char(']');
1240 return nullptr;
1241 }
1242 return &origBegin[2];
1243}
1244
1245// ONLY the IPv6 address is parsed here, WITHOUT the brackets
1246static const QChar *parseIp6(QString &host, const QChar *begin, const QChar *end, QUrl::ParsingMode mode)
1247{
1248 // ### Update to use QStringView once QStringView::indexOf and QStringView::lastIndexOf exists
1249 QString decoded;
1250 if (mode == QUrl::TolerantMode) {
1251 // this struct is kept in automatic storage because it's only 4 bytes
1252 const ushort decodeColon[] = { decode(':'), 0 };
1253 if (qt_urlRecode(decoded, begin, end, QUrl::ComponentFormattingOption::PrettyDecoded, decodeColon) == 0)
1254 decoded = QString(begin, end-begin);
1255 } else {
1256 decoded = QString(begin, end-begin);
1257 }
1258
1259 const QLatin1String zoneIdIdentifier("%25");
1260 QIPAddressUtils::IPv6Address address;
1261 QString zoneId;
1262
1263 const QChar *endBeforeZoneId = decoded.constEnd();
1264
1265 int zoneIdPosition = decoded.indexOf(zoneIdIdentifier);
1266 if ((zoneIdPosition != -1) && (decoded.lastIndexOf(zoneIdIdentifier) == zoneIdPosition)) {
1267 zoneId = decoded.mid(zoneIdPosition + zoneIdIdentifier.size());
1268 endBeforeZoneId = decoded.constBegin() + zoneIdPosition;
1269
1270 if (zoneId.isEmpty())
1271 return end;
1272 }
1273
1274 const QChar *ret = QIPAddressUtils::parseIp6(address, decoded.constBegin(), endBeforeZoneId);
1275 if (ret)
1276 return begin + (ret - decoded.constBegin());
1277
1278 host.reserve(host.size() + (decoded.constEnd() - decoded.constBegin()));
1279 host += QLatin1Char('[');
1280 QIPAddressUtils::toString(host, address);
1281
1282 if (!zoneId.isEmpty()) {
1283 host += zoneIdIdentifier;
1284 host += zoneId;
1285 }
1286 host += QLatin1Char(']');
1287 return nullptr;
1288}
1289
1290inline bool QUrlPrivate::setHost(const QString &value, int from, int iend, QUrl::ParsingMode mode)
1291{
1292 const QChar *begin = value.constData() + from;
1293 const QChar *end = value.constData() + iend;
1294
1295 const int len = end - begin;
1296 host.clear();
1297 sectionIsPresent |= Host;
1298 if (len == 0)
1299 return true;
1300
1301 if (begin[0].unicode() == '[') {
1302 // IPv6Address or IPvFuture
1303 // smallest IPv6 address is "[::]" (len = 4)
1304 // smallest IPvFuture address is "[v7.X]" (len = 6)
1305 if (end[-1].unicode() != ']') {
1306 setError(HostMissingEndBracket, value);
1307 return false;
1308 }
1309
1310 if (len > 5 && begin[1].unicode() == 'v') {
1311 const QChar *c = parseIpFuture(host, begin, end, mode);
1312 if (c)
1313 setError(InvalidIPvFutureError, value, c - value.constData());
1314 return !c;
1315 } else if (begin[1].unicode() == 'v') {
1316 setError(InvalidIPvFutureError, value, from);
1317 }
1318
1319 const QChar *c = parseIp6(host, begin + 1, end - 1, mode);
1320 if (!c)
1321 return true;
1322
1323 if (c == end - 1)
1324 setError(InvalidIPv6AddressError, value, from);
1325 else
1326 setError(InvalidCharacterInIPv6Error, value, c - value.constData());
1327 return false;
1328 }
1329
1330 // check if it's an IPv4 address
1331 QIPAddressUtils::IPv4Address ip4;
1332 if (QIPAddressUtils::parseIp4(ip4, begin, end)) {
1333 // yes, it was
1334 QIPAddressUtils::toString(host, ip4);
1335 return true;
1336 }
1337
1338 // This is probably a reg-name.
1339 // But it can also be an encoded string that, when decoded becomes one
1340 // of the types above.
1341 //
1342 // Two types of encoding are possible:
1343 // percent encoding (e.g., "%31%30%2E%30%2E%30%2E%31" -> "10.0.0.1")
1344 // Unicode encoding (some non-ASCII characters case-fold to digits
1345 // when nameprepping is done)
1346 //
1347 // The qt_ACE_do function below applies nameprepping and the STD3 check.
1348 // That means a Unicode string may become an IPv4 address, but it cannot
1349 // produce a '[' or a '%'.
1350
1351 // check for percent-encoding first
1352 QString s;
1353 if (mode == QUrl::TolerantMode && qt_urlRecode(s, begin, end, { }, nullptr)) {
1354 // something was decoded
1355 // anything encoded left?
1356 int pos = s.indexOf(QChar(0x25)); // '%'
1357 if (pos != -1) {
1358 setError(InvalidRegNameError, s, pos);
1359 return false;
1360 }
1361
1362 // recurse
1363 return setHost(s, 0, s.length(), QUrl::StrictMode);
1364 }
1365
1366 s = qt_ACE_do(QString::fromRawData(begin, len), NormalizeAce, ForbidLeadingDot);
1367 if (s.isEmpty()) {
1368 setError(InvalidRegNameError, value);
1369 return false;
1370 }
1371
1372 // check IPv4 again
1373 if (QIPAddressUtils::parseIp4(ip4, s.constBegin(), s.constEnd())) {
1374 QIPAddressUtils::toString(host, ip4);
1375 } else {
1376 host = s;
1377 }
1378 return true;
1379}
1380
1381inline void QUrlPrivate::parse(const QString &url, QUrl::ParsingMode parsingMode)
1382{
1383 // URI-reference = URI / relative-ref
1384 // URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
1385 // relative-ref = relative-part [ "?" query ] [ "#" fragment ]
1386 // hier-part = "//" authority path-abempty
1387 // / other path types
1388 // relative-part = "//" authority path-abempty
1389 // / other path types here
1390
1391 sectionIsPresent = 0;
1392 flags = 0;
1393 clearError();
1394
1395 // find the important delimiters
1396 int colon = -1;
1397 int question = -1;
1398 int hash = -1;
1399 const int len = url.length();
1400 const QChar *const begin = url.constData();
1401 const ushort *const data = reinterpret_cast<const ushort *>(begin);
1402
1403 for (int i = 0; i < len; ++i) {
1404 uint uc = data[i];
1405 if (uc == '#' && hash == -1) {
1406 hash = i;
1407
1408 // nothing more to be found
1409 break;
1410 }
1411
1412 if (question == -1) {
1413 if (uc == ':' && colon == -1)
1414 colon = i;
1415 else if (uc == '?')
1416 question = i;
1417 }
1418 }
1419
1420 // check if we have a scheme
1421 int hierStart;
1422 if (colon != -1 && setScheme(url, colon, /* don't set error */ false)) {
1423 hierStart = colon + 1;
1424 } else {
1425 // recover from a failed scheme: it might not have been a scheme at all
1426 scheme.clear();
1427 sectionIsPresent = 0;
1428 hierStart = 0;
1429 }
1430
1431 int pathStart;
1432 int hierEnd = qMin<uint>(qMin<uint>(question, hash), len);
1433 if (hierEnd - hierStart >= 2 && data[hierStart] == '/' && data[hierStart + 1] == '/') {
1434 // we have an authority, it ends at the first slash after these
1435 int authorityEnd = hierEnd;
1436 for (int i = hierStart + 2; i < authorityEnd ; ++i) {
1437 if (data[i] == '/') {
1438 authorityEnd = i;
1439 break;
1440 }
1441 }
1442
1443 setAuthority(url, hierStart + 2, authorityEnd, parsingMode);
1444
1445 // even if we failed to set the authority properly, let's try to recover
1446 pathStart = authorityEnd;
1447 setPath(url, pathStart, hierEnd);
1448 } else {
1449 userName.clear();
1450 password.clear();
1451 host.clear();
1452 port = -1;
1453 pathStart = hierStart;
1454
1455 if (hierStart < hierEnd)
1456 setPath(url, hierStart, hierEnd);
1457 else
1458 path.clear();
1459 }
1460
1461 if (uint(question) < uint(hash))
1462 setQuery(url, question + 1, qMin<uint>(hash, len));
1463
1464 if (hash != -1)
1465 setFragment(url, hash + 1, len);
1466
1467 if (error || parsingMode == QUrl::TolerantMode)
1468 return;
1469
1470 // The parsing so far was partially tolerant of errors, except for the
1471 // scheme parser (which is always strict) and the authority (which was
1472 // executed in strict mode).
1473 // If we haven't found any errors so far, continue the strict-mode parsing
1474 // from the path component onwards.
1475
1476 if (!validateComponent(Path, url, pathStart, hierEnd))
1477 return;
1478 if (uint(question) < uint(hash) && !validateComponent(Query, url, question + 1, qMin<uint>(hash, len)))
1479 return;
1480 if (hash != -1)
1481 validateComponent(Fragment, url, hash + 1, len);
1482}
1483
1484QString QUrlPrivate::toLocalFile(QUrl::FormattingOptions options) const
1485{
1486 QString tmp;
1487 QString ourPath;
1488 appendPath(ourPath, options, QUrlPrivate::Path);
1489
1490 // magic for shared drive on windows
1491 if (!host.isEmpty()) {
1492 tmp = QLatin1String("//") + host;
1493#ifdef Q_OS_WIN // QTBUG-42346, WebDAV is visible as local file on Windows only.
1494 if (scheme == webDavScheme())
1495 tmp += webDavSslTag();
1496#endif
1497 if (!ourPath.isEmpty() && !ourPath.startsWith(QLatin1Char('/')))
1498 tmp += QLatin1Char('/');
1499 tmp += ourPath;
1500 } else {
1501 tmp = ourPath;
1502#ifdef Q_OS_WIN
1503 // magic for drives on windows
1504 if (ourPath.length() > 2 && ourPath.at(0) == QLatin1Char('/') && ourPath.at(2) == QLatin1Char(':'))
1505 tmp.remove(0, 1);
1506#endif
1507 }
1508 return tmp;
1509}
1510
1511/*
1512 From http://www.ietf.org/rfc/rfc3986.txt, 5.2.3: Merge paths
1513
1514 Returns a merge of the current path with the relative path passed
1515 as argument.
1516
1517 Note: \a relativePath is relative (does not start with '/').
1518*/
1519inline QString QUrlPrivate::mergePaths(const QString &relativePath) const
1520{
1521 // If the base URI has a defined authority component and an empty
1522 // path, then return a string consisting of "/" concatenated with
1523 // the reference's path; otherwise,
1524 if (!host.isEmpty() && path.isEmpty())
1525 return QLatin1Char('/') + relativePath;
1526
1527 // Return a string consisting of the reference's path component
1528 // appended to all but the last segment of the base URI's path
1529 // (i.e., excluding any characters after the right-most "/" in the
1530 // base URI path, or excluding the entire base URI path if it does
1531 // not contain any "/" characters).
1532 QString newPath;
1533 if (!path.contains(QLatin1Char('/')))
1534 newPath = relativePath;
1535 else
1536 newPath = path.leftRef(path.lastIndexOf(QLatin1Char('/')) + 1) + relativePath;
1537
1538 return newPath;
1539}
1540
1541/*
1542 From http://www.ietf.org/rfc/rfc3986.txt, 5.2.4: Remove dot segments
1543
1544 Removes unnecessary ../ and ./ from the path. Used for normalizing
1545 the URL.
1546*/
1547static void removeDotsFromPath(QString *path)
1548{
1549 // The input buffer is initialized with the now-appended path
1550 // components and the output buffer is initialized to the empty
1551 // string.
1552 QChar *out = path->data();
1553 const QChar *in = out;
1554 const QChar *end = out + path->size();
1555
1556 // If the input buffer consists only of
1557 // "." or "..", then remove that from the input
1558 // buffer;
1559 if (path->size() == 1 && in[0].unicode() == '.')
1560 ++in;
1561 else if (path->size() == 2 && in[0].unicode() == '.' && in[1].unicode() == '.')
1562 in += 2;
1563 // While the input buffer is not empty, loop:
1564 while (in < end) {
1565
1566 // otherwise, if the input buffer begins with a prefix of "../" or "./",
1567 // then remove that prefix from the input buffer;
1568 if (path->size() >= 2 && in[0].unicode() == '.' && in[1].unicode() == '/')
1569 in += 2;
1570 else if (path->size() >= 3 && in[0].unicode() == '.'
1571 && in[1].unicode() == '.' && in[2].unicode() == '/')
1572 in += 3;
1573
1574 // otherwise, if the input buffer begins with a prefix of
1575 // "/./" or "/.", where "." is a complete path segment,
1576 // then replace that prefix with "/" in the input buffer;
1577 if (in <= end - 3 && in[0].unicode() == '/' && in[1].unicode() == '.'
1578 && in[2].unicode() == '/') {
1579 in += 2;
1580 continue;
1581 } else if (in == end - 2 && in[0].unicode() == '/' && in[1].unicode() == '.') {
1582 *out++ = QLatin1Char('/');
1583 in += 2;
1584 break;
1585 }
1586
1587 // otherwise, if the input buffer begins with a prefix
1588 // of "/../" or "/..", where ".." is a complete path
1589 // segment, then replace that prefix with "/" in the
1590 // input buffer and remove the last //segment and its
1591 // preceding "/" (if any) from the output buffer;
1592 if (in <= end - 4 && in[0].unicode() == '/' && in[1].unicode() == '.'
1593 && in[2].unicode() == '.' && in[3].unicode() == '/') {
1594 while (out > path->constData() && (--out)->unicode() != '/')
1595 ;
1596 if (out == path->constData() && out->unicode() != '/')
1597 ++in;
1598 in += 3;
1599 continue;
1600 } else if (in == end - 3 && in[0].unicode() == '/' && in[1].unicode() == '.'
1601 && in[2].unicode() == '.') {
1602 while (out > path->constData() && (--out)->unicode() != '/')
1603 ;
1604 if (out->unicode() == '/')
1605 ++out;
1606 in += 3;
1607 break;
1608 }
1609
1610 // otherwise move the first path segment in
1611 // the input buffer to the end of the output
1612 // buffer, including the initial "/" character
1613 // (if any) and any subsequent characters up
1614 // to, but not including, the next "/"
1615 // character or the end of the input buffer.
1616 *out++ = *in++;
1617 while (in < end && in->unicode() != '/')
1618 *out++ = *in++;
1619 }
1620 path->truncate(out - path->constData());
1621}
1622
1623inline QUrlPrivate::ErrorCode QUrlPrivate::validityError(QString *source, int *position) const
1624{
1625 Q_ASSERT(!source == !position);
1626 if (error) {
1627 if (source) {
1628 *source = error->source;
1629 *position = error->position;
1630 }
1631 return error->code;
1632 }
1633
1634 // There are three more cases of invalid URLs that QUrl recognizes and they
1635 // are only possible with constructed URLs (setXXX methods), not with
1636 // parsing. Therefore, they are tested here.
1637 //
1638 // Two cases are a non-empty path that doesn't start with a slash and:
1639 // - with an authority
1640 // - without an authority, without scheme but the path with a colon before
1641 // the first slash
1642 // The third case is an empty authority and a non-empty path that starts
1643 // with "//".
1644 // Those cases are considered invalid because toString() would produce a URL
1645 // that wouldn't be parsed back to the same QUrl.
1646
1647 if (path.isEmpty())
1648 return NoError;
1649 if (path.at(0) == QLatin1Char('/')) {
1650 if (hasAuthority() || path.length() == 1 || path.at(1) != QLatin1Char('/'))
1651 return NoError;
1652 if (source) {
1653 *source = path;
1654 *position = 0;
1655 }
1656 return AuthorityAbsentAndPathIsDoubleSlash;
1657 }
1658
1659 if (sectionIsPresent & QUrlPrivate::Host) {
1660 if (source) {
1661 *source = path;
1662 *position = 0;
1663 }
1664 return AuthorityPresentAndPathIsRelative;
1665 }
1666 if (sectionIsPresent & QUrlPrivate::Scheme)
1667 return NoError;
1668
1669 // check for a path of "text:text/"
1670 for (int i = 0; i < path.length(); ++i) {
1671 ushort c = path.at(i).unicode();
1672 if (c == '/') {
1673 // found the slash before the colon
1674 return NoError;
1675 }
1676 if (c == ':') {
1677 // found the colon before the slash, it's invalid
1678 if (source) {
1679 *source = path;
1680 *position = i;
1681 }
1682 return RelativeUrlPathContainsColonBeforeSlash;
1683 }
1684 }
1685 return NoError;
1686}
1687
1688bool QUrlPrivate::validateComponent(QUrlPrivate::Section section, const QString &input,
1689 int begin, int end)
1690{
1691 // What we need to look out for, that the regular parser tolerates:
1692 // - percent signs not followed by two hex digits
1693 // - forbidden characters, which should always appear encoded
1694 // '"' / '<' / '>' / '\' / '^' / '`' / '{' / '|' / '}' / BKSP
1695 // control characters
1696 // - delimiters not allowed in certain positions
1697 // . scheme: parser is already strict
1698 // . user info: gen-delims except ":" disallowed ("/" / "?" / "#" / "[" / "]" / "@")
1699 // . host: parser is stricter than the standard
1700 // . port: parser is stricter than the standard
1701 // . path: all delimiters allowed
1702 // . fragment: all delimiters allowed
1703 // . query: all delimiters allowed
1704 static const char forbidden[] = "\"<>\\^`{|}\x7F";
1705 static const char forbiddenUserInfo[] = ":/?#[]@";
1706
1707 Q_ASSERT(section != Authority && section != Hierarchy && section != FullUrl);
1708
1709 const ushort *const data = reinterpret_cast<const ushort *>(input.constData());
1710 for (uint i = uint(begin); i < uint(end); ++i) {
1711 uint uc = data[i];
1712 if (uc >= 0x80)
1713 continue;
1714
1715 bool error = false;
1716 if ((uc == '%' && (uint(end) < i + 2 || !isHex(data[i + 1]) || !isHex(data[i + 2])))
1717 || uc <= 0x20 || strchr(forbidden, uc)) {
1718 // found an error
1719 error = true;
1720 } else if (section & UserInfo) {
1721 if (section == UserInfo && strchr(forbiddenUserInfo + 1, uc))
1722 error = true;
1723 else if (section != UserInfo && strchr(forbiddenUserInfo, uc))
1724 error = true;
1725 }
1726
1727 if (!error)
1728 continue;
1729
1730 ErrorCode errorCode = ErrorCode(int(section) << 8);
1731 if (section == UserInfo) {
1732 // is it the user name or the password?
1733 errorCode = InvalidUserNameError;
1734 for (uint j = uint(begin); j < i; ++j)
1735 if (data[j] == ':') {
1736 errorCode = InvalidPasswordError;
1737 break;
1738 }
1739 }
1740
1741 setError(errorCode, input, i);
1742 return false;
1743 }
1744
1745 // no errors
1746 return true;
1747}
1748
1749#if 0
1750inline void QUrlPrivate::validate() const
1751{
1752 QUrlPrivate *that = (QUrlPrivate *)this;
1753 that->encodedOriginal = that->toEncoded(); // may detach
1754 parse(ParseOnly);
1755
1756 QURL_SETFLAG(that->stateFlags, Validated);
1757
1758 if (!isValid)
1759 return;
1760
1761 QString auth = authority(); // causes the non-encoded forms to be valid
1762
1763 // authority() calls canonicalHost() which sets this
1764 if (!isHostValid)
1765 return;
1766
1767 if (scheme == QLatin1String("mailto")) {
1768 if (!host.isEmpty() || port != -1 || !userName.isEmpty() || !password.isEmpty()) {
1769 that->isValid = false;
1770 that->errorInfo.setParams(0, QT_TRANSLATE_NOOP(QUrl, "expected empty host, username,"
1771 "port and password"),
1772 0, 0);
1773 }
1774 } else if (scheme == ftpScheme() || scheme == httpScheme()) {
1775 if (host.isEmpty() && !(path.isEmpty() && encodedPath.isEmpty())) {
1776 that->isValid = false;
1777 that->errorInfo.setParams(0, QT_TRANSLATE_NOOP(QUrl, "the host is empty, but not the path"),
1778 0, 0);
1779 }
1780 }
1781}
1782#endif
1783
1784/*!
1785 \macro QT_NO_URL_CAST_FROM_STRING
1786 \relates QUrl
1787
1788 Disables automatic conversions from QString (or char *) to QUrl.
1789
1790 Compiling your code with this define is useful when you have a lot of
1791 code that uses QString for file names and you wish to convert it to
1792 use QUrl for network transparency. In any code that uses QUrl, it can
1793 help avoid missing QUrl::resolved() calls, and other misuses of
1794 QString to QUrl conversions.
1795
1796 \oldcode
1797 url = filename; // probably not what you want
1798 \newcode
1799 url = QUrl::fromLocalFile(filename);
1800 url = baseurl.resolved(QUrl(filename));
1801 \endcode
1802
1803 \sa QT_NO_CAST_FROM_ASCII
1804*/
1805
1806
1807/*!
1808 Constructs a URL by parsing \a url. QUrl will automatically percent encode
1809 all characters that are not allowed in a URL and decode the percent-encoded
1810 sequences that represent an unreserved character (letters, digits, hyphens,
1811 undercores, dots and tildes). All other characters are left in their
1812 original forms.
1813
1814 Parses the \a url using the parser mode \a parsingMode. In TolerantMode
1815 (the default), QUrl will correct certain mistakes, notably the presence of
1816 a percent character ('%') not followed by two hexadecimal digits, and it
1817 will accept any character in any position. In StrictMode, encoding mistakes
1818 will not be tolerated and QUrl will also check that certain forbidden
1819 characters are not present in unencoded form. If an error is detected in
1820 StrictMode, isValid() will return false. The parsing mode DecodedMode is not
1821 permitted in this context.
1822
1823 Example:
1824
1825 \snippet code/src_corelib_io_qurl.cpp 0
1826
1827 To construct a URL from an encoded string, you can also use fromEncoded():
1828
1829 \snippet code/src_corelib_io_qurl.cpp 1
1830
1831 Both functions are equivalent and, in Qt 5, both functions accept encoded
1832 data. Usually, the choice of the QUrl constructor or setUrl() versus
1833 fromEncoded() will depend on the source data: the constructor and setUrl()
1834 take a QString, whereas fromEncoded takes a QByteArray.
1835
1836 \sa setUrl(), fromEncoded(), TolerantMode
1837*/
1838QUrl::QUrl(const QString &url, ParsingMode parsingMode) : d(nullptr)
1839{
1840 setUrl(url, parsingMode);
1841}
1842
1843/*!
1844 Constructs an empty QUrl object.
1845*/
1846QUrl::QUrl() : d(nullptr)
1847{
1848}
1849
1850/*!
1851 Constructs a copy of \a other.
1852*/
1853QUrl::QUrl(const QUrl &other) : d(other.d)
1854{
1855 if (d)
1856 d->ref.ref();
1857}
1858
1859/*!
1860 Destructor; called immediately before the object is deleted.
1861*/
1862QUrl::~QUrl()
1863{
1864 if (d && !d->ref.deref())
1865 delete d;
1866}
1867
1868/*!
1869 Returns \c true if the URL is non-empty and valid; otherwise returns \c false.
1870
1871 The URL is run through a conformance test. Every part of the URL
1872 must conform to the standard encoding rules of the URI standard
1873 for the URL to be reported as valid.
1874
1875 \snippet code/src_corelib_io_qurl.cpp 2
1876*/
1877bool QUrl::isValid() const
1878{
1879 if (isEmpty()) {
1880 // also catches d == nullptr
1881 return false;
1882 }
1883 return d->validityError() == QUrlPrivate::NoError;
1884}
1885
1886/*!
1887 Returns \c true if the URL has no data; otherwise returns \c false.
1888
1889 \sa clear()
1890*/
1891bool QUrl::isEmpty() const
1892{
1893 if (!d) return true;
1894 return d->isEmpty();
1895}
1896
1897/*!
1898 Resets the content of the QUrl. After calling this function, the
1899 QUrl is equal to one that has been constructed with the default
1900 empty constructor.
1901
1902 \sa isEmpty()
1903*/
1904void QUrl::clear()
1905{
1906 if (d && !d->ref.deref())
1907 delete d;
1908 d = nullptr;
1909}
1910
1911/*!
1912 Parses \a url and sets this object to that value. QUrl will automatically
1913 percent encode all characters that are not allowed in a URL and decode the
1914 percent-encoded sequences that represent an unreserved character (letters,
1915 digits, hyphens, undercores, dots and tildes). All other characters are
1916 left in their original forms.
1917
1918 Parses the \a url using the parser mode \a parsingMode. In TolerantMode
1919 (the default), QUrl will correct certain mistakes, notably the presence of
1920 a percent character ('%') not followed by two hexadecimal digits, and it
1921 will accept any character in any position. In StrictMode, encoding mistakes
1922 will not be tolerated and QUrl will also check that certain forbidden
1923 characters are not present in unencoded form. If an error is detected in
1924 StrictMode, isValid() will return false. The parsing mode DecodedMode is
1925 not permitted in this context and will produce a run-time warning.
1926
1927 \sa url(), toString()
1928*/
1929void QUrl::setUrl(const QString &url, ParsingMode parsingMode)
1930{
1931 if (parsingMode == DecodedMode) {
1932 qWarning("QUrl: QUrl::DecodedMode is not permitted when parsing a full URL");
1933 } else {
1934 detach();
1935 d->parse(url, parsingMode);
1936 }
1937}
1938
1939/*!
1940 \fn void QUrl::setEncodedUrl(const QByteArray &encodedUrl, ParsingMode parsingMode)
1941 \deprecated
1942 Constructs a URL by parsing the contents of \a encodedUrl.
1943
1944 \a encodedUrl is assumed to be a URL string in percent encoded
1945 form, containing only ASCII characters.
1946
1947 The parsing mode \a parsingMode is used for parsing \a encodedUrl.
1948
1949 \obsolete Use setUrl(QString::fromUtf8(encodedUrl), parsingMode)
1950
1951 \sa setUrl()
1952*/
1953
1954/*!
1955 Sets the scheme of the URL to \a scheme. As a scheme can only
1956 contain ASCII characters, no conversion or decoding is done on the
1957 input. It must also start with an ASCII letter.
1958
1959 The scheme describes the type (or protocol) of the URL. It's
1960 represented by one or more ASCII characters at the start the URL.
1961
1962 A scheme is strictly \l {http://www.ietf.org/rfc/rfc3986.txt} {RFC 3986}-compliant:
1963 \tt {scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )}
1964
1965 The following example shows a URL where the scheme is "ftp":
1966
1967 \image qurl-authority2.png
1968
1969 To set the scheme, the following call is used:
1970 \snippet code/src_corelib_io_qurl.cpp 11
1971
1972 The scheme can also be empty, in which case the URL is interpreted
1973 as relative.
1974
1975 \sa scheme(), isRelative()
1976*/
1977void QUrl::setScheme(const QString &scheme)
1978{
1979 detach();
1980 d->clearError();
1981 if (scheme.isEmpty()) {
1982 // schemes are not allowed to be empty
1983 d->sectionIsPresent &= ~QUrlPrivate::Scheme;
1984 d->flags &= ~QUrlPrivate::IsLocalFile;
1985 d->scheme.clear();
1986 } else {
1987 d->setScheme(scheme, scheme.length(), /* do set error */ true);
1988 }
1989}
1990
1991/*!
1992 Returns the scheme of the URL. If an empty string is returned,
1993 this means the scheme is undefined and the URL is then relative.
1994
1995 The scheme can only contain US-ASCII letters or digits, which means it
1996 cannot contain any character that would otherwise require encoding.
1997 Additionally, schemes are always returned in lowercase form.
1998
1999 \sa setScheme(), isRelative()
2000*/
2001QString QUrl::scheme() const
2002{
2003 if (!d) return QString();
2004
2005 return d->scheme;
2006}
2007
2008/*!
2009 Sets the authority of the URL to \a authority.
2010
2011 The authority of a URL is the combination of user info, a host
2012 name and a port. All of these elements are optional; an empty
2013 authority is therefore valid.
2014
2015 The user info and host are separated by a '@', and the host and
2016 port are separated by a ':'. If the user info is empty, the '@'
2017 must be omitted; although a stray ':' is permitted if the port is
2018 empty.
2019
2020 The following example shows a valid authority string:
2021
2022 \image qurl-authority.png
2023
2024 The \a authority data is interpreted according to \a mode: in StrictMode,
2025 any '%' characters must be followed by exactly two hexadecimal characters
2026 and some characters (including space) are not allowed in undecoded form. In
2027 TolerantMode (the default), all characters are accepted in undecoded form
2028 and the tolerant parser will correct stray '%' not followed by two hex
2029 characters.
2030
2031 This function does not allow \a mode to be QUrl::DecodedMode. To set fully
2032 decoded data, call setUserName(), setPassword(), setHost() and setPort()
2033 individually.
2034
2035 \sa setUserInfo(), setHost(), setPort()
2036*/
2037void QUrl::setAuthority(const QString &authority, ParsingMode mode)
2038{
2039 detach();
2040 d->clearError();
2041
2042 if (mode == DecodedMode) {
2043 qWarning("QUrl::setAuthority(): QUrl::DecodedMode is not permitted in this function");
2044 return;
2045 }
2046
2047 d->setAuthority(authority, 0, authority.length(), mode);
2048 if (authority.isNull()) {
2049 // QUrlPrivate::setAuthority cleared almost everything
2050 // but it leaves the Host bit set
2051 d->sectionIsPresent &= ~QUrlPrivate::Authority;
2052 }
2053}
2054
2055/*!
2056 Returns the authority of the URL if it is defined; otherwise
2057 an empty string is returned.
2058
2059 This function returns an unambiguous value, which may contain that
2060 characters still percent-encoded, plus some control sequences not
2061 representable in decoded form in QString.
2062
2063 The \a options argument controls how to format the user info component. The
2064 value of QUrl::FullyDecoded is not permitted in this function. If you need
2065 to obtain fully decoded data, call userName(), password(), host() and
2066 port() individually.
2067
2068 \sa setAuthority(), userInfo(), userName(), password(), host(), port()
2069*/
2070QString QUrl::authority(ComponentFormattingOptions options) const
2071{
2072 QString result;
2073 if (!d)
2074 return result;
2075
2076 if (options == QUrl::FullyDecoded) {
2077 qWarning("QUrl::authority(): QUrl::FullyDecoded is not permitted in this function");
2078 return result;
2079 }
2080
2081 d->appendAuthority(result, options, QUrlPrivate::Authority);
2082 return result;
2083}
2084
2085/*!
2086 Sets the user info of the URL to \a userInfo. The user info is an
2087 optional part of the authority of the URL, as described in
2088 setAuthority().
2089
2090 The user info consists of a user name and optionally a password,
2091 separated by a ':'. If the password is empty, the colon must be
2092 omitted. The following example shows a valid user info string:
2093
2094 \image qurl-authority3.png
2095
2096 The \a userInfo data is interpreted according to \a mode: in StrictMode,
2097 any '%' characters must be followed by exactly two hexadecimal characters
2098 and some characters (including space) are not allowed in undecoded form. In
2099 TolerantMode (the default), all characters are accepted in undecoded form
2100 and the tolerant parser will correct stray '%' not followed by two hex
2101 characters.
2102
2103 This function does not allow \a mode to be QUrl::DecodedMode. To set fully
2104 decoded data, call setUserName() and setPassword() individually.
2105
2106 \sa userInfo(), setUserName(), setPassword(), setAuthority()
2107*/
2108void QUrl::setUserInfo(const QString &userInfo, ParsingMode mode)
2109{
2110 detach();
2111 d->clearError();
2112 QString trimmed = userInfo.trimmed();
2113 if (mode == DecodedMode) {
2114 qWarning("QUrl::setUserInfo(): QUrl::DecodedMode is not permitted in this function");
2115 return;
2116 }
2117
2118 d->setUserInfo(trimmed, 0, trimmed.length());
2119 if (userInfo.isNull()) {
2120 // QUrlPrivate::setUserInfo cleared almost everything
2121 // but it leaves the UserName bit set
2122 d->sectionIsPresent &= ~QUrlPrivate::UserInfo;
2123 } else if (mode == StrictMode && !d->validateComponent(QUrlPrivate::UserInfo, userInfo)) {
2124 d->sectionIsPresent &= ~QUrlPrivate::UserInfo;
2125 d->userName.clear();
2126 d->password.clear();
2127 }
2128}
2129
2130/*!
2131 Returns the user info of the URL, or an empty string if the user
2132 info is undefined.
2133
2134 This function returns an unambiguous value, which may contain that
2135 characters still percent-encoded, plus some control sequences not
2136 representable in decoded form in QString.
2137
2138 The \a options argument controls how to format the user info component. The
2139 value of QUrl::FullyDecoded is not permitted in this function. If you need
2140 to obtain fully decoded data, call userName() and password() individually.
2141
2142 \sa setUserInfo(), userName(), password(), authority()
2143*/
2144QString QUrl::userInfo(ComponentFormattingOptions options) const
2145{
2146 QString result;
2147 if (!d)
2148 return result;
2149
2150 if (options == QUrl::FullyDecoded) {
2151 qWarning("QUrl::userInfo(): QUrl::FullyDecoded is not permitted in this function");
2152 return result;
2153 }
2154
2155 d->appendUserInfo(result, options, QUrlPrivate::UserInfo);
2156 return result;
2157}
2158
2159/*!
2160 Sets the URL's user name to \a userName. The \a userName is part
2161 of the user info element in the authority of the URL, as described
2162 in setUserInfo().
2163
2164 The \a userName data is interpreted according to \a mode: in StrictMode,
2165 any '%' characters must be followed by exactly two hexadecimal characters
2166 and some characters (including space) are not allowed in undecoded form. In
2167 TolerantMode (the default), all characters are accepted in undecoded form
2168 and the tolerant parser will correct stray '%' not followed by two hex
2169 characters. In DecodedMode, '%' stand for themselves and encoded characters
2170 are not possible.
2171
2172 QUrl::DecodedMode should be used when setting the user name from a data
2173 source which is not a URL, such as a password dialog shown to the user or
2174 with a user name obtained by calling userName() with the QUrl::FullyDecoded
2175 formatting option.
2176
2177 \sa userName(), setUserInfo()
2178*/
2179void QUrl::setUserName(const QString &userName, ParsingMode mode)
2180{
2181 detach();
2182 d->clearError();
2183
2184 QString data = userName;
2185 if (mode == DecodedMode) {
2186 parseDecodedComponent(data);
2187 mode = TolerantMode;
2188 }
2189
2190 d->setUserName(data, 0, data.length());
2191 if (userName.isNull())
2192 d->sectionIsPresent &= ~QUrlPrivate::UserName;
2193 else if (mode == StrictMode && !d->validateComponent(QUrlPrivate::UserName, userName))
2194 d->userName.clear();
2195}
2196
2197/*!
2198 Returns the user name of the URL if it is defined; otherwise
2199 an empty string is returned.
2200
2201 The \a options argument controls how to format the user name component. All
2202 values produce an unambiguous result. With QUrl::FullyDecoded, all
2203 percent-encoded sequences are decoded; otherwise, the returned value may
2204 contain some percent-encoded sequences for some control sequences not
2205 representable in decoded form in QString.
2206
2207 Note that QUrl::FullyDecoded may cause data loss if those non-representable
2208 sequences are present. It is recommended to use that value when the result
2209 will be used in a non-URL context, such as setting in QAuthenticator or
2210 negotiating a login.
2211
2212 \sa setUserName(), userInfo()
2213*/
2214QString QUrl::userName(ComponentFormattingOptions options) const
2215{
2216 QString result;
2217 if (d)
2218 d->appendUserName(result, options);
2219 return result;
2220}
2221
2222/*!
2223 \fn void QUrl::setEncodedUserName(const QByteArray &userName)
2224 \deprecated
2225 \since 4.4
2226
2227 Sets the URL's user name to the percent-encoded \a userName. The \a
2228 userName is part of the user info element in the authority of the
2229 URL, as described in setUserInfo().
2230
2231 \obsolete Use setUserName(QString::fromUtf8(userName))
2232
2233 \sa setUserName(), encodedUserName(), setUserInfo()
2234*/
2235
2236/*!
2237 \fn QByteArray QUrl::encodedUserName() const
2238 \deprecated
2239 \since 4.4
2240
2241 Returns the user name of the URL if it is defined; otherwise
2242 an empty string is returned. The returned value will have its
2243 non-ASCII and other control characters percent-encoded, as in
2244 toEncoded().
2245
2246 \obsolete Use userName(QUrl::FullyEncoded).toLatin1()
2247
2248 \sa setEncodedUserName()
2249*/
2250
2251/*!
2252 Sets the URL's password to \a password. The \a password is part of
2253 the user info element in the authority of the URL, as described in
2254 setUserInfo().
2255
2256 The \a password data is interpreted according to \a mode: in StrictMode,
2257 any '%' characters must be followed by exactly two hexadecimal characters
2258 and some characters (including space) are not allowed in undecoded form. In
2259 TolerantMode, all characters are accepted in undecoded form and the
2260 tolerant parser will correct stray '%' not followed by two hex characters.
2261 In DecodedMode, '%' stand for themselves and encoded characters are not
2262 possible.
2263
2264 QUrl::DecodedMode should be used when setting the password from a data
2265 source which is not a URL, such as a password dialog shown to the user or
2266 with a password obtained by calling password() with the QUrl::FullyDecoded
2267 formatting option.
2268
2269 \sa password(), setUserInfo()
2270*/
2271void QUrl::setPassword(const QString &password, ParsingMode mode)
2272{
2273 detach();
2274 d->clearError();
2275
2276 QString data = password;
2277 if (mode == DecodedMode) {
2278 parseDecodedComponent(data);
2279 mode = TolerantMode;
2280 }
2281
2282 d->setPassword(data, 0, data.length());
2283 if (password.isNull())
2284 d->sectionIsPresent &= ~QUrlPrivate::Password;
2285 else if (mode == StrictMode && !d->validateComponent(QUrlPrivate::Password, password))
2286 d->password.clear();
2287}
2288
2289/*!
2290 Returns the password of the URL if it is defined; otherwise
2291 an empty string is returned.
2292
2293 The \a options argument controls how to format the user name component. All
2294 values produce an unambiguous result. With QUrl::FullyDecoded, all
2295 percent-encoded sequences are decoded; otherwise, the returned value may
2296 contain some percent-encoded sequences for some control sequences not
2297 representable in decoded form in QString.
2298
2299 Note that QUrl::FullyDecoded may cause data loss if those non-representable
2300 sequences are present. It is recommended to use that value when the result
2301 will be used in a non-URL context, such as setting in QAuthenticator or
2302 negotiating a login.
2303
2304 \sa setPassword()
2305*/
2306QString QUrl::password(ComponentFormattingOptions options) const
2307{
2308 QString result;
2309 if (d)
2310 d->appendPassword(result, options);
2311 return result;
2312}
2313
2314/*!
2315 \fn void QUrl::setEncodedPassword(const QByteArray &password)
2316 \deprecated
2317 \since 4.4
2318
2319 Sets the URL's password to the percent-encoded \a password. The \a
2320 password is part of the user info element in the authority of the
2321 URL, as described in setUserInfo().
2322
2323 \obsolete Use setPassword(QString::fromUtf8(password));
2324
2325 \sa setPassword(), encodedPassword(), setUserInfo()
2326*/
2327
2328/*!
2329 \fn QByteArray QUrl::encodedPassword() const
2330 \deprecated
2331 \since 4.4
2332
2333 Returns the password of the URL if it is defined; otherwise an
2334 empty string is returned. The returned value will have its
2335 non-ASCII and other control characters percent-encoded, as in
2336 toEncoded().
2337
2338 \obsolete Use password(QUrl::FullyEncoded).toLatin1()
2339
2340 \sa setEncodedPassword(), toEncoded()
2341*/
2342
2343/*!
2344 Sets the host of the URL to \a host. The host is part of the
2345 authority.
2346
2347 The \a host data is interpreted according to \a mode: in StrictMode,
2348 any '%' characters must be followed by exactly two hexadecimal characters
2349 and some characters (including space) are not allowed in undecoded form. In
2350 TolerantMode, all characters are accepted in undecoded form and the
2351 tolerant parser will correct stray '%' not followed by two hex characters.
2352 In DecodedMode, '%' stand for themselves and encoded characters are not
2353 possible.
2354
2355 Note that, in all cases, the result of the parsing must be a valid hostname
2356 according to STD 3 rules, as modified by the Internationalized Resource
2357 Identifiers specification (RFC 3987). Invalid hostnames are not permitted
2358 and will cause isValid() to become false.
2359
2360 \sa host(), setAuthority()
2361*/
2362void QUrl::setHost(const QString &host, ParsingMode mode)
2363{
2364 detach();
2365 d->clearError();
2366
2367 QString data = host;
2368 if (mode == DecodedMode) {
2369 parseDecodedComponent(data);
2370 mode = TolerantMode;
2371 }
2372
2373 if (d->setHost(data, 0, data.length(), mode)) {
2374 if (host.isNull())
2375 d->sectionIsPresent &= ~QUrlPrivate::Host;
2376 } else if (!data.startsWith(QLatin1Char('['))) {
2377 // setHost failed, it might be IPv6 or IPvFuture in need of bracketing
2378 Q_ASSERT(d->error);
2379
2380 data.prepend(QLatin1Char('['));
2381 data.append(QLatin1Char(']'));
2382 if (!d->setHost(data, 0, data.length(), mode)) {
2383 // failed again
2384 if (data.contains(QLatin1Char(':'))) {
2385 // source data contains ':', so it's an IPv6 error
2386 d->error->code = QUrlPrivate::InvalidIPv6AddressError;
2387 }
2388 } else {
2389 // succeeded
2390 d->clearError();
2391 }
2392 }
2393}
2394
2395/*!
2396 Returns the host of the URL if it is defined; otherwise
2397 an empty string is returned.
2398
2399 The \a options argument controls how the hostname will be formatted. The
2400 QUrl::EncodeUnicode option will cause this function to return the hostname
2401 in the ASCII-Compatible Encoding (ACE) form, which is suitable for use in
2402 channels that are not 8-bit clean or that require the legacy hostname (such
2403 as DNS requests or in HTTP request headers). If that flag is not present,
2404 this function returns the International Domain Name (IDN) in Unicode form,
2405 according to the list of permissible top-level domains (see
2406 idnWhitelist()).
2407
2408 All other flags are ignored. Host names cannot contain control or percent
2409 characters, so the returned value can be considered fully decoded.
2410
2411 \sa setHost(), idnWhitelist(), setIdnWhitelist(), authority()
2412*/
2413QString QUrl::host(ComponentFormattingOptions options) const
2414{
2415 QString result;
2416 if (d) {
2417 d->appendHost(result, options);
2418 if (result.startsWith(QLatin1Char('[')))
2419 result = result.mid(1, result.length() - 2);
2420 }
2421 return result;
2422}
2423
2424/*!
2425 \fn void QUrl::setEncodedHost(const QByteArray &host)
2426 \deprecated
2427 \since 4.4
2428
2429 Sets the URL's host to the ACE- or percent-encoded \a host. The \a
2430 host is part of the user info element in the authority of the
2431 URL, as described in setAuthority().
2432
2433 \obsolete Use setHost(QString::fromUtf8(host)).
2434
2435 \sa setHost(), encodedHost(), setAuthority(), fromAce()
2436*/
2437
2438/*!
2439 \fn QByteArray QUrl::encodedHost() const
2440 \deprecated
2441 \since 4.4
2442
2443 Returns the host part of the URL if it is defined; otherwise
2444 an empty string is returned.
2445
2446 Note: encodedHost() does not return percent-encoded hostnames. Instead,
2447 the ACE-encoded (bare ASCII in Punycode encoding) form will be
2448 returned for any non-ASCII hostname.
2449
2450 This function is equivalent to calling QUrl::toAce() on the return
2451 value of host().
2452
2453 \obsolete Use host(QUrl::FullyEncoded).toLatin1() or toAce(host()).
2454
2455 \sa setEncodedHost()
2456*/
2457
2458/*!
2459 Sets the port of the URL to \a port. The port is part of the
2460 authority of the URL, as described in setAuthority().
2461
2462 \a port must be between 0 and 65535 inclusive. Setting the
2463 port to -1 indicates that the port is unspecified.
2464*/
2465void QUrl::setPort(int port)
2466{
2467 detach();
2468 d->clearError();
2469
2470 if (port < -1 || port > 65535) {
2471 d->setError(QUrlPrivate::InvalidPortError, QString::number(port), 0);
2472 port = -1;
2473 }
2474
2475 d->port = port;
2476 if (port != -1)
2477 d->sectionIsPresent |= QUrlPrivate::Host;
2478}
2479
2480/*!
2481 \since 4.1
2482
2483 Returns the port of the URL, or \a defaultPort if the port is
2484 unspecified.
2485
2486 Example:
2487
2488 \snippet code/src_corelib_io_qurl.cpp 3
2489*/
2490int QUrl::port(int defaultPort) const
2491{
2492 if (!d) return defaultPort;
2493 return d->port == -1 ? defaultPort : d->port;
2494}
2495
2496/*!
2497 Sets the path of the URL to \a path. The path is the part of the
2498 URL that comes after the authority but before the query string.
2499
2500 \image qurl-ftppath.png
2501
2502 For non-hierarchical schemes, the path will be everything
2503 following the scheme declaration, as in the following example:
2504
2505 \image qurl-mailtopath.png
2506
2507 The \a path data is interpreted according to \a mode: in StrictMode,
2508 any '%' characters must be followed by exactly two hexadecimal characters
2509 and some characters (including space) are not allowed in undecoded form. In
2510 TolerantMode, all characters are accepted in undecoded form and the
2511 tolerant parser will correct stray '%' not followed by two hex characters.
2512 In DecodedMode, '%' stand for themselves and encoded characters are not
2513 possible.
2514
2515 QUrl::DecodedMode should be used when setting the path from a data source
2516 which is not a URL, such as a dialog shown to the user or with a path
2517 obtained by calling path() with the QUrl::FullyDecoded formatting option.
2518
2519 \sa path()
2520*/
2521void QUrl::setPath(const QString &path, ParsingMode mode)
2522{
2523 detach();
2524 d->clearError();
2525
2526 QString data = path;
2527 if (mode == DecodedMode) {
2528 parseDecodedComponent(data);
2529 mode = TolerantMode;
2530 }
2531
2532 d->setPath(data, 0, data.length());
2533
2534 // optimized out, since there is no path delimiter
2535// if (path.isNull())
2536// d->sectionIsPresent &= ~QUrlPrivate::Path;
2537// else
2538 if (mode == StrictMode && !d->validateComponent(QUrlPrivate::Path, path))
2539 d->path.clear();
2540}
2541
2542/*!
2543 Returns the path of the URL.
2544
2545 \snippet code/src_corelib_io_qurl.cpp 12
2546
2547 The \a options argument controls how to format the path component. All
2548 values produce an unambiguous result. With QUrl::FullyDecoded, all
2549 percent-encoded sequences are decoded; otherwise, the returned value may
2550 contain some percent-encoded sequences for some control sequences not
2551 representable in decoded form in QString.
2552
2553 Note that QUrl::FullyDecoded may cause data loss if those non-representable
2554 sequences are present. It is recommended to use that value when the result
2555 will be used in a non-URL context, such as sending to an FTP server.
2556
2557 An example of data loss is when you have non-Unicode percent-encoded sequences
2558 and use FullyDecoded (the default):
2559
2560 \snippet code/src_corelib_io_qurl.cpp 13
2561
2562 In this example, there will be some level of data loss because the \c %FF cannot
2563 be converted.
2564
2565 Data loss can also occur when the path contains sub-delimiters (such as \c +):
2566
2567 \snippet code/src_corelib_io_qurl.cpp 14
2568
2569 Other decoding examples:
2570
2571 \snippet code/src_corelib_io_qurl.cpp 15
2572
2573 \sa setPath()
2574*/
2575QString QUrl::path(ComponentFormattingOptions options) const
2576{
2577 QString result;
2578 if (d)
2579 d->appendPath(result, options, QUrlPrivate::Path);
2580 return result;
2581}
2582
2583/*!
2584 \fn void QUrl::setEncodedPath(const QByteArray &path)
2585 \deprecated
2586 \since 4.4
2587
2588 Sets the URL's path to the percent-encoded \a path. The path is
2589 the part of the URL that comes after the authority but before the
2590 query string.
2591
2592 \image qurl-ftppath.png
2593
2594 For non-hierarchical schemes, the path will be everything
2595 following the scheme declaration, as in the following example:
2596
2597 \image qurl-mailtopath.png
2598
2599 \obsolete Use setPath(QString::fromUtf8(path)).
2600
2601 \sa setPath(), encodedPath(), setUserInfo()
2602*/
2603
2604/*!
2605 \fn QByteArray QUrl::encodedPath() const
2606 \deprecated
2607 \since 4.4
2608
2609 Returns the path of the URL if it is defined; otherwise an
2610 empty string is returned. The returned value will have its
2611 non-ASCII and other control characters percent-encoded, as in
2612 toEncoded().
2613
2614 \obsolete Use path(QUrl::FullyEncoded).toLatin1().
2615
2616 \sa setEncodedPath(), toEncoded()
2617*/
2618
2619/*!
2620 \since 5.2
2621
2622 Returns the name of the file, excluding the directory path.
2623
2624 Note that, if this QUrl object is given a path ending in a slash, the name of the file is considered empty.
2625
2626 If the path doesn't contain any slash, it is fully returned as the fileName.
2627
2628 Example:
2629
2630 \snippet code/src_corelib_io_qurl.cpp 7
2631
2632 The \a options argument controls how to format the file name component. All
2633 values produce an unambiguous result. With QUrl::FullyDecoded, all
2634 percent-encoded sequences are decoded; otherwise, the returned value may
2635 contain some percent-encoded sequences for some control sequences not
2636 representable in decoded form in QString.
2637
2638 \sa path()
2639*/
2640QString QUrl::fileName(ComponentFormattingOptions options) const
2641{
2642 const QString ourPath = path(options);
2643 const int slash = ourPath.lastIndexOf(QLatin1Char('/'));
2644 if (slash == -1)
2645 return ourPath;
2646 return ourPath.mid(slash + 1);
2647}
2648
2649/*!
2650 \since 4.2
2651
2652 Returns \c true if this URL contains a Query (i.e., if ? was seen on it).
2653
2654 \sa setQuery(), query(), hasFragment()
2655*/
2656bool QUrl::hasQuery() const
2657{
2658 if (!d) return false;
2659 return d->hasQuery();
2660}
2661
2662/*!
2663 Sets the query string of the URL to \a query.
2664
2665 This function is useful if you need to pass a query string that
2666 does not fit into the key-value pattern, or that uses a different
2667 scheme for encoding special characters than what is suggested by
2668 QUrl.
2669
2670 Passing a value of QString() to \a query (a null QString) unsets
2671 the query completely. However, passing a value of QString("")
2672 will set the query to an empty value, as if the original URL
2673 had a lone "?".
2674
2675 The \a query data is interpreted according to \a mode: in StrictMode,
2676 any '%' characters must be followed by exactly two hexadecimal characters
2677 and some characters (including space) are not allowed in undecoded form. In
2678 TolerantMode, all characters are accepted in undecoded form and the
2679 tolerant parser will correct stray '%' not followed by two hex characters.
2680 In DecodedMode, '%' stand for themselves and encoded characters are not
2681 possible.
2682
2683 Query strings often contain percent-encoded sequences, so use of
2684 DecodedMode is discouraged. One special sequence to be aware of is that of
2685 the plus character ('+'). QUrl does not convert spaces to plus characters,
2686 even though HTML forms posted by web browsers do. In order to represent an
2687 actual plus character in a query, the sequence "%2B" is usually used. This
2688 function will leave "%2B" sequences untouched in TolerantMode or
2689 StrictMode.
2690
2691 \sa query(), hasQuery()
2692*/
2693void QUrl::setQuery(const QString &query, ParsingMode mode)
2694{
2695 detach();
2696 d->clearError();
2697
2698 QString data = query;
2699 if (mode == DecodedMode) {
2700 parseDecodedComponent(data);
2701 mode = TolerantMode;
2702 }
2703
2704 d->setQuery(data, 0, data.length());
2705 if (query.isNull())
2706 d->sectionIsPresent &= ~QUrlPrivate::Query;
2707 else if (mode == StrictMode && !d->validateComponent(QUrlPrivate::Query, query))
2708 d->query.clear();
2709}
2710
2711/*!
2712 \fn void QUrl::setEncodedQuery(const QByteArray &query)
2713 \deprecated
2714
2715 Sets the query string of the URL to \a query. The string is
2716 inserted as-is, and no further encoding is performed when calling
2717 toEncoded().
2718
2719 This function is useful if you need to pass a query string that
2720 does not fit into the key-value pattern, or that uses a different
2721 scheme for encoding special characters than what is suggested by
2722 QUrl.
2723
2724 Passing a value of QByteArray() to \a query (a null QByteArray) unsets
2725 the query completely. However, passing a value of QByteArray("")
2726 will set the query to an empty value, as if the original URL
2727 had a lone "?".
2728
2729 \obsolete Use setQuery, which has the same null / empty behavior.
2730
2731 \sa encodedQuery(), hasQuery()
2732*/
2733
2734/*!
2735 \overload
2736 \since 5.0
2737 Sets the query string of the URL to \a query.
2738
2739 This function reconstructs the query string from the QUrlQuery object and
2740 sets on this QUrl object. This function does not have parsing parameters
2741 because the QUrlQuery contains data that is already parsed.
2742
2743 \sa query(), hasQuery()
2744*/
2745void QUrl::setQuery(const QUrlQuery &query)
2746{
2747 detach();
2748 d->clearError();
2749
2750 // we know the data is in the right format
2751 d->query = query.toString();
2752 if (query.isEmpty())
2753 d->sectionIsPresent &= ~QUrlPrivate::Query;
2754 else
2755 d->sectionIsPresent |= QUrlPrivate::Query;
2756}
2757
2758/*!
2759 \fn void QUrl::setQueryItems(const QList<QPair<QString, QString> > &query)
2760 \deprecated
2761
2762 Sets the query string of the URL to an encoded version of \a
2763 query. The contents of \a query are converted to a string
2764 internally, each pair delimited by the character returned by
2765 \l {QUrlQuery::queryPairDelimiter()}{queryPairDelimiter()}, and the key and value are delimited by
2766 \l {QUrlQuery::queryValueDelimiter()}{queryValueDelimiter()}
2767
2768 \note This method does not encode spaces (ASCII 0x20) as plus (+) signs,
2769 like HTML forms do. If you need that kind of encoding, you must encode
2770 the value yourself and use QUrl::setEncodedQueryItems.
2771
2772 \obsolete Use QUrlQuery and setQuery().
2773
2774 \sa queryItems(), setEncodedQueryItems()
2775*/
2776
2777/*!
2778 \fn void QUrl::setEncodedQueryItems(const QList<QPair<QByteArray, QByteArray> > &query)
2779 \deprecated
2780 \since 4.4
2781
2782 Sets the query string of the URL to the encoded version of \a
2783 query. The contents of \a query are converted to a string
2784 internally, each pair delimited by the character returned by
2785 \l {QUrlQuery::queryPairDelimiter()}{queryPairDelimiter()}, and the key and value are delimited by
2786 \l {QUrlQuery::queryValueDelimiter()}{queryValueDelimiter()}.
2787
2788 \obsolete Use QUrlQuery and setQuery().
2789
2790 \sa encodedQueryItems(), setQueryItems()
2791*/
2792
2793/*!
2794 \fn void QUrl::addQueryItem(const QString &key, const QString &value)
2795 \deprecated
2796
2797 Inserts the pair \a key = \a value into the query string of the
2798 URL.
2799
2800 The key-value pair is encoded before it is added to the query. The
2801 pair is converted into separate strings internally. The \a key and
2802 \a value is first encoded into UTF-8 and then delimited by the
2803 character returned by \l {QUrlQuery::queryValueDelimiter()}{queryValueDelimiter()}.
2804 Each key-value pair is delimited by the character returned by
2805 \l {QUrlQuery::queryPairDelimiter()}{queryPairDelimiter()}
2806
2807 \note This method does not encode spaces (ASCII 0x20) as plus (+) signs,
2808 like HTML forms do. If you need that kind of encoding, you must encode
2809 the value yourself and use QUrl::addEncodedQueryItem.
2810
2811 \obsolete Use QUrlQuery and setQuery().
2812
2813 \sa addEncodedQueryItem()
2814*/
2815
2816/*!
2817 \fn void QUrl::addEncodedQueryItem(const QByteArray &key, const QByteArray &value)
2818 \deprecated
2819 \since 4.4
2820
2821 Inserts the pair \a key = \a value into the query string of the
2822 URL.
2823
2824 \obsolete Use QUrlQuery and setQuery().
2825
2826 \sa addQueryItem()
2827*/
2828
2829/*!
2830 \fn QList<QPair<QString, QString> > QUrl::queryItems() const
2831 \deprecated
2832
2833 Returns the query string of the URL, as a map of keys and values.
2834
2835 \note This method does not decode spaces plus (+) signs as spaces (ASCII
2836 0x20), like HTML forms do. If you need that kind of decoding, you must
2837 use QUrl::encodedQueryItems and decode the data yourself.
2838
2839 \obsolete Use QUrlQuery.
2840
2841 \sa setQueryItems(), setEncodedQuery()
2842*/
2843
2844/*!
2845 \fn QList<QPair<QByteArray, QByteArray> > QUrl::encodedQueryItems() const
2846 \deprecated
2847 \since 4.4
2848
2849 Returns the query string of the URL, as a map of encoded keys and values.
2850
2851 \obsolete Use QUrlQuery.
2852
2853 \sa setEncodedQueryItems(), setQueryItems(), setEncodedQuery()
2854*/
2855
2856/*!
2857 \fn bool QUrl::hasQueryItem(const QString &key) const
2858 \deprecated
2859
2860 Returns \c true if there is a query string pair whose key is equal
2861 to \a key from the URL.
2862
2863 \obsolete Use QUrlQuery.
2864
2865 \sa hasEncodedQueryItem()
2866*/
2867
2868/*!
2869 \fn bool QUrl::hasEncodedQueryItem(const QByteArray &key) const
2870 \deprecated
2871 \since 4.4
2872
2873 Returns \c true if there is a query string pair whose key is equal
2874 to \a key from the URL.
2875
2876 \obsolete Use QUrlQuery.
2877
2878 \sa hasQueryItem()
2879*/
2880
2881/*!
2882 \fn QString QUrl::queryItemValue(const QString &key) const
2883 \deprecated
2884
2885 Returns the first query string value whose key is equal to \a key
2886 from the URL.
2887
2888 \note This method does not decode spaces plus (+) signs as spaces (ASCII
2889 0x20), like HTML forms do. If you need that kind of decoding, you must
2890 use QUrl::encodedQueryItemValue and decode the data yourself.
2891
2892 \obsolete Use QUrlQuery.
2893
2894 \sa allQueryItemValues()
2895*/
2896
2897/*!
2898 \fn QByteArray QUrl::encodedQueryItemValue(const QByteArray &key) const
2899 \deprecated
2900 \since 4.4
2901
2902 Returns the first query string value whose key is equal to \a key
2903 from the URL.
2904
2905 \obsolete Use QUrlQuery.
2906
2907 \sa queryItemValue(), allQueryItemValues()
2908*/
2909
2910/*!
2911 \fn QStringList QUrl::allQueryItemValues(const QString &key) const
2912 \deprecated
2913
2914 Returns the a list of query string values whose key is equal to
2915 \a key from the URL.
2916
2917 \note This method does not decode spaces plus (+) signs as spaces (ASCII
2918 0x20), like HTML forms do. If you need that kind of decoding, you must
2919 use QUrl::allEncodedQueryItemValues and decode the data yourself.
2920
2921 \obsolete Use QUrlQuery.
2922
2923 \sa queryItemValue()
2924*/
2925
2926/*!
2927 \fn QList<QByteArray> QUrl::allEncodedQueryItemValues(const QByteArray &key) const
2928 \deprecated
2929 \since 4.4
2930
2931 Returns the a list of query string values whose key is equal to
2932 \a key from the URL.
2933
2934 \obsolete Use QUrlQuery.
2935
2936 \sa allQueryItemValues(), queryItemValue(), encodedQueryItemValue()
2937*/
2938
2939/*!
2940 \fn void QUrl::removeQueryItem(const QString &key)
2941 \deprecated
2942
2943 Removes the first query string pair whose key is equal to \a key
2944 from the URL.
2945
2946 \obsolete Use QUrlQuery.
2947
2948 \sa removeAllQueryItems()
2949*/
2950
2951/*!
2952 \fn void QUrl::removeEncodedQueryItem(const QByteArray &key)
2953 \deprecated
2954 \since 4.4
2955
2956 Removes the first query string pair whose key is equal to \a key
2957 from the URL.
2958
2959 \obsolete Use QUrlQuery.
2960
2961 \sa removeQueryItem(), removeAllQueryItems()
2962*/
2963
2964/*!
2965 \fn void QUrl::removeAllQueryItems(const QString &key)
2966 \deprecated
2967
2968 Removes all the query string pairs whose key is equal to \a key
2969 from the URL.
2970
2971 \obsolete Use QUrlQuery.
2972
2973 \sa removeQueryItem()
2974*/
2975
2976/*!
2977 \fn void QUrl::removeAllEncodedQueryItems(const QByteArray &key)
2978 \deprecated
2979 \since 4.4
2980
2981 Removes all the query string pairs whose key is equal to \a key
2982 from the URL.
2983
2984 \obsolete Use QUrlQuery.
2985
2986 \sa removeQueryItem()
2987*/
2988
2989/*!
2990 \fn QByteArray QUrl::encodedQuery() const
2991 \deprecated
2992
2993 Returns the query string of the URL in percent encoded form.
2994
2995 \obsolete Use query(QUrl::FullyEncoded).toLatin1()
2996
2997 \sa setEncodedQuery(), query()
2998*/
2999
3000/*!
3001 Returns the query string of the URL if there's a query string, or an empty
3002 result if not. To determine if the parsed URL contained a query string, use
3003 hasQuery().
3004
3005 The \a options argument controls how to format the query component. All
3006 values produce an unambiguous result. With QUrl::FullyDecoded, all
3007 percent-encoded sequences are decoded; otherwise, the returned value may
3008 contain some percent-encoded sequences for some control sequences not
3009 representable in decoded form in QString.
3010
3011 Note that use of QUrl::FullyDecoded in queries is discouraged, as queries
3012 often contain data that is supposed to remain percent-encoded, including
3013 the use of the "%2B" sequence to represent a plus character ('+').
3014
3015 \sa setQuery(), hasQuery()
3016*/
3017QString QUrl::query(ComponentFormattingOptions options) const
3018{
3019 QString result;
3020 if (d) {
3021 d->appendQuery(result, options, QUrlPrivate::Query);
3022 if (d->hasQuery() && result.isNull())
3023 result.detach();
3024 }
3025 return result;
3026}
3027
3028/*!
3029 Sets the fragment of the URL to \a fragment. The fragment is the
3030 last part of the URL, represented by a '#' followed by a string of
3031 characters. It is typically used in HTTP for referring to a
3032 certain link or point on a page:
3033
3034 \image qurl-fragment.png
3035
3036 The fragment is sometimes also referred to as the URL "reference".
3037
3038 Passing an argument of QString() (a null QString) will unset the fragment.
3039 Passing an argument of QString("") (an empty but not null QString) will set the
3040 fragment to an empty string (as if the original URL had a lone "#").
3041
3042 The \a fragment data is interpreted according to \a mode: in StrictMode,
3043 any '%' characters must be followed by exactly two hexadecimal characters
3044 and some characters (including space) are not allowed in undecoded form. In
3045 TolerantMode, all characters are accepted in undecoded form and the
3046 tolerant parser will correct stray '%' not followed by two hex characters.
3047 In DecodedMode, '%' stand for themselves and encoded characters are not
3048 possible.
3049
3050 QUrl::DecodedMode should be used when setting the fragment from a data
3051 source which is not a URL or with a fragment obtained by calling
3052 fragment() with the QUrl::FullyDecoded formatting option.
3053
3054 \sa fragment(), hasFragment()
3055*/
3056void QUrl::setFragment(const QString &fragment, ParsingMode mode)
3057{
3058 detach();
3059 d->clearError();
3060
3061 QString data = fragment;
3062 if (mode == DecodedMode) {
3063 parseDecodedComponent(data);
3064 mode = TolerantMode;
3065 }
3066
3067 d->setFragment(data, 0, data.length());
3068 if (fragment.isNull())
3069 d->sectionIsPresent &= ~QUrlPrivate::Fragment;
3070 else if (mode == StrictMode && !d->validateComponent(QUrlPrivate::Fragment, fragment))
3071 d->fragment.clear();
3072}
3073
3074/*!
3075 Returns the fragment of the URL. To determine if the parsed URL contained a
3076 fragment, use hasFragment().
3077
3078 The \a options argument controls how to format the fragment component. All
3079 values produce an unambiguous result. With QUrl::FullyDecoded, all
3080 percent-encoded sequences are decoded; otherwise, the returned value may
3081 contain some percent-encoded sequences for some control sequences not
3082 representable in decoded form in QString.
3083
3084 Note that QUrl::FullyDecoded may cause data loss if those non-representable
3085 sequences are present. It is recommended to use that value when the result
3086 will be used in a non-URL context.
3087
3088 \sa setFragment(), hasFragment()
3089*/
3090QString QUrl::fragment(ComponentFormattingOptions options) const
3091{
3092 QString result;
3093 if (d) {
3094 d->appendFragment(result, options, QUrlPrivate::Fragment);
3095 if (d->hasFragment() && result.isNull())
3096 result.detach();
3097 }
3098 return result;
3099}
3100
3101/*!
3102 \fn void QUrl::setEncodedFragment(const QByteArray &fragment)
3103 \deprecated
3104 \since 4.4
3105
3106 Sets the URL's fragment to the percent-encoded \a fragment. The fragment is the
3107 last part of the URL, represented by a '#' followed by a string of
3108 characters. It is typically used in HTTP for referring to a
3109 certain link or point on a page:
3110
3111 \image qurl-fragment.png
3112
3113 The fragment is sometimes also referred to as the URL "reference".
3114
3115 Passing an argument of QByteArray() (a null QByteArray) will unset the fragment.
3116 Passing an argument of QByteArray("") (an empty but not null QByteArray)
3117 will set the fragment to an empty string (as if the original URL
3118 had a lone "#").
3119
3120 \obsolete Use setFragment(), which has the same behavior of null / empty.
3121
3122 \sa setFragment(), encodedFragment()
3123*/
3124
3125/*!
3126 \fn QByteArray QUrl::encodedFragment() const
3127 \deprecated
3128 \since 4.4
3129
3130 Returns the fragment of the URL if it is defined; otherwise an
3131 empty string is returned. The returned value will have its
3132 non-ASCII and other control characters percent-encoded, as in
3133 toEncoded().
3134
3135 \obsolete Use query(QUrl::FullyEncoded).toLatin1().
3136
3137 \sa setEncodedFragment(), toEncoded()
3138*/
3139
3140/*!
3141 \since 4.2
3142
3143 Returns \c true if this URL contains a fragment (i.e., if # was seen on it).
3144
3145 \sa fragment(), setFragment()
3146*/
3147bool QUrl::hasFragment() const
3148{
3149 if (!d) return false;
3150 return d->hasFragment();
3151}
3152
3153#if QT_DEPRECATED_SINCE(5, 15)
3154#if QT_CONFIG(topleveldomain)
3155/*!
3156 \since 4.8
3157
3158 \deprecated
3159
3160 Returns the TLD (Top-Level Domain) of the URL, (e.g. .co.uk, .net).
3161 Note that the return value is prefixed with a '.' unless the
3162 URL does not contain a valid TLD, in which case the function returns
3163 an empty string.
3164
3165 Note that this function considers a TLD to be any domain that allows users
3166 to register subdomains under, including many home, dynamic DNS websites and
3167 blogging providers. This is useful for determining whether two websites
3168 belong to the same infrastructure and communication should be allowed, such
3169 as browser cookies: two domains should be considered part of the same
3170 website if they share at least one label in addition to the value
3171 returned by this function.
3172
3173 \list
3174 \li \c{foo.co.uk} and \c{foo.com} do not share a top-level domain
3175 \li \c{foo.co.uk} and \c{bar.co.uk} share the \c{.co.uk} domain, but the next label is different
3176 \li \c{www.foo.co.uk} and \c{ftp.foo.co.uk} share the same top-level domain and one more label,
3177 so they are considered part of the same site
3178 \endlist
3179
3180 If \a options includes EncodeUnicode, the returned string will be in
3181 ASCII Compatible Encoding.
3182*/
3183QString QUrl::topLevelDomain(ComponentFormattingOptions options) const
3184{
3185 QString tld = qTopLevelDomain(host());
3186 if (options & EncodeUnicode) {
3187 return qt_ACE_do(tld, ToAceOnly, AllowLeadingDot);
3188 }
3189 return tld;
3190}
3191#endif
3192#endif // QT_DEPRECATED_SINCE(5, 15)
3193/*!
3194 Returns the result of the merge of this URL with \a relative. This
3195 URL is used as a base to convert \a relative to an absolute URL.
3196
3197 If \a relative is not a relative URL, this function will return \a
3198 relative directly. Otherwise, the paths of the two URLs are
3199 merged, and the new URL returned has the scheme and authority of
3200 the base URL, but with the merged path, as in the following
3201 example:
3202
3203 \snippet code/src_corelib_io_qurl.cpp 5
3204
3205 Calling resolved() with ".." returns a QUrl whose directory is
3206 one level higher than the original. Similarly, calling resolved()
3207 with "../.." removes two levels from the path. If \a relative is
3208 "/", the path becomes "/".
3209
3210 \sa isRelative()
3211*/
3212QUrl QUrl::resolved(const QUrl &relative) const
3213{
3214 if (!d) return relative;
3215 if (!relative.d) return *this;
3216
3217 QUrl t;
3218 if (!relative.d->scheme.isEmpty()) {
3219 t = relative;
3220 t.detach();
3221 } else {
3222 if (relative.d->hasAuthority()) {
3223 t = relative;
3224 t.detach();
3225 } else {
3226 t.d = new QUrlPrivate;
3227
3228 // copy the authority
3229 t.d->userName = d->userName;
3230 t.d->password = d->password;
3231 t.d->host = d->host;
3232 t.d->port = d->port;
3233 t.d->sectionIsPresent = d->sectionIsPresent & QUrlPrivate::Authority;
3234
3235 if (relative.d->path.isEmpty()) {
3236 t.d->path = d->path;
3237 if (relative.d->hasQuery()) {
3238 t.d->query = relative.d->query;
3239 t.d->sectionIsPresent |= QUrlPrivate::Query;
3240 } else if (d->hasQuery()) {
3241 t.d->query = d->query;
3242 t.d->sectionIsPresent |= QUrlPrivate::Query;
3243 }
3244 } else {
3245 t.d->path = relative.d->path.startsWith(QLatin1Char('/'))
3246 ? relative.d->path
3247 : d->mergePaths(relative.d->path);
3248 if (relative.d->hasQuery()) {
3249 t.d->query = relative.d->query;
3250 t.d->sectionIsPresent |= QUrlPrivate::Query;
3251 }
3252 }
3253 }
3254 t.d->scheme = d->scheme;
3255 if (d->hasScheme())
3256 t.d->sectionIsPresent |= QUrlPrivate::Scheme;
3257 else
3258 t.d->sectionIsPresent &= ~QUrlPrivate::Scheme;
3259 t.d->flags |= d->flags & QUrlPrivate::IsLocalFile;
3260 }
3261 t.d->fragment = relative.d->fragment;
3262 if (relative.d->hasFragment())
3263 t.d->sectionIsPresent |= QUrlPrivate::Fragment;
3264 else
3265 t.d->sectionIsPresent &= ~QUrlPrivate::Fragment;
3266
3267 removeDotsFromPath(&t.d->path);
3268
3269#if defined(QURL_DEBUG)
3270 qDebug("QUrl(\"%ls\").resolved(\"%ls\") = \"%ls\"",
3271 qUtf16Printable(url()),
3272 qUtf16Printable(relative.url()),
3273 qUtf16Printable(t.url()));
3274#endif
3275 return t;
3276}
3277
3278/*!
3279 Returns \c true if the URL is relative; otherwise returns \c false. A URL is
3280 relative reference if its scheme is undefined; this function is therefore
3281 equivalent to calling scheme().isEmpty().
3282
3283 Relative references are defined in RFC 3986 section 4.2.
3284
3285 \sa {Relative URLs vs Relative Paths}
3286*/
3287bool QUrl::isRelative() const
3288{
3289 if (!d) return true;
3290 return !d->hasScheme();
3291}
3292
3293/*!
3294 Returns a string representation of the URL. The output can be customized by
3295 passing flags with \a options. The option QUrl::FullyDecoded is not
3296 permitted in this function since it would generate ambiguous data.
3297
3298 The resulting QString can be passed back to a QUrl later on.
3299
3300 Synonym for toString(options).
3301
3302 \sa FormattingOptions, toEncoded(), toString()
3303*/
3304QString QUrl::url(FormattingOptions options) const
3305{
3306 return toString(options);
3307}
3308
3309/*!
3310 Returns a string representation of the URL. The output can be customized by
3311 passing flags with \a options. The option QUrl::FullyDecoded is not
3312 permitted in this function since it would generate ambiguous data.
3313
3314 The default formatting option is \l{QUrl::FormattingOptions}{PrettyDecoded}.
3315
3316 \sa FormattingOptions, url(), setUrl()
3317*/
3318QString QUrl::toString(FormattingOptions options) const
3319{
3320 QString url;
3321 if (!isValid()) {
3322 // also catches isEmpty()
3323 return url;
3324 }
3325 if ((options & QUrl::FullyDecoded) == QUrl::FullyDecoded) {
3326 qWarning("QUrl: QUrl::FullyDecoded is not permitted when reconstructing the full URL");
3327 options &= ~QUrl::FullyDecoded;
3328 //options |= QUrl::PrettyDecoded; // no-op, value is 0
3329 }
3330
3331 // return just the path if:
3332 // - QUrl::PreferLocalFile is passed
3333 // - QUrl::RemovePath isn't passed (rather stupid if the user did...)
3334 // - there's no query or fragment to return
3335 // that is, either they aren't present, or we're removing them
3336 // - it's a local file
3337 if (options.testFlag(QUrl::PreferLocalFile) && !options.testFlag(QUrl::RemovePath)
3338 && (!d->hasQuery() || options.testFlag(QUrl::RemoveQuery))
3339 && (!d->hasFragment() || options.testFlag(QUrl::RemoveFragment))
3340 && isLocalFile()) {
3341 url = d->toLocalFile(options | QUrl::FullyDecoded);
3342 return url;
3343 }
3344
3345 // for the full URL, we consider that the reserved characters are prettier if encoded
3346 if (options & DecodeReserved)
3347 options &= ~EncodeReserved;
3348 else
3349 options |= EncodeReserved;
3350
3351 if (!(options & QUrl::RemoveScheme) && d->hasScheme())
3352 url += d->scheme + QLatin1Char(':');
3353
3354 bool pathIsAbsolute = d->path.startsWith(QLatin1Char('/'));
3355 if (!((options & QUrl::RemoveAuthority) == QUrl::RemoveAuthority) && d->hasAuthority()) {
3356 url += QLatin1String("//");
3357 d->appendAuthority(url, options, QUrlPrivate::FullUrl);
3358 } else if (isLocalFile() && pathIsAbsolute) {
3359 // Comply with the XDG file URI spec, which requires triple slashes.
3360 url += QLatin1String("//");
3361 }
3362
3363 if (!(options & QUrl::RemovePath))
3364 d->appendPath(url, options, QUrlPrivate::FullUrl);
3365
3366 if (!(options & QUrl::RemoveQuery) && d->hasQuery()) {
3367 url += QLatin1Char('?');
3368 d->appendQuery(url, options, QUrlPrivate::FullUrl);
3369 }
3370 if (!(options & QUrl::RemoveFragment) && d->hasFragment()) {
3371 url += QLatin1Char('#');
3372 d->appendFragment(url, options, QUrlPrivate::FullUrl);
3373 }
3374
3375 return url;
3376}
3377
3378/*!
3379 \since 5.0
3380
3381 Returns a human-displayable string representation of the URL.
3382 The output can be customized by passing flags with \a options.
3383 The option RemovePassword is always enabled, since passwords
3384 should never be shown back to users.
3385
3386 With the default options, the resulting QString can be passed back
3387 to a QUrl later on, but any password that was present initially will
3388 be lost.
3389
3390 \sa FormattingOptions, toEncoded(), toString()
3391*/
3392
3393QString QUrl::toDisplayString(FormattingOptions options) const
3394{
3395 return toString(options | RemovePassword);
3396}
3397
3398/*!
3399 \since 5.2
3400
3401 Returns an adjusted version of the URL.
3402 The output can be customized by passing flags with \a options.
3403
3404 The encoding options from QUrl::ComponentFormattingOption don't make
3405 much sense for this method, nor does QUrl::PreferLocalFile.
3406
3407 This is always equivalent to QUrl(url.toString(options)).
3408
3409 \sa FormattingOptions, toEncoded(), toString()
3410*/
3411QUrl QUrl::adjusted(QUrl::FormattingOptions options) const
3412{
3413 if (!isValid()) {
3414 // also catches isEmpty()
3415 return QUrl();
3416 }
3417 QUrl that = *this;
3418 if (options & RemoveScheme)
3419 that.setScheme(QString());
3420 if ((options & RemoveAuthority) == RemoveAuthority) {
3421 that.setAuthority(QString());
3422 } else {
3423 if ((options & RemoveUserInfo) == RemoveUserInfo)
3424 that.setUserInfo(QString());
3425 else if (options & RemovePassword)
3426 that.setPassword(QString());
3427 if (options & RemovePort)
3428 that.setPort(-1);
3429 }
3430 if (options & RemoveQuery)
3431 that.setQuery(QString());
3432 if (options & RemoveFragment)
3433 that.setFragment(QString());
3434 if (options & RemovePath) {
3435 that.setPath(QString());
3436 } else if (options & (StripTrailingSlash | RemoveFilename | NormalizePathSegments)) {
3437 that.detach();
3438 QString path;
3439 d->appendPath(path, options | FullyEncoded, QUrlPrivate::Path);
3440 that.d->setPath(path, 0, path.length());
3441 }
3442 return that;
3443}
3444
3445/*!
3446 Returns the encoded representation of the URL if it's valid;
3447 otherwise an empty QByteArray is returned. The output can be
3448 customized by passing flags with \a options.
3449
3450 The user info, path and fragment are all converted to UTF-8, and
3451 all non-ASCII characters are then percent encoded. The host name
3452 is encoded using Punycode.
3453*/
3454QByteArray QUrl::toEncoded(FormattingOptions options) const
3455{
3456 options &= ~(FullyDecoded | FullyEncoded);
3457 return toString(options | FullyEncoded).toLatin1();
3458}
3459
3460/*!
3461 \fn QUrl QUrl::fromEncoded(const QByteArray &input, ParsingMode parsingMode)
3462
3463 Parses \a input and returns the corresponding QUrl. \a input is
3464 assumed to be in encoded form, containing only ASCII characters.
3465
3466 Parses the URL using \a parsingMode. See setUrl() for more information on
3467 this parameter. QUrl::DecodedMode is not permitted in this context.
3468
3469 \sa toEncoded(), setUrl()
3470*/
3471QUrl QUrl::fromEncoded(const QByteArray &input, ParsingMode mode)
3472{
3473 return QUrl(QString::fromUtf8(input.constData(), input.size()), mode);
3474}
3475
3476/*!
3477 Returns a decoded copy of \a input. \a input is first decoded from
3478 percent encoding, then converted from UTF-8 to unicode.
3479
3480 \note Given invalid input (such as a string containing the sequence "%G5",
3481 which is not a valid hexadecimal number) the output will be invalid as
3482 well. As an example: the sequence "%G5" could be decoded to 'W'.
3483*/
3484QString QUrl::fromPercentEncoding(const QByteArray &input)
3485{
3486 QByteArray ba = QByteArray::fromPercentEncoding(input);
3487 return QString::fromUtf8(ba, ba.size());
3488}
3489
3490/*!
3491 Returns an encoded copy of \a input. \a input is first converted
3492 to UTF-8, and all ASCII-characters that are not in the unreserved group
3493 are percent encoded. To prevent characters from being percent encoded
3494 pass them to \a exclude. To force characters to be percent encoded pass
3495 them to \a include.
3496
3497 Unreserved is defined as:
3498 \tt {ALPHA / DIGIT / "-" / "." / "_" / "~"}
3499
3500 \snippet code/src_corelib_io_qurl.cpp 6
3501*/
3502QByteArray QUrl::toPercentEncoding(const QString &input, const QByteArray &exclude, const QByteArray &include)
3503{
3504 return input.toUtf8().toPercentEncoding(exclude, include);
3505}
3506
3507/*!
3508 \internal
3509 \since 5.0
3510 Used in the setEncodedXXX compatibility functions. Converts \a ba to
3511 QString form.
3512*/
3513QString QUrl::fromEncodedComponent_helper(const QByteArray &ba)
3514{
3515 return qt_urlRecodeByteArray(ba);
3516}
3517
3518/*!
3519 \fn QByteArray QUrl::toPunycode(const QString &uc)
3520 \obsolete
3521 Returns a \a uc in Punycode encoding.
3522
3523 Punycode is a Unicode encoding used for internationalized domain
3524 names, as defined in RFC3492. If you want to convert a domain name from
3525 Unicode to its ASCII-compatible representation, use toAce().
3526*/
3527
3528/*!
3529 \fn QString QUrl::fromPunycode(const QByteArray &pc)
3530 \obsolete
3531 Returns the Punycode decoded representation of \a pc.
3532
3533 Punycode is a Unicode encoding used for internationalized domain
3534 names, as defined in RFC3492. If you want to convert a domain from
3535 its ASCII-compatible encoding to the Unicode representation, use
3536 fromAce().
3537*/
3538
3539/*!
3540 \since 4.2
3541
3542 Returns the Unicode form of the given domain name
3543 \a domain, which is encoded in the ASCII Compatible Encoding (ACE).
3544 The result of this function is considered equivalent to \a domain.
3545
3546 If the value in \a domain cannot be encoded, it will be converted
3547 to QString and returned.
3548
3549 The ASCII Compatible Encoding (ACE) is defined by RFC 3490, RFC 3491
3550 and RFC 3492. It is part of the Internationalizing Domain Names in
3551 Applications (IDNA) specification, which allows for domain names
3552 (like \c "example.com") to be written using international
3553 characters.
3554*/
3555QString QUrl::fromAce(const QByteArray &domain)
3556{
3557 return qt_ACE_do(QString::fromLatin1(domain), NormalizeAce, ForbidLeadingDot /*FIXME: make configurable*/);
3558}
3559
3560/*!
3561 \since 4.2
3562
3563 Returns the ASCII Compatible Encoding of the given domain name \a domain.
3564 The result of this function is considered equivalent to \a domain.
3565
3566 The ASCII-Compatible Encoding (ACE) is defined by RFC 3490, RFC 3491
3567 and RFC 3492. It is part of the Internationalizing Domain Names in
3568 Applications (IDNA) specification, which allows for domain names
3569 (like \c "example.com") to be written using international
3570 characters.
3571
3572 This function returns an empty QByteArray if \a domain is not a valid
3573 hostname. Note, in particular, that IPv6 literals are not valid domain
3574 names.
3575*/
3576QByteArray QUrl::toAce(const QString &domain)
3577{
3578 return qt_ACE_do(domain, ToAceOnly, ForbidLeadingDot /*FIXME: make configurable*/).toLatin1();
3579}
3580
3581/*!
3582 \internal
3583
3584 Returns \c true if this URL is "less than" the given \a url. This
3585 provides a means of ordering URLs.
3586*/
3587bool QUrl::operator <(const QUrl &url) const
3588{
3589 if (!d || !url.d) {
3590 bool thisIsEmpty = !d || d->isEmpty();
3591 bool thatIsEmpty = !url.d || url.d->isEmpty();
3592
3593 // sort an empty URL first
3594 return thisIsEmpty && !thatIsEmpty;
3595 }
3596
3597 int cmp;
3598 cmp = d->scheme.compare(url.d->scheme);
3599 if (cmp != 0)
3600 return cmp < 0;
3601
3602 cmp = d->userName.compare(url.d->userName);
3603 if (cmp != 0)
3604 return cmp < 0;
3605
3606 cmp = d->password.compare(url.d->password);
3607 if (cmp != 0)
3608 return cmp < 0;
3609
3610 cmp = d->host.compare(url.d->host);
3611 if (cmp != 0)
3612 return cmp < 0;
3613
3614 if (d->port != url.d->port)
3615 return d->port < url.d->port;
3616
3617 cmp = d->path.compare(url.d->path);
3618 if (cmp != 0)
3619 return cmp < 0;
3620
3621 if (d->hasQuery() != url.d->hasQuery())
3622 return url.d->hasQuery();
3623
3624 cmp = d->query.compare(url.d->query);
3625 if (cmp != 0)
3626 return cmp < 0;
3627
3628 if (d->hasFragment() != url.d->hasFragment())
3629 return url.d->hasFragment();
3630
3631 cmp = d->fragment.compare(url.d->fragment);
3632 return cmp < 0;
3633}
3634
3635/*!
3636 Returns \c true if this URL and the given \a url are equal;
3637 otherwise returns \c false.
3638*/
3639bool QUrl::operator ==(const QUrl &url) const
3640{
3641 if (!d && !url.d)
3642 return true;
3643 if (!d)
3644 return url.d->isEmpty();
3645 if (!url.d)
3646 return d->isEmpty();
3647
3648 // First, compare which sections are present, since it speeds up the
3649 // processing considerably. We just have to ignore the host-is-present flag
3650 // for local files (the "file" protocol), due to the requirements of the
3651 // XDG file URI specification.
3652 int mask = QUrlPrivate::FullUrl;
3653 if (isLocalFile())
3654 mask &= ~QUrlPrivate::Host;
3655 return (d->sectionIsPresent & mask) == (url.d->sectionIsPresent & mask) &&
3656 d->scheme == url.d->scheme &&
3657 d->userName == url.d->userName &&
3658 d->password == url.d->password &&
3659 d->host == url.d->host &&
3660 d->port == url.d->port &&
3661 d->path == url.d->path &&
3662 d->query == url.d->query &&
3663 d->fragment == url.d->fragment;
3664}
3665
3666/*!
3667 \since 5.2
3668
3669 Returns \c true if this URL and the given \a url are equal after
3670 applying \a options to both; otherwise returns \c false.
3671
3672 This is equivalent to calling adjusted(options) on both URLs
3673 and comparing the resulting urls, but faster.
3674
3675*/
3676bool QUrl::matches(const QUrl &url, FormattingOptions options) const
3677{
3678 if (!d && !url.d)
3679 return true;
3680 if (!d)
3681 return url.d->isEmpty();
3682 if (!url.d)
3683 return d->isEmpty();
3684
3685 // First, compare which sections are present, since it speeds up the
3686 // processing considerably. We just have to ignore the host-is-present flag
3687 // for local files (the "file" protocol), due to the requirements of the
3688 // XDG file URI specification.
3689 int mask = QUrlPrivate::FullUrl;
3690 if (isLocalFile())
3691 mask &= ~QUrlPrivate::Host;
3692
3693 if (options.testFlag(QUrl::RemoveScheme))
3694 mask &= ~QUrlPrivate::Scheme;
3695 else if (d->scheme != url.d->scheme)
3696 return false;
3697
3698 if (options.testFlag(QUrl::RemovePassword))
3699 mask &= ~QUrlPrivate::Password;
3700 else if (d->password != url.d->password)
3701 return false;
3702
3703 if (options.testFlag(QUrl::RemoveUserInfo))
3704 mask &= ~QUrlPrivate::UserName;
3705 else if (d->userName != url.d->userName)
3706 return false;
3707
3708 if (options.testFlag(QUrl::RemovePort))
3709 mask &= ~QUrlPrivate::Port;
3710 else if (d->port != url.d->port)
3711 return false;
3712
3713 if (options.testFlag(QUrl::RemoveAuthority))
3714 mask &= ~QUrlPrivate::Host;
3715 else if (d->host != url.d->host)
3716 return false;
3717
3718 if (options.testFlag(QUrl::RemoveQuery))
3719 mask &= ~QUrlPrivate::Query;
3720 else if (d->query != url.d->query)
3721 return false;
3722
3723 if (options.testFlag(QUrl::RemoveFragment))
3724 mask &= ~QUrlPrivate::Fragment;
3725 else if (d->fragment != url.d->fragment)
3726 return false;
3727
3728 if ((d->sectionIsPresent & mask) != (url.d->sectionIsPresent & mask))
3729 return false;
3730
3731 if (options.testFlag(QUrl::RemovePath))
3732 return true;
3733
3734 // Compare paths, after applying path-related options
3735 QString path1;
3736 d->appendPath(path1, options, QUrlPrivate::Path);
3737 QString path2;
3738 url.d->appendPath(path2, options, QUrlPrivate::Path);
3739 return path1 == path2;
3740}
3741
3742/*!
3743 Returns \c true if this URL and the given \a url are not equal;
3744 otherwise returns \c false.
3745*/
3746bool QUrl::operator !=(const QUrl &url) const
3747{
3748 return !(*this == url);
3749}
3750
3751/*!
3752 Assigns the specified \a url to this object.
3753*/
3754QUrl &QUrl::operator =(const QUrl &url)
3755{
3756 if (!d) {
3757 if (url.d) {
3758 url.d->ref.ref();
3759 d = url.d;
3760 }
3761 } else {
3762 if (url.d)
3763 qAtomicAssign(d, url.d);
3764 else
3765 clear();
3766 }
3767 return *this;
3768}
3769
3770/*!
3771 Assigns the specified \a url to this object.
3772*/
3773QUrl &QUrl::operator =(const QString &url)
3774{
3775 if (url.isEmpty()) {
3776 clear();
3777 } else {
3778 detach();
3779 d->parse(url, TolerantMode);
3780 }
3781 return *this;
3782}
3783
3784/*!
3785 \fn void QUrl::swap(QUrl &other)
3786 \since 4.8
3787
3788 Swaps URL \a other with this URL. This operation is very
3789 fast and never fails.
3790*/
3791
3792/*!
3793 \internal
3794
3795 Forces a detach.
3796*/
3797void QUrl::detach()
3798{
3799 if (!d)
3800 d = new QUrlPrivate;
3801 else
3802 qAtomicDetach(d);
3803}
3804
3805/*!
3806 \internal
3807*/
3808bool QUrl::isDetached() const
3809{
3810 return !d || d->ref.loadRelaxed() == 1;
3811}
3812
3813
3814/*!
3815 Returns a QUrl representation of \a localFile, interpreted as a local
3816 file. This function accepts paths separated by slashes as well as the
3817 native separator for this platform.
3818
3819 This function also accepts paths with a doubled leading slash (or
3820 backslash) to indicate a remote file, as in
3821 "//servername/path/to/file.txt". Note that only certain platforms can
3822 actually open this file using QFile::open().
3823
3824 An empty \a localFile leads to an empty URL (since Qt 5.4).
3825
3826 \snippet code/src_corelib_io_qurl.cpp 16
3827
3828 In the first line in snippet above, a file URL is constructed from a
3829 local, relative path. A file URL with a relative path only makes sense
3830 if there is a base URL to resolve it against. For example:
3831
3832 \snippet code/src_corelib_io_qurl.cpp 17
3833
3834 To resolve such a URL, it's necessary to remove the scheme beforehand:
3835
3836 \snippet code/src_corelib_io_qurl.cpp 18
3837
3838 For this reason, it is better to use a relative URL (that is, no scheme)
3839 for relative file paths:
3840
3841 \snippet code/src_corelib_io_qurl.cpp 19
3842
3843 \sa toLocalFile(), isLocalFile(), QDir::toNativeSeparators()
3844*/
3845QUrl QUrl::fromLocalFile(const QString &localFile)
3846{
3847 QUrl url;
3848 if (localFile.isEmpty())
3849 return url;
3850 QString scheme = fileScheme();
3851 QString deslashified = QDir::fromNativeSeparators(localFile);
3852
3853 // magic for drives on windows
3854 if (deslashified.length() > 1 && deslashified.at(1) == QLatin1Char(':') && deslashified.at(0) != QLatin1Char('/')) {
3855 deslashified.prepend(QLatin1Char('/'));
3856 } else if (deslashified.startsWith(QLatin1String("//"))) {
3857 // magic for shared drive on windows
3858 int indexOfPath = deslashified.indexOf(QLatin1Char('/'), 2);
3859 QStringRef hostSpec = deslashified.midRef(2, indexOfPath - 2);
3860 // Check for Windows-specific WebDAV specification: "//host@SSL/path".
3861 if (hostSpec.endsWith(webDavSslTag(), Qt::CaseInsensitive)) {
3862 hostSpec.truncate(hostSpec.size() - 4);
3863 scheme = webDavScheme();
3864 }
3865
3866 // hosts can't be IPv6 addresses without [], so we can use QUrlPrivate::setHost
3867 url.detach();
3868 if (!url.d->setHost(hostSpec.toString(), 0, hostSpec.size(), StrictMode)) {
3869 if (url.d->error->code != QUrlPrivate::InvalidRegNameError)
3870 return url;
3871
3872 // Path hostname is not a valid URL host, so set it entirely in the path
3873 // (by leaving deslashified unchanged)
3874 } else if (indexOfPath > 2) {
3875 deslashified = deslashified.right(deslashified.length() - indexOfPath);
3876 } else {
3877 deslashified.clear();
3878 }
3879 }
3880
3881 url.setScheme(scheme);
3882 url.setPath(deslashified, DecodedMode);
3883 return url;
3884}
3885
3886/*!
3887 Returns the path of this URL formatted as a local file path. The path
3888 returned will use forward slashes, even if it was originally created
3889 from one with backslashes.
3890
3891 If this URL contains a non-empty hostname, it will be encoded in the
3892 returned value in the form found on SMB networks (for example,
3893 "//servername/path/to/file.txt").
3894
3895 \snippet code/src_corelib_io_qurl.cpp 20
3896
3897 Note: if the path component of this URL contains a non-UTF-8 binary
3898 sequence (such as %80), the behaviour of this function is undefined.
3899
3900 \sa fromLocalFile(), isLocalFile()
3901*/
3902QString QUrl::toLocalFile() const
3903{
3904 // the call to isLocalFile() also ensures that we're parsed
3905 if (!isLocalFile())
3906 return QString();
3907
3908 return d->toLocalFile(QUrl::FullyDecoded);
3909}
3910
3911/*!
3912 \since 4.8
3913 Returns \c true if this URL is pointing to a local file path. A URL is a
3914 local file path if the scheme is "file".
3915
3916 Note that this function considers URLs with hostnames to be local file
3917 paths, even if the eventual file path cannot be opened with
3918 QFile::open().
3919
3920 \sa fromLocalFile(), toLocalFile()
3921*/
3922bool QUrl::isLocalFile() const
3923{
3924 return d && d->isLocalFile();
3925}
3926
3927/*!
3928 Returns \c true if this URL is a parent of \a childUrl. \a childUrl is a child
3929 of this URL if the two URLs share the same scheme and authority,
3930 and this URL's path is a parent of the path of \a childUrl.
3931*/
3932bool QUrl::isParentOf(const QUrl &childUrl) const
3933{
3934 QString childPath = childUrl.path();
3935
3936 if (!d)
3937 return ((childUrl.scheme().isEmpty())
3938 && (childUrl.authority().isEmpty())
3939 && childPath.length() > 0 && childPath.at(0) == QLatin1Char('/'));
3940
3941 QString ourPath = path();
3942
3943 return ((childUrl.scheme().isEmpty() || d->scheme == childUrl.scheme())
3944 && (childUrl.authority().isEmpty() || authority() == childUrl.authority())
3945 && childPath.startsWith(ourPath)
3946 && ((ourPath.endsWith(QLatin1Char('/')) && childPath.length() > ourPath.length())
3947 || (!ourPath.endsWith(QLatin1Char('/'))
3948 && childPath.length() > ourPath.length() && childPath.at(ourPath.length()) == QLatin1Char('/'))));
3949}
3950
3951
3952#ifndef QT_NO_DATASTREAM
3953/*! \relates QUrl
3954
3955 Writes url \a url to the stream \a out and returns a reference
3956 to the stream.
3957
3958 \sa{Serializing Qt Data Types}{Format of the QDataStream operators}
3959*/
3960QDataStream &operator<<(QDataStream &out, const QUrl &url)
3961{
3962 QByteArray u;
3963 if (url.isValid())
3964 u = url.toEncoded();
3965 out << u;
3966 return out;
3967}
3968
3969/*! \relates QUrl
3970
3971 Reads a url into \a url from the stream \a in and returns a
3972 reference to the stream.
3973
3974 \sa{Serializing Qt Data Types}{Format of the QDataStream operators}
3975*/
3976QDataStream &operator>>(QDataStream &in, QUrl &url)
3977{
3978 QByteArray u;
3979 in >> u;
3980 url.setUrl(QString::fromLatin1(u));
3981 return in;
3982}
3983#endif // QT_NO_DATASTREAM
3984
3985#ifndef QT_NO_DEBUG_STREAM
3986QDebug operator<<(QDebug d, const QUrl &url)
3987{
3988 QDebugStateSaver saver(d);
3989 d.nospace() << "QUrl(" << url.toDisplayString() << ')';
3990 return d;
3991}
3992#endif
3993
3994static QString errorMessage(QUrlPrivate::ErrorCode errorCode, const QString &errorSource, int errorPosition)
3995{
3996 QChar c = uint(errorPosition) < uint(errorSource.length()) ?
3997 errorSource.at(errorPosition) : QChar(QChar::Null);
3998
3999 switch (errorCode) {
4000 case QUrlPrivate::NoError:
4001 Q_ASSERT_X(false, "QUrl::errorString",
4002 "Impossible: QUrl::errorString should have treated this condition");
4003 Q_UNREACHABLE();
4004 return QString();
4005
4006 case QUrlPrivate::InvalidSchemeError: {
4007 auto msg = QLatin1String("Invalid scheme (character '%1' not permitted)");
4008 return msg.arg(c);
4009 }
4010
4011 case QUrlPrivate::InvalidUserNameError:
4012 return QLatin1String("Invalid user name (character '%1' not permitted)")
4013 .arg(c);
4014
4015 case QUrlPrivate::InvalidPasswordError:
4016 return QLatin1String("Invalid password (character '%1' not permitted)")
4017 .arg(c);
4018
4019 case QUrlPrivate::InvalidRegNameError:
4020 if (errorPosition != -1)
4021 return QLatin1String("Invalid hostname (character '%1' not permitted)")
4022 .arg(c);
4023 else
4024 return QStringLiteral("Invalid hostname (contains invalid characters)");
4025 case QUrlPrivate::InvalidIPv4AddressError:
4026 return QString(); // doesn't happen yet
4027 case QUrlPrivate::InvalidIPv6AddressError:
4028 return QStringLiteral("Invalid IPv6 address");
4029 case QUrlPrivate::InvalidCharacterInIPv6Error:
4030 return QLatin1String("Invalid IPv6 address (character '%1' not permitted)").arg(c);
4031 case QUrlPrivate::InvalidIPvFutureError:
4032 return QLatin1String("Invalid IPvFuture address (character '%1' not permitted)").arg(c);
4033 case QUrlPrivate::HostMissingEndBracket:
4034 return QStringLiteral("Expected ']' to match '[' in hostname");
4035
4036 case QUrlPrivate::InvalidPortError:
4037 return QStringLiteral("Invalid port or port number out of range");
4038 case QUrlPrivate::PortEmptyError:
4039 return QStringLiteral("Port field was empty");
4040
4041 case QUrlPrivate::InvalidPathError:
4042 return QLatin1String("Invalid path (character '%1' not permitted)")
4043 .arg(c);
4044
4045 case QUrlPrivate::InvalidQueryError:
4046 return QLatin1String("Invalid query (character '%1' not permitted)")
4047 .arg(c);
4048
4049 case QUrlPrivate::InvalidFragmentError:
4050 return QLatin1String("Invalid fragment (character '%1' not permitted)")
4051 .arg(c);
4052
4053 case QUrlPrivate::AuthorityPresentAndPathIsRelative:
4054 return QStringLiteral("Path component is relative and authority is present");
4055 case QUrlPrivate::AuthorityAbsentAndPathIsDoubleSlash:
4056 return QStringLiteral("Path component starts with '//' and authority is absent");
4057 case QUrlPrivate::RelativeUrlPathContainsColonBeforeSlash:
4058 return QStringLiteral("Relative URL's path component contains ':' before any '/'");
4059 }
4060
4061 Q_ASSERT_X(false, "QUrl::errorString", "Cannot happen, unknown error");
4062 Q_UNREACHABLE();
4063 return QString();
4064}
4065
4066static inline void appendComponentIfPresent(QString &msg, bool present, const char *componentName,
4067 const QString &component)
4068{
4069 if (present) {
4070 msg += QLatin1String(componentName);
4071 msg += QLatin1Char('"');
4072 msg += component;
4073 msg += QLatin1String("\",");
4074 }
4075}
4076
4077/*!
4078 \since 4.2
4079
4080 Returns an error message if the last operation that modified this QUrl
4081 object ran into a parsing error. If no error was detected, this function
4082 returns an empty string and isValid() returns \c true.
4083
4084 The error message returned by this function is technical in nature and may
4085 not be understood by end users. It is mostly useful to developers trying to
4086 understand why QUrl will not accept some input.
4087
4088 \sa QUrl::ParsingMode
4089*/
4090QString QUrl::errorString() const
4091{
4092 QString msg;
4093 if (!d)
4094 return msg;
4095
4096 QString errorSource;
4097 int errorPosition = 0;
4098 QUrlPrivate::ErrorCode errorCode = d->validityError(&errorSource, &errorPosition);
4099 if (errorCode == QUrlPrivate::NoError)
4100 return msg;
4101
4102 msg += errorMessage(errorCode, errorSource, errorPosition);
4103 msg += QLatin1String("; source was \"");
4104 msg += errorSource;
4105 msg += QLatin1String("\";");
4106 appendComponentIfPresent(msg, d->sectionIsPresent & QUrlPrivate::Scheme,
4107 " scheme = ", d->scheme);
4108 appendComponentIfPresent(msg, d->sectionIsPresent & QUrlPrivate::UserInfo,
4109 " userinfo = ", userInfo());
4110 appendComponentIfPresent(msg, d->sectionIsPresent & QUrlPrivate::Host,
4111 " host = ", d->host);
4112 appendComponentIfPresent(msg, d->port != -1,
4113 " port = ", QString::number(d->port));
4114 appendComponentIfPresent(msg, !d->path.isEmpty(),
4115 " path = ", d->path);
4116 appendComponentIfPresent(msg, d->sectionIsPresent & QUrlPrivate::Query,
4117 " query = ", d->query);
4118 appendComponentIfPresent(msg, d->sectionIsPresent & QUrlPrivate::Fragment,
4119 " fragment = ", d->fragment);
4120 if (msg.endsWith(QLatin1Char(',')))
4121 msg.chop(1);
4122 return msg;
4123}
4124
4125/*!
4126 \since 5.1
4127
4128 Converts a list of \a urls into a list of QString objects, using toString(\a options).
4129*/
4130QStringList QUrl::toStringList(const QList<