Revert of Add support for escaped target names in isolate driver. (patchset #6 id...
[chromium-blink-merge.git] / net / base / mime_util.cc
blobe4901277c3f8c12e9207a83deddfeee0fa09ad71
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <algorithm>
6 #include <iterator>
7 #include <map>
8 #include <string>
10 #include "base/containers/hash_tables.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "net/base/mime_util.h"
19 #include "net/base/platform_mime_util.h"
20 #include "net/http/http_util.h"
22 #if defined(OS_ANDROID)
23 #include "base/android/build_info.h"
24 #endif
26 using std::string;
28 namespace net {
30 // Singleton utility class for mime types.
31 class MimeUtil : public PlatformMimeUtil {
32 public:
33 enum Codec {
34 INVALID_CODEC,
35 PCM,
36 MP3,
37 MPEG2_AAC_LC,
38 MPEG2_AAC_MAIN,
39 MPEG2_AAC_SSR,
40 MPEG4_AAC_LC,
41 MPEG4_AAC_SBR_v1,
42 MPEG4_AAC_SBR_PS_v2,
43 VORBIS,
44 OPUS,
45 H264_BASELINE,
46 H264_MAIN,
47 H264_HIGH,
48 VP8,
49 VP9,
50 THEORA
53 bool GetMimeTypeFromExtension(const base::FilePath::StringType& ext,
54 std::string* mime_type) const;
56 bool GetMimeTypeFromFile(const base::FilePath& file_path,
57 std::string* mime_type) const;
59 bool GetWellKnownMimeTypeFromExtension(const base::FilePath::StringType& ext,
60 std::string* mime_type) const;
62 bool IsSupportedImageMimeType(const std::string& mime_type) const;
63 bool IsSupportedMediaMimeType(const std::string& mime_type) const;
64 bool IsSupportedNonImageMimeType(const std::string& mime_type) const;
65 bool IsUnsupportedTextMimeType(const std::string& mime_type) const;
66 bool IsSupportedJavascriptMimeType(const std::string& mime_type) const;
68 bool IsSupportedMimeType(const std::string& mime_type) const;
70 bool MatchesMimeType(const std::string &mime_type_pattern,
71 const std::string &mime_type) const;
73 bool ParseMimeTypeWithoutParameter(const std::string& type_string,
74 std::string* top_level_type,
75 std::string* subtype) const;
77 bool IsValidTopLevelMimeType(const std::string& type_string) const;
79 bool AreSupportedMediaCodecs(const std::vector<std::string>& codecs) const;
81 void ParseCodecString(const std::string& codecs,
82 std::vector<std::string>* codecs_out,
83 bool strip);
85 bool IsStrictMediaMimeType(const std::string& mime_type) const;
86 SupportsType IsSupportedStrictMediaMimeType(
87 const std::string& mime_type,
88 const std::vector<std::string>& codecs) const;
90 void RemoveProprietaryMediaTypesAndCodecsForTests();
92 private:
93 friend struct base::DefaultLazyInstanceTraits<MimeUtil>;
95 typedef base::hash_set<std::string> MimeMappings;
97 typedef base::hash_set<int> CodecSet;
98 typedef std::map<std::string, CodecSet> StrictMappings;
99 struct CodecEntry {
100 CodecEntry() : codec(INVALID_CODEC), is_ambiguous(true) {}
101 CodecEntry(Codec c, bool ambiguous) : codec(c), is_ambiguous(ambiguous) {}
102 Codec codec;
103 bool is_ambiguous;
105 typedef std::map<std::string, CodecEntry> StringToCodecMappings;
107 MimeUtil();
109 // Returns IsSupported if all codec IDs in |codecs| are unambiguous
110 // and are supported by the platform. MayBeSupported is returned if
111 // at least one codec ID in |codecs| is ambiguous but all the codecs
112 // are supported by the platform. IsNotSupported is returned if at
113 // least one codec ID is not supported by the platform.
114 SupportsType AreSupportedCodecs(
115 const CodecSet& supported_codecs,
116 const std::vector<std::string>& codecs) const;
118 // For faster lookup, keep hash sets.
119 void InitializeMimeTypeMaps();
121 bool GetMimeTypeFromExtensionHelper(const base::FilePath::StringType& ext,
122 bool include_platform_types,
123 std::string* mime_type) const;
125 // Converts a codec ID into an Codec enum value and indicates
126 // whether the conversion was ambiguous.
127 // Returns true if this method was able to map |codec_id| to a specific
128 // Codec enum value. |codec| and |is_ambiguous| are only valid if true
129 // is returned. Otherwise their value is undefined after the call.
130 // |is_ambiguous| is true if |codec_id| did not have enough information to
131 // unambiguously determine the proper Codec enum value. If |is_ambiguous|
132 // is true |codec| contains the best guess for the intended Codec enum value.
133 bool StringToCodec(const std::string& codec_id,
134 Codec* codec,
135 bool* is_ambiguous) const;
137 // Returns true if |codec| is supported by the platform.
138 // Note: This method will return false if the platform supports proprietary
139 // codecs but |allow_proprietary_codecs_| is set to false.
140 bool IsCodecSupported(Codec codec) const;
142 // Returns true if |codec| refers to a proprietary codec.
143 bool IsCodecProprietary(Codec codec) const;
145 // Returns true and sets |*default_codec| if |mime_type| has a default codec
146 // associated with it. Returns false otherwise and the value of
147 // |*default_codec| is undefined.
148 bool GetDefaultCodecLowerCase(const std::string& mime_type_lower_case,
149 Codec* default_codec) const;
151 // Returns true if |mime_type_lower_case| has a default codec associated with
152 // it and IsCodecSupported() returns true for that particular codec.
153 bool IsDefaultCodecSupportedLowerCase(
154 const std::string& mime_type_lower_case) const;
156 MimeMappings image_map_;
157 MimeMappings media_map_;
158 MimeMappings non_image_map_;
159 MimeMappings unsupported_text_map_;
160 MimeMappings javascript_map_;
162 // A map of mime_types and hash map of the supported codecs for the mime_type.
163 StrictMappings strict_format_map_;
165 // Keeps track of whether proprietary codec support should be
166 // advertised to callers.
167 bool allow_proprietary_codecs_;
169 // Lookup table for string compare based string -> Codec mappings.
170 StringToCodecMappings string_to_codec_map_;
171 }; // class MimeUtil
173 // This variable is Leaky because we need to access it from WorkerPool threads.
174 static base::LazyInstance<MimeUtil>::Leaky g_mime_util =
175 LAZY_INSTANCE_INITIALIZER;
177 struct MimeInfo {
178 const char* const mime_type;
179 const char* const extensions; // comma separated list
182 static const MimeInfo primary_mappings[] = {
183 { "text/html", "html,htm,shtml,shtm" },
184 { "text/css", "css" },
185 { "text/xml", "xml" },
186 { "image/gif", "gif" },
187 { "image/jpeg", "jpeg,jpg" },
188 { "image/webp", "webp" },
189 { "image/png", "png" },
190 { "video/mp4", "mp4,m4v" },
191 { "audio/x-m4a", "m4a" },
192 { "audio/mp3", "mp3" },
193 { "video/ogg", "ogv,ogm" },
194 { "audio/ogg", "ogg,oga,opus" },
195 { "video/webm", "webm" },
196 { "audio/webm", "webm" },
197 { "audio/wav", "wav" },
198 { "application/xhtml+xml", "xhtml,xht,xhtm" },
199 { "application/x-chrome-extension", "crx" },
200 { "multipart/related", "mhtml,mht" }
203 static const MimeInfo secondary_mappings[] = {
204 { "application/octet-stream", "exe,com,bin" },
205 { "application/gzip", "gz" },
206 { "application/pdf", "pdf" },
207 { "application/postscript", "ps,eps,ai" },
208 { "application/javascript", "js" },
209 { "application/font-woff", "woff" },
210 { "image/bmp", "bmp" },
211 { "image/x-icon", "ico" },
212 { "image/vnd.microsoft.icon", "ico" },
213 { "image/jpeg", "jfif,pjpeg,pjp" },
214 { "image/tiff", "tiff,tif" },
215 { "image/x-xbitmap", "xbm" },
216 { "image/svg+xml", "svg,svgz" },
217 { "image/x-png", "png"},
218 { "message/rfc822", "eml" },
219 { "text/plain", "txt,text" },
220 { "text/html", "ehtml" },
221 { "application/rss+xml", "rss" },
222 { "application/rdf+xml", "rdf" },
223 { "text/xml", "xsl,xbl,xslt" },
224 { "application/vnd.mozilla.xul+xml", "xul" },
225 { "application/x-shockwave-flash", "swf,swl" },
226 { "application/pkcs7-mime", "p7m,p7c,p7z" },
227 { "application/pkcs7-signature", "p7s" },
228 { "application/x-mpegurl", "m3u8" },
231 static const char* FindMimeType(const MimeInfo* mappings,
232 size_t mappings_len,
233 const char* ext) {
234 size_t ext_len = strlen(ext);
236 for (size_t i = 0; i < mappings_len; ++i) {
237 const char* extensions = mappings[i].extensions;
238 for (;;) {
239 size_t end_pos = strcspn(extensions, ",");
240 if (end_pos == ext_len &&
241 base::strncasecmp(extensions, ext, ext_len) == 0)
242 return mappings[i].mime_type;
243 extensions += end_pos;
244 if (!*extensions)
245 break;
246 extensions += 1; // skip over comma
249 return NULL;
252 bool MimeUtil::GetMimeTypeFromExtension(const base::FilePath::StringType& ext,
253 string* result) const {
254 return GetMimeTypeFromExtensionHelper(ext, true, result);
257 bool MimeUtil::GetWellKnownMimeTypeFromExtension(
258 const base::FilePath::StringType& ext,
259 string* result) const {
260 return GetMimeTypeFromExtensionHelper(ext, false, result);
263 bool MimeUtil::GetMimeTypeFromFile(const base::FilePath& file_path,
264 string* result) const {
265 base::FilePath::StringType file_name_str = file_path.Extension();
266 if (file_name_str.empty())
267 return false;
268 return GetMimeTypeFromExtension(file_name_str.substr(1), result);
271 bool MimeUtil::GetMimeTypeFromExtensionHelper(
272 const base::FilePath::StringType& ext,
273 bool include_platform_types,
274 string* result) const {
275 // Avoids crash when unable to handle a long file path. See crbug.com/48733.
276 const unsigned kMaxFilePathSize = 65536;
277 if (ext.length() > kMaxFilePathSize)
278 return false;
280 // We implement the same algorithm as Mozilla for mapping a file extension to
281 // a mime type. That is, we first check a hard-coded list (that cannot be
282 // overridden), and then if not found there, we defer to the system registry.
283 // Finally, we scan a secondary hard-coded list to catch types that we can
284 // deduce but that we also want to allow the OS to override.
286 base::FilePath path_ext(ext);
287 const string ext_narrow_str = path_ext.AsUTF8Unsafe();
288 const char* mime_type = FindMimeType(primary_mappings,
289 arraysize(primary_mappings),
290 ext_narrow_str.c_str());
291 if (mime_type) {
292 *result = mime_type;
293 return true;
296 if (include_platform_types && GetPlatformMimeTypeFromExtension(ext, result))
297 return true;
299 mime_type = FindMimeType(secondary_mappings, arraysize(secondary_mappings),
300 ext_narrow_str.c_str());
301 if (mime_type) {
302 *result = mime_type;
303 return true;
306 return false;
309 // From WebKit's WebCore/platform/MIMETypeRegistry.cpp:
311 static const char* const supported_image_types[] = {
312 "image/jpeg",
313 "image/pjpeg",
314 "image/jpg",
315 "image/webp",
316 "image/png",
317 "image/gif",
318 "image/bmp",
319 "image/vnd.microsoft.icon", // ico
320 "image/x-icon", // ico
321 "image/x-xbitmap", // xbm
322 "image/x-png"
325 // A list of media types: http://en.wikipedia.org/wiki/Internet_media_type
326 // A comprehensive mime type list: http://plugindoc.mozdev.org/winmime.php
327 // This set of codecs is supported by all variations of Chromium.
328 static const char* const common_media_types[] = {
329 // Ogg.
330 "audio/ogg",
331 "application/ogg",
332 #if !defined(OS_ANDROID) // Android doesn't support Ogg Theora.
333 "video/ogg",
334 #endif
336 // WebM.
337 "video/webm",
338 "audio/webm",
340 // Wav.
341 "audio/wav",
342 "audio/x-wav",
344 #if defined(OS_ANDROID)
345 // HLS. Supported by Android ICS and above.
346 "application/vnd.apple.mpegurl",
347 "application/x-mpegurl",
348 #endif
351 // List of proprietary types only supported by Google Chrome.
352 static const char* const proprietary_media_types[] = {
353 // MPEG-4.
354 "video/mp4",
355 "video/x-m4v",
356 "audio/mp4",
357 "audio/x-m4a",
359 // MP3.
360 "audio/mp3",
361 "audio/x-mp3",
362 "audio/mpeg",
363 "audio/aac",
365 #if defined(ENABLE_MPEG2TS_STREAM_PARSER)
366 // MPEG-2 TS.
367 "video/mp2t",
368 #endif
371 // Note:
372 // - does not include javascript types list (see supported_javascript_types)
373 // - does not include types starting with "text/" (see
374 // IsSupportedNonImageMimeType())
375 static const char* const supported_non_image_types[] = {
376 "image/svg+xml", // SVG is text-based XML, even though it has an image/ type
377 "application/xml",
378 "application/atom+xml",
379 "application/rss+xml",
380 "application/xhtml+xml",
381 "application/json",
382 "multipart/related", // For MHTML support.
383 "multipart/x-mixed-replace"
384 // Note: ADDING a new type here will probably render it AS HTML. This can
385 // result in cross site scripting.
388 // Dictionary of cryptographic file mime types.
389 struct CertificateMimeTypeInfo {
390 const char* const mime_type;
391 CertificateMimeType cert_type;
394 static const CertificateMimeTypeInfo supported_certificate_types[] = {
395 { "application/x-x509-user-cert",
396 CERTIFICATE_MIME_TYPE_X509_USER_CERT },
397 #if defined(OS_ANDROID)
398 { "application/x-x509-ca-cert", CERTIFICATE_MIME_TYPE_X509_CA_CERT },
399 { "application/x-pkcs12", CERTIFICATE_MIME_TYPE_PKCS12_ARCHIVE },
400 #endif
403 // These types are excluded from the logic that allows all text/ types because
404 // while they are technically text, it's very unlikely that a user expects to
405 // see them rendered in text form.
406 static const char* const unsupported_text_types[] = {
407 "text/calendar",
408 "text/x-calendar",
409 "text/x-vcalendar",
410 "text/vcalendar",
411 "text/vcard",
412 "text/x-vcard",
413 "text/directory",
414 "text/ldif",
415 "text/qif",
416 "text/x-qif",
417 "text/x-csv",
418 "text/x-vcf",
419 "text/rtf",
420 "text/comma-separated-values",
421 "text/csv",
422 "text/tab-separated-values",
423 "text/tsv",
424 "text/ofx", // http://crbug.com/162238
425 "text/vnd.sun.j2me.app-descriptor" // http://crbug.com/176450
428 // Mozilla 1.8 and WinIE 7 both accept text/javascript and text/ecmascript.
429 // Mozilla 1.8 accepts application/javascript, application/ecmascript, and
430 // application/x-javascript, but WinIE 7 doesn't.
431 // WinIE 7 accepts text/javascript1.1 - text/javascript1.3, text/jscript, and
432 // text/livescript, but Mozilla 1.8 doesn't.
433 // Mozilla 1.8 allows leading and trailing whitespace, but WinIE 7 doesn't.
434 // Mozilla 1.8 and WinIE 7 both accept the empty string, but neither accept a
435 // whitespace-only string.
436 // We want to accept all the values that either of these browsers accept, but
437 // not other values.
438 static const char* const supported_javascript_types[] = {
439 "text/javascript",
440 "text/ecmascript",
441 "application/javascript",
442 "application/ecmascript",
443 "application/x-javascript",
444 "text/javascript1.1",
445 "text/javascript1.2",
446 "text/javascript1.3",
447 "text/jscript",
448 "text/livescript"
451 #if defined(OS_ANDROID)
452 static bool IsCodecSupportedOnAndroid(MimeUtil::Codec codec) {
453 switch (codec) {
454 case MimeUtil::INVALID_CODEC:
455 return false;
457 case MimeUtil::PCM:
458 case MimeUtil::MP3:
459 case MimeUtil::MPEG4_AAC_LC:
460 case MimeUtil::MPEG4_AAC_SBR_v1:
461 case MimeUtil::MPEG4_AAC_SBR_PS_v2:
462 case MimeUtil::H264_BASELINE:
463 case MimeUtil::H264_MAIN:
464 case MimeUtil::H264_HIGH:
465 case MimeUtil::VP8:
466 case MimeUtil::VORBIS:
467 return true;
469 case MimeUtil::MPEG2_AAC_LC:
470 case MimeUtil::MPEG2_AAC_MAIN:
471 case MimeUtil::MPEG2_AAC_SSR:
472 // MPEG-2 variants of AAC are not supported on Android.
473 return false;
475 case MimeUtil::VP9:
476 // VP9 is supported only in KitKat+ (API Level 19).
477 return base::android::BuildInfo::GetInstance()->sdk_int() >= 19;
479 case MimeUtil::OPUS:
480 // Opus is supported only in Lollipop+ (API Level 21).
481 return base::android::BuildInfo::GetInstance()->sdk_int() >= 21;
483 case MimeUtil::THEORA:
484 return false;
487 return false;
490 static bool IsMimeTypeSupportedOnAndroid(const std::string& mimeType) {
491 // HLS codecs are supported in ICS and above (API level 14)
492 if ((!mimeType.compare("application/vnd.apple.mpegurl") ||
493 !mimeType.compare("application/x-mpegurl")) &&
494 base::android::BuildInfo::GetInstance()->sdk_int() < 14) {
495 return false;
497 return true;
499 #endif
501 struct MediaFormatStrict {
502 const char* const mime_type;
503 const char* const codecs_list;
506 // Following is the list of RFC 6381 compliant codecs:
507 // mp4a.66 - MPEG-2 AAC MAIN
508 // mp4a.67 - MPEG-2 AAC LC
509 // mp4a.68 - MPEG-2 AAC SSR
510 // mp4a.69 - MPEG-2 extension to MPEG-1
511 // mp4a.6B - MPEG-1 audio
512 // mp4a.40.2 - MPEG-4 AAC LC
513 // mp4a.40.02 - MPEG-4 AAC LC (leading 0 in aud-oti for compatibility)
514 // mp4a.40.5 - MPEG-4 HE-AAC v1 (AAC LC + SBR)
515 // mp4a.40.05 - MPEG-4 HE-AAC v1 (AAC LC + SBR) (leading 0 in aud-oti for
516 // compatibility)
517 // mp4a.40.29 - MPEG-4 HE-AAC v2 (AAC LC + SBR + PS)
519 // avc1.42E0xx - H.264 Baseline
520 // avc1.4D40xx - H.264 Main
521 // avc1.6400xx - H.264 High
522 static const char kMP4AudioCodecsExpression[] =
523 "mp4a.66,mp4a.67,mp4a.68,mp4a.69,mp4a.6B,mp4a.40.2,mp4a.40.02,mp4a.40.5,"
524 "mp4a.40.05,mp4a.40.29";
525 static const char kMP4VideoCodecsExpression[] =
526 // This is not a complete list of supported avc1 codecs. It is simply used
527 // to register support for the corresponding Codec enum. Instead of using
528 // strings in these three arrays, we should use the Codec enum values.
529 // This will avoid confusion and unnecessary parsing at runtime.
530 // kUnambiguousCodecStringMap/kAmbiguousCodecStringMap should be the only
531 // mapping from strings to codecs. See crbug.com/461009.
532 "avc1.42E00A,avc1.4D400A,avc1.64000A,"
533 "mp4a.66,mp4a.67,mp4a.68,mp4a.69,mp4a.6B,mp4a.40.2,mp4a.40.02,mp4a.40.5,"
534 "mp4a.40.05,mp4a.40.29";
536 // These containers are also included in
537 // common_media_types/proprietary_media_types. See crbug.com/461012.
538 static const MediaFormatStrict format_codec_mappings[] = {
539 {"video/webm", "opus,vorbis,vp8,vp8.0,vp9,vp9.0"},
540 {"audio/webm", "opus,vorbis"},
541 {"audio/wav", "1"},
542 {"audio/x-wav", "1"},
543 // Android does not support Opus in Ogg container.
544 #if defined(OS_ANDROID)
545 {"video/ogg", "theora,vorbis"},
546 {"audio/ogg", "vorbis"},
547 {"application/ogg", "theora,vorbis"},
548 #else
549 {"video/ogg", "opus,theora,vorbis"},
550 {"audio/ogg", "opus,vorbis"},
551 {"application/ogg", "opus,theora,vorbis"},
552 #endif
553 {"audio/mpeg", "mp3"},
554 {"audio/mp3", ""},
555 {"audio/x-mp3", ""},
556 {"audio/mp4", kMP4AudioCodecsExpression},
557 {"audio/x-m4a", kMP4AudioCodecsExpression},
558 {"video/mp4", kMP4VideoCodecsExpression},
559 {"video/x-m4v", kMP4VideoCodecsExpression},
560 {"application/x-mpegurl", kMP4VideoCodecsExpression},
561 {"application/vnd.apple.mpegurl", kMP4VideoCodecsExpression}};
563 struct CodecIDMappings {
564 const char* const codec_id;
565 MimeUtil::Codec codec;
568 // List of codec IDs that provide enough information to determine the
569 // codec and profile being requested.
571 // The "mp4a" strings come from RFC 6381.
572 static const CodecIDMappings kUnambiguousCodecStringMap[] = {
573 {"1", MimeUtil::PCM}, // We only allow this for WAV so it isn't ambiguous.
574 // avc1/avc3.XXXXXX may be unambiguous; handled by ParseH264CodecID().
575 {"mp3", MimeUtil::MP3},
576 {"mp4a.66", MimeUtil::MPEG2_AAC_MAIN},
577 {"mp4a.67", MimeUtil::MPEG2_AAC_LC},
578 {"mp4a.68", MimeUtil::MPEG2_AAC_SSR},
579 {"mp4a.69", MimeUtil::MP3},
580 {"mp4a.6B", MimeUtil::MP3},
581 {"mp4a.40.2", MimeUtil::MPEG4_AAC_LC},
582 {"mp4a.40.02", MimeUtil::MPEG4_AAC_LC},
583 {"mp4a.40.5", MimeUtil::MPEG4_AAC_SBR_v1},
584 {"mp4a.40.05", MimeUtil::MPEG4_AAC_SBR_v1},
585 {"mp4a.40.29", MimeUtil::MPEG4_AAC_SBR_PS_v2},
586 {"vorbis", MimeUtil::VORBIS},
587 {"opus", MimeUtil::OPUS},
588 {"vp8", MimeUtil::VP8},
589 {"vp8.0", MimeUtil::VP8},
590 {"vp9", MimeUtil::VP9},
591 {"vp9.0", MimeUtil::VP9},
592 {"theora", MimeUtil::THEORA}};
594 // List of codec IDs that are ambiguous and don't provide
595 // enough information to determine the codec and profile.
596 // The codec in these entries indicate the codec and profile
597 // we assume the user is trying to indicate.
598 static const CodecIDMappings kAmbiguousCodecStringMap[] = {
599 {"mp4a.40", MimeUtil::MPEG4_AAC_LC},
600 {"avc1", MimeUtil::H264_BASELINE},
601 {"avc3", MimeUtil::H264_BASELINE},
602 // avc1/avc3.XXXXXX may be ambiguous; handled by ParseH264CodecID().
605 MimeUtil::MimeUtil() : allow_proprietary_codecs_(false) {
606 InitializeMimeTypeMaps();
609 SupportsType MimeUtil::AreSupportedCodecs(
610 const CodecSet& supported_codecs,
611 const std::vector<std::string>& codecs) const {
612 DCHECK(!supported_codecs.empty());
613 DCHECK(!codecs.empty());
615 SupportsType result = IsSupported;
616 for (size_t i = 0; i < codecs.size(); ++i) {
617 bool is_ambiguous = true;
618 Codec codec = INVALID_CODEC;
619 if (!StringToCodec(codecs[i], &codec, &is_ambiguous))
620 return IsNotSupported;
622 if (!IsCodecSupported(codec) ||
623 supported_codecs.find(codec) == supported_codecs.end()) {
624 return IsNotSupported;
627 if (is_ambiguous)
628 result = MayBeSupported;
631 return result;
634 void MimeUtil::InitializeMimeTypeMaps() {
635 for (size_t i = 0; i < arraysize(supported_image_types); ++i)
636 image_map_.insert(supported_image_types[i]);
638 // Initialize the supported non-image types.
639 for (size_t i = 0; i < arraysize(supported_non_image_types); ++i)
640 non_image_map_.insert(supported_non_image_types[i]);
641 for (size_t i = 0; i < arraysize(supported_certificate_types); ++i)
642 non_image_map_.insert(supported_certificate_types[i].mime_type);
643 for (size_t i = 0; i < arraysize(unsupported_text_types); ++i)
644 unsupported_text_map_.insert(unsupported_text_types[i]);
645 for (size_t i = 0; i < arraysize(supported_javascript_types); ++i)
646 non_image_map_.insert(supported_javascript_types[i]);
647 for (size_t i = 0; i < arraysize(common_media_types); ++i) {
648 #if defined(OS_ANDROID)
649 if (!IsMimeTypeSupportedOnAndroid(common_media_types[i]))
650 continue;
651 #endif
652 non_image_map_.insert(common_media_types[i]);
654 #if defined(USE_PROPRIETARY_CODECS)
655 allow_proprietary_codecs_ = true;
657 for (size_t i = 0; i < arraysize(proprietary_media_types); ++i)
658 non_image_map_.insert(proprietary_media_types[i]);
659 #endif
661 // Initialize the supported media types.
662 for (size_t i = 0; i < arraysize(common_media_types); ++i) {
663 #if defined(OS_ANDROID)
664 if (!IsMimeTypeSupportedOnAndroid(common_media_types[i]))
665 continue;
666 #endif
667 media_map_.insert(common_media_types[i]);
669 #if defined(USE_PROPRIETARY_CODECS)
670 for (size_t i = 0; i < arraysize(proprietary_media_types); ++i)
671 media_map_.insert(proprietary_media_types[i]);
672 #endif
674 for (size_t i = 0; i < arraysize(supported_javascript_types); ++i)
675 javascript_map_.insert(supported_javascript_types[i]);
677 for (size_t i = 0; i < arraysize(kUnambiguousCodecStringMap); ++i) {
678 string_to_codec_map_[kUnambiguousCodecStringMap[i].codec_id] =
679 CodecEntry(kUnambiguousCodecStringMap[i].codec, false);
682 for (size_t i = 0; i < arraysize(kAmbiguousCodecStringMap); ++i) {
683 string_to_codec_map_[kAmbiguousCodecStringMap[i].codec_id] =
684 CodecEntry(kAmbiguousCodecStringMap[i].codec, true);
687 // Initialize the strict supported media types.
688 for (size_t i = 0; i < arraysize(format_codec_mappings); ++i) {
689 std::vector<std::string> mime_type_codecs;
690 ParseCodecString(format_codec_mappings[i].codecs_list,
691 &mime_type_codecs,
692 false);
694 CodecSet codecs;
695 for (size_t j = 0; j < mime_type_codecs.size(); ++j) {
696 Codec codec = INVALID_CODEC;
697 bool is_ambiguous = true;
698 CHECK(StringToCodec(mime_type_codecs[j], &codec, &is_ambiguous));
699 DCHECK(!is_ambiguous);
700 codecs.insert(codec);
703 strict_format_map_[format_codec_mappings[i].mime_type] = codecs;
707 bool MimeUtil::IsSupportedImageMimeType(const std::string& mime_type) const {
708 return image_map_.find(base::StringToLowerASCII(mime_type)) !=
709 image_map_.end();
712 bool MimeUtil::IsSupportedMediaMimeType(const std::string& mime_type) const {
713 return media_map_.find(base::StringToLowerASCII(mime_type)) !=
714 media_map_.end();
717 bool MimeUtil::IsSupportedNonImageMimeType(const std::string& mime_type) const {
718 return non_image_map_.find(base::StringToLowerASCII(mime_type)) !=
719 non_image_map_.end() ||
720 (StartsWithASCII(mime_type, "text/", false /* case insensitive */) &&
721 !IsUnsupportedTextMimeType(mime_type)) ||
722 (StartsWithASCII(mime_type, "application/", false) &&
723 MatchesMimeType("application/*+json", mime_type));
726 bool MimeUtil::IsUnsupportedTextMimeType(const std::string& mime_type) const {
727 return unsupported_text_map_.find(base::StringToLowerASCII(mime_type)) !=
728 unsupported_text_map_.end();
731 bool MimeUtil::IsSupportedJavascriptMimeType(
732 const std::string& mime_type) const {
733 return javascript_map_.find(mime_type) != javascript_map_.end();
736 // Mirrors WebViewImpl::CanShowMIMEType()
737 bool MimeUtil::IsSupportedMimeType(const std::string& mime_type) const {
738 return (StartsWithASCII(mime_type, "image/", false) &&
739 IsSupportedImageMimeType(mime_type)) ||
740 IsSupportedNonImageMimeType(mime_type);
743 // Tests for MIME parameter equality. Each parameter in the |mime_type_pattern|
744 // must be matched by a parameter in the |mime_type|. If there are no
745 // parameters in the pattern, the match is a success.
747 // According rfc2045 keys of parameters are case-insensitive, while values may
748 // or may not be case-sensitive, but they are usually case-sensitive. So, this
749 // function matches values in *case-sensitive* manner, however note that this
750 // may produce some false negatives.
751 bool MatchesMimeTypeParameters(const std::string& mime_type_pattern,
752 const std::string& mime_type) {
753 typedef std::map<std::string, std::string> StringPairMap;
755 const std::string::size_type semicolon = mime_type_pattern.find(';');
756 const std::string::size_type test_semicolon = mime_type.find(';');
757 if (semicolon != std::string::npos) {
758 if (test_semicolon == std::string::npos)
759 return false;
761 base::StringPairs pattern_parameters;
762 base::SplitStringIntoKeyValuePairs(mime_type_pattern.substr(semicolon + 1),
763 '=', ';', &pattern_parameters);
764 base::StringPairs test_parameters;
765 base::SplitStringIntoKeyValuePairs(mime_type.substr(test_semicolon + 1),
766 '=', ';', &test_parameters);
768 // Put the parameters to maps with the keys converted to lower case.
769 StringPairMap pattern_parameter_map;
770 for (const auto& pair : pattern_parameters) {
771 pattern_parameter_map[base::StringToLowerASCII(pair.first)] = pair.second;
774 StringPairMap test_parameter_map;
775 for (const auto& pair : test_parameters) {
776 test_parameter_map[base::StringToLowerASCII(pair.first)] = pair.second;
779 if (pattern_parameter_map.size() > test_parameter_map.size())
780 return false;
782 for (const auto& parameter_pair : pattern_parameter_map) {
783 const auto& test_parameter_pair_it =
784 test_parameter_map.find(parameter_pair.first);
785 if (test_parameter_pair_it == test_parameter_map.end())
786 return false;
787 if (parameter_pair.second != test_parameter_pair_it->second)
788 return false;
792 return true;
795 // This comparison handles absolute maching and also basic
796 // wildcards. The plugin mime types could be:
797 // application/x-foo
798 // application/*
799 // application/*+xml
800 // *
801 // Also tests mime parameters -- all parameters in the pattern must be present
802 // in the tested type for a match to succeed.
803 bool MimeUtil::MatchesMimeType(const std::string& mime_type_pattern,
804 const std::string& mime_type) const {
805 if (mime_type_pattern.empty())
806 return false;
808 std::string::size_type semicolon = mime_type_pattern.find(';');
809 const std::string base_pattern(mime_type_pattern.substr(0, semicolon));
810 semicolon = mime_type.find(';');
811 const std::string base_type(mime_type.substr(0, semicolon));
813 if (base_pattern == "*" || base_pattern == "*/*")
814 return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
816 const std::string::size_type star = base_pattern.find('*');
817 if (star == std::string::npos) {
818 if (base_pattern.size() == base_type.size() &&
819 base::strncasecmp(base_pattern.c_str(), base_type.c_str(),
820 base_pattern.size()) == 0) {
821 return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
822 } else {
823 return false;
827 // Test length to prevent overlap between |left| and |right|.
828 if (base_type.length() < base_pattern.length() - 1)
829 return false;
831 const std::string left(base_pattern.substr(0, star));
832 const std::string right(base_pattern.substr(star + 1));
834 if (!StartsWithASCII(base_type, left, false))
835 return false;
837 if (!right.empty() && !EndsWith(base_type, right, false))
838 return false;
840 return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
843 // See http://www.iana.org/assignments/media-types/media-types.xhtml
844 static const char* const legal_top_level_types[] = {
845 "application",
846 "audio",
847 "example",
848 "image",
849 "message",
850 "model",
851 "multipart",
852 "text",
853 "video",
856 bool MimeUtil::ParseMimeTypeWithoutParameter(
857 const std::string& type_string,
858 std::string* top_level_type,
859 std::string* subtype) const {
860 std::vector<std::string> components;
861 base::SplitString(type_string, '/', &components);
862 if (components.size() != 2 ||
863 !HttpUtil::IsToken(components[0]) ||
864 !HttpUtil::IsToken(components[1]))
865 return false;
867 if (top_level_type)
868 *top_level_type = components[0];
869 if (subtype)
870 *subtype = components[1];
871 return true;
874 bool MimeUtil::IsValidTopLevelMimeType(const std::string& type_string) const {
875 std::string lower_type = base::StringToLowerASCII(type_string);
876 for (size_t i = 0; i < arraysize(legal_top_level_types); ++i) {
877 if (lower_type.compare(legal_top_level_types[i]) == 0)
878 return true;
881 return type_string.size() > 2 && StartsWithASCII(type_string, "x-", false);
884 bool MimeUtil::AreSupportedMediaCodecs(
885 const std::vector<std::string>& codecs) const {
886 for (size_t i = 0; i < codecs.size(); ++i) {
887 Codec codec = INVALID_CODEC;
888 bool is_ambiguous = true;
889 if (!StringToCodec(codecs[i], &codec, &is_ambiguous) ||
890 !IsCodecSupported(codec)) {
891 return false;
894 return true;
897 void MimeUtil::ParseCodecString(const std::string& codecs,
898 std::vector<std::string>* codecs_out,
899 bool strip) {
900 std::string no_quote_codecs;
901 base::TrimString(codecs, "\"", &no_quote_codecs);
902 base::SplitString(no_quote_codecs, ',', codecs_out);
904 if (!strip)
905 return;
907 // Strip everything past the first '.'
908 for (std::vector<std::string>::iterator it = codecs_out->begin();
909 it != codecs_out->end();
910 ++it) {
911 size_t found = it->find_first_of('.');
912 if (found != std::string::npos)
913 it->resize(found);
917 bool MimeUtil::IsStrictMediaMimeType(const std::string& mime_type) const {
918 return strict_format_map_.find(base::StringToLowerASCII(mime_type)) !=
919 strict_format_map_.end();
922 SupportsType MimeUtil::IsSupportedStrictMediaMimeType(
923 const std::string& mime_type,
924 const std::vector<std::string>& codecs) const {
925 const std::string mime_type_lower_case = base::StringToLowerASCII(mime_type);
926 StrictMappings::const_iterator it_strict_map =
927 strict_format_map_.find(mime_type_lower_case);
928 if (it_strict_map == strict_format_map_.end())
929 return codecs.empty() ? MayBeSupported : IsNotSupported;
931 if (it_strict_map->second.empty()) {
932 // We get here if the mimetype does not expect a codecs parameter.
933 return (codecs.empty() &&
934 IsDefaultCodecSupportedLowerCase(mime_type_lower_case))
935 ? IsSupported
936 : IsNotSupported;
939 if (codecs.empty()) {
940 // We get here if the mimetype expects to get a codecs parameter,
941 // but didn't get one. If |mime_type_lower_case| does not have a default
942 // codec the best we can do is say "maybe" because we don't have enough
943 // information.
944 Codec default_codec = INVALID_CODEC;
945 if (!GetDefaultCodecLowerCase(mime_type_lower_case, &default_codec))
946 return MayBeSupported;
948 return IsCodecSupported(default_codec) ? IsSupported : IsNotSupported;
951 return AreSupportedCodecs(it_strict_map->second, codecs);
954 void MimeUtil::RemoveProprietaryMediaTypesAndCodecsForTests() {
955 for (size_t i = 0; i < arraysize(proprietary_media_types); ++i) {
956 non_image_map_.erase(proprietary_media_types[i]);
957 media_map_.erase(proprietary_media_types[i]);
959 allow_proprietary_codecs_ = false;
962 // Returns true iff |profile_str| conforms to hex string "42y0", where y is one
963 // of [8..F]. Requiring constraint_set0_flag be set and profile_idc be 0x42 is
964 // taken from ISO-14496-10 7.3.2.1, 7.4.2.1, and Annex A.2.1.
966 // |profile_str| is the first four characters of the H.264 suffix string
967 // (ignoring the last 2 characters of the full 6 character suffix that are
968 // level_idc). From ISO-14496-10 7.3.2.1, it consists of:
969 // 8 bits: profile_idc: required to be 0x42 here.
970 // 1 bit: constraint_set0_flag : required to be true here.
971 // 1 bit: constraint_set1_flag : ignored here.
972 // 1 bit: constraint_set2_flag : ignored here.
973 // 1 bit: constraint_set3_flag : ignored here.
974 // 4 bits: reserved : required to be 0 here.
976 // The spec indicates other ways, not implemented here, that a |profile_str|
977 // can indicate a baseline conforming decoder is sufficient for decode in Annex
978 // A.2.1: "[profile_idc not necessarily 0x42] with constraint_set0_flag set and
979 // in which level_idc and constraint_set3_flag represent a level less than or
980 // equal to the specified level."
981 static bool IsValidH264BaselineProfile(const std::string& profile_str) {
982 uint32 constraint_set_bits;
983 if (profile_str.size() != 4 ||
984 profile_str[0] != '4' ||
985 profile_str[1] != '2' ||
986 profile_str[3] != '0' ||
987 !base::HexStringToUInt(base::StringPiece(profile_str.c_str() + 2, 1),
988 &constraint_set_bits)) {
989 return false;
992 return constraint_set_bits >= 8;
995 static bool IsValidH264Level(const std::string& level_str) {
996 uint32 level;
997 if (level_str.size() != 2 || !base::HexStringToUInt(level_str, &level))
998 return false;
1000 // Valid levels taken from Table A-1 in ISO-14496-10.
1001 // Essentially |level_str| is toHex(10 * level).
1002 return ((level >= 10 && level <= 13) ||
1003 (level >= 20 && level <= 22) ||
1004 (level >= 30 && level <= 32) ||
1005 (level >= 40 && level <= 42) ||
1006 (level >= 50 && level <= 51));
1009 // Handle parsing H.264 codec IDs as outlined in RFC 6381 and ISO-14496-10.
1010 // avc1.42y0xx, y >= 8 - H.264 Baseline
1011 // avc1.4D40xx - H.264 Main
1012 // avc1.6400xx - H.264 High
1014 // avc1.xxxxxx & avc3.xxxxxx are considered ambiguous forms that are trying to
1015 // signal H.264 Baseline. For example, the idc_level, profile_idc and
1016 // constraint_set3_flag pieces may explicitly require decoder to conform to
1017 // baseline profile at the specified level (see Annex A and constraint_set0 in
1018 // ISO-14496-10).
1019 static bool ParseH264CodecID(const std::string& codec_id,
1020 MimeUtil::Codec* codec,
1021 bool* is_ambiguous) {
1022 // Make sure we have avc1.xxxxxx or avc3.xxxxxx
1023 if (codec_id.size() != 11 ||
1024 (!StartsWithASCII(codec_id, "avc1.", true) &&
1025 !StartsWithASCII(codec_id, "avc3.", true))) {
1026 return false;
1029 std::string profile = StringToUpperASCII(codec_id.substr(5, 4));
1030 if (IsValidH264BaselineProfile(profile)) {
1031 *codec = MimeUtil::H264_BASELINE;
1032 } else if (profile == "4D40") {
1033 *codec = MimeUtil::H264_MAIN;
1034 } else if (profile == "6400") {
1035 *codec = MimeUtil::H264_HIGH;
1036 } else {
1037 *codec = MimeUtil::H264_BASELINE;
1038 *is_ambiguous = true;
1039 return true;
1042 *is_ambiguous = !IsValidH264Level(StringToUpperASCII(codec_id.substr(9)));
1043 return true;
1046 bool MimeUtil::StringToCodec(const std::string& codec_id,
1047 Codec* codec,
1048 bool* is_ambiguous) const {
1049 StringToCodecMappings::const_iterator itr =
1050 string_to_codec_map_.find(codec_id);
1051 if (itr != string_to_codec_map_.end()) {
1052 *codec = itr->second.codec;
1053 *is_ambiguous = itr->second.is_ambiguous;
1054 return true;
1057 // If |codec_id| is not in |string_to_codec_map_|, then we assume that it is
1058 // an H.264 codec ID because currently those are the only ones that can't be
1059 // stored in the |string_to_codec_map_| and require parsing.
1060 return ParseH264CodecID(codec_id, codec, is_ambiguous);
1063 bool MimeUtil::IsCodecSupported(Codec codec) const {
1064 DCHECK_NE(codec, INVALID_CODEC);
1066 #if defined(OS_ANDROID)
1067 if (!IsCodecSupportedOnAndroid(codec))
1068 return false;
1069 #endif
1071 return allow_proprietary_codecs_ || !IsCodecProprietary(codec);
1074 bool MimeUtil::IsCodecProprietary(Codec codec) const {
1075 switch (codec) {
1076 case INVALID_CODEC:
1077 case MP3:
1078 case MPEG2_AAC_LC:
1079 case MPEG2_AAC_MAIN:
1080 case MPEG2_AAC_SSR:
1081 case MPEG4_AAC_LC:
1082 case MPEG4_AAC_SBR_v1:
1083 case MPEG4_AAC_SBR_PS_v2:
1084 case H264_BASELINE:
1085 case H264_MAIN:
1086 case H264_HIGH:
1087 return true;
1089 case PCM:
1090 case VORBIS:
1091 case OPUS:
1092 case VP8:
1093 case VP9:
1094 case THEORA:
1095 return false;
1098 return true;
1101 bool MimeUtil::GetDefaultCodecLowerCase(const std::string& mime_type_lower_case,
1102 Codec* default_codec) const {
1103 if (mime_type_lower_case == "audio/mpeg" ||
1104 mime_type_lower_case == "audio/mp3" ||
1105 mime_type_lower_case == "audio/x-mp3") {
1106 *default_codec = MimeUtil::MP3;
1107 return true;
1110 return false;
1113 bool MimeUtil::IsDefaultCodecSupportedLowerCase(
1114 const std::string& mime_type_lower_case) const {
1115 Codec default_codec = Codec::INVALID_CODEC;
1116 if (!GetDefaultCodecLowerCase(mime_type_lower_case, &default_codec))
1117 return false;
1118 return IsCodecSupported(default_codec);
1121 //----------------------------------------------------------------------------
1122 // Wrappers for the singleton
1123 //----------------------------------------------------------------------------
1125 bool GetMimeTypeFromExtension(const base::FilePath::StringType& ext,
1126 std::string* mime_type) {
1127 return g_mime_util.Get().GetMimeTypeFromExtension(ext, mime_type);
1130 bool GetMimeTypeFromFile(const base::FilePath& file_path,
1131 std::string* mime_type) {
1132 return g_mime_util.Get().GetMimeTypeFromFile(file_path, mime_type);
1135 bool GetWellKnownMimeTypeFromExtension(const base::FilePath::StringType& ext,
1136 std::string* mime_type) {
1137 return g_mime_util.Get().GetWellKnownMimeTypeFromExtension(ext, mime_type);
1140 bool GetPreferredExtensionForMimeType(const std::string& mime_type,
1141 base::FilePath::StringType* extension) {
1142 return g_mime_util.Get().GetPreferredExtensionForMimeType(mime_type,
1143 extension);
1146 bool IsSupportedImageMimeType(const std::string& mime_type) {
1147 return g_mime_util.Get().IsSupportedImageMimeType(mime_type);
1150 bool IsSupportedMediaMimeType(const std::string& mime_type) {
1151 return g_mime_util.Get().IsSupportedMediaMimeType(mime_type);
1154 bool IsSupportedNonImageMimeType(const std::string& mime_type) {
1155 return g_mime_util.Get().IsSupportedNonImageMimeType(mime_type);
1158 bool IsUnsupportedTextMimeType(const std::string& mime_type) {
1159 return g_mime_util.Get().IsUnsupportedTextMimeType(mime_type);
1162 bool IsSupportedJavascriptMimeType(const std::string& mime_type) {
1163 return g_mime_util.Get().IsSupportedJavascriptMimeType(mime_type);
1166 bool IsSupportedMimeType(const std::string& mime_type) {
1167 return g_mime_util.Get().IsSupportedMimeType(mime_type);
1170 bool MatchesMimeType(const std::string& mime_type_pattern,
1171 const std::string& mime_type) {
1172 return g_mime_util.Get().MatchesMimeType(mime_type_pattern, mime_type);
1175 bool ParseMimeTypeWithoutParameter(const std::string& type_string,
1176 std::string* top_level_type,
1177 std::string* subtype) {
1178 return g_mime_util.Get().ParseMimeTypeWithoutParameter(
1179 type_string, top_level_type, subtype);
1182 bool IsValidTopLevelMimeType(const std::string& type_string) {
1183 return g_mime_util.Get().IsValidTopLevelMimeType(type_string);
1186 bool AreSupportedMediaCodecs(const std::vector<std::string>& codecs) {
1187 return g_mime_util.Get().AreSupportedMediaCodecs(codecs);
1190 bool IsStrictMediaMimeType(const std::string& mime_type) {
1191 return g_mime_util.Get().IsStrictMediaMimeType(mime_type);
1194 SupportsType IsSupportedStrictMediaMimeType(
1195 const std::string& mime_type,
1196 const std::vector<std::string>& codecs) {
1197 return g_mime_util.Get().IsSupportedStrictMediaMimeType(mime_type, codecs);
1200 void ParseCodecString(const std::string& codecs,
1201 std::vector<std::string>* codecs_out,
1202 const bool strip) {
1203 g_mime_util.Get().ParseCodecString(codecs, codecs_out, strip);
1206 namespace {
1208 // From http://www.w3schools.com/media/media_mimeref.asp and
1209 // http://plugindoc.mozdev.org/winmime.php
1210 static const char* const kStandardImageTypes[] = {
1211 "image/bmp",
1212 "image/cis-cod",
1213 "image/gif",
1214 "image/ief",
1215 "image/jpeg",
1216 "image/webp",
1217 "image/pict",
1218 "image/pipeg",
1219 "image/png",
1220 "image/svg+xml",
1221 "image/tiff",
1222 "image/vnd.microsoft.icon",
1223 "image/x-cmu-raster",
1224 "image/x-cmx",
1225 "image/x-icon",
1226 "image/x-portable-anymap",
1227 "image/x-portable-bitmap",
1228 "image/x-portable-graymap",
1229 "image/x-portable-pixmap",
1230 "image/x-rgb",
1231 "image/x-xbitmap",
1232 "image/x-xpixmap",
1233 "image/x-xwindowdump"
1235 static const char* const kStandardAudioTypes[] = {
1236 "audio/aac",
1237 "audio/aiff",
1238 "audio/amr",
1239 "audio/basic",
1240 "audio/midi",
1241 "audio/mp3",
1242 "audio/mp4",
1243 "audio/mpeg",
1244 "audio/mpeg3",
1245 "audio/ogg",
1246 "audio/vorbis",
1247 "audio/wav",
1248 "audio/webm",
1249 "audio/x-m4a",
1250 "audio/x-ms-wma",
1251 "audio/vnd.rn-realaudio",
1252 "audio/vnd.wave"
1254 static const char* const kStandardVideoTypes[] = {
1255 "video/avi",
1256 "video/divx",
1257 "video/flc",
1258 "video/mp4",
1259 "video/mpeg",
1260 "video/ogg",
1261 "video/quicktime",
1262 "video/sd-video",
1263 "video/webm",
1264 "video/x-dv",
1265 "video/x-m4v",
1266 "video/x-mpeg",
1267 "video/x-ms-asf",
1268 "video/x-ms-wmv"
1271 struct StandardType {
1272 const char* const leading_mime_type;
1273 const char* const* standard_types;
1274 size_t standard_types_len;
1276 static const StandardType kStandardTypes[] = {
1277 { "image/", kStandardImageTypes, arraysize(kStandardImageTypes) },
1278 { "audio/", kStandardAudioTypes, arraysize(kStandardAudioTypes) },
1279 { "video/", kStandardVideoTypes, arraysize(kStandardVideoTypes) },
1280 { NULL, NULL, 0 }
1283 void GetExtensionsFromHardCodedMappings(
1284 const MimeInfo* mappings,
1285 size_t mappings_len,
1286 const std::string& leading_mime_type,
1287 base::hash_set<base::FilePath::StringType>* extensions) {
1288 for (size_t i = 0; i < mappings_len; ++i) {
1289 if (StartsWithASCII(mappings[i].mime_type, leading_mime_type, false)) {
1290 std::vector<string> this_extensions;
1291 base::SplitString(mappings[i].extensions, ',', &this_extensions);
1292 for (size_t j = 0; j < this_extensions.size(); ++j) {
1293 #if defined(OS_WIN)
1294 base::FilePath::StringType extension(
1295 base::UTF8ToWide(this_extensions[j]));
1296 #else
1297 base::FilePath::StringType extension(this_extensions[j]);
1298 #endif
1299 extensions->insert(extension);
1305 void GetExtensionsHelper(
1306 const char* const* standard_types,
1307 size_t standard_types_len,
1308 const std::string& leading_mime_type,
1309 base::hash_set<base::FilePath::StringType>* extensions) {
1310 for (size_t i = 0; i < standard_types_len; ++i) {
1311 g_mime_util.Get().GetPlatformExtensionsForMimeType(standard_types[i],
1312 extensions);
1315 // Also look up the extensions from hard-coded mappings in case that some
1316 // supported extensions are not registered in the system registry, like ogg.
1317 GetExtensionsFromHardCodedMappings(primary_mappings,
1318 arraysize(primary_mappings),
1319 leading_mime_type,
1320 extensions);
1322 GetExtensionsFromHardCodedMappings(secondary_mappings,
1323 arraysize(secondary_mappings),
1324 leading_mime_type,
1325 extensions);
1328 // Note that the elements in the source set will be appended to the target
1329 // vector.
1330 template<class T>
1331 void HashSetToVector(base::hash_set<T>* source, std::vector<T>* target) {
1332 size_t old_target_size = target->size();
1333 target->resize(old_target_size + source->size());
1334 size_t i = 0;
1335 for (typename base::hash_set<T>::iterator iter = source->begin();
1336 iter != source->end(); ++iter, ++i)
1337 (*target)[old_target_size + i] = *iter;
1340 } // namespace
1342 void GetExtensionsForMimeType(
1343 const std::string& unsafe_mime_type,
1344 std::vector<base::FilePath::StringType>* extensions) {
1345 if (unsafe_mime_type == "*/*" || unsafe_mime_type == "*")
1346 return;
1348 const std::string mime_type = base::StringToLowerASCII(unsafe_mime_type);
1349 base::hash_set<base::FilePath::StringType> unique_extensions;
1351 if (EndsWith(mime_type, "/*", false)) {
1352 std::string leading_mime_type = mime_type.substr(0, mime_type.length() - 1);
1354 // Find the matching StandardType from within kStandardTypes, or fall
1355 // through to the last (default) StandardType.
1356 const StandardType* type = NULL;
1357 for (size_t i = 0; i < arraysize(kStandardTypes); ++i) {
1358 type = &(kStandardTypes[i]);
1359 if (type->leading_mime_type &&
1360 leading_mime_type == type->leading_mime_type)
1361 break;
1363 DCHECK(type);
1364 GetExtensionsHelper(type->standard_types,
1365 type->standard_types_len,
1366 leading_mime_type,
1367 &unique_extensions);
1368 } else {
1369 g_mime_util.Get().GetPlatformExtensionsForMimeType(mime_type,
1370 &unique_extensions);
1372 // Also look up the extensions from hard-coded mappings in case that some
1373 // supported extensions are not registered in the system registry, like ogg.
1374 GetExtensionsFromHardCodedMappings(primary_mappings,
1375 arraysize(primary_mappings),
1376 mime_type,
1377 &unique_extensions);
1379 GetExtensionsFromHardCodedMappings(secondary_mappings,
1380 arraysize(secondary_mappings),
1381 mime_type,
1382 &unique_extensions);
1385 HashSetToVector(&unique_extensions, extensions);
1388 void RemoveProprietaryMediaTypesAndCodecsForTests() {
1389 g_mime_util.Get().RemoveProprietaryMediaTypesAndCodecsForTests();
1392 CertificateMimeType GetCertificateMimeTypeForMimeType(
1393 const std::string& mime_type) {
1394 // Don't create a map, there is only one entry in the table,
1395 // except on Android.
1396 for (size_t i = 0; i < arraysize(supported_certificate_types); ++i) {
1397 if (base::strcasecmp(mime_type.c_str(),
1398 net::supported_certificate_types[i].mime_type) == 0) {
1399 return net::supported_certificate_types[i].cert_type;
1402 return CERTIFICATE_MIME_TYPE_UNKNOWN;
1405 bool IsSupportedCertificateMimeType(const std::string& mime_type) {
1406 CertificateMimeType file_type =
1407 GetCertificateMimeTypeForMimeType(mime_type);
1408 return file_type != CERTIFICATE_MIME_TYPE_UNKNOWN;
1411 void AddMultipartValueForUpload(const std::string& value_name,
1412 const std::string& value,
1413 const std::string& mime_boundary,
1414 const std::string& content_type,
1415 std::string* post_data) {
1416 DCHECK(post_data);
1417 // First line is the boundary.
1418 post_data->append("--" + mime_boundary + "\r\n");
1419 // Next line is the Content-disposition.
1420 post_data->append("Content-Disposition: form-data; name=\"" +
1421 value_name + "\"\r\n");
1422 if (!content_type.empty()) {
1423 // If Content-type is specified, the next line is that.
1424 post_data->append("Content-Type: " + content_type + "\r\n");
1426 // Leave an empty line and append the value.
1427 post_data->append("\r\n" + value + "\r\n");
1430 void AddMultipartFinalDelimiterForUpload(const std::string& mime_boundary,
1431 std::string* post_data) {
1432 DCHECK(post_data);
1433 post_data->append("--" + mime_boundary + "--\r\n");
1436 } // namespace net