7dd51a2945d4556a6ce45f858546e9c60ba8af69
[platform/framework/web/crosswalk.git] / src / net / base / mime_util.cc
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.
4
5 #include <algorithm>
6 #include <iterator>
7 #include <map>
8 #include <string>
9
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"
21
22 #if defined(OS_ANDROID)
23 #include "base/android/build_info.h"
24 #endif
25
26 using std::string;
27
28 namespace {
29
30 struct MediaType {
31   const char name[12];
32   const char matcher[13];
33 };
34
35 static const MediaType kIanaMediaTypes[] = {
36   { "application", "application/" },
37   { "audio", "audio/" },
38   { "example", "example/" },
39   { "image", "image/" },
40   { "message", "message/" },
41   { "model", "model/" },
42   { "multipart", "multipart/" },
43   { "text", "text/" },
44   { "video", "video/" },
45 };
46
47 }  // namespace
48
49 namespace net {
50
51 // Singleton utility class for mime types.
52 class MimeUtil : public PlatformMimeUtil {
53  public:
54   enum Codec {
55     INVALID_CODEC,
56     PCM,
57     MP3,
58     MPEG2_AAC_LC,
59     MPEG2_AAC_MAIN,
60     MPEG2_AAC_SSR,
61     MPEG4_AAC_LC,
62     MPEG4_AAC_SBRv1,
63     VORBIS,
64     OPUS,
65     H264_BASELINE,
66     H264_MAIN,
67     H264_HIGH,
68     VP8,
69     VP9,
70     THEORA
71   };
72
73   bool GetMimeTypeFromExtension(const base::FilePath::StringType& ext,
74                                 std::string* mime_type) const;
75
76   bool GetMimeTypeFromFile(const base::FilePath& file_path,
77                            std::string* mime_type) const;
78
79   bool GetWellKnownMimeTypeFromExtension(const base::FilePath::StringType& ext,
80                                          std::string* mime_type) const;
81
82   bool IsSupportedImageMimeType(const std::string& mime_type) const;
83   bool IsSupportedMediaMimeType(const std::string& mime_type) const;
84   bool IsSupportedNonImageMimeType(const std::string& mime_type) const;
85   bool IsUnsupportedTextMimeType(const std::string& mime_type) const;
86   bool IsSupportedJavascriptMimeType(const std::string& mime_type) const;
87
88   bool IsSupportedMimeType(const std::string& mime_type) const;
89
90   bool MatchesMimeType(const std::string &mime_type_pattern,
91                        const std::string &mime_type) const;
92
93   bool ParseMimeTypeWithoutParameter(const std::string& type_string,
94                                      std::string* top_level_type,
95                                      std::string* subtype) const;
96
97   bool IsValidTopLevelMimeType(const std::string& type_string) const;
98
99   bool AreSupportedMediaCodecs(const std::vector<std::string>& codecs) const;
100
101   void ParseCodecString(const std::string& codecs,
102                         std::vector<std::string>* codecs_out,
103                         bool strip);
104
105   bool IsStrictMediaMimeType(const std::string& mime_type) const;
106   SupportsType IsSupportedStrictMediaMimeType(
107       const std::string& mime_type,
108       const std::vector<std::string>& codecs) const;
109
110   void RemoveProprietaryMediaTypesAndCodecsForTests();
111
112  private:
113   friend struct base::DefaultLazyInstanceTraits<MimeUtil>;
114
115   typedef base::hash_set<std::string> MimeMappings;
116
117   typedef base::hash_set<int> CodecSet;
118   typedef std::map<std::string, CodecSet> StrictMappings;
119   struct CodecEntry {
120     CodecEntry() : codec(INVALID_CODEC), is_ambiguous(true) {}
121     CodecEntry(Codec c, bool ambiguous) : codec(c), is_ambiguous(ambiguous) {}
122     Codec codec;
123     bool is_ambiguous;
124   };
125   typedef std::map<std::string, CodecEntry> StringToCodecMappings;
126
127   MimeUtil();
128
129   // Returns IsSupported if all codec IDs in |codecs| are unambiguous
130   // and are supported by the platform. MayBeSupported is returned if
131   // at least one codec ID in |codecs| is ambiguous but all the codecs
132   // are supported by the platform. IsNotSupported is returned if at
133   // least one codec ID  is not supported by the platform.
134   SupportsType AreSupportedCodecs(
135       const CodecSet& supported_codecs,
136       const std::vector<std::string>& codecs) const;
137
138   // For faster lookup, keep hash sets.
139   void InitializeMimeTypeMaps();
140
141   bool GetMimeTypeFromExtensionHelper(const base::FilePath::StringType& ext,
142                                       bool include_platform_types,
143                                       std::string* mime_type) const;
144
145   // Converts a codec ID into an Codec enum value and indicates
146   // whether the conversion was ambiguous.
147   // Returns true if this method was able to map |codec_id| to a specific
148   // Codec enum value. |codec| and |is_ambiguous| are only valid if true
149   // is returned. Otherwise their value is undefined after the call.
150   // |is_ambiguous| is true if |codec_id| did not have enough information to
151   // unambiguously determine the proper Codec enum value. If |is_ambiguous|
152   // is true |codec| contains the best guess for the intended Codec enum value.
153   bool StringToCodec(const std::string& codec_id,
154                      Codec* codec,
155                      bool* is_ambiguous) const;
156
157   // Returns true if |codec| is supported by the platform.
158   // Note: This method will return false if the platform supports proprietary
159   // codecs but |allow_proprietary_codecs_| is set to false.
160   bool IsCodecSupported(Codec codec) const;
161
162   // Returns true if |codec| refers to a proprietary codec.
163   bool IsCodecProprietary(Codec codec) const;
164
165   // Returns true and sets |*default_codec| if |mime_type| has a
166   // default codec associated with it.
167   // Returns false otherwise and the value of |*default_codec| is undefined.
168   bool GetDefaultCodec(const std::string& mime_type,
169                        Codec* default_codec) const;
170
171   // Returns true if |mime_type| has a default codec associated with it
172   // and IsCodecSupported() returns true for that particular codec.
173   bool IsDefaultCodecSupported(const std::string& mime_type) const;
174
175   MimeMappings image_map_;
176   MimeMappings media_map_;
177   MimeMappings non_image_map_;
178   MimeMappings unsupported_text_map_;
179   MimeMappings javascript_map_;
180
181   // A map of mime_types and hash map of the supported codecs for the mime_type.
182   StrictMappings strict_format_map_;
183
184   // Keeps track of whether proprietary codec support should be
185   // advertised to callers.
186   bool allow_proprietary_codecs_;
187
188   // Lookup table for string compare based string -> Codec mappings.
189   StringToCodecMappings string_to_codec_map_;
190 };  // class MimeUtil
191
192 // This variable is Leaky because we need to access it from WorkerPool threads.
193 static base::LazyInstance<MimeUtil>::Leaky g_mime_util =
194     LAZY_INSTANCE_INITIALIZER;
195
196 struct MimeInfo {
197   const char* mime_type;
198   const char* extensions;  // comma separated list
199 };
200
201 static const MimeInfo primary_mappings[] = {
202   { "text/html", "html,htm,shtml,shtm" },
203   { "text/css", "css" },
204   { "text/xml", "xml" },
205   { "image/gif", "gif" },
206   { "image/jpeg", "jpeg,jpg" },
207   { "image/webp", "webp" },
208   { "image/png", "png" },
209   { "video/mp4", "mp4,m4v" },
210   { "audio/x-m4a", "m4a" },
211   { "audio/mp3", "mp3" },
212   { "video/ogg", "ogv,ogm" },
213   { "audio/ogg", "ogg,oga,opus" },
214   { "video/webm", "webm" },
215   { "audio/webm", "webm" },
216   { "audio/wav", "wav" },
217   { "application/xhtml+xml", "xhtml,xht,xhtm" },
218   { "application/x-chrome-extension", "crx" },
219   { "multipart/related", "mhtml,mht" }
220 };
221
222 static const MimeInfo secondary_mappings[] = {
223   { "application/octet-stream", "exe,com,bin" },
224   { "application/gzip", "gz" },
225   { "application/pdf", "pdf" },
226   { "application/postscript", "ps,eps,ai" },
227   { "application/javascript", "js" },
228   { "application/font-woff", "woff" },
229   { "image/bmp", "bmp" },
230   { "image/x-icon", "ico" },
231   { "image/vnd.microsoft.icon", "ico" },
232   { "image/jpeg", "jfif,pjpeg,pjp" },
233   { "image/tiff", "tiff,tif" },
234   { "image/x-xbitmap", "xbm" },
235   { "image/svg+xml", "svg,svgz" },
236   { "image/x-png", "png"},
237   { "message/rfc822", "eml" },
238   { "text/plain", "txt,text" },
239   { "text/html", "ehtml" },
240   { "application/rss+xml", "rss" },
241   { "application/rdf+xml", "rdf" },
242   { "text/xml", "xsl,xbl,xslt" },
243   { "application/vnd.mozilla.xul+xml", "xul" },
244   { "application/x-shockwave-flash", "swf,swl" },
245   { "application/pkcs7-mime", "p7m,p7c,p7z" },
246   { "application/pkcs7-signature", "p7s" }
247 };
248
249 static const char* FindMimeType(const MimeInfo* mappings,
250                                 size_t mappings_len,
251                                 const char* ext) {
252   size_t ext_len = strlen(ext);
253
254   for (size_t i = 0; i < mappings_len; ++i) {
255     const char* extensions = mappings[i].extensions;
256     for (;;) {
257       size_t end_pos = strcspn(extensions, ",");
258       if (end_pos == ext_len &&
259           base::strncasecmp(extensions, ext, ext_len) == 0)
260         return mappings[i].mime_type;
261       extensions += end_pos;
262       if (!*extensions)
263         break;
264       extensions += 1;  // skip over comma
265     }
266   }
267   return NULL;
268 }
269
270 bool MimeUtil::GetMimeTypeFromExtension(const base::FilePath::StringType& ext,
271                                         string* result) const {
272   return GetMimeTypeFromExtensionHelper(ext, true, result);
273 }
274
275 bool MimeUtil::GetWellKnownMimeTypeFromExtension(
276     const base::FilePath::StringType& ext,
277     string* result) const {
278   return GetMimeTypeFromExtensionHelper(ext, false, result);
279 }
280
281 bool MimeUtil::GetMimeTypeFromFile(const base::FilePath& file_path,
282                                    string* result) const {
283   base::FilePath::StringType file_name_str = file_path.Extension();
284   if (file_name_str.empty())
285     return false;
286   return GetMimeTypeFromExtension(file_name_str.substr(1), result);
287 }
288
289 bool MimeUtil::GetMimeTypeFromExtensionHelper(
290     const base::FilePath::StringType& ext,
291     bool include_platform_types,
292     string* result) const {
293   // Avoids crash when unable to handle a long file path. See crbug.com/48733.
294   const unsigned kMaxFilePathSize = 65536;
295   if (ext.length() > kMaxFilePathSize)
296     return false;
297
298   // We implement the same algorithm as Mozilla for mapping a file extension to
299   // a mime type.  That is, we first check a hard-coded list (that cannot be
300   // overridden), and then if not found there, we defer to the system registry.
301   // Finally, we scan a secondary hard-coded list to catch types that we can
302   // deduce but that we also want to allow the OS to override.
303
304   base::FilePath path_ext(ext);
305   const string ext_narrow_str = path_ext.AsUTF8Unsafe();
306   const char* mime_type = FindMimeType(primary_mappings,
307                                        arraysize(primary_mappings),
308                                        ext_narrow_str.c_str());
309   if (mime_type) {
310     *result = mime_type;
311     return true;
312   }
313
314   if (include_platform_types && GetPlatformMimeTypeFromExtension(ext, result))
315     return true;
316
317   mime_type = FindMimeType(secondary_mappings, arraysize(secondary_mappings),
318                            ext_narrow_str.c_str());
319   if (mime_type) {
320     *result = mime_type;
321     return true;
322   }
323
324   return false;
325 }
326
327 // From WebKit's WebCore/platform/MIMETypeRegistry.cpp:
328
329 static const char* const supported_image_types[] = {
330   "image/jpeg",
331   "image/pjpeg",
332   "image/jpg",
333   "image/webp",
334   "image/png",
335   "image/gif",
336   "image/bmp",
337   "image/vnd.microsoft.icon",    // ico
338   "image/x-icon",    // ico
339   "image/x-xbitmap",  // xbm
340   "image/x-png"
341 };
342
343 // A list of media types: http://en.wikipedia.org/wiki/Internet_media_type
344 // A comprehensive mime type list: http://plugindoc.mozdev.org/winmime.php
345 // This set of codecs is supported by all variations of Chromium.
346 static const char* const common_media_types[] = {
347   // Ogg.
348   "audio/ogg",
349   "application/ogg",
350 #if !defined(OS_ANDROID)  // Android doesn't support Ogg Theora.
351   "video/ogg",
352 #endif
353
354   // WebM.
355   "video/webm",
356   "audio/webm",
357
358   // Wav.
359   "audio/wav",
360   "audio/x-wav",
361
362 #if defined(OS_ANDROID)
363   // HLS. Supported by Android ICS and above.
364   "application/vnd.apple.mpegurl",
365   "application/x-mpegurl",
366 #endif
367 };
368
369 // List of proprietary types only supported by Google Chrome.
370 static const char* const proprietary_media_types[] = {
371   // MPEG-4.
372   "video/mp4",
373   "video/x-m4v",
374   "audio/mp4",
375   "audio/x-m4a",
376
377   // MP3.
378   "audio/mp3",
379   "audio/x-mp3",
380   "audio/mpeg",
381 };
382
383 // Note:
384 // - does not include javascript types list (see supported_javascript_types)
385 // - does not include types starting with "text/" (see
386 //   IsSupportedNonImageMimeType())
387 static const char* const supported_non_image_types[] = {
388   "image/svg+xml",  // SVG is text-based XML, even though it has an image/ type
389   "application/xml",
390   "application/atom+xml",
391   "application/rss+xml",
392   "application/xhtml+xml",
393   "application/json",
394   "multipart/related",  // For MHTML support.
395   "multipart/x-mixed-replace"
396   // Note: ADDING a new type here will probably render it AS HTML. This can
397   // result in cross site scripting.
398 };
399
400 // Dictionary of cryptographic file mime types.
401 struct CertificateMimeTypeInfo {
402   const char* mime_type;
403   CertificateMimeType cert_type;
404 };
405
406 static const CertificateMimeTypeInfo supported_certificate_types[] = {
407   { "application/x-x509-user-cert",
408       CERTIFICATE_MIME_TYPE_X509_USER_CERT },
409 #if defined(OS_ANDROID)
410   { "application/x-x509-ca-cert", CERTIFICATE_MIME_TYPE_X509_CA_CERT },
411   { "application/x-pkcs12", CERTIFICATE_MIME_TYPE_PKCS12_ARCHIVE },
412 #endif
413 };
414
415 // These types are excluded from the logic that allows all text/ types because
416 // while they are technically text, it's very unlikely that a user expects to
417 // see them rendered in text form.
418 static const char* const unsupported_text_types[] = {
419   "text/calendar",
420   "text/x-calendar",
421   "text/x-vcalendar",
422   "text/vcalendar",
423   "text/vcard",
424   "text/x-vcard",
425   "text/directory",
426   "text/ldif",
427   "text/qif",
428   "text/x-qif",
429   "text/x-csv",
430   "text/x-vcf",
431   "text/rtf",
432   "text/comma-separated-values",
433   "text/csv",
434   "text/tab-separated-values",
435   "text/tsv",
436   "text/ofx",                           // http://crbug.com/162238
437   "text/vnd.sun.j2me.app-descriptor"    // http://crbug.com/176450
438 };
439
440 //  Mozilla 1.8 and WinIE 7 both accept text/javascript and text/ecmascript.
441 //  Mozilla 1.8 accepts application/javascript, application/ecmascript, and
442 // application/x-javascript, but WinIE 7 doesn't.
443 //  WinIE 7 accepts text/javascript1.1 - text/javascript1.3, text/jscript, and
444 // text/livescript, but Mozilla 1.8 doesn't.
445 //  Mozilla 1.8 allows leading and trailing whitespace, but WinIE 7 doesn't.
446 //  Mozilla 1.8 and WinIE 7 both accept the empty string, but neither accept a
447 // whitespace-only string.
448 //  We want to accept all the values that either of these browsers accept, but
449 // not other values.
450 static const char* const supported_javascript_types[] = {
451   "text/javascript",
452   "text/ecmascript",
453   "application/javascript",
454   "application/ecmascript",
455   "application/x-javascript",
456   "text/javascript1.1",
457   "text/javascript1.2",
458   "text/javascript1.3",
459   "text/jscript",
460   "text/livescript"
461 };
462
463 #if defined(OS_ANDROID)
464 static bool IsCodecSupportedOnAndroid(MimeUtil::Codec codec) {
465   switch (codec) {
466     case MimeUtil::INVALID_CODEC:
467       return false;
468
469     case MimeUtil::PCM:
470     case MimeUtil::MP3:
471     case MimeUtil::MPEG4_AAC_LC:
472     case MimeUtil::MPEG4_AAC_SBRv1:
473     case MimeUtil::H264_BASELINE:
474     case MimeUtil::VP8:
475     case MimeUtil::VORBIS:
476       return true;
477
478     case MimeUtil::MPEG2_AAC_LC:
479     case MimeUtil::MPEG2_AAC_MAIN:
480     case MimeUtil::MPEG2_AAC_SSR:
481       // MPEG-2 variants of AAC are not supported on Android.
482       return false;
483
484     case MimeUtil::H264_MAIN:
485     case MimeUtil::H264_HIGH:
486       // H.264 Main and High profiles are not supported on Android.
487       return false;
488
489     case MimeUtil::VP9:
490       // VP9 is supported only in KitKat+ (API Level 19).
491       return base::android::BuildInfo::GetInstance()->sdk_int() >= 19;
492
493     case MimeUtil::OPUS:
494       // TODO(vigneshv): Change this similar to the VP9 check once Opus is
495       // supported on Android (http://crbug.com/318436).
496       return false;
497
498     case MimeUtil::THEORA:
499       return false;
500   }
501
502   return false;
503 }
504
505 static bool IsMimeTypeSupportedOnAndroid(const std::string& mimeType) {
506   // HLS codecs are supported in ICS and above (API level 14)
507   if ((!mimeType.compare("application/vnd.apple.mpegurl") ||
508       !mimeType.compare("application/x-mpegurl")) &&
509       base::android::BuildInfo::GetInstance()->sdk_int() < 14) {
510     return false;
511   }
512   return true;
513 }
514 #endif
515
516 struct MediaFormatStrict {
517   const char* mime_type;
518   const char* codecs_list;
519 };
520
521 // Following is the list of RFC 6381 compliant codecs:
522 //   mp4a.66     - MPEG-2 AAC MAIN
523 //   mp4a.67     - MPEG-2 AAC LC
524 //   mp4a.68     - MPEG-2 AAC SSR
525 //   mp4a.69     - MPEG-2 extension to MPEG-1
526 //   mp4a.6B     - MPEG-1 audio
527 //   mp4a.40.2   - MPEG-4 AAC LC
528 //   mp4a.40.5   - MPEG-4 AAC SBRv1
529 //
530 //   avc1.42E0xx - H.264 Baseline
531 //   avc1.4D40xx - H.264 Main
532 //   avc1.6400xx - H.264 High
533 static const char kMP4AudioCodecsExpression[] =
534     "mp4a.66,mp4a.67,mp4a.68,mp4a.69,mp4a.6B,mp4a.40.2,mp4a.40.5";
535 static const char kMP4VideoCodecsExpression[] =
536     "avc1.42E00A,avc1.4D400A,avc1.64000A," \
537     "mp4a.66,mp4a.67,mp4a.68,mp4a.69,mp4a.6B,mp4a.40.2,mp4a.40.5";
538
539 static const MediaFormatStrict format_codec_mappings[] = {
540   { "video/webm", "opus,vorbis,vp8,vp8.0,vp9,vp9.0" },
541   { "audio/webm", "opus,vorbis" },
542   { "audio/wav", "1" },
543   { "audio/x-wav", "1" },
544   { "video/ogg", "opus,theora,vorbis" },
545   { "audio/ogg", "opus,vorbis" },
546   { "application/ogg", "opus,theora,vorbis" },
547   { "audio/mpeg", "mp3" },
548   { "audio/mp3", "" },
549   { "audio/x-mp3", "" },
550   { "audio/mp4", kMP4AudioCodecsExpression },
551   { "audio/x-m4a", kMP4AudioCodecsExpression },
552   { "video/mp4", kMP4VideoCodecsExpression },
553   { "video/x-m4v", kMP4VideoCodecsExpression },
554   { "application/x-mpegurl", kMP4VideoCodecsExpression },
555   { "application/vnd.apple.mpegurl", kMP4VideoCodecsExpression }
556 };
557
558 struct CodecIDMappings {
559   const char* const codec_id;
560   MimeUtil::Codec codec;
561 };
562
563 // List of codec IDs that provide enough information to determine the
564 // codec and profile being requested.
565 //
566 // The "mp4a" strings come from RFC 6381.
567 static const CodecIDMappings kUnambiguousCodecIDs[] = {
568   { "1", MimeUtil::PCM }, // We only allow this for WAV so it isn't ambiguous.
569   { "mp3", MimeUtil::MP3 },
570   { "mp4a.66", MimeUtil::MPEG2_AAC_MAIN },
571   { "mp4a.67", MimeUtil::MPEG2_AAC_LC },
572   { "mp4a.68", MimeUtil::MPEG2_AAC_SSR },
573   { "mp4a.69", MimeUtil::MP3 },
574   { "mp4a.6B", MimeUtil::MP3 },
575   { "mp4a.40.2", MimeUtil::MPEG4_AAC_LC },
576   { "mp4a.40.5", MimeUtil::MPEG4_AAC_SBRv1 },
577   { "vorbis", MimeUtil::VORBIS },
578   { "opus", MimeUtil::OPUS },
579   { "vp8", MimeUtil::VP8 },
580   { "vp8.0", MimeUtil::VP8 },
581   { "vp9", MimeUtil::VP9 },
582   { "vp9.0", MimeUtil::VP9 },
583   { "theora", MimeUtil::THEORA }
584 };
585
586 // List of codec IDs that are ambiguous and don't provide
587 // enough information to determine the codec and profile.
588 // The codec in these entries indicate the codec and profile
589 // we assume the user is trying to indicate.
590 static const CodecIDMappings kAmbiguousCodecIDs[] = {
591   { "mp4a.40", MimeUtil::MPEG4_AAC_LC },
592   { "avc1", MimeUtil::H264_BASELINE },
593   { "avc3", MimeUtil::H264_BASELINE },
594 };
595
596 MimeUtil::MimeUtil() : allow_proprietary_codecs_(false) {
597   InitializeMimeTypeMaps();
598 }
599
600 SupportsType MimeUtil::AreSupportedCodecs(
601     const CodecSet& supported_codecs,
602     const std::vector<std::string>& codecs) const {
603   DCHECK(!supported_codecs.empty());
604   DCHECK(!codecs.empty());
605
606   SupportsType result = IsSupported;
607   for (size_t i = 0; i < codecs.size(); ++i) {
608     bool is_ambiguous = true;
609     Codec codec = INVALID_CODEC;
610     if (!StringToCodec(codecs[i], &codec, &is_ambiguous))
611       return IsNotSupported;
612
613     if (!IsCodecSupported(codec) ||
614         supported_codecs.find(codec) == supported_codecs.end()) {
615       return IsNotSupported;
616     }
617
618     if (is_ambiguous)
619       result = MayBeSupported;
620   }
621
622   return result;
623 }
624
625 void MimeUtil::InitializeMimeTypeMaps() {
626   for (size_t i = 0; i < arraysize(supported_image_types); ++i)
627     image_map_.insert(supported_image_types[i]);
628
629   // Initialize the supported non-image types.
630   for (size_t i = 0; i < arraysize(supported_non_image_types); ++i)
631     non_image_map_.insert(supported_non_image_types[i]);
632   for (size_t i = 0; i < arraysize(supported_certificate_types); ++i)
633     non_image_map_.insert(supported_certificate_types[i].mime_type);
634   for (size_t i = 0; i < arraysize(unsupported_text_types); ++i)
635     unsupported_text_map_.insert(unsupported_text_types[i]);
636   for (size_t i = 0; i < arraysize(supported_javascript_types); ++i)
637     non_image_map_.insert(supported_javascript_types[i]);
638   for (size_t i = 0; i < arraysize(common_media_types); ++i) {
639 #if defined(OS_ANDROID)
640     if (!IsMimeTypeSupportedOnAndroid(common_media_types[i]))
641       continue;
642 #endif
643     non_image_map_.insert(common_media_types[i]);
644   }
645 #if defined(USE_PROPRIETARY_CODECS)
646   allow_proprietary_codecs_ = true;
647
648   for (size_t i = 0; i < arraysize(proprietary_media_types); ++i)
649     non_image_map_.insert(proprietary_media_types[i]);
650 #endif
651
652   // Initialize the supported media types.
653   for (size_t i = 0; i < arraysize(common_media_types); ++i) {
654 #if defined(OS_ANDROID)
655     if (!IsMimeTypeSupportedOnAndroid(common_media_types[i]))
656       continue;
657 #endif
658     media_map_.insert(common_media_types[i]);
659   }
660 #if defined(USE_PROPRIETARY_CODECS)
661   for (size_t i = 0; i < arraysize(proprietary_media_types); ++i)
662     media_map_.insert(proprietary_media_types[i]);
663 #endif
664
665   for (size_t i = 0; i < arraysize(supported_javascript_types); ++i)
666     javascript_map_.insert(supported_javascript_types[i]);
667
668   for (size_t i = 0; i < arraysize(kUnambiguousCodecIDs); ++i) {
669     string_to_codec_map_[kUnambiguousCodecIDs[i].codec_id] =
670         CodecEntry(kUnambiguousCodecIDs[i].codec, false);
671   }
672
673   for (size_t i = 0; i < arraysize(kAmbiguousCodecIDs); ++i) {
674     string_to_codec_map_[kAmbiguousCodecIDs[i].codec_id] =
675         CodecEntry(kAmbiguousCodecIDs[i].codec, true);
676   }
677
678   // Initialize the strict supported media types.
679   for (size_t i = 0; i < arraysize(format_codec_mappings); ++i) {
680     std::vector<std::string> mime_type_codecs;
681     ParseCodecString(format_codec_mappings[i].codecs_list,
682                      &mime_type_codecs,
683                      false);
684
685     CodecSet codecs;
686     for (size_t j = 0; j < mime_type_codecs.size(); ++j) {
687       Codec codec = INVALID_CODEC;
688       bool is_ambiguous = true;
689       CHECK(StringToCodec(mime_type_codecs[j], &codec, &is_ambiguous));
690       DCHECK(!is_ambiguous);
691       codecs.insert(codec);
692     }
693
694     strict_format_map_[format_codec_mappings[i].mime_type] = codecs;
695   }
696 }
697
698 bool MimeUtil::IsSupportedImageMimeType(const std::string& mime_type) const {
699   return image_map_.find(mime_type) != image_map_.end();
700 }
701
702 bool MimeUtil::IsSupportedMediaMimeType(const std::string& mime_type) const {
703   return media_map_.find(mime_type) != media_map_.end();
704 }
705
706 bool MimeUtil::IsSupportedNonImageMimeType(const std::string& mime_type) const {
707   return non_image_map_.find(mime_type) != non_image_map_.end() ||
708       (mime_type.compare(0, 5, "text/") == 0 &&
709        !IsUnsupportedTextMimeType(mime_type)) ||
710       (mime_type.compare(0, 12, "application/") == 0 &&
711        MatchesMimeType("application/*+json", mime_type));
712 }
713
714 bool MimeUtil::IsUnsupportedTextMimeType(const std::string& mime_type) const {
715   return unsupported_text_map_.find(mime_type) != unsupported_text_map_.end();
716 }
717
718 bool MimeUtil::IsSupportedJavascriptMimeType(
719     const std::string& mime_type) const {
720   return javascript_map_.find(mime_type) != javascript_map_.end();
721 }
722
723 // Mirrors WebViewImpl::CanShowMIMEType()
724 bool MimeUtil::IsSupportedMimeType(const std::string& mime_type) const {
725   return (mime_type.compare(0, 6, "image/") == 0 &&
726           IsSupportedImageMimeType(mime_type)) ||
727          IsSupportedNonImageMimeType(mime_type);
728 }
729
730 // Tests for MIME parameter equality. Each parameter in the |mime_type_pattern|
731 // must be matched by a parameter in the |mime_type|. If there are no
732 // parameters in the pattern, the match is a success.
733 bool MatchesMimeTypeParameters(const std::string& mime_type_pattern,
734                                const std::string& mime_type) {
735   const std::string::size_type semicolon = mime_type_pattern.find(';');
736   const std::string::size_type test_semicolon = mime_type.find(';');
737   if (semicolon != std::string::npos) {
738     if (test_semicolon == std::string::npos)
739       return false;
740
741     std::vector<std::string> pattern_parameters;
742     base::SplitString(mime_type_pattern.substr(semicolon + 1),
743                       ';', &pattern_parameters);
744
745     std::vector<std::string> test_parameters;
746     base::SplitString(mime_type.substr(test_semicolon + 1),
747                       ';', &test_parameters);
748
749     sort(pattern_parameters.begin(), pattern_parameters.end());
750     sort(test_parameters.begin(), test_parameters.end());
751     std::vector<std::string> difference =
752       base::STLSetDifference<std::vector<std::string> >(pattern_parameters,
753                                                         test_parameters);
754     return difference.size() == 0;
755   }
756   return true;
757 }
758
759 // This comparison handles absolute maching and also basic
760 // wildcards.  The plugin mime types could be:
761 //      application/x-foo
762 //      application/*
763 //      application/*+xml
764 //      *
765 // Also tests mime parameters -- all parameters in the pattern must be present
766 // in the tested type for a match to succeed.
767 bool MimeUtil::MatchesMimeType(const std::string& mime_type_pattern,
768                                const std::string& mime_type) const {
769   // Verify caller is passing lowercase strings.
770   DCHECK_EQ(base::StringToLowerASCII(mime_type_pattern), mime_type_pattern);
771   DCHECK_EQ(base::StringToLowerASCII(mime_type), mime_type);
772
773   if (mime_type_pattern.empty())
774     return false;
775
776   std::string::size_type semicolon = mime_type_pattern.find(';');
777   const std::string base_pattern(mime_type_pattern.substr(0, semicolon));
778   semicolon = mime_type.find(';');
779   const std::string base_type(mime_type.substr(0, semicolon));
780
781   if (base_pattern == "*" || base_pattern == "*/*")
782     return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
783
784   const std::string::size_type star = base_pattern.find('*');
785   if (star == std::string::npos) {
786     if (base_pattern == base_type)
787       return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
788     else
789       return false;
790   }
791
792   // Test length to prevent overlap between |left| and |right|.
793   if (base_type.length() < base_pattern.length() - 1)
794     return false;
795
796   const std::string left(base_pattern.substr(0, star));
797   const std::string right(base_pattern.substr(star + 1));
798
799   if (base_type.find(left) != 0)
800     return false;
801
802   if (!right.empty() &&
803       base_type.rfind(right) != base_type.length() - right.length())
804     return false;
805
806   return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
807 }
808
809 // See http://www.iana.org/assignments/media-types/media-types.xhtml
810 static const char* legal_top_level_types[] = {
811   "application",
812   "audio",
813   "example",
814   "image",
815   "message",
816   "model",
817   "multipart",
818   "text",
819   "video",
820 };
821
822 bool MimeUtil::ParseMimeTypeWithoutParameter(
823     const std::string& type_string,
824     std::string* top_level_type,
825     std::string* subtype) const {
826   std::vector<std::string> components;
827   base::SplitString(type_string, '/', &components);
828   if (components.size() != 2 ||
829       !HttpUtil::IsToken(components[0]) ||
830       !HttpUtil::IsToken(components[1]))
831     return false;
832
833   if (top_level_type)
834     *top_level_type = components[0];
835   if (subtype)
836     *subtype = components[1];
837   return true;
838 }
839
840 bool MimeUtil::IsValidTopLevelMimeType(const std::string& type_string) const {
841   std::string lower_type = base::StringToLowerASCII(type_string);
842   for (size_t i = 0; i < arraysize(legal_top_level_types); ++i) {
843     if (lower_type.compare(legal_top_level_types[i]) == 0)
844       return true;
845   }
846
847   return type_string.size() > 2 && StartsWithASCII(type_string, "x-", false);
848 }
849
850 bool MimeUtil::AreSupportedMediaCodecs(
851     const std::vector<std::string>& codecs) const {
852   for (size_t i = 0; i < codecs.size(); ++i) {
853     Codec codec = INVALID_CODEC;
854     bool is_ambiguous = true;
855     if (!StringToCodec(codecs[i], &codec, &is_ambiguous) ||
856         !IsCodecSupported(codec)) {
857       return false;
858     }
859   }
860   return true;
861 }
862
863 void MimeUtil::ParseCodecString(const std::string& codecs,
864                                 std::vector<std::string>* codecs_out,
865                                 bool strip) {
866   std::string no_quote_codecs;
867   base::TrimString(codecs, "\"", &no_quote_codecs);
868   base::SplitString(no_quote_codecs, ',', codecs_out);
869
870   if (!strip)
871     return;
872
873   // Strip everything past the first '.'
874   for (std::vector<std::string>::iterator it = codecs_out->begin();
875        it != codecs_out->end();
876        ++it) {
877     size_t found = it->find_first_of('.');
878     if (found != std::string::npos)
879       it->resize(found);
880   }
881 }
882
883 bool MimeUtil::IsStrictMediaMimeType(const std::string& mime_type) const {
884   return strict_format_map_.find(mime_type) != strict_format_map_.end();
885 }
886
887 SupportsType MimeUtil::IsSupportedStrictMediaMimeType(
888     const std::string& mime_type,
889     const std::vector<std::string>& codecs) const {
890   StrictMappings::const_iterator it_strict_map =
891       strict_format_map_.find(mime_type);
892   if (it_strict_map == strict_format_map_.end())
893     return codecs.empty() ? MayBeSupported : IsNotSupported;
894
895   if (it_strict_map->second.empty()) {
896     // We get here if the mimetype does not expect a codecs parameter.
897     return (codecs.empty() && IsDefaultCodecSupported(mime_type)) ?
898         IsSupported : IsNotSupported;
899   }
900
901   if (codecs.empty()) {
902     // We get here if the mimetype expects to get a codecs parameter,
903     // but didn't get one. If |mime_type| does not have a default codec
904     // the best we can do is say "maybe" because we don't have enough
905     // information.
906     Codec default_codec = INVALID_CODEC;
907     if (!GetDefaultCodec(mime_type, &default_codec))
908       return MayBeSupported;
909
910     return IsCodecSupported(default_codec) ? IsSupported : IsNotSupported;
911   }
912
913   return AreSupportedCodecs(it_strict_map->second, codecs);
914 }
915
916 void MimeUtil::RemoveProprietaryMediaTypesAndCodecsForTests() {
917   for (size_t i = 0; i < arraysize(proprietary_media_types); ++i) {
918     non_image_map_.erase(proprietary_media_types[i]);
919     media_map_.erase(proprietary_media_types[i]);
920   }
921   allow_proprietary_codecs_ = false;
922 }
923
924 static bool IsValidH264Level(const std::string& level_str) {
925   uint32 level;
926   if (level_str.size() != 2 || !base::HexStringToUInt(level_str, &level))
927     return false;
928
929   // Valid levels taken from Table A-1 in ISO-14496-10.
930   // Essentially |level_str| is toHex(10 * level).
931   return ((level >= 10 && level <= 13) ||
932           (level >= 20 && level <= 22) ||
933           (level >= 30 && level <= 32) ||
934           (level >= 40 && level <= 42) ||
935           (level >= 50 && level <= 51));
936 }
937
938 // Handle parsing H.264 codec IDs as outlined in RFC 6381
939 //   avc1.42E0xx - H.264 Baseline
940 //   avc1.4D40xx - H.264 Main
941 //   avc1.6400xx - H.264 High
942 //
943 //   avc1.xxxxxx & avc3.xxxxxx are considered ambiguous forms that
944 //   are trying to signal H.264 Baseline.
945 static bool ParseH264CodecID(const std::string& codec_id,
946                              MimeUtil::Codec* codec,
947                              bool* is_ambiguous) {
948   // Make sure we have avc1.xxxxxx or avc3.xxxxxx
949   if (codec_id.size() != 11 ||
950       (!StartsWithASCII(codec_id, "avc1.", true) &&
951        !StartsWithASCII(codec_id, "avc3.", true))) {
952     return false;
953   }
954
955   std::string profile = StringToUpperASCII(codec_id.substr(5, 4));
956   if (profile == "42E0") {
957     *codec = MimeUtil::H264_BASELINE;
958   } else if (profile == "4D40") {
959     *codec = MimeUtil::H264_MAIN;
960   } else if (profile == "6400") {
961     *codec = MimeUtil::H264_HIGH;
962   } else {
963     *codec = MimeUtil::H264_BASELINE;
964     *is_ambiguous = true;
965     return true;
966   }
967
968   *is_ambiguous = !IsValidH264Level(StringToUpperASCII(codec_id.substr(9)));
969   return true;
970 }
971
972 bool MimeUtil::StringToCodec(const std::string& codec_id,
973                              Codec* codec,
974                              bool* is_ambiguous) const {
975   StringToCodecMappings::const_iterator itr =
976       string_to_codec_map_.find(codec_id);
977   if (itr != string_to_codec_map_.end()) {
978     *codec = itr->second.codec;
979     *is_ambiguous = itr->second.is_ambiguous;
980     return true;
981   }
982
983   // If |codec_id| is not in |string_to_codec_map_|, then we assume that it is
984   // an H.264 codec ID because currently those are the only ones that can't be
985   // stored in the |string_to_codec_map_| and require parsing.
986   return ParseH264CodecID(codec_id, codec, is_ambiguous);
987 }
988
989 bool MimeUtil::IsCodecSupported(Codec codec) const {
990   DCHECK_NE(codec, INVALID_CODEC);
991
992 #if defined(OS_ANDROID)
993   if (!IsCodecSupportedOnAndroid(codec))
994     return false;
995 #endif
996
997   return allow_proprietary_codecs_ || !IsCodecProprietary(codec);
998 }
999
1000 bool MimeUtil::IsCodecProprietary(Codec codec) const {
1001   switch (codec) {
1002     case INVALID_CODEC:
1003     case MP3:
1004     case MPEG2_AAC_LC:
1005     case MPEG2_AAC_MAIN:
1006     case MPEG2_AAC_SSR:
1007     case MPEG4_AAC_LC:
1008     case MPEG4_AAC_SBRv1:
1009     case H264_BASELINE:
1010     case H264_MAIN:
1011     case H264_HIGH:
1012       return true;
1013
1014     case PCM:
1015     case VORBIS:
1016     case OPUS:
1017     case VP8:
1018     case VP9:
1019     case THEORA:
1020       return false;
1021   }
1022
1023   return true;
1024 }
1025
1026 bool MimeUtil::GetDefaultCodec(const std::string& mime_type,
1027                                Codec* default_codec) const {
1028   if (mime_type == "audio/mpeg" ||
1029       mime_type == "audio/mp3" ||
1030       mime_type == "audio/x-mp3") {
1031     *default_codec = MimeUtil::MP3;
1032     return true;
1033   }
1034
1035   return false;
1036 }
1037
1038
1039 bool MimeUtil::IsDefaultCodecSupported(const std::string& mime_type) const {
1040   Codec default_codec = Codec::INVALID_CODEC;
1041   if (!GetDefaultCodec(mime_type, &default_codec))
1042     return false;
1043   return IsCodecSupported(default_codec);
1044 }
1045
1046 //----------------------------------------------------------------------------
1047 // Wrappers for the singleton
1048 //----------------------------------------------------------------------------
1049
1050 bool GetMimeTypeFromExtension(const base::FilePath::StringType& ext,
1051                               std::string* mime_type) {
1052   return g_mime_util.Get().GetMimeTypeFromExtension(ext, mime_type);
1053 }
1054
1055 bool GetMimeTypeFromFile(const base::FilePath& file_path,
1056                          std::string* mime_type) {
1057   return g_mime_util.Get().GetMimeTypeFromFile(file_path, mime_type);
1058 }
1059
1060 bool GetWellKnownMimeTypeFromExtension(const base::FilePath::StringType& ext,
1061                                        std::string* mime_type) {
1062   return g_mime_util.Get().GetWellKnownMimeTypeFromExtension(ext, mime_type);
1063 }
1064
1065 bool GetPreferredExtensionForMimeType(const std::string& mime_type,
1066                                       base::FilePath::StringType* extension) {
1067   return g_mime_util.Get().GetPreferredExtensionForMimeType(mime_type,
1068                                                             extension);
1069 }
1070
1071 bool IsSupportedImageMimeType(const std::string& mime_type) {
1072   return g_mime_util.Get().IsSupportedImageMimeType(mime_type);
1073 }
1074
1075 bool IsSupportedMediaMimeType(const std::string& mime_type) {
1076   return g_mime_util.Get().IsSupportedMediaMimeType(mime_type);
1077 }
1078
1079 bool IsSupportedNonImageMimeType(const std::string& mime_type) {
1080   return g_mime_util.Get().IsSupportedNonImageMimeType(mime_type);
1081 }
1082
1083 bool IsUnsupportedTextMimeType(const std::string& mime_type) {
1084   return g_mime_util.Get().IsUnsupportedTextMimeType(mime_type);
1085 }
1086
1087 bool IsSupportedJavascriptMimeType(const std::string& mime_type) {
1088   return g_mime_util.Get().IsSupportedJavascriptMimeType(mime_type);
1089 }
1090
1091 bool IsSupportedMimeType(const std::string& mime_type) {
1092   return g_mime_util.Get().IsSupportedMimeType(mime_type);
1093 }
1094
1095 bool MatchesMimeType(const std::string& mime_type_pattern,
1096                      const std::string& mime_type) {
1097   return g_mime_util.Get().MatchesMimeType(mime_type_pattern, mime_type);
1098 }
1099
1100 bool ParseMimeTypeWithoutParameter(const std::string& type_string,
1101                                    std::string* top_level_type,
1102                                    std::string* subtype) {
1103   return g_mime_util.Get().ParseMimeTypeWithoutParameter(
1104       type_string, top_level_type, subtype);
1105 }
1106
1107 bool IsValidTopLevelMimeType(const std::string& type_string) {
1108   return g_mime_util.Get().IsValidTopLevelMimeType(type_string);
1109 }
1110
1111 bool AreSupportedMediaCodecs(const std::vector<std::string>& codecs) {
1112   return g_mime_util.Get().AreSupportedMediaCodecs(codecs);
1113 }
1114
1115 bool IsStrictMediaMimeType(const std::string& mime_type) {
1116   return g_mime_util.Get().IsStrictMediaMimeType(mime_type);
1117 }
1118
1119 SupportsType IsSupportedStrictMediaMimeType(
1120     const std::string& mime_type,
1121     const std::vector<std::string>& codecs) {
1122   return g_mime_util.Get().IsSupportedStrictMediaMimeType(mime_type, codecs);
1123 }
1124
1125 void ParseCodecString(const std::string& codecs,
1126                       std::vector<std::string>* codecs_out,
1127                       const bool strip) {
1128   g_mime_util.Get().ParseCodecString(codecs, codecs_out, strip);
1129 }
1130
1131 namespace {
1132
1133 // From http://www.w3schools.com/media/media_mimeref.asp and
1134 // http://plugindoc.mozdev.org/winmime.php
1135 static const char* const kStandardImageTypes[] = {
1136   "image/bmp",
1137   "image/cis-cod",
1138   "image/gif",
1139   "image/ief",
1140   "image/jpeg",
1141   "image/webp",
1142   "image/pict",
1143   "image/pipeg",
1144   "image/png",
1145   "image/svg+xml",
1146   "image/tiff",
1147   "image/vnd.microsoft.icon",
1148   "image/x-cmu-raster",
1149   "image/x-cmx",
1150   "image/x-icon",
1151   "image/x-portable-anymap",
1152   "image/x-portable-bitmap",
1153   "image/x-portable-graymap",
1154   "image/x-portable-pixmap",
1155   "image/x-rgb",
1156   "image/x-xbitmap",
1157   "image/x-xpixmap",
1158   "image/x-xwindowdump"
1159 };
1160 static const char* const kStandardAudioTypes[] = {
1161   "audio/aac",
1162   "audio/aiff",
1163   "audio/amr",
1164   "audio/basic",
1165   "audio/midi",
1166   "audio/mp3",
1167   "audio/mp4",
1168   "audio/mpeg",
1169   "audio/mpeg3",
1170   "audio/ogg",
1171   "audio/vorbis",
1172   "audio/wav",
1173   "audio/webm",
1174   "audio/x-m4a",
1175   "audio/x-ms-wma",
1176   "audio/vnd.rn-realaudio",
1177   "audio/vnd.wave"
1178 };
1179 static const char* const kStandardVideoTypes[] = {
1180   "video/avi",
1181   "video/divx",
1182   "video/flc",
1183   "video/mp4",
1184   "video/mpeg",
1185   "video/ogg",
1186   "video/quicktime",
1187   "video/sd-video",
1188   "video/webm",
1189   "video/x-dv",
1190   "video/x-m4v",
1191   "video/x-mpeg",
1192   "video/x-ms-asf",
1193   "video/x-ms-wmv"
1194 };
1195
1196 struct StandardType {
1197   const char* leading_mime_type;
1198   const char* const* standard_types;
1199   size_t standard_types_len;
1200 };
1201 static const StandardType kStandardTypes[] = {
1202   { "image/", kStandardImageTypes, arraysize(kStandardImageTypes) },
1203   { "audio/", kStandardAudioTypes, arraysize(kStandardAudioTypes) },
1204   { "video/", kStandardVideoTypes, arraysize(kStandardVideoTypes) },
1205   { NULL, NULL, 0 }
1206 };
1207
1208 void GetExtensionsFromHardCodedMappings(
1209     const MimeInfo* mappings,
1210     size_t mappings_len,
1211     const std::string& leading_mime_type,
1212     base::hash_set<base::FilePath::StringType>* extensions) {
1213   base::FilePath::StringType extension;
1214   for (size_t i = 0; i < mappings_len; ++i) {
1215     if (StartsWithASCII(mappings[i].mime_type, leading_mime_type, false)) {
1216       std::vector<string> this_extensions;
1217       base::SplitString(mappings[i].extensions, ',', &this_extensions);
1218       for (size_t j = 0; j < this_extensions.size(); ++j) {
1219 #if defined(OS_WIN)
1220         base::FilePath::StringType extension(
1221             base::UTF8ToWide(this_extensions[j]));
1222 #else
1223         base::FilePath::StringType extension(this_extensions[j]);
1224 #endif
1225         extensions->insert(extension);
1226       }
1227     }
1228   }
1229 }
1230
1231 void GetExtensionsHelper(
1232     const char* const* standard_types,
1233     size_t standard_types_len,
1234     const std::string& leading_mime_type,
1235     base::hash_set<base::FilePath::StringType>* extensions) {
1236   for (size_t i = 0; i < standard_types_len; ++i) {
1237     g_mime_util.Get().GetPlatformExtensionsForMimeType(standard_types[i],
1238                                                        extensions);
1239   }
1240
1241   // Also look up the extensions from hard-coded mappings in case that some
1242   // supported extensions are not registered in the system registry, like ogg.
1243   GetExtensionsFromHardCodedMappings(primary_mappings,
1244                                      arraysize(primary_mappings),
1245                                      leading_mime_type,
1246                                      extensions);
1247
1248   GetExtensionsFromHardCodedMappings(secondary_mappings,
1249                                      arraysize(secondary_mappings),
1250                                      leading_mime_type,
1251                                      extensions);
1252 }
1253
1254 // Note that the elements in the source set will be appended to the target
1255 // vector.
1256 template<class T>
1257 void HashSetToVector(base::hash_set<T>* source, std::vector<T>* target) {
1258   size_t old_target_size = target->size();
1259   target->resize(old_target_size + source->size());
1260   size_t i = 0;
1261   for (typename base::hash_set<T>::iterator iter = source->begin();
1262        iter != source->end(); ++iter, ++i)
1263     (*target)[old_target_size + i] = *iter;
1264 }
1265 }
1266
1267 void GetExtensionsForMimeType(
1268     const std::string& unsafe_mime_type,
1269     std::vector<base::FilePath::StringType>* extensions) {
1270   if (unsafe_mime_type == "*/*" || unsafe_mime_type == "*")
1271     return;
1272
1273   const std::string mime_type = base::StringToLowerASCII(unsafe_mime_type);
1274   base::hash_set<base::FilePath::StringType> unique_extensions;
1275
1276   if (EndsWith(mime_type, "/*", true)) {
1277     std::string leading_mime_type = mime_type.substr(0, mime_type.length() - 1);
1278
1279     // Find the matching StandardType from within kStandardTypes, or fall
1280     // through to the last (default) StandardType.
1281     const StandardType* type = NULL;
1282     for (size_t i = 0; i < arraysize(kStandardTypes); ++i) {
1283       type = &(kStandardTypes[i]);
1284       if (type->leading_mime_type &&
1285           leading_mime_type == type->leading_mime_type)
1286         break;
1287     }
1288     DCHECK(type);
1289     GetExtensionsHelper(type->standard_types,
1290                         type->standard_types_len,
1291                         leading_mime_type,
1292                         &unique_extensions);
1293   } else {
1294     g_mime_util.Get().GetPlatformExtensionsForMimeType(mime_type,
1295                                                        &unique_extensions);
1296
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                                        mime_type,
1302                                        &unique_extensions);
1303
1304     GetExtensionsFromHardCodedMappings(secondary_mappings,
1305                                        arraysize(secondary_mappings),
1306                                        mime_type,
1307                                        &unique_extensions);
1308   }
1309
1310   HashSetToVector(&unique_extensions, extensions);
1311 }
1312
1313 void RemoveProprietaryMediaTypesAndCodecsForTests() {
1314   g_mime_util.Get().RemoveProprietaryMediaTypesAndCodecsForTests();
1315 }
1316
1317 const std::string GetIANAMediaType(const std::string& mime_type) {
1318   for (size_t i = 0; i < arraysize(kIanaMediaTypes); ++i) {
1319     if (StartsWithASCII(mime_type, kIanaMediaTypes[i].matcher, true)) {
1320       return kIanaMediaTypes[i].name;
1321     }
1322   }
1323   return std::string();
1324 }
1325
1326 CertificateMimeType GetCertificateMimeTypeForMimeType(
1327     const std::string& mime_type) {
1328   // Don't create a map, there is only one entry in the table,
1329   // except on Android.
1330   for (size_t i = 0; i < arraysize(supported_certificate_types); ++i) {
1331     if (mime_type == net::supported_certificate_types[i].mime_type)
1332       return net::supported_certificate_types[i].cert_type;
1333   }
1334   return CERTIFICATE_MIME_TYPE_UNKNOWN;
1335 }
1336
1337 bool IsSupportedCertificateMimeType(const std::string& mime_type) {
1338   CertificateMimeType file_type =
1339       GetCertificateMimeTypeForMimeType(mime_type);
1340   return file_type != CERTIFICATE_MIME_TYPE_UNKNOWN;
1341 }
1342
1343 void AddMultipartValueForUpload(const std::string& value_name,
1344                                 const std::string& value,
1345                                 const std::string& mime_boundary,
1346                                 const std::string& content_type,
1347                                 std::string* post_data) {
1348   DCHECK(post_data);
1349   // First line is the boundary.
1350   post_data->append("--" + mime_boundary + "\r\n");
1351   // Next line is the Content-disposition.
1352   post_data->append("Content-Disposition: form-data; name=\"" +
1353                     value_name + "\"\r\n");
1354   if (!content_type.empty()) {
1355     // If Content-type is specified, the next line is that.
1356     post_data->append("Content-Type: " + content_type + "\r\n");
1357   }
1358   // Leave an empty line and append the value.
1359   post_data->append("\r\n" + value + "\r\n");
1360 }
1361
1362 void AddMultipartFinalDelimiterForUpload(const std::string& mime_boundary,
1363                                          std::string* post_data) {
1364   DCHECK(post_data);
1365   post_data->append("--" + mime_boundary + "--\r\n");
1366 }
1367
1368 }  // namespace net