Bug 1861709 replace AudioCallbackDriver::ThreadRunning() assertions that mean to...
[gecko.git] / netwerk / base / nsURLHelper.cpp
blob66d5b1fd2c60a5bc3b53e4ba1706858e5421c427
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=4 sw=2 sts=2 et cindent: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "nsURLHelper.h"
9 #include "mozilla/Encoding.h"
10 #include "mozilla/RangedPtr.h"
11 #include "mozilla/TextUtils.h"
13 #include <algorithm>
14 #include <iterator>
16 #include "nsASCIIMask.h"
17 #include "nsIFile.h"
18 #include "nsIURLParser.h"
19 #include "nsCOMPtr.h"
20 #include "nsCRT.h"
21 #include "nsNetCID.h"
22 #include "mozilla/Preferences.h"
23 #include "prnetdb.h"
24 #include "mozilla/StaticPrefs_network.h"
25 #include "mozilla/Tokenizer.h"
26 #include "nsEscape.h"
27 #include "nsDOMString.h"
28 #include "mozilla/net/rust_helper.h"
29 #include "mozilla/net/DNS.h"
31 using namespace mozilla;
33 //----------------------------------------------------------------------------
34 // Init/Shutdown
35 //----------------------------------------------------------------------------
37 static bool gInitialized = false;
38 static StaticRefPtr<nsIURLParser> gNoAuthURLParser;
39 static StaticRefPtr<nsIURLParser> gAuthURLParser;
40 static StaticRefPtr<nsIURLParser> gStdURLParser;
42 static void InitGlobals() {
43 nsCOMPtr<nsIURLParser> parser;
45 parser = do_GetService(NS_NOAUTHURLPARSER_CONTRACTID);
46 NS_ASSERTION(parser, "failed getting 'noauth' url parser");
47 if (parser) {
48 gNoAuthURLParser = parser;
51 parser = do_GetService(NS_AUTHURLPARSER_CONTRACTID);
52 NS_ASSERTION(parser, "failed getting 'auth' url parser");
53 if (parser) {
54 gAuthURLParser = parser;
57 parser = do_GetService(NS_STDURLPARSER_CONTRACTID);
58 NS_ASSERTION(parser, "failed getting 'std' url parser");
59 if (parser) {
60 gStdURLParser = parser;
63 gInitialized = true;
66 void net_ShutdownURLHelper() {
67 if (gInitialized) {
68 gInitialized = false;
70 gNoAuthURLParser = nullptr;
71 gAuthURLParser = nullptr;
72 gStdURLParser = nullptr;
75 //----------------------------------------------------------------------------
76 // nsIURLParser getters
77 //----------------------------------------------------------------------------
79 nsIURLParser* net_GetAuthURLParser() {
80 if (!gInitialized) InitGlobals();
81 return gAuthURLParser;
84 nsIURLParser* net_GetNoAuthURLParser() {
85 if (!gInitialized) InitGlobals();
86 return gNoAuthURLParser;
89 nsIURLParser* net_GetStdURLParser() {
90 if (!gInitialized) InitGlobals();
91 return gStdURLParser;
94 //---------------------------------------------------------------------------
95 // GetFileFromURLSpec implementations
96 //---------------------------------------------------------------------------
97 nsresult net_GetURLSpecFromDir(nsIFile* aFile, nsACString& result) {
98 nsAutoCString escPath;
99 nsresult rv = net_GetURLSpecFromActualFile(aFile, escPath);
100 if (NS_FAILED(rv)) return rv;
102 if (escPath.Last() != '/') {
103 escPath += '/';
106 result = escPath;
107 return NS_OK;
110 nsresult net_GetURLSpecFromFile(nsIFile* aFile, nsACString& result) {
111 nsAutoCString escPath;
112 nsresult rv = net_GetURLSpecFromActualFile(aFile, escPath);
113 if (NS_FAILED(rv)) return rv;
115 // if this file references a directory, then we need to ensure that the
116 // URL ends with a slash. this is important since it affects the rules
117 // for relative URL resolution when this URL is used as a base URL.
118 // if the file does not exist, then we make no assumption about its type,
119 // and simply leave the URL unmodified.
120 if (escPath.Last() != '/') {
121 bool dir;
122 rv = aFile->IsDirectory(&dir);
123 if (NS_SUCCEEDED(rv) && dir) escPath += '/';
126 result = escPath;
127 return NS_OK;
130 //----------------------------------------------------------------------------
131 // file:// URL parsing
132 //----------------------------------------------------------------------------
134 nsresult net_ParseFileURL(const nsACString& inURL, nsACString& outDirectory,
135 nsACString& outFileBaseName,
136 nsACString& outFileExtension) {
137 nsresult rv;
139 if (inURL.Length() >
140 (uint32_t)StaticPrefs::network_standard_url_max_length()) {
141 return NS_ERROR_MALFORMED_URI;
144 outDirectory.Truncate();
145 outFileBaseName.Truncate();
146 outFileExtension.Truncate();
148 const nsPromiseFlatCString& flatURL = PromiseFlatCString(inURL);
149 const char* url = flatURL.get();
151 nsAutoCString scheme;
152 rv = net_ExtractURLScheme(flatURL, scheme);
153 if (NS_FAILED(rv)) return rv;
155 if (!scheme.EqualsLiteral("file")) {
156 NS_ERROR("must be a file:// url");
157 return NS_ERROR_UNEXPECTED;
160 nsIURLParser* parser = net_GetNoAuthURLParser();
161 NS_ENSURE_TRUE(parser, NS_ERROR_UNEXPECTED);
163 uint32_t pathPos, filepathPos, directoryPos, basenamePos, extensionPos;
164 int32_t pathLen, filepathLen, directoryLen, basenameLen, extensionLen;
166 // invoke the parser to extract the URL path
167 rv = parser->ParseURL(url, flatURL.Length(), nullptr,
168 nullptr, // don't care about scheme
169 nullptr, nullptr, // don't care about authority
170 &pathPos, &pathLen);
171 if (NS_FAILED(rv)) return rv;
173 // invoke the parser to extract filepath from the path
174 rv = parser->ParsePath(url + pathPos, pathLen, &filepathPos, &filepathLen,
175 nullptr, nullptr, // don't care about query
176 nullptr, nullptr); // don't care about ref
177 if (NS_FAILED(rv)) return rv;
179 filepathPos += pathPos;
181 // invoke the parser to extract the directory and filename from filepath
182 rv = parser->ParseFilePath(url + filepathPos, filepathLen, &directoryPos,
183 &directoryLen, &basenamePos, &basenameLen,
184 &extensionPos, &extensionLen);
185 if (NS_FAILED(rv)) return rv;
187 if (directoryLen > 0) {
188 outDirectory = Substring(inURL, filepathPos + directoryPos, directoryLen);
190 if (basenameLen > 0) {
191 outFileBaseName = Substring(inURL, filepathPos + basenamePos, basenameLen);
193 if (extensionLen > 0) {
194 outFileExtension =
195 Substring(inURL, filepathPos + extensionPos, extensionLen);
197 // since we are using a no-auth url parser, there will never be a host
198 // XXX not strictly true... file://localhost/foo/bar.html is a valid URL
200 return NS_OK;
203 //----------------------------------------------------------------------------
204 // path manipulation functions
205 //----------------------------------------------------------------------------
207 // Replace all /./ with a / while resolving URLs
208 // But only till #?
209 void net_CoalesceDirs(netCoalesceFlags flags, char* path) {
210 /* Stolen from the old netlib's mkparse.c.
212 * modifies a url of the form /foo/../foo1 -> /foo1
213 * and /foo/./foo1 -> /foo/foo1
214 * and /foo/foo1/.. -> /foo/
216 char* fwdPtr = path;
217 char* urlPtr = path;
218 char* lastslash = path;
219 uint32_t traversal = 0;
220 uint32_t special_ftp_len = 0;
222 /* Remember if this url is a special ftp one: */
223 if (flags & NET_COALESCE_DOUBLE_SLASH_IS_ROOT) {
224 /* some schemes (for example ftp) have the speciality that
225 the path can begin // or /%2F to mark the root of the
226 servers filesystem, a simple / only marks the root relative
227 to the user loging in. We remember the length of the marker */
228 if (nsCRT::strncasecmp(path, "/%2F", 4) == 0) {
229 special_ftp_len = 4;
230 } else if (strncmp(path, "//", 2) == 0) {
231 special_ftp_len = 2;
235 /* find the last slash before # or ? */
236 for (; (*fwdPtr != '\0') && (*fwdPtr != '?') && (*fwdPtr != '#'); ++fwdPtr) {
239 /* found nothing, but go back one only */
240 /* if there is something to go back to */
241 if (fwdPtr != path && *fwdPtr == '\0') {
242 --fwdPtr;
245 /* search the slash */
246 for (; (fwdPtr != path) && (*fwdPtr != '/'); --fwdPtr) {
248 lastslash = fwdPtr;
249 fwdPtr = path;
251 /* replace all %2E or %2e with . in the path */
252 /* but stop at lastchar if non null */
253 for (; (*fwdPtr != '\0') && (*fwdPtr != '?') && (*fwdPtr != '#') &&
254 (*lastslash == '\0' || fwdPtr != lastslash);
255 ++fwdPtr) {
256 if (*fwdPtr == '%' && *(fwdPtr + 1) == '2' &&
257 (*(fwdPtr + 2) == 'E' || *(fwdPtr + 2) == 'e')) {
258 *urlPtr++ = '.';
259 ++fwdPtr;
260 ++fwdPtr;
261 } else {
262 *urlPtr++ = *fwdPtr;
265 // Copy remaining stuff past the #?;
266 for (; *fwdPtr != '\0'; ++fwdPtr) {
267 *urlPtr++ = *fwdPtr;
269 *urlPtr = '\0'; // terminate the url
271 // start again, this time for real
272 fwdPtr = path;
273 urlPtr = path;
275 for (; (*fwdPtr != '\0') && (*fwdPtr != '?') && (*fwdPtr != '#'); ++fwdPtr) {
276 if (*fwdPtr == '/' && *(fwdPtr + 1) == '.' && *(fwdPtr + 2) == '/') {
277 // remove . followed by slash
278 ++fwdPtr;
279 } else if (*fwdPtr == '/' && *(fwdPtr + 1) == '.' && *(fwdPtr + 2) == '.' &&
280 (*(fwdPtr + 3) == '/' ||
281 *(fwdPtr + 3) == '\0' || // This will take care of
282 *(fwdPtr + 3) == '?' || // something like foo/bar/..#sometag
283 *(fwdPtr + 3) == '#')) {
284 // remove foo/..
285 // reverse the urlPtr to the previous slash if possible
286 // if url does not allow relative root then drop .. above root
287 // otherwise retain them in the path
288 if (traversal > 0 || !(flags & NET_COALESCE_ALLOW_RELATIVE_ROOT)) {
289 if (urlPtr != path) urlPtr--; // we must be going back at least by one
290 for (; *urlPtr != '/' && urlPtr != path; urlPtr--) {
291 ; // null body
293 --traversal; // count back
294 // forward the fwdPtr past the ../
295 fwdPtr += 2;
296 // if we have reached the beginning of the path
297 // while searching for the previous / and we remember
298 // that it is an url that begins with /%2F then
299 // advance urlPtr again by 3 chars because /%2F already
300 // marks the root of the path
301 if (urlPtr == path && special_ftp_len > 3) {
302 ++urlPtr;
303 ++urlPtr;
304 ++urlPtr;
306 // special case if we have reached the end
307 // to preserve the last /
308 if (*fwdPtr == '.' && *(fwdPtr + 1) == '\0') ++urlPtr;
309 } else {
310 // there are to much /.. in this path, just copy them instead.
311 // forward the urlPtr past the /.. and copying it
313 // However if we remember it is an url that starts with
314 // /%2F and urlPtr just points at the "F" of "/%2F" then do
315 // not overwrite it with the /, just copy .. and move forward
316 // urlPtr.
317 if (special_ftp_len > 3 && urlPtr == path + special_ftp_len - 1) {
318 ++urlPtr;
319 } else {
320 *urlPtr++ = *fwdPtr;
322 ++fwdPtr;
323 *urlPtr++ = *fwdPtr;
324 ++fwdPtr;
325 *urlPtr++ = *fwdPtr;
327 } else {
328 // count the hierachie, but only if we do not have reached
329 // the root of some special urls with a special root marker
330 if (*fwdPtr == '/' && *(fwdPtr + 1) != '.' &&
331 (special_ftp_len != 2 || *(fwdPtr + 1) != '/')) {
332 traversal++;
334 // copy the url incrementaly
335 *urlPtr++ = *fwdPtr;
340 * Now lets remove trailing . case
341 * /foo/foo1/. -> /foo/foo1/
344 if ((urlPtr > (path + 1)) && (*(urlPtr - 1) == '.') &&
345 (*(urlPtr - 2) == '/')) {
346 urlPtr--;
349 // Copy remaining stuff past the #?;
350 for (; *fwdPtr != '\0'; ++fwdPtr) {
351 *urlPtr++ = *fwdPtr;
353 *urlPtr = '\0'; // terminate the url
356 //----------------------------------------------------------------------------
357 // scheme fu
358 //----------------------------------------------------------------------------
360 static bool net_IsValidSchemeChar(const char aChar) {
361 return mozilla::net::rust_net_is_valid_scheme_char(aChar);
364 /* Extract URI-Scheme if possible */
365 nsresult net_ExtractURLScheme(const nsACString& inURI, nsACString& scheme) {
366 nsACString::const_iterator start, end;
367 inURI.BeginReading(start);
368 inURI.EndReading(end);
370 // Strip C0 and space from begining
371 while (start != end) {
372 if ((uint8_t)*start > 0x20) {
373 break;
375 start++;
378 Tokenizer p(Substring(start, end), "\r\n\t");
379 p.Record();
380 if (!p.CheckChar(IsAsciiAlpha)) {
381 // First char must be alpha
382 return NS_ERROR_MALFORMED_URI;
385 while (p.CheckChar(net_IsValidSchemeChar) || p.CheckWhite()) {
386 // Skip valid scheme characters or \r\n\t
389 if (!p.CheckChar(':')) {
390 return NS_ERROR_MALFORMED_URI;
393 p.Claim(scheme);
394 scheme.StripTaggedASCII(ASCIIMask::MaskCRLFTab());
395 ToLowerCase(scheme);
396 return NS_OK;
399 bool net_IsValidScheme(const nsACString& scheme) {
400 return mozilla::net::rust_net_is_valid_scheme(&scheme);
403 bool net_IsAbsoluteURL(const nsACString& uri) {
404 nsACString::const_iterator start, end;
405 uri.BeginReading(start);
406 uri.EndReading(end);
408 // Strip C0 and space from begining
409 while (start != end) {
410 if ((uint8_t)*start > 0x20) {
411 break;
413 start++;
416 Tokenizer p(Substring(start, end), "\r\n\t");
418 // First char must be alpha
419 if (!p.CheckChar(IsAsciiAlpha)) {
420 return false;
423 while (p.CheckChar(net_IsValidSchemeChar) || p.CheckWhite()) {
424 // Skip valid scheme characters or \r\n\t
426 if (!p.CheckChar(':')) {
427 return false;
429 p.SkipWhites();
431 if (!p.CheckChar('/')) {
432 return false;
434 p.SkipWhites();
436 if (p.CheckChar('/')) {
437 // aSpec is really absolute. Ignore aBaseURI in this case
438 return true;
440 return false;
443 void net_FilterURIString(const nsACString& input, nsACString& result) {
444 result.Truncate();
446 const auto* start = input.BeginReading();
447 const auto* end = input.EndReading();
449 // Trim off leading and trailing invalid chars.
450 auto charFilter = [](char c) { return static_cast<uint8_t>(c) > 0x20; };
451 const auto* newStart = std::find_if(start, end, charFilter);
452 const auto* newEnd =
453 std::find_if(std::reverse_iterator<decltype(end)>(end),
454 std::reverse_iterator<decltype(newStart)>(newStart),
455 charFilter)
456 .base();
458 // Check if chars need to be stripped.
459 bool needsStrip = false;
460 const ASCIIMaskArray& mask = ASCIIMask::MaskCRLFTab();
461 for (const auto* itr = start; itr != end; ++itr) {
462 if (ASCIIMask::IsMasked(mask, *itr)) {
463 needsStrip = true;
464 break;
468 // Just use the passed in string rather than creating new copies if no
469 // changes are necessary.
470 if (newStart == start && newEnd == end && !needsStrip) {
471 result = input;
472 return;
475 result.Assign(Substring(newStart, newEnd));
476 if (needsStrip) {
477 result.StripTaggedASCII(mask);
481 nsresult net_FilterAndEscapeURI(const nsACString& aInput, uint32_t aFlags,
482 const ASCIIMaskArray& aFilterMask,
483 nsACString& aResult) {
484 aResult.Truncate();
486 const auto* start = aInput.BeginReading();
487 const auto* end = aInput.EndReading();
489 // Trim off leading and trailing invalid chars.
490 auto charFilter = [](char c) { return static_cast<uint8_t>(c) > 0x20; };
491 const auto* newStart = std::find_if(start, end, charFilter);
492 const auto* newEnd =
493 std::find_if(std::reverse_iterator<decltype(end)>(end),
494 std::reverse_iterator<decltype(newStart)>(newStart),
495 charFilter)
496 .base();
498 return NS_EscapeAndFilterURL(Substring(newStart, newEnd), aFlags,
499 &aFilterMask, aResult, fallible);
502 #if defined(XP_WIN)
503 bool net_NormalizeFileURL(const nsACString& aURL, nsCString& aResultBuf) {
504 bool writing = false;
506 nsACString::const_iterator beginIter, endIter;
507 aURL.BeginReading(beginIter);
508 aURL.EndReading(endIter);
510 const char *s, *begin = beginIter.get();
512 for (s = begin; s != endIter.get(); ++s) {
513 if (*s == '\\') {
514 writing = true;
515 if (s > begin) aResultBuf.Append(begin, s - begin);
516 aResultBuf += '/';
517 begin = s + 1;
520 if (writing && s > begin) aResultBuf.Append(begin, s - begin);
522 return writing;
524 #endif
526 //----------------------------------------------------------------------------
527 // miscellaneous (i.e., stuff that should really be elsewhere)
528 //----------------------------------------------------------------------------
530 static inline void ToLower(char& c) {
531 if ((unsigned)(c - 'A') <= (unsigned)('Z' - 'A')) c += 'a' - 'A';
534 void net_ToLowerCase(char* str, uint32_t length) {
535 for (char* end = str + length; str < end; ++str) ToLower(*str);
538 void net_ToLowerCase(char* str) {
539 for (; *str; ++str) ToLower(*str);
542 char* net_FindCharInSet(const char* iter, const char* stop, const char* set) {
543 for (; iter != stop && *iter; ++iter) {
544 for (const char* s = set; *s; ++s) {
545 if (*iter == *s) return (char*)iter;
548 return (char*)iter;
551 char* net_FindCharNotInSet(const char* iter, const char* stop,
552 const char* set) {
553 repeat:
554 for (const char* s = set; *s; ++s) {
555 if (*iter == *s) {
556 if (++iter == stop) break;
557 goto repeat;
560 return (char*)iter;
563 char* net_RFindCharNotInSet(const char* stop, const char* iter,
564 const char* set) {
565 --iter;
566 --stop;
568 if (iter == stop) return (char*)iter;
570 repeat:
571 for (const char* s = set; *s; ++s) {
572 if (*iter == *s) {
573 if (--iter == stop) break;
574 goto repeat;
577 return (char*)iter;
580 #define HTTP_LWS " \t"
582 // Return the index of the closing quote of the string, if any
583 static uint32_t net_FindStringEnd(const nsCString& flatStr,
584 uint32_t stringStart, char stringDelim) {
585 NS_ASSERTION(stringStart < flatStr.Length() &&
586 flatStr.CharAt(stringStart) == stringDelim &&
587 (stringDelim == '"' || stringDelim == '\''),
588 "Invalid stringStart");
590 const char set[] = {stringDelim, '\\', '\0'};
591 do {
592 // stringStart points to either the start quote or the last
593 // escaped char (the char following a '\\')
595 // Write to searchStart here, so that when we get back to the
596 // top of the loop right outside this one we search from the
597 // right place.
598 uint32_t stringEnd = flatStr.FindCharInSet(set, stringStart + 1);
599 if (stringEnd == uint32_t(kNotFound)) return flatStr.Length();
601 if (flatStr.CharAt(stringEnd) == '\\') {
602 // Hit a backslash-escaped char. Need to skip over it.
603 stringStart = stringEnd + 1;
604 if (stringStart == flatStr.Length()) return stringStart;
606 // Go back to looking for the next escape or the string end
607 continue;
610 return stringEnd;
612 } while (true);
614 MOZ_ASSERT_UNREACHABLE("How did we get here?");
615 return flatStr.Length();
618 static uint32_t net_FindMediaDelimiter(const nsCString& flatStr,
619 uint32_t searchStart, char delimiter) {
620 do {
621 // searchStart points to the spot from which we should start looking
622 // for the delimiter.
623 const char delimStr[] = {delimiter, '"', '\0'};
624 uint32_t curDelimPos = flatStr.FindCharInSet(delimStr, searchStart);
625 if (curDelimPos == uint32_t(kNotFound)) return flatStr.Length();
627 char ch = flatStr.CharAt(curDelimPos);
628 if (ch == delimiter) {
629 // Found delimiter
630 return curDelimPos;
633 // We hit the start of a quoted string. Look for its end.
634 searchStart = net_FindStringEnd(flatStr, curDelimPos, ch);
635 if (searchStart == flatStr.Length()) return searchStart;
637 ++searchStart;
639 // searchStart now points to the first char after the end of the
640 // string, so just go back to the top of the loop and look for
641 // |delimiter| again.
642 } while (true);
644 MOZ_ASSERT_UNREACHABLE("How did we get here?");
645 return flatStr.Length();
648 // aOffset should be added to aCharsetStart and aCharsetEnd if this
649 // function sets them.
650 static void net_ParseMediaType(const nsACString& aMediaTypeStr,
651 nsACString& aContentType,
652 nsACString& aContentCharset, int32_t aOffset,
653 bool* aHadCharset, int32_t* aCharsetStart,
654 int32_t* aCharsetEnd, bool aStrict) {
655 const nsCString& flatStr = PromiseFlatCString(aMediaTypeStr);
656 const char* start = flatStr.get();
657 const char* end = start + flatStr.Length();
659 // Trim LWS leading and trailing whitespace from type. We include '(' in
660 // the trailing trim set to catch media-type comments, which are not at all
661 // standard, but may occur in rare cases.
662 const char* type = net_FindCharNotInSet(start, end, HTTP_LWS);
663 const char* typeEnd = net_FindCharInSet(type, end, HTTP_LWS ";(");
665 const char* charset = "";
666 const char* charsetEnd = charset;
667 int32_t charsetParamStart = 0;
668 int32_t charsetParamEnd = 0;
670 uint32_t consumed = typeEnd - type;
672 // Iterate over parameters
673 bool typeHasCharset = false;
674 uint32_t paramStart = flatStr.FindChar(';', typeEnd - start);
675 if (paramStart != uint32_t(kNotFound)) {
676 // We have parameters. Iterate over them.
677 uint32_t curParamStart = paramStart + 1;
678 do {
679 uint32_t curParamEnd =
680 net_FindMediaDelimiter(flatStr, curParamStart, ';');
682 const char* paramName = net_FindCharNotInSet(
683 start + curParamStart, start + curParamEnd, HTTP_LWS);
684 static const char charsetStr[] = "charset=";
685 if (nsCRT::strncasecmp(paramName, charsetStr, sizeof(charsetStr) - 1) ==
686 0) {
687 charset = paramName + sizeof(charsetStr) - 1;
688 charsetEnd = start + curParamEnd;
689 typeHasCharset = true;
690 charsetParamStart = curParamStart - 1;
691 charsetParamEnd = curParamEnd;
694 consumed = curParamEnd;
695 curParamStart = curParamEnd + 1;
696 } while (curParamStart < flatStr.Length());
699 bool charsetNeedsQuotedStringUnescaping = false;
700 if (typeHasCharset) {
701 // Trim LWS leading and trailing whitespace from charset. We include
702 // '(' in the trailing trim set to catch media-type comments, which are
703 // not at all standard, but may occur in rare cases.
704 charset = net_FindCharNotInSet(charset, charsetEnd, HTTP_LWS);
705 if (*charset == '"') {
706 charsetNeedsQuotedStringUnescaping = true;
707 charsetEnd =
708 start + net_FindStringEnd(flatStr, charset - start, *charset);
709 charset++;
710 NS_ASSERTION(charsetEnd >= charset, "Bad charset parsing");
711 } else {
712 charsetEnd = net_FindCharInSet(charset, charsetEnd, HTTP_LWS ";(");
716 // if the server sent "*/*", it is meaningless, so do not store it.
717 // also, if type is the same as aContentType, then just update the
718 // charset. however, if charset is empty and aContentType hasn't
719 // changed, then don't wipe-out an existing aContentCharset. We
720 // also want to reject a mime-type if it does not include a slash.
721 // some servers give junk after the charset parameter, which may
722 // include a comma, so this check makes us a bit more tolerant.
724 if (type != typeEnd && memchr(type, '/', typeEnd - type) != nullptr &&
725 (aStrict ? (net_FindCharNotInSet(start + consumed, end, HTTP_LWS) == end)
726 : (strncmp(type, "*/*", typeEnd - type) != 0))) {
727 // Common case here is that aContentType is empty
728 bool eq = !aContentType.IsEmpty() &&
729 aContentType.Equals(Substring(type, typeEnd),
730 nsCaseInsensitiveCStringComparator);
731 if (!eq) {
732 aContentType.Assign(type, typeEnd - type);
733 ToLowerCase(aContentType);
736 if ((!eq && *aHadCharset) || typeHasCharset) {
737 *aHadCharset = true;
738 if (charsetNeedsQuotedStringUnescaping) {
739 // parameters using the "quoted-string" syntax need
740 // backslash-escapes to be unescaped (see RFC 2616 Section 2.2)
741 aContentCharset.Truncate();
742 for (const char* c = charset; c != charsetEnd; c++) {
743 if (*c == '\\' && c + 1 != charsetEnd) {
744 // eat escape
745 c++;
747 aContentCharset.Append(*c);
749 } else {
750 aContentCharset.Assign(charset, charsetEnd - charset);
752 if (typeHasCharset) {
753 *aCharsetStart = charsetParamStart + aOffset;
754 *aCharsetEnd = charsetParamEnd + aOffset;
757 // Only set a new charset position if this is a different type
758 // from the last one we had and it doesn't already have a
759 // charset param. If this is the same type, we probably want
760 // to leave the charset position on its first occurrence.
761 if (!eq && !typeHasCharset) {
762 int32_t charsetStart = int32_t(paramStart);
763 if (charsetStart == kNotFound) charsetStart = flatStr.Length();
765 *aCharsetEnd = *aCharsetStart = charsetStart + aOffset;
770 #undef HTTP_LWS
772 void net_ParseContentType(const nsACString& aHeaderStr,
773 nsACString& aContentType, nsACString& aContentCharset,
774 bool* aHadCharset) {
775 int32_t dummy1, dummy2;
776 net_ParseContentType(aHeaderStr, aContentType, aContentCharset, aHadCharset,
777 &dummy1, &dummy2);
780 void net_ParseContentType(const nsACString& aHeaderStr,
781 nsACString& aContentType, nsACString& aContentCharset,
782 bool* aHadCharset, int32_t* aCharsetStart,
783 int32_t* aCharsetEnd) {
785 // Augmented BNF (from RFC 2616 section 3.7):
787 // header-value = media-type *( LWS "," LWS media-type )
788 // media-type = type "/" subtype *( LWS ";" LWS parameter )
789 // type = token
790 // subtype = token
791 // parameter = attribute "=" value
792 // attribute = token
793 // value = token | quoted-string
796 // Examples:
798 // text/html
799 // text/html, text/html
800 // text/html,text/html; charset=ISO-8859-1
801 // text/html,text/html; charset="ISO-8859-1"
802 // text/html;charset=ISO-8859-1, text/html
803 // text/html;charset='ISO-8859-1', text/html
804 // application/octet-stream
807 *aHadCharset = false;
808 const nsCString& flatStr = PromiseFlatCString(aHeaderStr);
810 // iterate over media-types. Note that ',' characters can happen
811 // inside quoted strings, so we need to watch out for that.
812 uint32_t curTypeStart = 0;
813 do {
814 // curTypeStart points to the start of the current media-type. We want
815 // to look for its end.
816 uint32_t curTypeEnd = net_FindMediaDelimiter(flatStr, curTypeStart, ',');
818 // At this point curTypeEnd points to the spot where the media-type
819 // starting at curTypeEnd ends. Time to parse that!
820 net_ParseMediaType(
821 Substring(flatStr, curTypeStart, curTypeEnd - curTypeStart),
822 aContentType, aContentCharset, curTypeStart, aHadCharset, aCharsetStart,
823 aCharsetEnd, false);
825 // And let's move on to the next media-type
826 curTypeStart = curTypeEnd + 1;
827 } while (curTypeStart < flatStr.Length());
830 void net_ParseRequestContentType(const nsACString& aHeaderStr,
831 nsACString& aContentType,
832 nsACString& aContentCharset,
833 bool* aHadCharset) {
835 // Augmented BNF (from RFC 7231 section 3.1.1.1):
837 // media-type = type "/" subtype *( OWS ";" OWS parameter )
838 // type = token
839 // subtype = token
840 // parameter = token "=" ( token / quoted-string )
842 // Examples:
844 // text/html
845 // text/html; charset=ISO-8859-1
846 // text/html; charset="ISO-8859-1"
847 // application/octet-stream
850 aContentType.Truncate();
851 aContentCharset.Truncate();
852 *aHadCharset = false;
853 const nsCString& flatStr = PromiseFlatCString(aHeaderStr);
855 // At this point curTypeEnd points to the spot where the media-type
856 // starting at curTypeEnd ends. Time to parse that!
857 nsAutoCString contentType, contentCharset;
858 bool hadCharset = false;
859 int32_t dummy1, dummy2;
860 uint32_t typeEnd = net_FindMediaDelimiter(flatStr, 0, ',');
861 if (typeEnd != flatStr.Length()) {
862 // We have some stuff left at the end, so this is not a valid
863 // request Content-Type header.
864 return;
866 net_ParseMediaType(flatStr, contentType, contentCharset, 0, &hadCharset,
867 &dummy1, &dummy2, true);
869 aContentType = contentType;
870 aContentCharset = contentCharset;
871 *aHadCharset = hadCharset;
874 bool net_IsValidHostName(const nsACString& host) {
875 // The host name is limited to 253 ascii characters.
876 if (host.Length() > 253) {
877 return false;
880 const char* end = host.EndReading();
881 // Use explicit whitelists to select which characters we are
882 // willing to send to lower-level DNS logic. This is more
883 // self-documenting, and can also be slightly faster than the
884 // blacklist approach, since DNS names are the common case, and
885 // the commonest characters will tend to be near the start of
886 // the list.
888 // Whitelist for DNS names (RFC 1035) with extra characters added
889 // for pragmatic reasons "$+_"
890 // see https://bugzilla.mozilla.org/show_bug.cgi?id=355181#c2
891 if (net_FindCharNotInSet(host.BeginReading(), end,
892 "abcdefghijklmnopqrstuvwxyz"
893 ".-0123456789"
894 "ABCDEFGHIJKLMNOPQRSTUVWXYZ$+_") == end) {
895 return true;
898 // Might be a valid IPv6 link-local address containing a percent sign
899 return mozilla::net::HostIsIPLiteral(host);
902 bool net_IsValidIPv4Addr(const nsACString& aAddr) {
903 return mozilla::net::rust_net_is_valid_ipv4_addr(&aAddr);
906 bool net_IsValidIPv6Addr(const nsACString& aAddr) {
907 return mozilla::net::rust_net_is_valid_ipv6_addr(&aAddr);
910 bool net_GetDefaultStatusTextForCode(uint16_t aCode, nsACString& aOutText) {
911 switch (aCode) {
912 // start with the most common
913 case 200:
914 aOutText.AssignLiteral("OK");
915 break;
916 case 404:
917 aOutText.AssignLiteral("Not Found");
918 break;
919 case 301:
920 aOutText.AssignLiteral("Moved Permanently");
921 break;
922 case 304:
923 aOutText.AssignLiteral("Not Modified");
924 break;
925 case 307:
926 aOutText.AssignLiteral("Temporary Redirect");
927 break;
928 case 500:
929 aOutText.AssignLiteral("Internal Server Error");
930 break;
932 // also well known
933 case 100:
934 aOutText.AssignLiteral("Continue");
935 break;
936 case 101:
937 aOutText.AssignLiteral("Switching Protocols");
938 break;
939 case 201:
940 aOutText.AssignLiteral("Created");
941 break;
942 case 202:
943 aOutText.AssignLiteral("Accepted");
944 break;
945 case 203:
946 aOutText.AssignLiteral("Non Authoritative");
947 break;
948 case 204:
949 aOutText.AssignLiteral("No Content");
950 break;
951 case 205:
952 aOutText.AssignLiteral("Reset Content");
953 break;
954 case 206:
955 aOutText.AssignLiteral("Partial Content");
956 break;
957 case 207:
958 aOutText.AssignLiteral("Multi-Status");
959 break;
960 case 208:
961 aOutText.AssignLiteral("Already Reported");
962 break;
963 case 300:
964 aOutText.AssignLiteral("Multiple Choices");
965 break;
966 case 302:
967 aOutText.AssignLiteral("Found");
968 break;
969 case 303:
970 aOutText.AssignLiteral("See Other");
971 break;
972 case 305:
973 aOutText.AssignLiteral("Use Proxy");
974 break;
975 case 308:
976 aOutText.AssignLiteral("Permanent Redirect");
977 break;
978 case 400:
979 aOutText.AssignLiteral("Bad Request");
980 break;
981 case 401:
982 aOutText.AssignLiteral("Unauthorized");
983 break;
984 case 402:
985 aOutText.AssignLiteral("Payment Required");
986 break;
987 case 403:
988 aOutText.AssignLiteral("Forbidden");
989 break;
990 case 405:
991 aOutText.AssignLiteral("Method Not Allowed");
992 break;
993 case 406:
994 aOutText.AssignLiteral("Not Acceptable");
995 break;
996 case 407:
997 aOutText.AssignLiteral("Proxy Authentication Required");
998 break;
999 case 408:
1000 aOutText.AssignLiteral("Request Timeout");
1001 break;
1002 case 409:
1003 aOutText.AssignLiteral("Conflict");
1004 break;
1005 case 410:
1006 aOutText.AssignLiteral("Gone");
1007 break;
1008 case 411:
1009 aOutText.AssignLiteral("Length Required");
1010 break;
1011 case 412:
1012 aOutText.AssignLiteral("Precondition Failed");
1013 break;
1014 case 413:
1015 aOutText.AssignLiteral("Request Entity Too Large");
1016 break;
1017 case 414:
1018 aOutText.AssignLiteral("Request URI Too Long");
1019 break;
1020 case 415:
1021 aOutText.AssignLiteral("Unsupported Media Type");
1022 break;
1023 case 416:
1024 aOutText.AssignLiteral("Requested Range Not Satisfiable");
1025 break;
1026 case 417:
1027 aOutText.AssignLiteral("Expectation Failed");
1028 break;
1029 case 418:
1030 aOutText.AssignLiteral("I'm a teapot");
1031 break;
1032 case 421:
1033 aOutText.AssignLiteral("Misdirected Request");
1034 break;
1035 case 422:
1036 aOutText.AssignLiteral("Unprocessable Entity");
1037 break;
1038 case 423:
1039 aOutText.AssignLiteral("Locked");
1040 break;
1041 case 424:
1042 aOutText.AssignLiteral("Failed Dependency");
1043 break;
1044 case 425:
1045 aOutText.AssignLiteral("Too Early");
1046 break;
1047 case 426:
1048 aOutText.AssignLiteral("Upgrade Required");
1049 break;
1050 case 428:
1051 aOutText.AssignLiteral("Precondition Required");
1052 break;
1053 case 429:
1054 aOutText.AssignLiteral("Too Many Requests");
1055 break;
1056 case 431:
1057 aOutText.AssignLiteral("Request Header Fields Too Large");
1058 break;
1059 case 451:
1060 aOutText.AssignLiteral("Unavailable For Legal Reasons");
1061 break;
1062 case 501:
1063 aOutText.AssignLiteral("Not Implemented");
1064 break;
1065 case 502:
1066 aOutText.AssignLiteral("Bad Gateway");
1067 break;
1068 case 503:
1069 aOutText.AssignLiteral("Service Unavailable");
1070 break;
1071 case 504:
1072 aOutText.AssignLiteral("Gateway Timeout");
1073 break;
1074 case 505:
1075 aOutText.AssignLiteral("HTTP Version Unsupported");
1076 break;
1077 case 506:
1078 aOutText.AssignLiteral("Variant Also Negotiates");
1079 break;
1080 case 507:
1081 aOutText.AssignLiteral("Insufficient Storage ");
1082 break;
1083 case 508:
1084 aOutText.AssignLiteral("Loop Detected");
1085 break;
1086 case 510:
1087 aOutText.AssignLiteral("Not Extended");
1088 break;
1089 case 511:
1090 aOutText.AssignLiteral("Network Authentication Required");
1091 break;
1092 default:
1093 aOutText.AssignLiteral("No Reason Phrase");
1094 return false;
1096 return true;
1099 namespace mozilla {
1100 static auto MakeNameMatcher(const nsAString& aName) {
1101 return [&aName](const auto& param) { return param.mKey.Equals(aName); };
1104 bool URLParams::Has(const nsAString& aName) {
1105 return std::any_of(mParams.cbegin(), mParams.cend(), MakeNameMatcher(aName));
1108 bool URLParams::Has(const nsAString& aName, const nsAString& aValue) {
1109 return std::any_of(
1110 mParams.cbegin(), mParams.cend(), [&aName, &aValue](const auto& param) {
1111 return param.mKey.Equals(aName) && param.mValue.Equals(aValue);
1115 void URLParams::Get(const nsAString& aName, nsString& aRetval) {
1116 SetDOMStringToNull(aRetval);
1118 const auto end = mParams.cend();
1119 const auto it = std::find_if(mParams.cbegin(), end, MakeNameMatcher(aName));
1120 if (it != end) {
1121 aRetval.Assign(it->mValue);
1125 void URLParams::GetAll(const nsAString& aName, nsTArray<nsString>& aRetval) {
1126 aRetval.Clear();
1128 for (uint32_t i = 0, len = mParams.Length(); i < len; ++i) {
1129 if (mParams[i].mKey.Equals(aName)) {
1130 aRetval.AppendElement(mParams[i].mValue);
1135 void URLParams::Append(const nsAString& aName, const nsAString& aValue) {
1136 Param* param = mParams.AppendElement();
1137 param->mKey = aName;
1138 param->mValue = aValue;
1141 void URLParams::Set(const nsAString& aName, const nsAString& aValue) {
1142 Param* param = nullptr;
1143 for (uint32_t i = 0, len = mParams.Length(); i < len;) {
1144 if (!mParams[i].mKey.Equals(aName)) {
1145 ++i;
1146 continue;
1148 if (!param) {
1149 param = &mParams[i];
1150 ++i;
1151 continue;
1153 // Remove duplicates.
1154 mParams.RemoveElementAt(i);
1155 --len;
1158 if (!param) {
1159 param = mParams.AppendElement();
1160 param->mKey = aName;
1163 param->mValue = aValue;
1166 void URLParams::Delete(const nsAString& aName) {
1167 mParams.RemoveElementsBy(
1168 [&aName](const auto& param) { return param.mKey.Equals(aName); });
1171 void URLParams::Delete(const nsAString& aName, const nsAString& aValue) {
1172 mParams.RemoveElementsBy([&aName, &aValue](const auto& param) {
1173 return param.mKey.Equals(aName) && param.mValue.Equals(aValue);
1177 /* static */
1178 void URLParams::ConvertString(const nsACString& aInput, nsAString& aOutput) {
1179 if (NS_FAILED(UTF_8_ENCODING->DecodeWithoutBOMHandling(aInput, aOutput))) {
1180 MOZ_CRASH("Out of memory when converting URL params.");
1184 /* static */
1185 void URLParams::DecodeString(const nsACString& aInput, nsAString& aOutput) {
1186 const char* const end = aInput.EndReading();
1188 nsAutoCString unescaped;
1190 for (const char* iter = aInput.BeginReading(); iter != end;) {
1191 // replace '+' with U+0020
1192 if (*iter == '+') {
1193 unescaped.Append(' ');
1194 ++iter;
1195 continue;
1198 // Percent decode algorithm
1199 if (*iter == '%') {
1200 const char* const first = iter + 1;
1201 const char* const second = first + 1;
1203 const auto asciiHexDigit = [](char x) {
1204 return (x >= 0x41 && x <= 0x46) || (x >= 0x61 && x <= 0x66) ||
1205 (x >= 0x30 && x <= 0x39);
1208 const auto hexDigit = [](char x) {
1209 return x >= 0x30 && x <= 0x39
1210 ? x - 0x30
1211 : (x >= 0x41 && x <= 0x46 ? x - 0x37 : x - 0x57);
1214 if (first != end && second != end && asciiHexDigit(*first) &&
1215 asciiHexDigit(*second)) {
1216 unescaped.Append(hexDigit(*first) * 16 + hexDigit(*second));
1217 iter = second + 1;
1218 } else {
1219 unescaped.Append('%');
1220 ++iter;
1223 continue;
1226 unescaped.Append(*iter);
1227 ++iter;
1230 // XXX It seems rather wasteful to first decode into a UTF-8 nsCString and
1231 // then convert the whole string to UTF-16, at least if we exceed the inline
1232 // storage size.
1233 ConvertString(unescaped, aOutput);
1236 /* static */
1237 bool URLParams::ParseNextInternal(const char*& aStart, const char* const aEnd,
1238 nsAString* aOutDecodedName,
1239 nsAString* aOutDecodedValue) {
1240 nsDependentCSubstring string;
1242 const char* const iter = std::find(aStart, aEnd, '&');
1243 if (iter != aEnd) {
1244 string.Rebind(aStart, iter);
1245 aStart = iter + 1;
1246 } else {
1247 string.Rebind(aStart, aEnd);
1248 aStart = aEnd;
1251 if (string.IsEmpty()) {
1252 return false;
1255 const auto* const eqStart = string.BeginReading();
1256 const auto* const eqEnd = string.EndReading();
1257 const auto* const eqIter = std::find(eqStart, eqEnd, '=');
1259 nsDependentCSubstring name;
1260 nsDependentCSubstring value;
1262 if (eqIter != eqEnd) {
1263 name.Rebind(eqStart, eqIter);
1264 value.Rebind(eqIter + 1, eqEnd);
1265 } else {
1266 name.Rebind(string, 0);
1269 DecodeString(name, *aOutDecodedName);
1270 DecodeString(value, *aOutDecodedValue);
1272 return true;
1275 /* static */
1276 bool URLParams::Extract(const nsACString& aInput, const nsAString& aName,
1277 nsAString& aValue) {
1278 aValue.SetIsVoid(true);
1279 return !URLParams::Parse(
1280 aInput, [&aName, &aValue](const nsAString& name, nsString&& value) {
1281 if (aName == name) {
1282 aValue = std::move(value);
1283 return false;
1285 return true;
1289 void URLParams::ParseInput(const nsACString& aInput) {
1290 // Remove all the existing data before parsing a new input.
1291 DeleteAll();
1293 URLParams::Parse(aInput, [this](nsString&& name, nsString&& value) {
1294 mParams.AppendElement(Param{std::move(name), std::move(value)});
1295 return true;
1299 namespace {
1301 void SerializeString(const nsCString& aInput, nsAString& aValue) {
1302 const unsigned char* p = (const unsigned char*)aInput.get();
1303 const unsigned char* end = p + aInput.Length();
1305 while (p != end) {
1306 // ' ' to '+'
1307 if (*p == 0x20) {
1308 aValue.Append(0x2B);
1309 // Percent Encode algorithm
1310 } else if (*p == 0x2A || *p == 0x2D || *p == 0x2E ||
1311 (*p >= 0x30 && *p <= 0x39) || (*p >= 0x41 && *p <= 0x5A) ||
1312 *p == 0x5F || (*p >= 0x61 && *p <= 0x7A)) {
1313 aValue.Append(*p);
1314 } else {
1315 aValue.AppendPrintf("%%%.2X", *p);
1318 ++p;
1322 } // namespace
1324 void URLParams::Serialize(nsAString& aValue, bool aEncode) const {
1325 aValue.Truncate();
1326 bool first = true;
1328 for (uint32_t i = 0, len = mParams.Length(); i < len; ++i) {
1329 if (first) {
1330 first = false;
1331 } else {
1332 aValue.Append('&');
1335 // XXX Actually, it's not necessary to build a new string object. Generally,
1336 // such cases could just convert each codepoint one-by-one.
1337 if (aEncode) {
1338 SerializeString(NS_ConvertUTF16toUTF8(mParams[i].mKey), aValue);
1339 aValue.Append('=');
1340 SerializeString(NS_ConvertUTF16toUTF8(mParams[i].mValue), aValue);
1341 } else {
1342 aValue.Append(mParams[i].mKey);
1343 aValue.Append('=');
1344 aValue.Append(mParams[i].mValue);
1349 void URLParams::Sort() {
1350 mParams.StableSort([](const Param& lhs, const Param& rhs) {
1351 return Compare(lhs.mKey, rhs.mKey);
1355 } // namespace mozilla