Work on Windows GN component build.
[chromium-blink-merge.git] / net / base / mime_util.cc
blob0b42b85920239bded4ff775fa81c2544b8889d36
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.
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;
489 #endif
491 struct MediaFormatStrict {
492 const char* const mime_type;
493 const char* const codecs_list;
496 // Following is the list of RFC 6381 compliant codecs:
497 // mp4a.66 - MPEG-2 AAC MAIN
498 // mp4a.67 - MPEG-2 AAC LC
499 // mp4a.68 - MPEG-2 AAC SSR
500 // mp4a.69 - MPEG-2 extension to MPEG-1
501 // mp4a.6B - MPEG-1 audio
502 // mp4a.40.2 - MPEG-4 AAC LC
503 // mp4a.40.02 - MPEG-4 AAC LC (leading 0 in aud-oti for compatibility)
504 // mp4a.40.5 - MPEG-4 HE-AAC v1 (AAC LC + SBR)
505 // mp4a.40.05 - MPEG-4 HE-AAC v1 (AAC LC + SBR) (leading 0 in aud-oti for
506 // compatibility)
507 // mp4a.40.29 - MPEG-4 HE-AAC v2 (AAC LC + SBR + PS)
509 // avc1.42E0xx - H.264 Baseline
510 // avc1.4D40xx - H.264 Main
511 // avc1.6400xx - H.264 High
512 static const char kMP4AudioCodecsExpression[] =
513 "mp4a.66,mp4a.67,mp4a.68,mp4a.69,mp4a.6B,mp4a.40.2,mp4a.40.02,mp4a.40.5,"
514 "mp4a.40.05,mp4a.40.29";
515 static const char kMP4VideoCodecsExpression[] =
516 // This is not a complete list of supported avc1 codecs. It is simply used
517 // to register support for the corresponding Codec enum. Instead of using
518 // strings in these three arrays, we should use the Codec enum values.
519 // This will avoid confusion and unnecessary parsing at runtime.
520 // kUnambiguousCodecStringMap/kAmbiguousCodecStringMap should be the only
521 // mapping from strings to codecs. See crbug.com/461009.
522 "avc1.42E00A,avc1.4D400A,avc1.64000A,"
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";
526 // These containers are also included in
527 // common_media_types/proprietary_media_types. See crbug.com/461012.
528 static const MediaFormatStrict format_codec_mappings[] = {
529 {"video/webm", "opus,vorbis,vp8,vp8.0,vp9,vp9.0"},
530 {"audio/webm", "opus,vorbis"},
531 {"audio/wav", "1"},
532 {"audio/x-wav", "1"},
533 // Android does not support Opus in Ogg container.
534 #if defined(OS_ANDROID)
535 {"video/ogg", "theora,vorbis"},
536 {"audio/ogg", "vorbis"},
537 {"application/ogg", "theora,vorbis"},
538 #else
539 {"video/ogg", "opus,theora,vorbis"},
540 {"audio/ogg", "opus,vorbis"},
541 {"application/ogg", "opus,theora,vorbis"},
542 #endif
543 {"audio/mpeg", "mp3"},
544 {"audio/mp3", ""},
545 {"audio/x-mp3", ""},
546 {"audio/mp4", kMP4AudioCodecsExpression},
547 {"audio/x-m4a", kMP4AudioCodecsExpression},
548 {"video/mp4", kMP4VideoCodecsExpression},
549 {"video/x-m4v", kMP4VideoCodecsExpression},
550 {"application/x-mpegurl", kMP4VideoCodecsExpression},
551 {"application/vnd.apple.mpegurl", kMP4VideoCodecsExpression}};
553 struct CodecIDMappings {
554 const char* const codec_id;
555 MimeUtil::Codec codec;
558 // List of codec IDs that provide enough information to determine the
559 // codec and profile being requested.
561 // The "mp4a" strings come from RFC 6381.
562 static const CodecIDMappings kUnambiguousCodecStringMap[] = {
563 {"1", MimeUtil::PCM}, // We only allow this for WAV so it isn't ambiguous.
564 // avc1/avc3.XXXXXX may be unambiguous; handled by ParseH264CodecID().
565 {"mp3", MimeUtil::MP3},
566 {"mp4a.66", MimeUtil::MPEG2_AAC_MAIN},
567 {"mp4a.67", MimeUtil::MPEG2_AAC_LC},
568 {"mp4a.68", MimeUtil::MPEG2_AAC_SSR},
569 {"mp4a.69", MimeUtil::MP3},
570 {"mp4a.6B", MimeUtil::MP3},
571 {"mp4a.40.2", MimeUtil::MPEG4_AAC_LC},
572 {"mp4a.40.02", MimeUtil::MPEG4_AAC_LC},
573 {"mp4a.40.5", MimeUtil::MPEG4_AAC_SBR_v1},
574 {"mp4a.40.05", MimeUtil::MPEG4_AAC_SBR_v1},
575 {"mp4a.40.29", MimeUtil::MPEG4_AAC_SBR_PS_v2},
576 {"vorbis", MimeUtil::VORBIS},
577 {"opus", MimeUtil::OPUS},
578 {"vp8", MimeUtil::VP8},
579 {"vp8.0", MimeUtil::VP8},
580 {"vp9", MimeUtil::VP9},
581 {"vp9.0", MimeUtil::VP9},
582 {"theora", MimeUtil::THEORA}};
584 // List of codec IDs that are ambiguous and don't provide
585 // enough information to determine the codec and profile.
586 // The codec in these entries indicate the codec and profile
587 // we assume the user is trying to indicate.
588 static const CodecIDMappings kAmbiguousCodecStringMap[] = {
589 {"mp4a.40", MimeUtil::MPEG4_AAC_LC},
590 {"avc1", MimeUtil::H264_BASELINE},
591 {"avc3", MimeUtil::H264_BASELINE},
592 // avc1/avc3.XXXXXX may be ambiguous; handled by ParseH264CodecID().
595 MimeUtil::MimeUtil() : allow_proprietary_codecs_(false) {
596 InitializeMimeTypeMaps();
599 SupportsType MimeUtil::AreSupportedCodecs(
600 const CodecSet& supported_codecs,
601 const std::vector<std::string>& codecs) const {
602 DCHECK(!supported_codecs.empty());
603 DCHECK(!codecs.empty());
605 SupportsType result = IsSupported;
606 for (size_t i = 0; i < codecs.size(); ++i) {
607 bool is_ambiguous = true;
608 Codec codec = INVALID_CODEC;
609 if (!StringToCodec(codecs[i], &codec, &is_ambiguous))
610 return IsNotSupported;
612 if (!IsCodecSupported(codec) ||
613 supported_codecs.find(codec) == supported_codecs.end()) {
614 return IsNotSupported;
617 if (is_ambiguous)
618 result = MayBeSupported;
621 return result;
624 void MimeUtil::InitializeMimeTypeMaps() {
625 for (size_t i = 0; i < arraysize(supported_image_types); ++i)
626 image_map_.insert(supported_image_types[i]);
628 // Initialize the supported non-image types.
629 for (size_t i = 0; i < arraysize(supported_non_image_types); ++i)
630 non_image_map_.insert(supported_non_image_types[i]);
631 for (size_t i = 0; i < arraysize(supported_certificate_types); ++i)
632 non_image_map_.insert(supported_certificate_types[i].mime_type);
633 for (size_t i = 0; i < arraysize(unsupported_text_types); ++i)
634 unsupported_text_map_.insert(unsupported_text_types[i]);
635 for (size_t i = 0; i < arraysize(supported_javascript_types); ++i)
636 non_image_map_.insert(supported_javascript_types[i]);
637 for (size_t i = 0; i < arraysize(common_media_types); ++i) {
638 non_image_map_.insert(common_media_types[i]);
640 #if defined(USE_PROPRIETARY_CODECS)
641 allow_proprietary_codecs_ = true;
643 for (size_t i = 0; i < arraysize(proprietary_media_types); ++i)
644 non_image_map_.insert(proprietary_media_types[i]);
645 #endif
647 // Initialize the supported media types.
648 for (size_t i = 0; i < arraysize(common_media_types); ++i) {
649 media_map_.insert(common_media_types[i]);
651 #if defined(USE_PROPRIETARY_CODECS)
652 for (size_t i = 0; i < arraysize(proprietary_media_types); ++i)
653 media_map_.insert(proprietary_media_types[i]);
654 #endif
656 for (size_t i = 0; i < arraysize(supported_javascript_types); ++i)
657 javascript_map_.insert(supported_javascript_types[i]);
659 for (size_t i = 0; i < arraysize(kUnambiguousCodecStringMap); ++i) {
660 string_to_codec_map_[kUnambiguousCodecStringMap[i].codec_id] =
661 CodecEntry(kUnambiguousCodecStringMap[i].codec, false);
664 for (size_t i = 0; i < arraysize(kAmbiguousCodecStringMap); ++i) {
665 string_to_codec_map_[kAmbiguousCodecStringMap[i].codec_id] =
666 CodecEntry(kAmbiguousCodecStringMap[i].codec, true);
669 // Initialize the strict supported media types.
670 for (size_t i = 0; i < arraysize(format_codec_mappings); ++i) {
671 std::vector<std::string> mime_type_codecs;
672 ParseCodecString(format_codec_mappings[i].codecs_list,
673 &mime_type_codecs,
674 false);
676 CodecSet codecs;
677 for (size_t j = 0; j < mime_type_codecs.size(); ++j) {
678 Codec codec = INVALID_CODEC;
679 bool is_ambiguous = true;
680 CHECK(StringToCodec(mime_type_codecs[j], &codec, &is_ambiguous));
681 DCHECK(!is_ambiguous);
682 codecs.insert(codec);
685 strict_format_map_[format_codec_mappings[i].mime_type] = codecs;
689 bool MimeUtil::IsSupportedImageMimeType(const std::string& mime_type) const {
690 return image_map_.find(base::StringToLowerASCII(mime_type)) !=
691 image_map_.end();
694 bool MimeUtil::IsSupportedMediaMimeType(const std::string& mime_type) const {
695 return media_map_.find(base::StringToLowerASCII(mime_type)) !=
696 media_map_.end();
699 bool MimeUtil::IsSupportedNonImageMimeType(const std::string& mime_type) const {
700 return non_image_map_.find(base::StringToLowerASCII(mime_type)) !=
701 non_image_map_.end() ||
702 (StartsWithASCII(mime_type, "text/", false /* case insensitive */) &&
703 !IsUnsupportedTextMimeType(mime_type)) ||
704 (StartsWithASCII(mime_type, "application/", false) &&
705 MatchesMimeType("application/*+json", mime_type));
708 bool MimeUtil::IsUnsupportedTextMimeType(const std::string& mime_type) const {
709 return unsupported_text_map_.find(base::StringToLowerASCII(mime_type)) !=
710 unsupported_text_map_.end();
713 bool MimeUtil::IsSupportedJavascriptMimeType(
714 const std::string& mime_type) const {
715 return javascript_map_.find(mime_type) != javascript_map_.end();
718 // Mirrors WebViewImpl::CanShowMIMEType()
719 bool MimeUtil::IsSupportedMimeType(const std::string& mime_type) const {
720 return (StartsWithASCII(mime_type, "image/", false) &&
721 IsSupportedImageMimeType(mime_type)) ||
722 IsSupportedNonImageMimeType(mime_type);
725 // Tests for MIME parameter equality. Each parameter in the |mime_type_pattern|
726 // must be matched by a parameter in the |mime_type|. If there are no
727 // parameters in the pattern, the match is a success.
729 // According rfc2045 keys of parameters are case-insensitive, while values may
730 // or may not be case-sensitive, but they are usually case-sensitive. So, this
731 // function matches values in *case-sensitive* manner, however note that this
732 // may produce some false negatives.
733 bool MatchesMimeTypeParameters(const std::string& mime_type_pattern,
734 const std::string& mime_type) {
735 typedef std::map<std::string, std::string> StringPairMap;
737 const std::string::size_type semicolon = mime_type_pattern.find(';');
738 const std::string::size_type test_semicolon = mime_type.find(';');
739 if (semicolon != std::string::npos) {
740 if (test_semicolon == std::string::npos)
741 return false;
743 base::StringPairs pattern_parameters;
744 base::SplitStringIntoKeyValuePairs(mime_type_pattern.substr(semicolon + 1),
745 '=', ';', &pattern_parameters);
746 base::StringPairs test_parameters;
747 base::SplitStringIntoKeyValuePairs(mime_type.substr(test_semicolon + 1),
748 '=', ';', &test_parameters);
750 // Put the parameters to maps with the keys converted to lower case.
751 StringPairMap pattern_parameter_map;
752 for (const auto& pair : pattern_parameters) {
753 pattern_parameter_map[base::StringToLowerASCII(pair.first)] = pair.second;
756 StringPairMap test_parameter_map;
757 for (const auto& pair : test_parameters) {
758 test_parameter_map[base::StringToLowerASCII(pair.first)] = pair.second;
761 if (pattern_parameter_map.size() > test_parameter_map.size())
762 return false;
764 for (const auto& parameter_pair : pattern_parameter_map) {
765 const auto& test_parameter_pair_it =
766 test_parameter_map.find(parameter_pair.first);
767 if (test_parameter_pair_it == test_parameter_map.end())
768 return false;
769 if (parameter_pair.second != test_parameter_pair_it->second)
770 return false;
774 return true;
777 // This comparison handles absolute maching and also basic
778 // wildcards. The plugin mime types could be:
779 // application/x-foo
780 // application/*
781 // application/*+xml
782 // *
783 // Also tests mime parameters -- all parameters in the pattern must be present
784 // in the tested type for a match to succeed.
785 bool MimeUtil::MatchesMimeType(const std::string& mime_type_pattern,
786 const std::string& mime_type) const {
787 if (mime_type_pattern.empty())
788 return false;
790 std::string::size_type semicolon = mime_type_pattern.find(';');
791 const std::string base_pattern(mime_type_pattern.substr(0, semicolon));
792 semicolon = mime_type.find(';');
793 const std::string base_type(mime_type.substr(0, semicolon));
795 if (base_pattern == "*" || base_pattern == "*/*")
796 return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
798 const std::string::size_type star = base_pattern.find('*');
799 if (star == std::string::npos) {
800 if (base_pattern.size() == base_type.size() &&
801 base::strncasecmp(base_pattern.c_str(), base_type.c_str(),
802 base_pattern.size()) == 0) {
803 return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
804 } else {
805 return false;
809 // Test length to prevent overlap between |left| and |right|.
810 if (base_type.length() < base_pattern.length() - 1)
811 return false;
813 const std::string left(base_pattern.substr(0, star));
814 const std::string right(base_pattern.substr(star + 1));
816 if (!StartsWithASCII(base_type, left, false))
817 return false;
819 if (!right.empty() && !EndsWith(base_type, right, false))
820 return false;
822 return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
825 // See http://www.iana.org/assignments/media-types/media-types.xhtml
826 static const char* const legal_top_level_types[] = {
827 "application",
828 "audio",
829 "example",
830 "image",
831 "message",
832 "model",
833 "multipart",
834 "text",
835 "video",
838 bool MimeUtil::ParseMimeTypeWithoutParameter(
839 const std::string& type_string,
840 std::string* top_level_type,
841 std::string* subtype) const {
842 std::vector<std::string> components;
843 base::SplitString(type_string, '/', &components);
844 if (components.size() != 2 ||
845 !HttpUtil::IsToken(components[0]) ||
846 !HttpUtil::IsToken(components[1]))
847 return false;
849 if (top_level_type)
850 *top_level_type = components[0];
851 if (subtype)
852 *subtype = components[1];
853 return true;
856 bool MimeUtil::IsValidTopLevelMimeType(const std::string& type_string) const {
857 std::string lower_type = base::StringToLowerASCII(type_string);
858 for (size_t i = 0; i < arraysize(legal_top_level_types); ++i) {
859 if (lower_type.compare(legal_top_level_types[i]) == 0)
860 return true;
863 return type_string.size() > 2 && StartsWithASCII(type_string, "x-", false);
866 bool MimeUtil::AreSupportedMediaCodecs(
867 const std::vector<std::string>& codecs) const {
868 for (size_t i = 0; i < codecs.size(); ++i) {
869 Codec codec = INVALID_CODEC;
870 bool is_ambiguous = true;
871 if (!StringToCodec(codecs[i], &codec, &is_ambiguous) ||
872 !IsCodecSupported(codec)) {
873 return false;
876 return true;
879 void MimeUtil::ParseCodecString(const std::string& codecs,
880 std::vector<std::string>* codecs_out,
881 bool strip) {
882 std::string no_quote_codecs;
883 base::TrimString(codecs, "\"", &no_quote_codecs);
884 base::SplitString(no_quote_codecs, ',', codecs_out);
886 if (!strip)
887 return;
889 // Strip everything past the first '.'
890 for (std::vector<std::string>::iterator it = codecs_out->begin();
891 it != codecs_out->end();
892 ++it) {
893 size_t found = it->find_first_of('.');
894 if (found != std::string::npos)
895 it->resize(found);
899 bool MimeUtil::IsStrictMediaMimeType(const std::string& mime_type) const {
900 return strict_format_map_.find(base::StringToLowerASCII(mime_type)) !=
901 strict_format_map_.end();
904 SupportsType MimeUtil::IsSupportedStrictMediaMimeType(
905 const std::string& mime_type,
906 const std::vector<std::string>& codecs) const {
907 const std::string mime_type_lower_case = base::StringToLowerASCII(mime_type);
908 StrictMappings::const_iterator it_strict_map =
909 strict_format_map_.find(mime_type_lower_case);
910 if (it_strict_map == strict_format_map_.end())
911 return codecs.empty() ? MayBeSupported : IsNotSupported;
913 if (it_strict_map->second.empty()) {
914 // We get here if the mimetype does not expect a codecs parameter.
915 return (codecs.empty() &&
916 IsDefaultCodecSupportedLowerCase(mime_type_lower_case))
917 ? IsSupported
918 : IsNotSupported;
921 if (codecs.empty()) {
922 // We get here if the mimetype expects to get a codecs parameter,
923 // but didn't get one. If |mime_type_lower_case| does not have a default
924 // codec the best we can do is say "maybe" because we don't have enough
925 // information.
926 Codec default_codec = INVALID_CODEC;
927 if (!GetDefaultCodecLowerCase(mime_type_lower_case, &default_codec))
928 return MayBeSupported;
930 return IsCodecSupported(default_codec) ? IsSupported : IsNotSupported;
933 return AreSupportedCodecs(it_strict_map->second, codecs);
936 void MimeUtil::RemoveProprietaryMediaTypesAndCodecsForTests() {
937 for (size_t i = 0; i < arraysize(proprietary_media_types); ++i) {
938 non_image_map_.erase(proprietary_media_types[i]);
939 media_map_.erase(proprietary_media_types[i]);
941 allow_proprietary_codecs_ = false;
944 // Returns true iff |profile_str| conforms to hex string "42y0", where y is one
945 // of [8..F]. Requiring constraint_set0_flag be set and profile_idc be 0x42 is
946 // taken from ISO-14496-10 7.3.2.1, 7.4.2.1, and Annex A.2.1.
948 // |profile_str| is the first four characters of the H.264 suffix string
949 // (ignoring the last 2 characters of the full 6 character suffix that are
950 // level_idc). From ISO-14496-10 7.3.2.1, it consists of:
951 // 8 bits: profile_idc: required to be 0x42 here.
952 // 1 bit: constraint_set0_flag : required to be true here.
953 // 1 bit: constraint_set1_flag : ignored here.
954 // 1 bit: constraint_set2_flag : ignored here.
955 // 1 bit: constraint_set3_flag : ignored here.
956 // 4 bits: reserved : required to be 0 here.
958 // The spec indicates other ways, not implemented here, that a |profile_str|
959 // can indicate a baseline conforming decoder is sufficient for decode in Annex
960 // A.2.1: "[profile_idc not necessarily 0x42] with constraint_set0_flag set and
961 // in which level_idc and constraint_set3_flag represent a level less than or
962 // equal to the specified level."
963 static bool IsValidH264BaselineProfile(const std::string& profile_str) {
964 uint32 constraint_set_bits;
965 if (profile_str.size() != 4 ||
966 profile_str[0] != '4' ||
967 profile_str[1] != '2' ||
968 profile_str[3] != '0' ||
969 !base::HexStringToUInt(base::StringPiece(profile_str.c_str() + 2, 1),
970 &constraint_set_bits)) {
971 return false;
974 return constraint_set_bits >= 8;
977 static bool IsValidH264Level(const std::string& level_str) {
978 uint32 level;
979 if (level_str.size() != 2 || !base::HexStringToUInt(level_str, &level))
980 return false;
982 // Valid levels taken from Table A-1 in ISO-14496-10.
983 // Essentially |level_str| is toHex(10 * level).
984 return ((level >= 10 && level <= 13) ||
985 (level >= 20 && level <= 22) ||
986 (level >= 30 && level <= 32) ||
987 (level >= 40 && level <= 42) ||
988 (level >= 50 && level <= 51));
991 // Handle parsing H.264 codec IDs as outlined in RFC 6381 and ISO-14496-10.
992 // avc1.42y0xx, y >= 8 - H.264 Baseline
993 // avc1.4D40xx - H.264 Main
994 // avc1.6400xx - H.264 High
996 // avc1.xxxxxx & avc3.xxxxxx are considered ambiguous forms that are trying to
997 // signal H.264 Baseline. For example, the idc_level, profile_idc and
998 // constraint_set3_flag pieces may explicitly require decoder to conform to
999 // baseline profile at the specified level (see Annex A and constraint_set0 in
1000 // ISO-14496-10).
1001 static bool ParseH264CodecID(const std::string& codec_id,
1002 MimeUtil::Codec* codec,
1003 bool* is_ambiguous) {
1004 // Make sure we have avc1.xxxxxx or avc3.xxxxxx
1005 if (codec_id.size() != 11 ||
1006 (!StartsWithASCII(codec_id, "avc1.", true) &&
1007 !StartsWithASCII(codec_id, "avc3.", true))) {
1008 return false;
1011 std::string profile = StringToUpperASCII(codec_id.substr(5, 4));
1012 if (IsValidH264BaselineProfile(profile)) {
1013 *codec = MimeUtil::H264_BASELINE;
1014 } else if (profile == "4D40") {
1015 *codec = MimeUtil::H264_MAIN;
1016 } else if (profile == "6400") {
1017 *codec = MimeUtil::H264_HIGH;
1018 } else {
1019 *codec = MimeUtil::H264_BASELINE;
1020 *is_ambiguous = true;
1021 return true;
1024 *is_ambiguous = !IsValidH264Level(StringToUpperASCII(codec_id.substr(9)));
1025 return true;
1028 bool MimeUtil::StringToCodec(const std::string& codec_id,
1029 Codec* codec,
1030 bool* is_ambiguous) const {
1031 StringToCodecMappings::const_iterator itr =
1032 string_to_codec_map_.find(codec_id);
1033 if (itr != string_to_codec_map_.end()) {
1034 *codec = itr->second.codec;
1035 *is_ambiguous = itr->second.is_ambiguous;
1036 return true;
1039 // If |codec_id| is not in |string_to_codec_map_|, then we assume that it is
1040 // an H.264 codec ID because currently those are the only ones that can't be
1041 // stored in the |string_to_codec_map_| and require parsing.
1042 return ParseH264CodecID(codec_id, codec, is_ambiguous);
1045 bool MimeUtil::IsCodecSupported(Codec codec) const {
1046 DCHECK_NE(codec, INVALID_CODEC);
1048 #if defined(OS_ANDROID)
1049 if (!IsCodecSupportedOnAndroid(codec))
1050 return false;
1051 #endif
1053 return allow_proprietary_codecs_ || !IsCodecProprietary(codec);
1056 bool MimeUtil::IsCodecProprietary(Codec codec) const {
1057 switch (codec) {
1058 case INVALID_CODEC:
1059 case MP3:
1060 case MPEG2_AAC_LC:
1061 case MPEG2_AAC_MAIN:
1062 case MPEG2_AAC_SSR:
1063 case MPEG4_AAC_LC:
1064 case MPEG4_AAC_SBR_v1:
1065 case MPEG4_AAC_SBR_PS_v2:
1066 case H264_BASELINE:
1067 case H264_MAIN:
1068 case H264_HIGH:
1069 return true;
1071 case PCM:
1072 case VORBIS:
1073 case OPUS:
1074 case VP8:
1075 case VP9:
1076 case THEORA:
1077 return false;
1080 return true;
1083 bool MimeUtil::GetDefaultCodecLowerCase(const std::string& mime_type_lower_case,
1084 Codec* default_codec) const {
1085 if (mime_type_lower_case == "audio/mpeg" ||
1086 mime_type_lower_case == "audio/mp3" ||
1087 mime_type_lower_case == "audio/x-mp3") {
1088 *default_codec = MimeUtil::MP3;
1089 return true;
1092 return false;
1095 bool MimeUtil::IsDefaultCodecSupportedLowerCase(
1096 const std::string& mime_type_lower_case) const {
1097 Codec default_codec = Codec::INVALID_CODEC;
1098 if (!GetDefaultCodecLowerCase(mime_type_lower_case, &default_codec))
1099 return false;
1100 return IsCodecSupported(default_codec);
1103 //----------------------------------------------------------------------------
1104 // Wrappers for the singleton
1105 //----------------------------------------------------------------------------
1107 bool GetMimeTypeFromExtension(const base::FilePath::StringType& ext,
1108 std::string* mime_type) {
1109 return g_mime_util.Get().GetMimeTypeFromExtension(ext, mime_type);
1112 bool GetMimeTypeFromFile(const base::FilePath& file_path,
1113 std::string* mime_type) {
1114 return g_mime_util.Get().GetMimeTypeFromFile(file_path, mime_type);
1117 bool GetWellKnownMimeTypeFromExtension(const base::FilePath::StringType& ext,
1118 std::string* mime_type) {
1119 return g_mime_util.Get().GetWellKnownMimeTypeFromExtension(ext, mime_type);
1122 bool GetPreferredExtensionForMimeType(const std::string& mime_type,
1123 base::FilePath::StringType* extension) {
1124 return g_mime_util.Get().GetPreferredExtensionForMimeType(mime_type,
1125 extension);
1128 bool IsSupportedImageMimeType(const std::string& mime_type) {
1129 return g_mime_util.Get().IsSupportedImageMimeType(mime_type);
1132 bool IsSupportedMediaMimeType(const std::string& mime_type) {
1133 return g_mime_util.Get().IsSupportedMediaMimeType(mime_type);
1136 bool IsSupportedNonImageMimeType(const std::string& mime_type) {
1137 return g_mime_util.Get().IsSupportedNonImageMimeType(mime_type);
1140 bool IsUnsupportedTextMimeType(const std::string& mime_type) {
1141 return g_mime_util.Get().IsUnsupportedTextMimeType(mime_type);
1144 bool IsSupportedJavascriptMimeType(const std::string& mime_type) {
1145 return g_mime_util.Get().IsSupportedJavascriptMimeType(mime_type);
1148 bool IsSupportedMimeType(const std::string& mime_type) {
1149 return g_mime_util.Get().IsSupportedMimeType(mime_type);
1152 bool MatchesMimeType(const std::string& mime_type_pattern,
1153 const std::string& mime_type) {
1154 return g_mime_util.Get().MatchesMimeType(mime_type_pattern, mime_type);
1157 bool ParseMimeTypeWithoutParameter(const std::string& type_string,
1158 std::string* top_level_type,
1159 std::string* subtype) {
1160 return g_mime_util.Get().ParseMimeTypeWithoutParameter(
1161 type_string, top_level_type, subtype);
1164 bool IsValidTopLevelMimeType(const std::string& type_string) {
1165 return g_mime_util.Get().IsValidTopLevelMimeType(type_string);
1168 bool AreSupportedMediaCodecs(const std::vector<std::string>& codecs) {
1169 return g_mime_util.Get().AreSupportedMediaCodecs(codecs);
1172 bool IsStrictMediaMimeType(const std::string& mime_type) {
1173 return g_mime_util.Get().IsStrictMediaMimeType(mime_type);
1176 SupportsType IsSupportedStrictMediaMimeType(
1177 const std::string& mime_type,
1178 const std::vector<std::string>& codecs) {
1179 return g_mime_util.Get().IsSupportedStrictMediaMimeType(mime_type, codecs);
1182 void ParseCodecString(const std::string& codecs,
1183 std::vector<std::string>* codecs_out,
1184 const bool strip) {
1185 g_mime_util.Get().ParseCodecString(codecs, codecs_out, strip);
1188 namespace {
1190 // From http://www.w3schools.com/media/media_mimeref.asp and
1191 // http://plugindoc.mozdev.org/winmime.php
1192 static const char* const kStandardImageTypes[] = {
1193 "image/bmp",
1194 "image/cis-cod",
1195 "image/gif",
1196 "image/ief",
1197 "image/jpeg",
1198 "image/webp",
1199 "image/pict",
1200 "image/pipeg",
1201 "image/png",
1202 "image/svg+xml",
1203 "image/tiff",
1204 "image/vnd.microsoft.icon",
1205 "image/x-cmu-raster",
1206 "image/x-cmx",
1207 "image/x-icon",
1208 "image/x-portable-anymap",
1209 "image/x-portable-bitmap",
1210 "image/x-portable-graymap",
1211 "image/x-portable-pixmap",
1212 "image/x-rgb",
1213 "image/x-xbitmap",
1214 "image/x-xpixmap",
1215 "image/x-xwindowdump"
1217 static const char* const kStandardAudioTypes[] = {
1218 "audio/aac",
1219 "audio/aiff",
1220 "audio/amr",
1221 "audio/basic",
1222 "audio/midi",
1223 "audio/mp3",
1224 "audio/mp4",
1225 "audio/mpeg",
1226 "audio/mpeg3",
1227 "audio/ogg",
1228 "audio/vorbis",
1229 "audio/wav",
1230 "audio/webm",
1231 "audio/x-m4a",
1232 "audio/x-ms-wma",
1233 "audio/vnd.rn-realaudio",
1234 "audio/vnd.wave"
1236 static const char* const kStandardVideoTypes[] = {
1237 "video/avi",
1238 "video/divx",
1239 "video/flc",
1240 "video/mp4",
1241 "video/mpeg",
1242 "video/ogg",
1243 "video/quicktime",
1244 "video/sd-video",
1245 "video/webm",
1246 "video/x-dv",
1247 "video/x-m4v",
1248 "video/x-mpeg",
1249 "video/x-ms-asf",
1250 "video/x-ms-wmv"
1253 struct StandardType {
1254 const char* const leading_mime_type;
1255 const char* const* standard_types;
1256 size_t standard_types_len;
1258 static const StandardType kStandardTypes[] = {
1259 { "image/", kStandardImageTypes, arraysize(kStandardImageTypes) },
1260 { "audio/", kStandardAudioTypes, arraysize(kStandardAudioTypes) },
1261 { "video/", kStandardVideoTypes, arraysize(kStandardVideoTypes) },
1262 { NULL, NULL, 0 }
1265 void GetExtensionsFromHardCodedMappings(
1266 const MimeInfo* mappings,
1267 size_t mappings_len,
1268 const std::string& leading_mime_type,
1269 base::hash_set<base::FilePath::StringType>* extensions) {
1270 for (size_t i = 0; i < mappings_len; ++i) {
1271 if (StartsWithASCII(mappings[i].mime_type, leading_mime_type, false)) {
1272 std::vector<string> this_extensions;
1273 base::SplitString(mappings[i].extensions, ',', &this_extensions);
1274 for (size_t j = 0; j < this_extensions.size(); ++j) {
1275 #if defined(OS_WIN)
1276 base::FilePath::StringType extension(
1277 base::UTF8ToWide(this_extensions[j]));
1278 #else
1279 base::FilePath::StringType extension(this_extensions[j]);
1280 #endif
1281 extensions->insert(extension);
1287 void GetExtensionsHelper(
1288 const char* const* standard_types,
1289 size_t standard_types_len,
1290 const std::string& leading_mime_type,
1291 base::hash_set<base::FilePath::StringType>* extensions) {
1292 for (size_t i = 0; i < standard_types_len; ++i) {
1293 g_mime_util.Get().GetPlatformExtensionsForMimeType(standard_types[i],
1294 extensions);
1297 // Also look up the extensions from hard-coded mappings in case that some
1298 // supported extensions are not registered in the system registry, like ogg.
1299 GetExtensionsFromHardCodedMappings(primary_mappings,
1300 arraysize(primary_mappings),
1301 leading_mime_type,
1302 extensions);
1304 GetExtensionsFromHardCodedMappings(secondary_mappings,
1305 arraysize(secondary_mappings),
1306 leading_mime_type,
1307 extensions);
1310 // Note that the elements in the source set will be appended to the target
1311 // vector.
1312 template<class T>
1313 void HashSetToVector(base::hash_set<T>* source, std::vector<T>* target) {
1314 size_t old_target_size = target->size();
1315 target->resize(old_target_size + source->size());
1316 size_t i = 0;
1317 for (typename base::hash_set<T>::iterator iter = source->begin();
1318 iter != source->end(); ++iter, ++i)
1319 (*target)[old_target_size + i] = *iter;
1322 } // namespace
1324 void GetExtensionsForMimeType(
1325 const std::string& unsafe_mime_type,
1326 std::vector<base::FilePath::StringType>* extensions) {
1327 if (unsafe_mime_type == "*/*" || unsafe_mime_type == "*")
1328 return;
1330 const std::string mime_type = base::StringToLowerASCII(unsafe_mime_type);
1331 base::hash_set<base::FilePath::StringType> unique_extensions;
1333 if (EndsWith(mime_type, "/*", false)) {
1334 std::string leading_mime_type = mime_type.substr(0, mime_type.length() - 1);
1336 // Find the matching StandardType from within kStandardTypes, or fall
1337 // through to the last (default) StandardType.
1338 const StandardType* type = NULL;
1339 for (size_t i = 0; i < arraysize(kStandardTypes); ++i) {
1340 type = &(kStandardTypes[i]);
1341 if (type->leading_mime_type &&
1342 leading_mime_type == type->leading_mime_type)
1343 break;
1345 DCHECK(type);
1346 GetExtensionsHelper(type->standard_types,
1347 type->standard_types_len,
1348 leading_mime_type,
1349 &unique_extensions);
1350 } else {
1351 g_mime_util.Get().GetPlatformExtensionsForMimeType(mime_type,
1352 &unique_extensions);
1354 // Also look up the extensions from hard-coded mappings in case that some
1355 // supported extensions are not registered in the system registry, like ogg.
1356 GetExtensionsFromHardCodedMappings(primary_mappings,
1357 arraysize(primary_mappings),
1358 mime_type,
1359 &unique_extensions);
1361 GetExtensionsFromHardCodedMappings(secondary_mappings,
1362 arraysize(secondary_mappings),
1363 mime_type,
1364 &unique_extensions);
1367 HashSetToVector(&unique_extensions, extensions);
1370 void RemoveProprietaryMediaTypesAndCodecsForTests() {
1371 g_mime_util.Get().RemoveProprietaryMediaTypesAndCodecsForTests();
1374 CertificateMimeType GetCertificateMimeTypeForMimeType(
1375 const std::string& mime_type) {
1376 // Don't create a map, there is only one entry in the table,
1377 // except on Android.
1378 for (size_t i = 0; i < arraysize(supported_certificate_types); ++i) {
1379 if (base::strcasecmp(mime_type.c_str(),
1380 net::supported_certificate_types[i].mime_type) == 0) {
1381 return net::supported_certificate_types[i].cert_type;
1384 return CERTIFICATE_MIME_TYPE_UNKNOWN;
1387 bool IsSupportedCertificateMimeType(const std::string& mime_type) {
1388 CertificateMimeType file_type =
1389 GetCertificateMimeTypeForMimeType(mime_type);
1390 return file_type != CERTIFICATE_MIME_TYPE_UNKNOWN;
1393 void AddMultipartValueForUpload(const std::string& value_name,
1394 const std::string& value,
1395 const std::string& mime_boundary,
1396 const std::string& content_type,
1397 std::string* post_data) {
1398 DCHECK(post_data);
1399 // First line is the boundary.
1400 post_data->append("--" + mime_boundary + "\r\n");
1401 // Next line is the Content-disposition.
1402 post_data->append("Content-Disposition: form-data; name=\"" +
1403 value_name + "\"\r\n");
1404 if (!content_type.empty()) {
1405 // If Content-type is specified, the next line is that.
1406 post_data->append("Content-Type: " + content_type + "\r\n");
1408 // Leave an empty line and append the value.
1409 post_data->append("\r\n" + value + "\r\n");
1412 void AddMultipartFinalDelimiterForUpload(const std::string& mime_boundary,
1413 std::string* post_data) {
1414 DCHECK(post_data);
1415 post_data->append("--" + mime_boundary + "--\r\n");
1418 } // namespace net