095e50af3dd671322f476bb4b5d4f7de8a52a5da
[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 const std::initializer_list<TypeExtensionPair>& commonMediaTypes()
274 {
275     // A table of common media MIME types and file extensions used when a platform's
276     // specific MIME type lookup doesn't have a match for a media file extension.
277     static std::initializer_list<TypeExtensionPair> commonMediaTypes = {
278         // Ogg
279         { "application/ogg"_s, "ogx"_s },
280         { "audio/ogg"_s, "ogg"_s },
281         { "audio/ogg"_s, "oga"_s },
282         { "video/ogg"_s, "ogv"_s },
283
284         // Annodex
285         { "application/annodex"_s, "anx"_s },
286         { "audio/annodex"_s, "axa"_s },
287         { "video/annodex"_s, "axv"_s },
288         { "audio/speex"_s, "spx"_s },
289
290         // WebM
291         { "video/webm"_s, "webm"_s },
292         { "audio/webm"_s, "webm"_s },
293
294         // MPEG
295         { "audio/mpeg"_s, "m1a"_s },
296         { "audio/mpeg"_s, "m2a"_s },
297         { "audio/mpeg"_s, "m1s"_s },
298         { "audio/mpeg"_s, "mpa"_s },
299         { "video/mpeg"_s, "mpg"_s },
300         { "video/mpeg"_s, "m15"_s },
301         { "video/mpeg"_s, "m1s"_s },
302         { "video/mpeg"_s, "m1v"_s },
303         { "video/mpeg"_s, "m75"_s },
304         { "video/mpeg"_s, "mpa"_s },
305         { "video/mpeg"_s, "mpeg"_s },
306         { "video/mpeg"_s, "mpm"_s },
307         { "video/mpeg"_s, "mpv"_s },
308
309         // MPEG playlist
310         { "application/vnd.apple.mpegurl"_s, "m3u8"_s },
311         { "application/mpegurl"_s, "m3u8"_s },
312         { "application/x-mpegurl"_s, "m3u8"_s },
313         { "audio/mpegurl"_s, "m3url"_s },
314         { "audio/x-mpegurl"_s, "m3url"_s },
315         { "audio/mpegurl"_s, "m3u"_s },
316         { "audio/x-mpegurl"_s, "m3u"_s },
317
318         // MPEG-4
319         { "video/x-m4v"_s, "m4v"_s },
320         { "audio/x-m4a"_s, "m4a"_s },
321         { "audio/x-m4b"_s, "m4b"_s },
322         { "audio/x-m4p"_s, "m4p"_s },
323         { "audio/mp4"_s, "m4a"_s },
324
325         // MP3
326         { "audio/mp3"_s, "mp3"_s },
327         { "audio/x-mp3"_s, "mp3"_s },
328         { "audio/x-mpeg"_s, "mp3"_s },
329
330         // MPEG-2
331         { "video/x-mpeg2"_s, "mp2"_s },
332         { "video/mpeg2"_s, "vob"_s },
333         { "video/mpeg2"_s, "mod"_s },
334         { "video/m2ts"_s, "m2ts"_s },
335         { "video/x-m2ts"_s, "m2t"_s },
336         { "video/x-m2ts"_s, "ts"_s },
337
338         // 3GP/3GP2
339         { "audio/3gpp"_s, "3gpp"_s },
340         { "audio/3gpp2"_s, "3g2"_s },
341         { "application/x-mpeg"_s, "amc"_s },
342
343         // AAC
344         { "audio/aac"_s, "aac"_s },
345         { "audio/aac"_s, "adts"_s },
346         { "audio/x-aac"_s, "m4r"_s },
347
348         // CoreAudio File
349         { "audio/x-caf"_s, "caf"_s },
350         { "audio/x-gsm"_s, "gsm"_s },
351
352         // ADPCM
353         { "audio/x-wav"_s, "wav"_s },
354         { "audio/vnd.wave"_s, "wav"_s },
355     };
356     return commonMediaTypes;
357 }
358
359 static const HashMap<String, Vector<String>, ASCIICaseInsensitiveHash>& commonMimeTypesMap()
360 {
361     ASSERT(isMainThread());
362     static NeverDestroyed<HashMap<String, Vector<String>, ASCIICaseInsensitiveHash>> mimeTypesMap = [] {
363         HashMap<String, Vector<String>, ASCIICaseInsensitiveHash> map;
364         for (auto& pair : commonMediaTypes()) {
365             ASCIILiteral type = pair.type;
366             ASCIILiteral extension = pair.extension;
367             map.ensure(extension, [type, extension] {
368                 // First type in the vector must always be the one from getMIMETypeForExtension,
369                 // so we can use the map without also calling getMIMETypeForExtension each time.
370                 Vector<String> synonyms;
371                 String systemType = MIMETypeRegistry::getMIMETypeForExtension(extension);
372                 if (!systemType.isEmpty() && type != systemType)
373                     synonyms.append(systemType);
374                 return synonyms;
375             }).iterator->value.append(type);
376         }
377         return map;
378     }();
379     return mimeTypesMap;
380 }
381
382 static const Vector<String>* typesForCommonExtension(const String& extension)
383 {
384     auto mapEntry = commonMimeTypesMap().find(extension);
385     if (mapEntry == commonMimeTypesMap().end())
386         return nullptr;
387     return &mapEntry->value;
388 }
389
390 String MIMETypeRegistry::getMediaMIMETypeForExtension(const String& extension)
391 {
392     auto* vector = typesForCommonExtension(extension);
393     if (vector)
394         return (*vector)[0];
395     return getMIMETypeForExtension(extension);
396 }
397
398 Vector<String> MIMETypeRegistry::getMediaMIMETypesForExtension(const String& extension)
399 {
400     auto* vector = typesForCommonExtension(extension);
401     if (vector)
402         return *vector;
403     String type = getMIMETypeForExtension(extension);
404     if (!type.isNull())
405         return { { type } };
406     return { };
407 }
408
409 String MIMETypeRegistry::getMIMETypeForPath(const String& path)
410 {
411     size_t pos = path.reverseFind('.');
412     if (pos != notFound) {
413         String extension = path.substring(pos + 1);
414         String result = getMIMETypeForExtension(extension);
415         if (result.length())
416             return result;
417     }
418     return defaultMIMEType();
419 }
420
421 bool MIMETypeRegistry::isSupportedImageMIMEType(const String& mimeType)
422 {
423     if (mimeType.isEmpty())
424         return false;
425     String normalizedMIMEType = getNormalizedMIMEType(mimeType);
426     return supportedImageMIMETypes().contains(normalizedMIMEType) || additionalSupportedImageMIMETypes().contains(normalizedMIMEType);
427 }
428
429 bool MIMETypeRegistry::isSupportedImageVideoOrSVGMIMEType(const String& mimeType)
430 {
431     if (isSupportedImageMIMEType(mimeType) || equalLettersIgnoringASCIICase(mimeType, "image/svg+xml"))
432         return true;
433
434 #if HAVE(AVASSETREADER)
435     if (ImageDecoderAVFObjC::supportsContainerType(mimeType))
436         return true;
437 #endif
438
439     return false;
440 }
441
442 std::unique_ptr<MIMETypeRegistryThreadGlobalData> MIMETypeRegistry::createMIMETypeRegistryThreadGlobalData()
443 {
444 #if PLATFORM(COCOA)
445     RetainPtr<CFArrayRef> supportedTypes = adoptCF(CGImageDestinationCopyTypeIdentifiers());
446     HashSet<String, ASCIICaseInsensitiveHash> supportedImageMIMETypesForEncoding;
447     CFIndex count = CFArrayGetCount(supportedTypes.get());
448     for (CFIndex i = 0; i < count; i++) {
449         CFStringRef supportedType = reinterpret_cast<CFStringRef>(CFArrayGetValueAtIndex(supportedTypes.get(), i));
450         if (isSupportedImageType(supportedType)) {
451             String mimeType = MIMETypeForImageType(supportedType);
452             supportedImageMIMETypesForEncoding.add(mimeType);
453         }
454     }
455 #else
456     HashSet<String, ASCIICaseInsensitiveHash> supportedImageMIMETypesForEncoding = std::initializer_list<String> {
457 #if USE(CG) || USE(DIRECT2D)
458         // FIXME: Add Windows support for all the supported UTI's when a way to convert from MIMEType to UTI reliably is found.
459         // For now, only support PNG, JPEG and GIF. See <rdar://problem/6095286>.
460         "image/png"_s,
461         "image/jpeg"_s,
462         "image/gif"_s,
463 #elif PLATFORM(GTK)
464         "image/png"_s,
465         "image/jpeg"_s,
466         "image/tiff"_s,
467         "image/bmp"_s,
468         "image/ico"_s,
469 #elif USE(CAIRO)
470         "image/png"_s,
471 #endif
472     };
473 #endif
474     return makeUnique<MIMETypeRegistryThreadGlobalData>(WTFMove(supportedImageMIMETypesForEncoding));
475 }
476
477 bool MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(const String& mimeType)
478 {
479     if (mimeType.isEmpty())
480         return false;
481     return threadGlobalData().mimeTypeRegistryThreadGlobalData().supportedImageMIMETypesForEncoding().contains(mimeType);
482 }
483
484 bool MIMETypeRegistry::isSupportedJavaScriptMIMEType(const String& mimeType)
485 {
486     if (mimeType.isEmpty())
487         return false;
488
489     if (!isMainThread()) {
490         bool isSupported = false;
491         callOnMainThreadAndWait([&isSupported, mimeType = mimeType.isolatedCopy()] {
492             isSupported = isSupportedJavaScriptMIMEType(mimeType);
493         });
494         return isSupported;
495     }
496
497     return supportedJavaScriptMIMETypes().contains(mimeType);
498 }
499
500 bool MIMETypeRegistry::isSupportedStyleSheetMIMEType(const String& mimeType)
501 {
502     return equalLettersIgnoringASCIICase(mimeType, "text/css");
503 }
504
505 bool MIMETypeRegistry::isSupportedFontMIMEType(const String& mimeType)
506 {
507     static const unsigned fontLength = 5;
508     if (!startsWithLettersIgnoringASCIICase(mimeType, "font/"))
509         return false;
510     auto subtype = StringView { mimeType }.substring(fontLength);
511     return equalLettersIgnoringASCIICase(subtype, "woff")
512         || equalLettersIgnoringASCIICase(subtype, "woff2")
513         || equalLettersIgnoringASCIICase(subtype, "otf")
514         || equalLettersIgnoringASCIICase(subtype, "ttf")
515         || equalLettersIgnoringASCIICase(subtype, "sfnt");
516 }
517
518 bool MIMETypeRegistry::isTextMediaPlaylistMIMEType(const String& mimeType)
519 {
520     if (startsWithLettersIgnoringASCIICase(mimeType, "application/")) {
521         static const unsigned applicationLength = 12;
522         auto subtype = StringView { mimeType }.substring(applicationLength);
523         return equalLettersIgnoringASCIICase(subtype, "vnd.apple.mpegurl")
524             || equalLettersIgnoringASCIICase(subtype, "mpegurl")
525             || equalLettersIgnoringASCIICase(subtype, "x-mpegurl");
526     }
527
528     if (startsWithLettersIgnoringASCIICase(mimeType, "audio/")) {
529         static const unsigned audioLength = 6;
530         auto subtype = StringView { mimeType }.substring(audioLength);
531         return equalLettersIgnoringASCIICase(subtype, "mpegurl")
532             || equalLettersIgnoringASCIICase(subtype, "x-mpegurl");
533     }
534
535     return false;
536 }
537
538 bool MIMETypeRegistry::isSupportedJSONMIMEType(const String& mimeType)
539 {
540     if (mimeType.isEmpty())
541         return false;
542
543     if (equalLettersIgnoringASCIICase(mimeType, "application/json"))
544         return true;
545
546     // When detecting +json ensure there is a non-empty type / subtype preceeding the suffix.
547     if (mimeType.endsWithIgnoringASCIICase("+json") && mimeType.length() >= 8) {
548         size_t slashPosition = mimeType.find('/');
549         if (slashPosition != notFound && slashPosition > 0 && slashPosition <= mimeType.length() - 6)
550             return true;
551     }
552
553     return false;
554 }
555
556 bool MIMETypeRegistry::isSupportedNonImageMIMEType(const String& mimeType)
557 {
558     if (mimeType.isEmpty())
559         return false;
560     return supportedNonImageMIMETypes().contains(mimeType);
561 }
562
563 bool MIMETypeRegistry::isSupportedMediaMIMEType(const String& mimeType)
564 {
565     if (mimeType.isEmpty())
566         return false;
567     return supportedMediaMIMETypes().contains(mimeType);
568 }
569
570 bool MIMETypeRegistry::isSupportedTextTrackMIMEType(const String& mimeType)
571 {
572     return equalLettersIgnoringASCIICase(mimeType, "text/vtt");
573 }
574
575 bool MIMETypeRegistry::isUnsupportedTextMIMEType(const String& mimeType)
576 {
577     if (mimeType.isEmpty())
578         return false;
579     return unsupportedTextMIMETypes().contains(mimeType);
580 }
581
582 bool MIMETypeRegistry::isTextMIMEType(const String& mimeType)
583 {
584     return isSupportedJavaScriptMIMEType(mimeType)
585         || isSupportedJSONMIMEType(mimeType) // Render JSON as text/plain.
586         || (startsWithLettersIgnoringASCIICase(mimeType, "text/")
587             && !equalLettersIgnoringASCIICase(mimeType, "text/html")
588             && !equalLettersIgnoringASCIICase(mimeType, "text/xml")
589             && !equalLettersIgnoringASCIICase(mimeType, "text/xsl"));
590 }
591
592 static inline bool isValidXMLMIMETypeChar(UChar c)
593 {
594     // Valid characters per RFCs 3023 and 2045: 0-9a-zA-Z_-+~!$^{}|.%'`#&*
595     return isASCIIAlphanumeric(c) || c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' || c == '*' || c == '+'
596         || c == '-' || c == '.' || c == '^' || c == '_' || c == '`' || c == '{' || c == '|' || c == '}' || c == '~';
597 }
598
599 bool MIMETypeRegistry::isXMLMIMEType(const String& mimeType)
600 {
601     if (equalLettersIgnoringASCIICase(mimeType, "text/xml") || equalLettersIgnoringASCIICase(mimeType, "application/xml") || equalLettersIgnoringASCIICase(mimeType, "text/xsl"))
602         return true;
603
604     if (!mimeType.endsWithIgnoringASCIICase("+xml"))
605         return false;
606
607     size_t slashPosition = mimeType.find('/');
608     // Take into account the '+xml' ending of mimeType.
609     if (slashPosition == notFound || !slashPosition || slashPosition == mimeType.length() - 5)
610         return false;
611
612     // Again, mimeType ends with '+xml', no need to check the validity of that substring.
613     size_t mimeLength = mimeType.length();
614     for (size_t i = 0; i < mimeLength - 4; ++i) {
615         if (!isValidXMLMIMETypeChar(mimeType[i]) && i != slashPosition)
616             return false;
617     }
618
619     return true;
620 }
621
622 bool MIMETypeRegistry::isXMLEntityMIMEType(StringView mimeType)
623 {
624     return equalLettersIgnoringASCIICase(mimeType, "text/xml-external-parsed-entity")
625         || equalLettersIgnoringASCIICase(mimeType, "application/xml-external-parsed-entity");
626 }
627
628 bool MIMETypeRegistry::isJavaAppletMIMEType(const String& mimeType)
629 {
630     // Since this set is very limited and is likely to remain so we won't bother with the overhead
631     // of using a hash set.
632     // Any of the MIME types below may be followed by any number of specific versions of the JVM,
633     // which is why we use startsWith()
634     return startsWithLettersIgnoringASCIICase(mimeType, "application/x-java-applet")
635         || startsWithLettersIgnoringASCIICase(mimeType, "application/x-java-bean")
636         || startsWithLettersIgnoringASCIICase(mimeType, "application/x-java-vm");
637 }
638
639 bool MIMETypeRegistry::isPDFMIMEType(const String& mimeType)
640 {
641     if (mimeType.isEmpty())
642         return false;
643     return pdfMIMETypes().contains(mimeType);
644 }
645
646 bool MIMETypeRegistry::isPostScriptMIMEType(const String& mimeType)
647 {
648     return mimeType == "application/postscript";
649 }
650
651 bool MIMETypeRegistry::isPDFOrPostScriptMIMEType(const String& mimeType)
652 {
653     return isPDFMIMEType(mimeType) || isPostScriptMIMEType(mimeType);
654 }
655
656 bool MIMETypeRegistry::canShowMIMEType(const String& mimeType)
657 {
658     if (isSupportedImageMIMEType(mimeType) || isSupportedNonImageMIMEType(mimeType) || isSupportedMediaMIMEType(mimeType))
659         return true;
660
661     if (isSupportedJavaScriptMIMEType(mimeType) || isSupportedJSONMIMEType(mimeType))
662         return true;
663
664 #if USE(QUICK_LOOK)
665     if (PreviewConverter::supportsMIMEType(mimeType))
666         return true;
667 #endif
668
669     if (startsWithLettersIgnoringASCIICase(mimeType, "text/"))
670         return !isUnsupportedTextMIMEType(mimeType);
671
672     return false;
673 }
674
675 const String& defaultMIMEType()
676 {
677     static NeverDestroyed<const String> defaultMIMEType(MAKE_STATIC_STRING_IMPL("application/octet-stream"));
678     return defaultMIMEType;
679 }
680
681 const HashSet<String, ASCIICaseInsensitiveHash>& MIMETypeRegistry::systemPreviewMIMETypes()
682 {
683     static NeverDestroyed<HashSet<String, ASCIICaseInsensitiveHash>> systemPreviewMIMETypes = std::initializer_list<String> {
684         // The official type: https://www.iana.org/assignments/media-types/model/vnd.usdz+zip
685         "model/vnd.usdz+zip",
686         // Unofficial, but supported because we documented them.
687         "model/usd",
688         "model/vnd.pixar.usd",
689         // Reality files.
690         "model/vnd.reality"
691     };
692     return systemPreviewMIMETypes;
693 }
694
695 bool MIMETypeRegistry::isSystemPreviewMIMEType(const String& mimeType)
696 {
697     if (mimeType.isEmpty())
698         return false;
699     return systemPreviewMIMETypes().contains(mimeType);
700 }
701
702 #if !USE(CURL)
703
704 // FIXME: Not sure why it makes sense to have a cross-platform function when only CURL has the concept
705 // of a "normalized" MIME type.
706 String MIMETypeRegistry::getNormalizedMIMEType(const String& mimeType)
707 {
708     return mimeType;
709 }
710
711 #else
712
713 String MIMETypeRegistry::getNormalizedMIMEType(const String& mimeType)
714 {
715     static const auto mimeTypeAssociationMap = makeNeverDestroyed([] {
716         static const std::pair<ASCIILiteral, ASCIILiteral> mimeTypeAssociations[] = {
717             { "image/x-ms-bmp"_s, "image/bmp"_s },
718             { "image/x-windows-bmp"_s, "image/bmp"_s },
719             { "image/x-bmp"_s, "image/bmp"_s },
720             { "image/x-bitmap"_s, "image/bmp"_s },
721             { "image/x-ms-bitmap"_s, "image/bmp"_s },
722             { "image/jpg"_s, "image/jpeg"_s },
723             { "image/pjpeg"_s, "image/jpeg"_s },
724             { "image/x-png"_s, "image/png"_s },
725             { "image/vnd.rim.png"_s, "image/png"_s },
726             { "image/ico"_s, "image/vnd.microsoft.icon"_s },
727             { "image/icon"_s, "image/vnd.microsoft.icon"_s },
728             { "text/ico"_s, "image/vnd.microsoft.icon"_s },
729             { "application/ico"_s, "image/vnd.microsoft.icon"_s },
730             { "image/x-icon"_s, "image/vnd.microsoft.icon"_s },
731             { "audio/vnd.qcelp"_s, "audio/qcelp"_s },
732             { "audio/qcp"_s, "audio/qcelp"_s },
733             { "audio/vnd.qcp"_s, "audio/qcelp"_s },
734             { "audio/wav"_s, "audio/x-wav"_s },
735             { "audio/vnd.wave"_s, "audio/x-wav"_s },
736             { "audio/mid"_s, "audio/midi"_s },
737             { "audio/sp-midi"_s, "audio/midi"_s },
738             { "audio/x-mid"_s, "audio/midi"_s },
739             { "audio/x-midi"_s, "audio/midi"_s },
740             { "audio/x-mpeg"_s, "audio/mpeg"_s },
741             { "audio/mp3"_s, "audio/mpeg"_s },
742             { "audio/x-mp3"_s, "audio/mpeg"_s },
743             { "audio/mpeg3"_s, "audio/mpeg"_s },
744             { "audio/x-mpeg3"_s, "audio/mpeg"_s },
745             { "audio/mpg3"_s, "audio/mpeg"_s },
746             { "audio/mpg"_s, "audio/mpeg"_s },
747             { "audio/x-mpg"_s, "audio/mpeg"_s },
748             { "audio/m4a"_s, "audio/mp4"_s },
749             { "audio/x-m4a"_s, "audio/mp4"_s },
750             { "audio/x-mp4"_s, "audio/mp4"_s },
751             { "audio/x-aac"_s, "audio/aac"_s },
752             { "audio/x-amr"_s, "audio/amr"_s },
753             { "audio/mpegurl"_s, "audio/x-mpegurl"_s },
754             { "audio/flac"_s, "audio/x-flac"_s },
755             { "video/3gp"_s, "video/3gpp"_s },
756             { "video/avi"_s, "video/x-msvideo"_s },
757             { "video/x-m4v"_s, "video/mp4"_s },
758             { "video/x-quicktime"_s, "video/quicktime"_s },
759             { "application/java"_s, "application/java-archive"_s },
760             { "application/x-java-archive"_s, "application/java-archive"_s },
761             { "application/x-zip-compressed"_s, "application/zip"_s },
762             { "text/cache-manifest"_s, "text/plain"_s },
763         };
764
765         HashMap<String, String, ASCIICaseInsensitiveHash> map;
766         for (auto& pair : mimeTypeAssociations)
767             map.add(pair.first, pair.second);
768         return map;
769     }());
770
771     auto it = mimeTypeAssociationMap.get().find(mimeType);
772     if (it != mimeTypeAssociationMap.get().end())
773         return it->value;
774     return mimeType;
775 }
776
777 #endif
778
779 String MIMETypeRegistry::appendFileExtensionIfNecessary(const String& filename, const String& mimeType)
780 {
781     if (filename.isEmpty() || filename.contains('.') || equalIgnoringASCIICase(mimeType, defaultMIMEType()))
782         return filename;
783
784     auto preferredExtension = getPreferredExtensionForMIMEType(mimeType);
785     if (preferredExtension.isEmpty())
786         return filename;
787
788     return makeString(filename, '.', preferredExtension);
789 }
790
791 } // namespace WebCore