Unreviewed, reverting r260769.
[WebKit.git] / Source / WebCore / platform / MIMETypeRegistry.cpp
1 /*
2  * Copyright (C) 2006-2019 Apple Inc. All rights reserved.
3  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "MIMETypeRegistry.h"
29
30 #include "MediaPlayer.h"
31 #include "ThreadGlobalData.h"
32 #include <wtf/HashMap.h>
33 #include <wtf/MainThread.h>
34 #include <wtf/NeverDestroyed.h>
35 #include <wtf/StdLibExtras.h>
36
37 #if USE(CG)
38 #include "ImageSourceCG.h"
39 #include "UTIRegistry.h"
40 #include <ImageIO/ImageIO.h>
41 #include <wtf/RetainPtr.h>
42 #endif
43
44 #if USE(CG) && PLATFORM(COCOA)
45 #include "UTIUtilities.h"
46 #endif
47
48 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
49 #include "ArchiveFactory.h"
50 #endif
51
52 #if HAVE(AVASSETREADER)
53 #include "ContentType.h"
54 #include "ImageDecoderAVFObjC.h"
55 #endif
56
57 #if USE(QUICK_LOOK)
58 #include "PreviewConverter.h"
59 #endif
60
61 namespace WebCore {
62
63 const HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::supportedImageMIMETypes()
64 {
65     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> supportedImageMIMETypes = std::initializer_list<String> {
66 #if USE(CG)
67         // This represents the subset of allowed image UTIs for which CoreServices has a corresponding MIME type.
68         "image/tiff"_s,
69         "image/gif"_s,
70         "image/jpeg"_s,
71         "image/vnd.microsoft.icon"_s,
72         "image/jp2"_s,
73         "image/apng"_s,
74         "image/png"_s,
75         "image/bmp"_s,
76
77         "image/x-icon"_s, // Favicons don't have a MIME type in the registry either.
78         "image/pjpeg"_s, //  We only get one MIME type per UTI, hence our need to add these manually
79 #if HAVE(WEBP)
80         "image/webp"_s,
81 #endif
82 #if PLATFORM(IOS_FAMILY)
83         // Add malformed image mimetype for compatibility with Mail and to handle malformed mimetypes from the net
84         // These were removed for <rdar://problem/6564538> Re-enable UTI code in WebCore now that MobileCoreServices exists
85         // But Mail relies on at least image/tif reported as being supported (should be image/tiff).
86         // This can be removed when Mail addresses:
87         // <rdar://problem/7879510> Mail should use standard image mimetypes
88         // and we fix sniffing so that it corrects items such as image/jpg -> image/jpeg.
89
90         // JPEG (image/jpeg)
91         "image/jpg"_s,
92         "image/jp_"_s,
93         "image/jpe_"_s,
94         "application/jpg"_s,
95         "application/x-jpg"_s,
96         "image/pipeg"_s,
97         "image/vnd.switfview-jpeg"_s,
98         "image/x-xbitmap"_s,
99
100         // GIF (image/gif)
101         "image/gi_"_s,
102
103         // PNG (image/png)
104         "application/png"_s,
105         "application/x-png"_s,
106
107         // TIFF (image/tiff)
108         "image/x-tif"_s,
109         "image/tif"_s,
110         "image/x-tiff"_s,
111         "application/tif"_s,
112         "application/x-tif"_s,
113         "application/tiff"_s,
114         "application/x-tiff"_s,
115
116         // BMP (image/bmp, image/x-bitmap)
117         "image/x-bmp"_s,
118         "image/x-win-bitmap"_s,
119         "image/x-windows-bmp"_s,
120         "image/ms-bmp"_s,
121         "image/x-ms-bmp"_s,
122         "application/bmp"_s,
123         "application/x-bmp"_s,
124         "application/x-win-bitmap"_s,
125 #endif
126 #else
127         // assume that all implementations at least support the following standard
128         // image types:
129         "image/jpeg"_s,
130         "image/png"_s,
131         "image/gif"_s,
132         "image/bmp"_s,
133         "image/vnd.microsoft.icon"_s, // ico
134         "image/x-icon"_s, // ico
135         "image/x-xbitmap"_s, // xbm
136 #if ENABLE(APNG)
137         "image/apng"_s,
138 #endif
139 #if USE(OPENJPEG)
140         "image/jp2"_s,
141         "image/jpeg2000"_s,
142 #endif
143 #if USE(WEBP)
144         "image/webp"_s,
145 #endif
146 #endif
147     };
148
149 #if USE(CG)
150 #ifndef NDEBUG
151     // Esnure supportedImageMIMETypes() is in sync with defaultSupportedImageTypes().
152     static std::once_flag onceFlag;
153     std::call_once(onceFlag, [] {
154         for (auto& imageType : defaultSupportedImageTypes()) {
155             auto mimeType = MIMETypeForImageType(imageType);
156             ASSERT_IMPLIES(!mimeType.isEmpty(), supportedImageMIMETypes.get().contains(mimeType));
157         }
158     });
159 #endif
160 #endif
161     return supportedImageMIMETypes;
162 }
163
164 HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::additionalSupportedImageMIMETypes()
165 {
166     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> additionalSupportedImageMIMETypes;
167     return additionalSupportedImageMIMETypes;
168 }
169
170 static const HashSet<String, ASCIICaseInsensitiveHash>& supportedJavaScriptMIMETypes()
171 {
172     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> supportedJavaScriptMIMETypes = std::initializer_list<String> {
173         // https://html.spec.whatwg.org/multipage/scripting.html#javascript-mime-type
174         "text/javascript"_s,
175         "text/ecmascript"_s,
176         "application/javascript"_s,
177         "application/ecmascript"_s,
178         "application/x-javascript"_s,
179         "application/x-ecmascript"_s,
180         "text/javascript1.0"_s,
181         "text/javascript1.1"_s,
182         "text/javascript1.2"_s,
183         "text/javascript1.3"_s,
184         "text/javascript1.4"_s,
185         "text/javascript1.5"_s,
186         "text/jscript"_s,
187         "text/livescript"_s,
188         "text/x-javascript"_s,
189         "text/x-ecmascript"_s,
190     };
191     return supportedJavaScriptMIMETypes;
192 }
193
194 HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::supportedNonImageMIMETypes()
195 {
196     static auto supportedNonImageMIMETypes = makeNeverDestroyed([] {
197         HashSet<String, ASCIICaseInsensitiveHash> supportedNonImageMIMETypes = std::initializer_list<String> {
198             "text/html"_s,
199             "text/xml"_s,
200             "text/xsl"_s,
201             "text/plain"_s,
202             "text/"_s,
203             "application/xml"_s,
204             "application/xhtml+xml"_s,
205 #if !PLATFORM(IOS_FAMILY)
206             "application/vnd.wap.xhtml+xml"_s,
207             "application/rss+xml"_s,
208             "application/atom+xml"_s,
209 #endif
210             "application/json"_s,
211             "image/svg+xml"_s,
212 #if ENABLE(FTPDIR)
213             "application/x-ftp-directory"_s,
214 #endif
215             "multipart/x-mixed-replace"_s,
216         // Note: Adding a new type here will probably render it as HTML.
217         // This can result in cross-site scripting vulnerabilities.
218         };
219         supportedNonImageMIMETypes.add(supportedJavaScriptMIMETypes().begin(), supportedJavaScriptMIMETypes().end());
220 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
221         ArchiveFactory::registerKnownArchiveMIMETypes(supportedNonImageMIMETypes);
222 #endif
223         return supportedNonImageMIMETypes;
224     }());
225     return supportedNonImageMIMETypes;
226 }
227
228 const HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::supportedMediaMIMETypes()
229 {
230     static const auto supportedMediaMIMETypes = makeNeverDestroyed([] {
231         HashSet<String, ASCIICaseInsensitiveHash> supportedMediaMIMETypes;
232 #if ENABLE(VIDEO)
233         MediaPlayer::getSupportedTypes(supportedMediaMIMETypes);
234 #endif
235         return supportedMediaMIMETypes;
236     }());
237     return supportedMediaMIMETypes;
238 }
239
240 const HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::pdfMIMETypes()
241 {
242     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> pdfMIMETypes = std::initializer_list<String> {
243         "application/pdf"_s,
244         "text/pdf"_s,
245     };
246     return pdfMIMETypes;
247 }
248
249 const HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::unsupportedTextMIMETypes()
250 {
251     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> unsupportedTextMIMETypes = std::initializer_list<String> {
252         "text/calendar"_s,
253         "text/x-calendar"_s,
254         "text/x-vcalendar"_s,
255         "text/vcalendar"_s,
256         "text/vcard"_s,
257         "text/x-vcard"_s,
258         "text/directory"_s,
259         "text/ldif"_s,
260         "text/qif"_s,
261         "text/x-qif"_s,
262         "text/x-csv"_s,
263         "text/x-vcf"_s,
264 #if !PLATFORM(IOS_FAMILY)
265         "text/rtf"_s,
266 #else
267         "text/vnd.sun.j2me.app-descriptor"_s,
268 #endif
269     };
270     return unsupportedTextMIMETypes;
271 }
272
273 Optional<HashMap<String, Vector<String>, ASCIICaseInsensitiveHash>>& overriddenMimeTypesMap()
274 {
275     static NeverDestroyed<Optional<HashMap<String, Vector<String>, ASCIICaseInsensitiveHash>>> map;
276     return map;
277 }
278
279 const std::initializer_list<TypeExtensionPair>& commonMediaTypes()
280 {
281     // A table of common media MIME types and file extensions used when a platform's
282     // specific MIME type lookup doesn't have a match for a media file extension.
283     static std::initializer_list<TypeExtensionPair> commonMediaTypes = {
284         // Ogg
285         { "application/ogg"_s, "ogx"_s },
286         { "audio/ogg"_s, "ogg"_s },
287         { "audio/ogg"_s, "oga"_s },
288         { "video/ogg"_s, "ogv"_s },
289
290         // Annodex
291         { "application/annodex"_s, "anx"_s },
292         { "audio/annodex"_s, "axa"_s },
293         { "video/annodex"_s, "axv"_s },
294         { "audio/speex"_s, "spx"_s },
295
296         // WebM
297         { "video/webm"_s, "webm"_s },
298         { "audio/webm"_s, "webm"_s },
299
300         // MPEG
301         { "audio/mpeg"_s, "m1a"_s },
302         { "audio/mpeg"_s, "m2a"_s },
303         { "audio/mpeg"_s, "m1s"_s },
304         { "audio/mpeg"_s, "mpa"_s },
305         { "video/mpeg"_s, "mpg"_s },
306         { "video/mpeg"_s, "m15"_s },
307         { "video/mpeg"_s, "m1s"_s },
308         { "video/mpeg"_s, "m1v"_s },
309         { "video/mpeg"_s, "m75"_s },
310         { "video/mpeg"_s, "mpa"_s },
311         { "video/mpeg"_s, "mpeg"_s },
312         { "video/mpeg"_s, "mpm"_s },
313         { "video/mpeg"_s, "mpv"_s },
314
315         // MPEG playlist
316         { "application/vnd.apple.mpegurl"_s, "m3u8"_s },
317         { "application/mpegurl"_s, "m3u8"_s },
318         { "application/x-mpegurl"_s, "m3u8"_s },
319         { "audio/mpegurl"_s, "m3url"_s },
320         { "audio/x-mpegurl"_s, "m3url"_s },
321         { "audio/mpegurl"_s, "m3u"_s },
322         { "audio/x-mpegurl"_s, "m3u"_s },
323
324         // MPEG-4
325         { "video/x-m4v"_s, "m4v"_s },
326         { "audio/x-m4a"_s, "m4a"_s },
327         { "audio/x-m4b"_s, "m4b"_s },
328         { "audio/x-m4p"_s, "m4p"_s },
329         { "audio/mp4"_s, "m4a"_s },
330
331         // MP3
332         { "audio/mp3"_s, "mp3"_s },
333         { "audio/x-mp3"_s, "mp3"_s },
334         { "audio/x-mpeg"_s, "mp3"_s },
335
336         // MPEG-2
337         { "video/x-mpeg2"_s, "mp2"_s },
338         { "video/mpeg2"_s, "vob"_s },
339         { "video/mpeg2"_s, "mod"_s },
340         { "video/m2ts"_s, "m2ts"_s },
341         { "video/x-m2ts"_s, "m2t"_s },
342         { "video/x-m2ts"_s, "ts"_s },
343
344         // 3GP/3GP2
345         { "audio/3gpp"_s, "3gpp"_s },
346         { "audio/3gpp2"_s, "3g2"_s },
347         { "application/x-mpeg"_s, "amc"_s },
348
349         // AAC
350         { "audio/aac"_s, "aac"_s },
351         { "audio/aac"_s, "adts"_s },
352         { "audio/x-aac"_s, "m4r"_s },
353
354         // CoreAudio File
355         { "audio/x-caf"_s, "caf"_s },
356         { "audio/x-gsm"_s, "gsm"_s },
357
358         // ADPCM
359         { "audio/x-wav"_s, "wav"_s },
360         { "audio/vnd.wave"_s, "wav"_s },
361     };
362     return commonMediaTypes;
363 }
364
365 const HashMap<String, Vector<String>, ASCIICaseInsensitiveHash>& commonMimeTypesMap()
366 {
367     ASSERT(isMainThread());
368     static NeverDestroyed<HashMap<String, Vector<String>, ASCIICaseInsensitiveHash>> mimeTypesMap = [] {
369         HashMap<String, Vector<String>, ASCIICaseInsensitiveHash> map;
370         for (auto& pair : commonMediaTypes()) {
371             ASCIILiteral type = pair.type;
372             ASCIILiteral extension = pair.extension;
373             map.ensure(extension, [type, extension] {
374                 // First type in the vector must always be the one from getMIMETypeForExtension,
375                 // so we can use the map without also calling getMIMETypeForExtension each time.
376                 Vector<String> synonyms;
377                 String systemType = MIMETypeRegistry::getMIMETypeForExtension(extension);
378                 if (!systemType.isEmpty() && type != systemType)
379                     synonyms.append(systemType);
380                 return synonyms;
381             }).iterator->value.append(type);
382         }
383         return map;
384     }();
385     return mimeTypesMap;
386 }
387
388 static const Vector<String>* typesForCommonExtension(const String& extension)
389 {
390     if (overriddenMimeTypesMap().hasValue()) {
391         auto mapEntry = overriddenMimeTypesMap()->find(extension);
392         if (mapEntry == overriddenMimeTypesMap()->end())
393             return nullptr;
394         return &mapEntry->value;
395     }
396     auto mapEntry = commonMimeTypesMap().find(extension);
397     if (mapEntry == commonMimeTypesMap().end())
398         return nullptr;
399     return &mapEntry->value;
400 }
401
402 String MIMETypeRegistry::getMediaMIMETypeForExtension(const String& extension)
403 {
404     auto* vector = typesForCommonExtension(extension);
405     if (vector)
406         return (*vector)[0];
407     return getMIMETypeForExtension(extension);
408 }
409
410 Vector<String> MIMETypeRegistry::getMediaMIMETypesForExtension(const String& extension)
411 {
412     auto* vector = typesForCommonExtension(extension);
413     if (vector)
414         return *vector;
415     String type = getMIMETypeForExtension(extension);
416     if (!type.isNull())
417         return { { type } };
418     return { };
419 }
420
421 String MIMETypeRegistry::getMIMETypeForPath(const String& path)
422 {
423     size_t pos = path.reverseFind('.');
424     if (pos != notFound) {
425         String extension = path.substring(pos + 1);
426         String result = getMIMETypeForExtension(extension);
427         if (result.length())
428             return result;
429     }
430     return defaultMIMEType();
431 }
432
433 bool MIMETypeRegistry::isSupportedImageMIMEType(const String& mimeType)
434 {
435     if (mimeType.isEmpty())
436         return false;
437     String normalizedMIMEType = getNormalizedMIMEType(mimeType);
438     return supportedImageMIMETypes().contains(normalizedMIMEType) || additionalSupportedImageMIMETypes().contains(normalizedMIMEType);
439 }
440
441 bool MIMETypeRegistry::isSupportedImageVideoOrSVGMIMEType(const String& mimeType)
442 {
443     if (isSupportedImageMIMEType(mimeType) || equalLettersIgnoringASCIICase(mimeType, "image/svg+xml"))
444         return true;
445
446 #if HAVE(AVASSETREADER)
447     if (ImageDecoderAVFObjC::supportsContainerType(mimeType))
448         return true;
449 #endif
450
451     return false;
452 }
453
454 std::unique_ptr<MIMETypeRegistryThreadGlobalData> MIMETypeRegistry::createMIMETypeRegistryThreadGlobalData()
455 {
456 #if PLATFORM(COCOA)
457     RetainPtr<CFArrayRef> supportedTypes = adoptCF(CGImageDestinationCopyTypeIdentifiers());
458     HashSet<String, ASCIICaseInsensitiveHash> supportedImageMIMETypesForEncoding;
459     CFIndex count = CFArrayGetCount(supportedTypes.get());
460     for (CFIndex i = 0; i < count; i++) {
461         CFStringRef supportedType = reinterpret_cast<CFStringRef>(CFArrayGetValueAtIndex(supportedTypes.get(), i));
462         if (isSupportedImageType(supportedType)) {
463             String mimeType = MIMETypeForImageType(supportedType);
464             supportedImageMIMETypesForEncoding.add(mimeType);
465         }
466     }
467 #else
468     HashSet<String, ASCIICaseInsensitiveHash> supportedImageMIMETypesForEncoding = std::initializer_list<String> {
469 #if USE(CG) || USE(DIRECT2D)
470         // FIXME: Add Windows support for all the supported UTI's when a way to convert from MIMEType to UTI reliably is found.
471         // For now, only support PNG, JPEG and GIF. See <rdar://problem/6095286>.
472         "image/png"_s,
473         "image/jpeg"_s,
474         "image/gif"_s,
475 #elif PLATFORM(GTK)
476         "image/png"_s,
477         "image/jpeg"_s,
478         "image/tiff"_s,
479         "image/bmp"_s,
480         "image/ico"_s,
481 #elif USE(CAIRO)
482         "image/png"_s,
483 #endif
484     };
485 #endif
486     return makeUnique<MIMETypeRegistryThreadGlobalData>(WTFMove(supportedImageMIMETypesForEncoding));
487 }
488
489 bool MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(const String& mimeType)
490 {
491     if (mimeType.isEmpty())
492         return false;
493     return threadGlobalData().mimeTypeRegistryThreadGlobalData().supportedImageMIMETypesForEncoding().contains(mimeType);
494 }
495
496 bool MIMETypeRegistry::isSupportedJavaScriptMIMEType(const String& mimeType)
497 {
498     if (mimeType.isEmpty())
499         return false;
500
501     if (!isMainThread()) {
502         bool isSupported = false;
503         callOnMainThreadAndWait([&isSupported, mimeType = mimeType.isolatedCopy()] {
504             isSupported = isSupportedJavaScriptMIMEType(mimeType);
505         });
506         return isSupported;
507     }
508
509     return supportedJavaScriptMIMETypes().contains(mimeType);
510 }
511
512 bool MIMETypeRegistry::isSupportedStyleSheetMIMEType(const String& mimeType)
513 {
514     return equalLettersIgnoringASCIICase(mimeType, "text/css");
515 }
516
517 bool MIMETypeRegistry::isSupportedFontMIMEType(const String& mimeType)
518 {
519     static const unsigned fontLength = 5;
520     if (!startsWithLettersIgnoringASCIICase(mimeType, "font/"))
521         return false;
522     auto subtype = StringView { mimeType }.substring(fontLength);
523     return equalLettersIgnoringASCIICase(subtype, "woff")
524         || equalLettersIgnoringASCIICase(subtype, "woff2")
525         || equalLettersIgnoringASCIICase(subtype, "otf")
526         || equalLettersIgnoringASCIICase(subtype, "ttf")
527         || equalLettersIgnoringASCIICase(subtype, "sfnt");
528 }
529
530 bool MIMETypeRegistry::isTextMediaPlaylistMIMEType(const String& mimeType)
531 {
532     if (startsWithLettersIgnoringASCIICase(mimeType, "application/")) {
533         static const unsigned applicationLength = 12;
534         auto subtype = StringView { mimeType }.substring(applicationLength);
535         return equalLettersIgnoringASCIICase(subtype, "vnd.apple.mpegurl")
536             || equalLettersIgnoringASCIICase(subtype, "mpegurl")
537             || equalLettersIgnoringASCIICase(subtype, "x-mpegurl");
538     }
539
540     if (startsWithLettersIgnoringASCIICase(mimeType, "audio/")) {
541         static const unsigned audioLength = 6;
542         auto subtype = StringView { mimeType }.substring(audioLength);
543         return equalLettersIgnoringASCIICase(subtype, "mpegurl")
544             || equalLettersIgnoringASCIICase(subtype, "x-mpegurl");
545     }
546
547     return false;
548 }
549
550 bool MIMETypeRegistry::isSupportedJSONMIMEType(const String& mimeType)
551 {
552     if (mimeType.isEmpty())
553         return false;
554
555     if (equalLettersIgnoringASCIICase(mimeType, "application/json"))
556         return true;
557
558     // When detecting +json ensure there is a non-empty type / subtype preceeding the suffix.
559     if (mimeType.endsWithIgnoringASCIICase("+json") && mimeType.length() >= 8) {
560         size_t slashPosition = mimeType.find('/');
561         if (slashPosition != notFound && slashPosition > 0 && slashPosition <= mimeType.length() - 6)
562             return true;
563     }
564
565     return false;
566 }
567
568 bool MIMETypeRegistry::isSupportedNonImageMIMEType(const String& mimeType)
569 {
570     if (mimeType.isEmpty())
571         return false;
572     return supportedNonImageMIMETypes().contains(mimeType);
573 }
574
575 bool MIMETypeRegistry::isSupportedMediaMIMEType(const String& mimeType)
576 {
577     if (mimeType.isEmpty())
578         return false;
579     return supportedMediaMIMETypes().contains(mimeType);
580 }
581
582 bool MIMETypeRegistry::isSupportedTextTrackMIMEType(const String& mimeType)
583 {
584     return equalLettersIgnoringASCIICase(mimeType, "text/vtt");
585 }
586
587 bool MIMETypeRegistry::isUnsupportedTextMIMEType(const String& mimeType)
588 {
589     if (mimeType.isEmpty())
590         return false;
591     return unsupportedTextMIMETypes().contains(mimeType);
592 }
593
594 bool MIMETypeRegistry::isTextMIMEType(const String& mimeType)
595 {
596     return isSupportedJavaScriptMIMEType(mimeType)
597         || isSupportedJSONMIMEType(mimeType) // Render JSON as text/plain.
598         || (startsWithLettersIgnoringASCIICase(mimeType, "text/")
599             && !equalLettersIgnoringASCIICase(mimeType, "text/html")
600             && !equalLettersIgnoringASCIICase(mimeType, "text/xml")
601             && !equalLettersIgnoringASCIICase(mimeType, "text/xsl"));
602 }
603
604 static inline bool isValidXMLMIMETypeChar(UChar c)
605 {
606     // Valid characters per RFCs 3023 and 2045: 0-9a-zA-Z_-+~!$^{}|.%'`#&*
607     return isASCIIAlphanumeric(c) || c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' || c == '*' || c == '+'
608         || c == '-' || c == '.' || c == '^' || c == '_' || c == '`' || c == '{' || c == '|' || c == '}' || c == '~';
609 }
610
611 bool MIMETypeRegistry::isXMLMIMEType(const String& mimeType)
612 {
613     if (equalLettersIgnoringASCIICase(mimeType, "text/xml") || equalLettersIgnoringASCIICase(mimeType, "application/xml") || equalLettersIgnoringASCIICase(mimeType, "text/xsl"))
614         return true;
615
616     if (!mimeType.endsWithIgnoringASCIICase("+xml"))
617         return false;
618
619     size_t slashPosition = mimeType.find('/');
620     // Take into account the '+xml' ending of mimeType.
621     if (slashPosition == notFound || !slashPosition || slashPosition == mimeType.length() - 5)
622         return false;
623
624     // Again, mimeType ends with '+xml', no need to check the validity of that substring.
625     size_t mimeLength = mimeType.length();
626     for (size_t i = 0; i < mimeLength - 4; ++i) {
627         if (!isValidXMLMIMETypeChar(mimeType[i]) && i != slashPosition)
628             return false;
629     }
630
631     return true;
632 }
633
634 bool MIMETypeRegistry::isXMLEntityMIMEType(StringView mimeType)
635 {
636     return equalLettersIgnoringASCIICase(mimeType, "text/xml-external-parsed-entity")
637         || equalLettersIgnoringASCIICase(mimeType, "application/xml-external-parsed-entity");
638 }
639
640 bool MIMETypeRegistry::isJavaAppletMIMEType(const String& mimeType)
641 {
642     // Since this set is very limited and is likely to remain so we won't bother with the overhead
643     // of using a hash set.
644     // Any of the MIME types below may be followed by any number of specific versions of the JVM,
645     // which is why we use startsWith()
646     return startsWithLettersIgnoringASCIICase(mimeType, "application/x-java-applet")
647         || startsWithLettersIgnoringASCIICase(mimeType, "application/x-java-bean")
648         || startsWithLettersIgnoringASCIICase(mimeType, "application/x-java-vm");
649 }
650
651 bool MIMETypeRegistry::isPDFMIMEType(const String& mimeType)
652 {
653     if (mimeType.isEmpty())
654         return false;
655     return pdfMIMETypes().contains(mimeType);
656 }
657
658 bool MIMETypeRegistry::isPostScriptMIMEType(const String& mimeType)
659 {
660     return mimeType == "application/postscript";
661 }
662
663 bool MIMETypeRegistry::isPDFOrPostScriptMIMEType(const String& mimeType)
664 {
665     return isPDFMIMEType(mimeType) || isPostScriptMIMEType(mimeType);
666 }
667
668 bool MIMETypeRegistry::canShowMIMEType(const String& mimeType)
669 {
670     if (isSupportedImageMIMEType(mimeType) || isSupportedNonImageMIMEType(mimeType) || isSupportedMediaMIMEType(mimeType))
671         return true;
672
673     if (isSupportedJavaScriptMIMEType(mimeType) || isSupportedJSONMIMEType(mimeType))
674         return true;
675
676 #if USE(QUICK_LOOK)
677     if (PreviewConverter::supportsMIMEType(mimeType))
678         return true;
679 #endif
680
681     if (startsWithLettersIgnoringASCIICase(mimeType, "text/"))
682         return !isUnsupportedTextMIMEType(mimeType);
683
684     return false;
685 }
686
687 const String& defaultMIMEType()
688 {
689     static NeverDestroyed<const String> defaultMIMEType(MAKE_STATIC_STRING_IMPL("application/octet-stream"));
690     return defaultMIMEType;
691 }
692
693 const HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::systemPreviewMIMETypes()
694 {
695     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> systemPreviewMIMETypes = std::initializer_list<String> {
696         // The official type: https://www.iana.org/assignments/media-types/model/vnd.usdz+zip
697         "model/vnd.usdz+zip",
698         // Unofficial, but supported because we documented them.
699         "model/usd",
700         "model/vnd.pixar.usd",
701         // Reality files.
702         "model/vnd.reality"
703     };
704     return systemPreviewMIMETypes;
705 }
706
707 bool MIMETypeRegistry::isSystemPreviewMIMEType(const String& mimeType)
708 {
709     if (mimeType.isEmpty())
710         return false;
711     return systemPreviewMIMETypes().contains(mimeType);
712 }
713
714 #if !USE(CURL)
715
716 // FIXME: Not sure why it makes sense to have a cross-platform function when only CURL has the concept
717 // of a "normalized" MIME type.
718 String MIMETypeRegistry::getNormalizedMIMEType(const String& mimeType)
719 {
720     return mimeType;
721 }
722
723 #else
724
725 String MIMETypeRegistry::getNormalizedMIMEType(const String& mimeType)
726 {
727     static const auto mimeTypeAssociationMap = makeNeverDestroyed([] {
728         static const std::pair<ASCIILiteral, ASCIILiteral> mimeTypeAssociations[] = {
729             { "image/x-ms-bmp"_s, "image/bmp"_s },
730             { "image/x-windows-bmp"_s, "image/bmp"_s },
731             { "image/x-bmp"_s, "image/bmp"_s },
732             { "image/x-bitmap"_s, "image/bmp"_s },
733             { "image/x-ms-bitmap"_s, "image/bmp"_s },
734             { "image/jpg"_s, "image/jpeg"_s },
735             { "image/pjpeg"_s, "image/jpeg"_s },
736             { "image/x-png"_s, "image/png"_s },
737             { "image/vnd.rim.png"_s, "image/png"_s },
738             { "image/ico"_s, "image/vnd.microsoft.icon"_s },
739             { "image/icon"_s, "image/vnd.microsoft.icon"_s },
740             { "text/ico"_s, "image/vnd.microsoft.icon"_s },
741             { "application/ico"_s, "image/vnd.microsoft.icon"_s },
742             { "image/x-icon"_s, "image/vnd.microsoft.icon"_s },
743             { "audio/vnd.qcelp"_s, "audio/qcelp"_s },
744             { "audio/qcp"_s, "audio/qcelp"_s },
745             { "audio/vnd.qcp"_s, "audio/qcelp"_s },
746             { "audio/wav"_s, "audio/x-wav"_s },
747             { "audio/vnd.wave"_s, "audio/x-wav"_s },
748             { "audio/mid"_s, "audio/midi"_s },
749             { "audio/sp-midi"_s, "audio/midi"_s },
750             { "audio/x-mid"_s, "audio/midi"_s },
751             { "audio/x-midi"_s, "audio/midi"_s },
752             { "audio/x-mpeg"_s, "audio/mpeg"_s },
753             { "audio/mp3"_s, "audio/mpeg"_s },
754             { "audio/x-mp3"_s, "audio/mpeg"_s },
755             { "audio/mpeg3"_s, "audio/mpeg"_s },
756             { "audio/x-mpeg3"_s, "audio/mpeg"_s },
757             { "audio/mpg3"_s, "audio/mpeg"_s },
758             { "audio/mpg"_s, "audio/mpeg"_s },
759             { "audio/x-mpg"_s, "audio/mpeg"_s },
760             { "audio/m4a"_s, "audio/mp4"_s },
761             { "audio/x-m4a"_s, "audio/mp4"_s },
762             { "audio/x-mp4"_s, "audio/mp4"_s },
763             { "audio/x-aac"_s, "audio/aac"_s },
764             { "audio/x-amr"_s, "audio/amr"_s },
765             { "audio/mpegurl"_s, "audio/x-mpegurl"_s },
766             { "audio/flac"_s, "audio/x-flac"_s },
767             { "video/3gp"_s, "video/3gpp"_s },
768             { "video/avi"_s, "video/x-msvideo"_s },
769             { "video/x-m4v"_s, "video/mp4"_s },
770             { "video/x-quicktime"_s, "video/quicktime"_s },
771             { "application/java"_s, "application/java-archive"_s },
772             { "application/x-java-archive"_s, "application/java-archive"_s },
773             { "application/x-zip-compressed"_s, "application/zip"_s },
774             { "text/cache-manifest"_s, "text/plain"_s },
775         };
776
777         HashMap<String, String, ASCIICaseInsensitiveHash> map;
778         for (auto& pair : mimeTypeAssociations)
779             map.add(pair.first, pair.second);
780         return map;
781     }());
782
783     auto it = mimeTypeAssociationMap.get().find(mimeType);
784     if (it != mimeTypeAssociationMap.get().end())
785         return it->value;
786     return mimeType;
787 }
788
789 #endif
790
791 String MIMETypeRegistry::appendFileExtensionIfNecessary(const String& filename, const String& mimeType)
792 {
793     if (filename.isEmpty() || filename.contains('.') || equalIgnoringASCIICase(mimeType, defaultMIMEType()))
794         return filename;
795
796     auto preferredExtension = getPreferredExtensionForMIMEType(mimeType);
797     if (preferredExtension.isEmpty())
798         return filename;
799
800     return makeString(filename, '.', preferredExtension);
801 }
802
803 } // namespace WebCore