61fa05887474ddedaddd6cc2bdc45adef3f5f49d
[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 #if USE(APPLE_INTERNAL_SDK)
62 #include <WebKitAdditions/AdditionalSystemPreviewTypes.h>
63 #else
64 #define ADDITIONAL_SYSTEM_PREVIEW_TYPES
65 #endif
66
67 namespace WebCore {
68
69 const HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::supportedImageMIMETypes()
70 {
71     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> supportedImageMIMETypes = std::initializer_list<String> {
72 #if USE(CG)
73         // This represents the subset of allowed image UTIs for which CoreServices has a corresponding MIME type.
74         "image/tiff"_s,
75         "image/gif"_s,
76         "image/jpeg"_s,
77         "image/vnd.microsoft.icon"_s,
78         "image/jp2"_s,
79         "image/apng"_s,
80         "image/png"_s,
81         "image/bmp"_s,
82
83         "image/x-icon"_s, // Favicons don't have a MIME type in the registry either.
84         "image/pjpeg"_s, //  We only get one MIME type per UTI, hence our need to add these manually
85 #if HAVE(WEBP)
86         "image/webp"_s,
87 #endif
88 #if PLATFORM(IOS_FAMILY)
89         // Add malformed image mimetype for compatibility with Mail and to handle malformed mimetypes from the net
90         // These were removed for <rdar://problem/6564538> Re-enable UTI code in WebCore now that MobileCoreServices exists
91         // But Mail relies on at least image/tif reported as being supported (should be image/tiff).
92         // This can be removed when Mail addresses:
93         // <rdar://problem/7879510> Mail should use standard image mimetypes
94         // and we fix sniffing so that it corrects items such as image/jpg -> image/jpeg.
95
96         // JPEG (image/jpeg)
97         "image/jpg"_s,
98         "image/jp_"_s,
99         "image/jpe_"_s,
100         "application/jpg"_s,
101         "application/x-jpg"_s,
102         "image/pipeg"_s,
103         "image/vnd.switfview-jpeg"_s,
104         "image/x-xbitmap"_s,
105
106         // GIF (image/gif)
107         "image/gi_"_s,
108
109         // PNG (image/png)
110         "application/png"_s,
111         "application/x-png"_s,
112
113         // TIFF (image/tiff)
114         "image/x-tif"_s,
115         "image/tif"_s,
116         "image/x-tiff"_s,
117         "application/tif"_s,
118         "application/x-tif"_s,
119         "application/tiff"_s,
120         "application/x-tiff"_s,
121
122         // BMP (image/bmp, image/x-bitmap)
123         "image/x-bmp"_s,
124         "image/x-win-bitmap"_s,
125         "image/x-windows-bmp"_s,
126         "image/ms-bmp"_s,
127         "image/x-ms-bmp"_s,
128         "application/bmp"_s,
129         "application/x-bmp"_s,
130         "application/x-win-bitmap"_s,
131 #endif
132 #else
133         // assume that all implementations at least support the following standard
134         // image types:
135         "image/jpeg"_s,
136         "image/png"_s,
137         "image/gif"_s,
138         "image/bmp"_s,
139         "image/vnd.microsoft.icon"_s, // ico
140         "image/x-icon"_s, // ico
141         "image/x-xbitmap"_s, // xbm
142 #if ENABLE(APNG)
143         "image/apng"_s,
144 #endif
145 #if USE(OPENJPEG)
146         "image/jp2"_s,
147         "image/jpeg2000"_s,
148 #endif
149 #if USE(WEBP)
150         "image/webp"_s,
151 #endif
152 #endif
153     };
154
155 #if USE(CG)
156 #ifndef NDEBUG
157     // Esnure supportedImageMIMETypes() is in sync with defaultSupportedImageTypes().
158     static std::once_flag onceFlag;
159     std::call_once(onceFlag, [] {
160         for (auto& imageType : defaultSupportedImageTypes()) {
161             auto mimeType = MIMETypeForImageType(imageType);
162             ASSERT_IMPLIES(!mimeType.isEmpty(), supportedImageMIMETypes.get().contains(mimeType));
163         }
164     });
165 #endif
166 #endif
167     return supportedImageMIMETypes;
168 }
169
170 HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::additionalSupportedImageMIMETypes()
171 {
172     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> additionalSupportedImageMIMETypes;
173     return additionalSupportedImageMIMETypes;
174 }
175
176 static const HashSet<String, ASCIICaseInsensitiveHash>& supportedJavaScriptMIMETypes()
177 {
178     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> supportedJavaScriptMIMETypes = std::initializer_list<String> {
179         // https://html.spec.whatwg.org/multipage/scripting.html#javascript-mime-type
180         "text/javascript"_s,
181         "text/ecmascript"_s,
182         "application/javascript"_s,
183         "application/ecmascript"_s,
184         "application/x-javascript"_s,
185         "application/x-ecmascript"_s,
186         "text/javascript1.0"_s,
187         "text/javascript1.1"_s,
188         "text/javascript1.2"_s,
189         "text/javascript1.3"_s,
190         "text/javascript1.4"_s,
191         "text/javascript1.5"_s,
192         "text/jscript"_s,
193         "text/livescript"_s,
194         "text/x-javascript"_s,
195         "text/x-ecmascript"_s,
196     };
197     return supportedJavaScriptMIMETypes;
198 }
199
200 HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::supportedNonImageMIMETypes()
201 {
202     static auto supportedNonImageMIMETypes = makeNeverDestroyed([] {
203         HashSet<String, ASCIICaseInsensitiveHash> supportedNonImageMIMETypes = std::initializer_list<String> {
204             "text/html"_s,
205             "text/xml"_s,
206             "text/xsl"_s,
207             "text/plain"_s,
208             "text/"_s,
209             "application/xml"_s,
210             "application/xhtml+xml"_s,
211 #if !PLATFORM(IOS_FAMILY)
212             "application/vnd.wap.xhtml+xml"_s,
213             "application/rss+xml"_s,
214             "application/atom+xml"_s,
215 #endif
216             "application/json"_s,
217             "image/svg+xml"_s,
218 #if ENABLE(FTPDIR)
219             "application/x-ftp-directory"_s,
220 #endif
221             "multipart/x-mixed-replace"_s,
222         // Note: Adding a new type here will probably render it as HTML.
223         // This can result in cross-site scripting vulnerabilities.
224         };
225         supportedNonImageMIMETypes.add(supportedJavaScriptMIMETypes().begin(), supportedJavaScriptMIMETypes().end());
226 #if ENABLE(WEB_ARCHIVE) || ENABLE(MHTML)
227         ArchiveFactory::registerKnownArchiveMIMETypes(supportedNonImageMIMETypes);
228 #endif
229         return supportedNonImageMIMETypes;
230     }());
231     return supportedNonImageMIMETypes;
232 }
233
234 const HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::supportedMediaMIMETypes()
235 {
236     static const auto supportedMediaMIMETypes = makeNeverDestroyed([] {
237         HashSet<String, ASCIICaseInsensitiveHash> supportedMediaMIMETypes;
238 #if ENABLE(VIDEO)
239         MediaPlayer::getSupportedTypes(supportedMediaMIMETypes);
240 #endif
241         return supportedMediaMIMETypes;
242     }());
243     return supportedMediaMIMETypes;
244 }
245
246 const HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::pdfMIMETypes()
247 {
248     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> pdfMIMETypes = std::initializer_list<String> {
249         "application/pdf"_s,
250         "text/pdf"_s,
251     };
252     return pdfMIMETypes;
253 }
254
255 const HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::unsupportedTextMIMETypes()
256 {
257     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> unsupportedTextMIMETypes = std::initializer_list<String> {
258         "text/calendar"_s,
259         "text/x-calendar"_s,
260         "text/x-vcalendar"_s,
261         "text/vcalendar"_s,
262         "text/vcard"_s,
263         "text/x-vcard"_s,
264         "text/directory"_s,
265         "text/ldif"_s,
266         "text/qif"_s,
267         "text/x-qif"_s,
268         "text/x-csv"_s,
269         "text/x-vcf"_s,
270 #if !PLATFORM(IOS_FAMILY)
271         "text/rtf"_s,
272 #else
273         "text/vnd.sun.j2me.app-descriptor"_s,
274 #endif
275     };
276     return unsupportedTextMIMETypes;
277 }
278
279 Optional<HashMap<String, Vector<String>, ASCIICaseInsensitiveHash>>& overriddenMimeTypesMap()
280 {
281     static NeverDestroyed<Optional<HashMap<String, Vector<String>, ASCIICaseInsensitiveHash>>> map;
282     return map;
283 }
284
285 const std::initializer_list<TypeExtensionPair>& commonMediaTypes()
286 {
287     // A table of common media MIME types and file extensions used when a platform's
288     // specific MIME type lookup doesn't have a match for a media file extension.
289     static std::initializer_list<TypeExtensionPair> commonMediaTypes = {
290         // Ogg
291         { "application/ogg"_s, "ogx"_s },
292         { "audio/ogg"_s, "ogg"_s },
293         { "audio/ogg"_s, "oga"_s },
294         { "video/ogg"_s, "ogv"_s },
295
296         // Annodex
297         { "application/annodex"_s, "anx"_s },
298         { "audio/annodex"_s, "axa"_s },
299         { "video/annodex"_s, "axv"_s },
300         { "audio/speex"_s, "spx"_s },
301
302         // WebM
303         { "video/webm"_s, "webm"_s },
304         { "audio/webm"_s, "webm"_s },
305
306         // MPEG
307         { "audio/mpeg"_s, "m1a"_s },
308         { "audio/mpeg"_s, "m2a"_s },
309         { "audio/mpeg"_s, "m1s"_s },
310         { "audio/mpeg"_s, "mpa"_s },
311         { "video/mpeg"_s, "mpg"_s },
312         { "video/mpeg"_s, "m15"_s },
313         { "video/mpeg"_s, "m1s"_s },
314         { "video/mpeg"_s, "m1v"_s },
315         { "video/mpeg"_s, "m75"_s },
316         { "video/mpeg"_s, "mpa"_s },
317         { "video/mpeg"_s, "mpeg"_s },
318         { "video/mpeg"_s, "mpm"_s },
319         { "video/mpeg"_s, "mpv"_s },
320
321         // MPEG playlist
322         { "application/vnd.apple.mpegurl"_s, "m3u8"_s },
323         { "application/mpegurl"_s, "m3u8"_s },
324         { "application/x-mpegurl"_s, "m3u8"_s },
325         { "audio/mpegurl"_s, "m3url"_s },
326         { "audio/x-mpegurl"_s, "m3url"_s },
327         { "audio/mpegurl"_s, "m3u"_s },
328         { "audio/x-mpegurl"_s, "m3u"_s },
329
330         // MPEG-4
331         { "video/x-m4v"_s, "m4v"_s },
332         { "audio/x-m4a"_s, "m4a"_s },
333         { "audio/x-m4b"_s, "m4b"_s },
334         { "audio/x-m4p"_s, "m4p"_s },
335         { "audio/mp4"_s, "m4a"_s },
336
337         // MP3
338         { "audio/mp3"_s, "mp3"_s },
339         { "audio/x-mp3"_s, "mp3"_s },
340         { "audio/x-mpeg"_s, "mp3"_s },
341
342         // MPEG-2
343         { "video/x-mpeg2"_s, "mp2"_s },
344         { "video/mpeg2"_s, "vob"_s },
345         { "video/mpeg2"_s, "mod"_s },
346         { "video/m2ts"_s, "m2ts"_s },
347         { "video/x-m2ts"_s, "m2t"_s },
348         { "video/x-m2ts"_s, "ts"_s },
349
350         // 3GP/3GP2
351         { "audio/3gpp"_s, "3gpp"_s },
352         { "audio/3gpp2"_s, "3g2"_s },
353         { "application/x-mpeg"_s, "amc"_s },
354
355         // AAC
356         { "audio/aac"_s, "aac"_s },
357         { "audio/aac"_s, "adts"_s },
358         { "audio/x-aac"_s, "m4r"_s },
359
360         // CoreAudio File
361         { "audio/x-caf"_s, "caf"_s },
362         { "audio/x-gsm"_s, "gsm"_s },
363
364         // ADPCM
365         { "audio/x-wav"_s, "wav"_s },
366         { "audio/vnd.wave"_s, "wav"_s },
367     };
368     return commonMediaTypes;
369 }
370
371 const HashMap<String, Vector<String>, ASCIICaseInsensitiveHash>& commonMimeTypesMap()
372 {
373     ASSERT(isMainThread());
374     static NeverDestroyed<HashMap<String, Vector<String>, ASCIICaseInsensitiveHash>> mimeTypesMap = [] {
375         HashMap<String, Vector<String>, ASCIICaseInsensitiveHash> map;
376         for (auto& pair : commonMediaTypes()) {
377             ASCIILiteral type = pair.type;
378             ASCIILiteral extension = pair.extension;
379             map.ensure(extension, [type, extension] {
380                 // First type in the vector must always be the one from getMIMETypeForExtension,
381                 // so we can use the map without also calling getMIMETypeForExtension each time.
382                 Vector<String> synonyms;
383                 String systemType = MIMETypeRegistry::getMIMETypeForExtension(extension);
384                 if (!systemType.isEmpty() && type != systemType)
385                     synonyms.append(systemType);
386                 return synonyms;
387             }).iterator->value.append(type);
388         }
389         return map;
390     }();
391     return mimeTypesMap;
392 }
393
394 static const Vector<String>* typesForCommonExtension(const String& extension)
395 {
396     if (overriddenMimeTypesMap().hasValue()) {
397         auto mapEntry = overriddenMimeTypesMap()->find(extension);
398         if (mapEntry == overriddenMimeTypesMap()->end())
399             return nullptr;
400         return &mapEntry->value;
401     }
402     auto mapEntry = commonMimeTypesMap().find(extension);
403     if (mapEntry == commonMimeTypesMap().end())
404         return nullptr;
405     return &mapEntry->value;
406 }
407
408 String MIMETypeRegistry::getMediaMIMETypeForExtension(const String& extension)
409 {
410     auto* vector = typesForCommonExtension(extension);
411     if (vector)
412         return (*vector)[0];
413     return getMIMETypeForExtension(extension);
414 }
415
416 Vector<String> MIMETypeRegistry::getMediaMIMETypesForExtension(const String& extension)
417 {
418     auto* vector = typesForCommonExtension(extension);
419     if (vector)
420         return *vector;
421     String type = getMIMETypeForExtension(extension);
422     if (!type.isNull())
423         return { { type } };
424     return { };
425 }
426
427 String MIMETypeRegistry::getMIMETypeForPath(const String& path)
428 {
429     size_t pos = path.reverseFind('.');
430     if (pos != notFound) {
431         String extension = path.substring(pos + 1);
432         String result = getMIMETypeForExtension(extension);
433         if (result.length())
434             return result;
435     }
436     return defaultMIMEType();
437 }
438
439 bool MIMETypeRegistry::isSupportedImageMIMEType(const String& mimeType)
440 {
441     if (mimeType.isEmpty())
442         return false;
443     String normalizedMIMEType = getNormalizedMIMEType(mimeType);
444     return supportedImageMIMETypes().contains(normalizedMIMEType) || additionalSupportedImageMIMETypes().contains(normalizedMIMEType);
445 }
446
447 bool MIMETypeRegistry::isSupportedImageVideoOrSVGMIMEType(const String& mimeType)
448 {
449     if (isSupportedImageMIMEType(mimeType) || equalLettersIgnoringASCIICase(mimeType, "image/svg+xml"))
450         return true;
451
452 #if HAVE(AVASSETREADER)
453     if (ImageDecoderAVFObjC::supportsContainerType(mimeType))
454         return true;
455 #endif
456
457     return false;
458 }
459
460 std::unique_ptr<MIMETypeRegistryThreadGlobalData> MIMETypeRegistry::createMIMETypeRegistryThreadGlobalData()
461 {
462 #if PLATFORM(COCOA)
463     RetainPtr<CFArrayRef> supportedTypes = adoptCF(CGImageDestinationCopyTypeIdentifiers());
464     HashSet<String, ASCIICaseInsensitiveHash> supportedImageMIMETypesForEncoding;
465     CFIndex count = CFArrayGetCount(supportedTypes.get());
466     for (CFIndex i = 0; i < count; i++) {
467         CFStringRef supportedType = reinterpret_cast<CFStringRef>(CFArrayGetValueAtIndex(supportedTypes.get(), i));
468         if (isSupportedImageType(supportedType)) {
469             String mimeType = MIMETypeForImageType(supportedType);
470             supportedImageMIMETypesForEncoding.add(mimeType);
471         }
472     }
473 #else
474     HashSet<String, ASCIICaseInsensitiveHash> supportedImageMIMETypesForEncoding = std::initializer_list<String> {
475 #if USE(CG) || USE(DIRECT2D)
476         // FIXME: Add Windows support for all the supported UTI's when a way to convert from MIMEType to UTI reliably is found.
477         // For now, only support PNG, JPEG and GIF. See <rdar://problem/6095286>.
478         "image/png"_s,
479         "image/jpeg"_s,
480         "image/gif"_s,
481 #elif PLATFORM(GTK)
482         "image/png"_s,
483         "image/jpeg"_s,
484         "image/tiff"_s,
485         "image/bmp"_s,
486         "image/ico"_s,
487 #elif USE(CAIRO)
488         "image/png"_s,
489 #endif
490     };
491 #endif
492     return makeUnique<MIMETypeRegistryThreadGlobalData>(WTFMove(supportedImageMIMETypesForEncoding));
493 }
494
495 bool MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(const String& mimeType)
496 {
497     if (mimeType.isEmpty())
498         return false;
499     return threadGlobalData().mimeTypeRegistryThreadGlobalData().supportedImageMIMETypesForEncoding().contains(mimeType);
500 }
501
502 bool MIMETypeRegistry::isSupportedJavaScriptMIMEType(const String& mimeType)
503 {
504     if (mimeType.isEmpty())
505         return false;
506
507     if (!isMainThread()) {
508         bool isSupported = false;
509         callOnMainThreadAndWait([&isSupported, mimeType = mimeType.isolatedCopy()] {
510             isSupported = isSupportedJavaScriptMIMEType(mimeType);
511         });
512         return isSupported;
513     }
514
515     return supportedJavaScriptMIMETypes().contains(mimeType);
516 }
517
518 bool MIMETypeRegistry::isSupportedStyleSheetMIMEType(const String& mimeType)
519 {
520     return equalLettersIgnoringASCIICase(mimeType, "text/css");
521 }
522
523 bool MIMETypeRegistry::isSupportedFontMIMEType(const String& mimeType)
524 {
525     static const unsigned fontLength = 5;
526     if (!startsWithLettersIgnoringASCIICase(mimeType, "font/"))
527         return false;
528     auto subtype = StringView { mimeType }.substring(fontLength);
529     return equalLettersIgnoringASCIICase(subtype, "woff")
530         || equalLettersIgnoringASCIICase(subtype, "woff2")
531         || equalLettersIgnoringASCIICase(subtype, "otf")
532         || equalLettersIgnoringASCIICase(subtype, "ttf")
533         || equalLettersIgnoringASCIICase(subtype, "sfnt");
534 }
535
536 bool MIMETypeRegistry::isTextMediaPlaylistMIMEType(const String& mimeType)
537 {
538     if (startsWithLettersIgnoringASCIICase(mimeType, "application/")) {
539         static const unsigned applicationLength = 12;
540         auto subtype = StringView { mimeType }.substring(applicationLength);
541         return equalLettersIgnoringASCIICase(subtype, "vnd.apple.mpegurl")
542             || equalLettersIgnoringASCIICase(subtype, "mpegurl")
543             || equalLettersIgnoringASCIICase(subtype, "x-mpegurl");
544     }
545
546     if (startsWithLettersIgnoringASCIICase(mimeType, "audio/")) {
547         static const unsigned audioLength = 6;
548         auto subtype = StringView { mimeType }.substring(audioLength);
549         return equalLettersIgnoringASCIICase(subtype, "mpegurl")
550             || equalLettersIgnoringASCIICase(subtype, "x-mpegurl");
551     }
552
553     return false;
554 }
555
556 bool MIMETypeRegistry::isSupportedJSONMIMEType(const String& mimeType)
557 {
558     if (mimeType.isEmpty())
559         return false;
560
561     if (equalLettersIgnoringASCIICase(mimeType, "application/json"))
562         return true;
563
564     // When detecting +json ensure there is a non-empty type / subtype preceeding the suffix.
565     if (mimeType.endsWithIgnoringASCIICase("+json") && mimeType.length() >= 8) {
566         size_t slashPosition = mimeType.find('/');
567         if (slashPosition != notFound && slashPosition > 0 && slashPosition <= mimeType.length() - 6)
568             return true;
569     }
570
571     return false;
572 }
573
574 bool MIMETypeRegistry::isSupportedNonImageMIMEType(const String& mimeType)
575 {
576     if (mimeType.isEmpty())
577         return false;
578     return supportedNonImageMIMETypes().contains(mimeType);
579 }
580
581 bool MIMETypeRegistry::isSupportedMediaMIMEType(const String& mimeType)
582 {
583     if (mimeType.isEmpty())
584         return false;
585     return supportedMediaMIMETypes().contains(mimeType);
586 }
587
588 bool MIMETypeRegistry::isSupportedTextTrackMIMEType(const String& mimeType)
589 {
590     return equalLettersIgnoringASCIICase(mimeType, "text/vtt");
591 }
592
593 bool MIMETypeRegistry::isUnsupportedTextMIMEType(const String& mimeType)
594 {
595     if (mimeType.isEmpty())
596         return false;
597     return unsupportedTextMIMETypes().contains(mimeType);
598 }
599
600 bool MIMETypeRegistry::isTextMIMEType(const String& mimeType)
601 {
602     return isSupportedJavaScriptMIMEType(mimeType)
603         || isSupportedJSONMIMEType(mimeType) // Render JSON as text/plain.
604         || (startsWithLettersIgnoringASCIICase(mimeType, "text/")
605             && !equalLettersIgnoringASCIICase(mimeType, "text/html")
606             && !equalLettersIgnoringASCIICase(mimeType, "text/xml")
607             && !equalLettersIgnoringASCIICase(mimeType, "text/xsl"));
608 }
609
610 static inline bool isValidXMLMIMETypeChar(UChar c)
611 {
612     // Valid characters per RFCs 3023 and 2045: 0-9a-zA-Z_-+~!$^{}|.%'`#&*
613     return isASCIIAlphanumeric(c) || c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' || c == '*' || c == '+'
614         || c == '-' || c == '.' || c == '^' || c == '_' || c == '`' || c == '{' || c == '|' || c == '}' || c == '~';
615 }
616
617 bool MIMETypeRegistry::isXMLMIMEType(const String& mimeType)
618 {
619     if (equalLettersIgnoringASCIICase(mimeType, "text/xml") || equalLettersIgnoringASCIICase(mimeType, "application/xml") || equalLettersIgnoringASCIICase(mimeType, "text/xsl"))
620         return true;
621
622     if (!mimeType.endsWithIgnoringASCIICase("+xml"))
623         return false;
624
625     size_t slashPosition = mimeType.find('/');
626     // Take into account the '+xml' ending of mimeType.
627     if (slashPosition == notFound || !slashPosition || slashPosition == mimeType.length() - 5)
628         return false;
629
630     // Again, mimeType ends with '+xml', no need to check the validity of that substring.
631     size_t mimeLength = mimeType.length();
632     for (size_t i = 0; i < mimeLength - 4; ++i) {
633         if (!isValidXMLMIMETypeChar(mimeType[i]) && i != slashPosition)
634             return false;
635     }
636
637     return true;
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         ADDITIONAL_SYSTEM_PREVIEW_TYPES
702     };
703     return systemPreviewMIMETypes;
704 }
705
706 bool MIMETypeRegistry::isSystemPreviewMIMEType(const String& mimeType)
707 {
708     if (mimeType.isEmpty())
709         return false;
710     return systemPreviewMIMETypes().contains(mimeType);
711 }
712
713 #if !USE(CURL)
714
715 // FIXME: Not sure why it makes sense to have a cross-platform function when only CURL has the concept
716 // of a "normalized" MIME type.
717 String MIMETypeRegistry::getNormalizedMIMEType(const String& mimeType)
718 {
719     return mimeType;
720 }
721
722 #else
723
724 String MIMETypeRegistry::getNormalizedMIMEType(const String& mimeType)
725 {
726     static const auto mimeTypeAssociationMap = makeNeverDestroyed([] {
727         static const std::pair<ASCIILiteral, ASCIILiteral> mimeTypeAssociations[] = {
728             { "image/x-ms-bmp"_s, "image/bmp"_s },
729             { "image/x-windows-bmp"_s, "image/bmp"_s },
730             { "image/x-bmp"_s, "image/bmp"_s },
731             { "image/x-bitmap"_s, "image/bmp"_s },
732             { "image/x-ms-bitmap"_s, "image/bmp"_s },
733             { "image/jpg"_s, "image/jpeg"_s },
734             { "image/pjpeg"_s, "image/jpeg"_s },
735             { "image/x-png"_s, "image/png"_s },
736             { "image/vnd.rim.png"_s, "image/png"_s },
737             { "image/ico"_s, "image/vnd.microsoft.icon"_s },
738             { "image/icon"_s, "image/vnd.microsoft.icon"_s },
739             { "text/ico"_s, "image/vnd.microsoft.icon"_s },
740             { "application/ico"_s, "image/vnd.microsoft.icon"_s },
741             { "image/x-icon"_s, "image/vnd.microsoft.icon"_s },
742             { "audio/vnd.qcelp"_s, "audio/qcelp"_s },
743             { "audio/qcp"_s, "audio/qcelp"_s },
744             { "audio/vnd.qcp"_s, "audio/qcelp"_s },
745             { "audio/wav"_s, "audio/x-wav"_s },
746             { "audio/vnd.wave"_s, "audio/x-wav"_s },
747             { "audio/mid"_s, "audio/midi"_s },
748             { "audio/sp-midi"_s, "audio/midi"_s },
749             { "audio/x-mid"_s, "audio/midi"_s },
750             { "audio/x-midi"_s, "audio/midi"_s },
751             { "audio/x-mpeg"_s, "audio/mpeg"_s },
752             { "audio/mp3"_s, "audio/mpeg"_s },
753             { "audio/x-mp3"_s, "audio/mpeg"_s },
754             { "audio/mpeg3"_s, "audio/mpeg"_s },
755             { "audio/x-mpeg3"_s, "audio/mpeg"_s },
756             { "audio/mpg3"_s, "audio/mpeg"_s },
757             { "audio/mpg"_s, "audio/mpeg"_s },
758             { "audio/x-mpg"_s, "audio/mpeg"_s },
759             { "audio/m4a"_s, "audio/mp4"_s },
760             { "audio/x-m4a"_s, "audio/mp4"_s },
761             { "audio/x-mp4"_s, "audio/mp4"_s },
762             { "audio/x-aac"_s, "audio/aac"_s },
763             { "audio/x-amr"_s, "audio/amr"_s },
764             { "audio/mpegurl"_s, "audio/x-mpegurl"_s },
765             { "audio/flac"_s, "audio/x-flac"_s },
766             { "video/3gp"_s, "video/3gpp"_s },
767             { "video/avi"_s, "video/x-msvideo"_s },
768             { "video/x-m4v"_s, "video/mp4"_s },
769             { "video/x-quicktime"_s, "video/quicktime"_s },
770             { "application/java"_s, "application/java-archive"_s },
771             { "application/x-java-archive"_s, "application/java-archive"_s },
772             { "application/x-zip-compressed"_s, "application/zip"_s },
773             { "text/cache-manifest"_s, "text/plain"_s },
774         };
775
776         HashMap<String, String, ASCIICaseInsensitiveHash> map;
777         for (auto& pair : mimeTypeAssociations)
778             map.add(pair.first, pair.second);
779         return map;
780     }());
781
782     auto it = mimeTypeAssociationMap.get().find(mimeType);
783     if (it != mimeTypeAssociationMap.get().end())
784         return it->value;
785     return mimeType;
786 }
787
788 #endif
789
790 String MIMETypeRegistry::appendFileExtensionIfNecessary(const String& filename, const String& mimeType)
791 {
792     if (filename.isEmpty())
793         return emptyString();
794
795     if (equalIgnoringASCIICase(mimeType, defaultMIMEType()))
796         return filename;
797
798     if (filename.reverseFind('.') != notFound)
799         return filename;
800
801     String preferredExtension = getPreferredExtensionForMIMEType(mimeType);
802     if (preferredExtension.isEmpty())
803         return filename;
804
805     return makeString(filename, '.', preferredExtension);
806 }
807
808 } // namespace WebCore