Upstream version 10.38.208.0
[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::H264_MAIN:
475     case MimeUtil::H264_HIGH:
476     case MimeUtil::VP8:
477     case MimeUtil::VORBIS:
478       return true;
479
480     case MimeUtil::MPEG2_AAC_LC:
481     case MimeUtil::MPEG2_AAC_MAIN:
482     case MimeUtil::MPEG2_AAC_SSR:
483       // MPEG-2 variants of AAC are not supported on Android.
484       return false;
485
486     case MimeUtil::VP9:
487       // VP9 is supported only in KitKat+ (API Level 19).
488       return base::android::BuildInfo::GetInstance()->sdk_int() >= 19;
489
490     case MimeUtil::OPUS:
491       // TODO(vigneshv): Change this similar to the VP9 check once Opus is
492       // supported on Android (http://crbug.com/318436).
493       return false;
494
495     case MimeUtil::THEORA:
496       return false;
497   }
498
499   return false;
500 }
501
502 static bool IsMimeTypeSupportedOnAndroid(const std::string& mimeType) {
503   // HLS codecs are supported in ICS and above (API level 14)
504   if ((!mimeType.compare("application/vnd.apple.mpegurl") ||
505       !mimeType.compare("application/x-mpegurl")) &&
506       base::android::BuildInfo::GetInstance()->sdk_int() < 14) {
507     return false;
508   }
509   return true;
510 }
511 #endif
512
513 struct MediaFormatStrict {
514   const char* mime_type;
515   const char* codecs_list;
516 };
517
518 // Following is the list of RFC 6381 compliant codecs:
519 //   mp4a.66     - MPEG-2 AAC MAIN
520 //   mp4a.67     - MPEG-2 AAC LC
521 //   mp4a.68     - MPEG-2 AAC SSR
522 //   mp4a.69     - MPEG-2 extension to MPEG-1
523 //   mp4a.6B     - MPEG-1 audio
524 //   mp4a.40.2   - MPEG-4 AAC LC
525 //   mp4a.40.5   - MPEG-4 AAC SBRv1
526 //
527 //   avc1.42E0xx - H.264 Baseline
528 //   avc1.4D40xx - H.264 Main
529 //   avc1.6400xx - H.264 High
530 static const char kMP4AudioCodecsExpression[] =
531     "mp4a.66,mp4a.67,mp4a.68,mp4a.69,mp4a.6B,mp4a.40.2,mp4a.40.5";
532 static const char kMP4VideoCodecsExpression[] =
533     "avc1.42E00A,avc1.4D400A,avc1.64000A," \
534     "mp4a.66,mp4a.67,mp4a.68,mp4a.69,mp4a.6B,mp4a.40.2,mp4a.40.5";
535
536 static const MediaFormatStrict format_codec_mappings[] = {
537   { "video/webm", "opus,vorbis,vp8,vp8.0,vp9,vp9.0" },
538   { "audio/webm", "opus,vorbis" },
539   { "audio/wav", "1" },
540   { "audio/x-wav", "1" },
541   { "video/ogg", "opus,theora,vorbis" },
542   { "audio/ogg", "opus,vorbis" },
543   { "application/ogg", "opus,theora,vorbis" },
544   { "audio/mpeg", "mp3" },
545   { "audio/mp3", "" },
546   { "audio/x-mp3", "" },
547   { "audio/mp4", kMP4AudioCodecsExpression },
548   { "audio/x-m4a", kMP4AudioCodecsExpression },
549   { "video/mp4", kMP4VideoCodecsExpression },
550   { "video/x-m4v", kMP4VideoCodecsExpression },
551   { "application/x-mpegurl", kMP4VideoCodecsExpression },
552   { "application/vnd.apple.mpegurl", kMP4VideoCodecsExpression }
553 };
554
555 struct CodecIDMappings {
556   const char* const codec_id;
557   MimeUtil::Codec codec;
558 };
559
560 // List of codec IDs that provide enough information to determine the
561 // codec and profile being requested.
562 //
563 // The "mp4a" strings come from RFC 6381.
564 static const CodecIDMappings kUnambiguousCodecIDs[] = {
565   { "1", MimeUtil::PCM }, // We only allow this for WAV so it isn't ambiguous.
566   { "mp3", MimeUtil::MP3 },
567   { "mp4a.66", MimeUtil::MPEG2_AAC_MAIN },
568   { "mp4a.67", MimeUtil::MPEG2_AAC_LC },
569   { "mp4a.68", MimeUtil::MPEG2_AAC_SSR },
570   { "mp4a.69", MimeUtil::MP3 },
571   { "mp4a.6B", MimeUtil::MP3 },
572   { "mp4a.40.2", MimeUtil::MPEG4_AAC_LC },
573   { "mp4a.40.5", MimeUtil::MPEG4_AAC_SBRv1 },
574   { "vorbis", MimeUtil::VORBIS },
575   { "opus", MimeUtil::OPUS },
576   { "vp8", MimeUtil::VP8 },
577   { "vp8.0", MimeUtil::VP8 },
578   { "vp9", MimeUtil::VP9 },
579   { "vp9.0", MimeUtil::VP9 },
580   { "theora", MimeUtil::THEORA }
581 };
582
583 // List of codec IDs that are ambiguous and don't provide
584 // enough information to determine the codec and profile.
585 // The codec in these entries indicate the codec and profile
586 // we assume the user is trying to indicate.
587 static const CodecIDMappings kAmbiguousCodecIDs[] = {
588   { "mp4a.40", MimeUtil::MPEG4_AAC_LC },
589   { "avc1", MimeUtil::H264_BASELINE },
590   { "avc3", MimeUtil::H264_BASELINE },
591 };
592
593 MimeUtil::MimeUtil() : allow_proprietary_codecs_(false) {
594   InitializeMimeTypeMaps();
595 }
596
597 SupportsType MimeUtil::AreSupportedCodecs(
598     const CodecSet& supported_codecs,
599     const std::vector<std::string>& codecs) const {
600   DCHECK(!supported_codecs.empty());
601   DCHECK(!codecs.empty());
602
603   SupportsType result = IsSupported;
604   for (size_t i = 0; i < codecs.size(); ++i) {
605     bool is_ambiguous = true;
606     Codec codec = INVALID_CODEC;
607     if (!StringToCodec(codecs[i], &codec, &is_ambiguous))
608       return IsNotSupported;
609
610     if (!IsCodecSupported(codec) ||
611         supported_codecs.find(codec) == supported_codecs.end()) {
612       return IsNotSupported;
613     }
614
615     if (is_ambiguous)
616       result = MayBeSupported;
617   }
618
619   return result;
620 }
621
622 void MimeUtil::InitializeMimeTypeMaps() {
623   for (size_t i = 0; i < arraysize(supported_image_types); ++i)
624     image_map_.insert(supported_image_types[i]);
625
626   // Initialize the supported non-image types.
627   for (size_t i = 0; i < arraysize(supported_non_image_types); ++i)
628     non_image_map_.insert(supported_non_image_types[i]);
629   for (size_t i = 0; i < arraysize(supported_certificate_types); ++i)
630     non_image_map_.insert(supported_certificate_types[i].mime_type);
631   for (size_t i = 0; i < arraysize(unsupported_text_types); ++i)
632     unsupported_text_map_.insert(unsupported_text_types[i]);
633   for (size_t i = 0; i < arraysize(supported_javascript_types); ++i)
634     non_image_map_.insert(supported_javascript_types[i]);
635   for (size_t i = 0; i < arraysize(common_media_types); ++i) {
636 #if defined(OS_ANDROID)
637     if (!IsMimeTypeSupportedOnAndroid(common_media_types[i]))
638       continue;
639 #endif
640     non_image_map_.insert(common_media_types[i]);
641   }
642 #if defined(USE_PROPRIETARY_CODECS)
643   allow_proprietary_codecs_ = true;
644
645   for (size_t i = 0; i < arraysize(proprietary_media_types); ++i)
646     non_image_map_.insert(proprietary_media_types[i]);
647 #endif
648
649   // Initialize the supported media types.
650   for (size_t i = 0; i < arraysize(common_media_types); ++i) {
651 #if defined(OS_ANDROID)
652     if (!IsMimeTypeSupportedOnAndroid(common_media_types[i]))
653       continue;
654 #endif
655     media_map_.insert(common_media_types[i]);
656   }
657 #if defined(USE_PROPRIETARY_CODECS)
658   for (size_t i = 0; i < arraysize(proprietary_media_types); ++i)
659     media_map_.insert(proprietary_media_types[i]);
660 #endif
661
662   for (size_t i = 0; i < arraysize(supported_javascript_types); ++i)
663     javascript_map_.insert(supported_javascript_types[i]);
664
665   for (size_t i = 0; i < arraysize(kUnambiguousCodecIDs); ++i) {
666     string_to_codec_map_[kUnambiguousCodecIDs[i].codec_id] =
667         CodecEntry(kUnambiguousCodecIDs[i].codec, false);
668   }
669
670   for (size_t i = 0; i < arraysize(kAmbiguousCodecIDs); ++i) {
671     string_to_codec_map_[kAmbiguousCodecIDs[i].codec_id] =
672         CodecEntry(kAmbiguousCodecIDs[i].codec, true);
673   }
674
675   // Initialize the strict supported media types.
676   for (size_t i = 0; i < arraysize(format_codec_mappings); ++i) {
677     std::vector<std::string> mime_type_codecs;
678     ParseCodecString(format_codec_mappings[i].codecs_list,
679                      &mime_type_codecs,
680                      false);
681
682     CodecSet codecs;
683     for (size_t j = 0; j < mime_type_codecs.size(); ++j) {
684       Codec codec = INVALID_CODEC;
685       bool is_ambiguous = true;
686       CHECK(StringToCodec(mime_type_codecs[j], &codec, &is_ambiguous));
687       DCHECK(!is_ambiguous);
688       codecs.insert(codec);
689     }
690
691     strict_format_map_[format_codec_mappings[i].mime_type] = codecs;
692   }
693 }
694
695 bool MimeUtil::IsSupportedImageMimeType(const std::string& mime_type) const {
696   return image_map_.find(mime_type) != image_map_.end();
697 }
698
699 bool MimeUtil::IsSupportedMediaMimeType(const std::string& mime_type) const {
700   return media_map_.find(mime_type) != media_map_.end();
701 }
702
703 bool MimeUtil::IsSupportedNonImageMimeType(const std::string& mime_type) const {
704   return non_image_map_.find(mime_type) != non_image_map_.end() ||
705       (mime_type.compare(0, 5, "text/") == 0 &&
706        !IsUnsupportedTextMimeType(mime_type)) ||
707       (mime_type.compare(0, 12, "application/") == 0 &&
708        MatchesMimeType("application/*+json", mime_type));
709 }
710
711 bool MimeUtil::IsUnsupportedTextMimeType(const std::string& mime_type) const {
712   return unsupported_text_map_.find(mime_type) != unsupported_text_map_.end();
713 }
714
715 bool MimeUtil::IsSupportedJavascriptMimeType(
716     const std::string& mime_type) const {
717   return javascript_map_.find(mime_type) != javascript_map_.end();
718 }
719
720 // Mirrors WebViewImpl::CanShowMIMEType()
721 bool MimeUtil::IsSupportedMimeType(const std::string& mime_type) const {
722   return (mime_type.compare(0, 6, "image/") == 0 &&
723           IsSupportedImageMimeType(mime_type)) ||
724          IsSupportedNonImageMimeType(mime_type);
725 }
726
727 // Tests for MIME parameter equality. Each parameter in the |mime_type_pattern|
728 // must be matched by a parameter in the |mime_type|. If there are no
729 // parameters in the pattern, the match is a success.
730 bool MatchesMimeTypeParameters(const std::string& mime_type_pattern,
731                                const std::string& mime_type) {
732   const std::string::size_type semicolon = mime_type_pattern.find(';');
733   const std::string::size_type test_semicolon = mime_type.find(';');
734   if (semicolon != std::string::npos) {
735     if (test_semicolon == std::string::npos)
736       return false;
737
738     std::vector<std::string> pattern_parameters;
739     base::SplitString(mime_type_pattern.substr(semicolon + 1),
740                       ';', &pattern_parameters);
741
742     std::vector<std::string> test_parameters;
743     base::SplitString(mime_type.substr(test_semicolon + 1),
744                       ';', &test_parameters);
745
746     sort(pattern_parameters.begin(), pattern_parameters.end());
747     sort(test_parameters.begin(), test_parameters.end());
748     std::vector<std::string> difference =
749       base::STLSetDifference<std::vector<std::string> >(pattern_parameters,
750                                                         test_parameters);
751     return difference.size() == 0;
752   }
753   return true;
754 }
755
756 // This comparison handles absolute maching and also basic
757 // wildcards.  The plugin mime types could be:
758 //      application/x-foo
759 //      application/*
760 //      application/*+xml
761 //      *
762 // Also tests mime parameters -- all parameters in the pattern must be present
763 // in the tested type for a match to succeed.
764 bool MimeUtil::MatchesMimeType(const std::string& mime_type_pattern,
765                                const std::string& mime_type) const {
766   // Verify caller is passing lowercase strings.
767   DCHECK_EQ(base::StringToLowerASCII(mime_type_pattern), mime_type_pattern);
768   DCHECK_EQ(base::StringToLowerASCII(mime_type), mime_type);
769
770   if (mime_type_pattern.empty())
771     return false;
772
773   std::string::size_type semicolon = mime_type_pattern.find(';');
774   const std::string base_pattern(mime_type_pattern.substr(0, semicolon));
775   semicolon = mime_type.find(';');
776   const std::string base_type(mime_type.substr(0, semicolon));
777
778   if (base_pattern == "*" || base_pattern == "*/*")
779     return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
780
781   const std::string::size_type star = base_pattern.find('*');
782   if (star == std::string::npos) {
783     if (base_pattern == base_type)
784       return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
785     else
786       return false;
787   }
788
789   // Test length to prevent overlap between |left| and |right|.
790   if (base_type.length() < base_pattern.length() - 1)
791     return false;
792
793   const std::string left(base_pattern.substr(0, star));
794   const std::string right(base_pattern.substr(star + 1));
795
796   if (base_type.find(left) != 0)
797     return false;
798
799   if (!right.empty() &&
800       base_type.rfind(right) != base_type.length() - right.length())
801     return false;
802
803   return MatchesMimeTypeParameters(mime_type_pattern, mime_type);
804 }
805
806 // See http://www.iana.org/assignments/media-types/media-types.xhtml
807 static const char* legal_top_level_types[] = {
808   "application",
809   "audio",
810   "example",
811   "image",
812   "message",
813   "model",
814   "multipart",
815   "text",
816   "video",
817 };
818
819 bool MimeUtil::ParseMimeTypeWithoutParameter(
820     const std::string& type_string,
821     std::string* top_level_type,
822     std::string* subtype) const {
823   std::vector<std::string> components;
824   base::SplitString(type_string, '/', &components);
825   if (components.size() != 2 ||
826       !HttpUtil::IsToken(components[0]) ||
827       !HttpUtil::IsToken(components[1]))
828     return false;
829
830   if (top_level_type)
831     *top_level_type = components[0];
832   if (subtype)
833     *subtype = components[1];
834   return true;
835 }
836
837 bool MimeUtil::IsValidTopLevelMimeType(const std::string& type_string) const {
838   std::string lower_type = base::StringToLowerASCII(type_string);
839   for (size_t i = 0; i < arraysize(legal_top_level_types); ++i) {
840     if (lower_type.compare(legal_top_level_types[i]) == 0)
841       return true;
842   }
843
844   return type_string.size() > 2 && StartsWithASCII(type_string, "x-", false);
845 }
846
847 bool MimeUtil::AreSupportedMediaCodecs(
848     const std::vector<std::string>& codecs) const {
849   for (size_t i = 0; i < codecs.size(); ++i) {
850     Codec codec = INVALID_CODEC;
851     bool is_ambiguous = true;
852     if (!StringToCodec(codecs[i], &codec, &is_ambiguous) ||
853         !IsCodecSupported(codec)) {
854       return false;
855     }
856   }
857   return true;
858 }
859
860 void MimeUtil::ParseCodecString(const std::string& codecs,
861                                 std::vector<std::string>* codecs_out,
862                                 bool strip) {
863   std::string no_quote_codecs;
864   base::TrimString(codecs, "\"", &no_quote_codecs);
865   base::SplitString(no_quote_codecs, ',', codecs_out);
866
867   if (!strip)
868     return;
869
870   // Strip everything past the first '.'
871   for (std::vector<std::string>::iterator it = codecs_out->begin();
872        it != codecs_out->end();
873        ++it) {
874     size_t found = it->find_first_of('.');
875     if (found != std::string::npos)
876       it->resize(found);
877   }
878 }
879
880 bool MimeUtil::IsStrictMediaMimeType(const std::string& mime_type) const {
881   return strict_format_map_.find(mime_type) != strict_format_map_.end();
882 }
883
884 SupportsType MimeUtil::IsSupportedStrictMediaMimeType(
885     const std::string& mime_type,
886     const std::vector<std::string>& codecs) const {
887   StrictMappings::const_iterator it_strict_map =
888       strict_format_map_.find(mime_type);
889   if (it_strict_map == strict_format_map_.end())
890     return codecs.empty() ? MayBeSupported : IsNotSupported;
891
892   if (it_strict_map->second.empty()) {
893     // We get here if the mimetype does not expect a codecs parameter.
894     return (codecs.empty() && IsDefaultCodecSupported(mime_type)) ?
895         IsSupported : IsNotSupported;
896   }
897
898   if (codecs.empty()) {
899     // We get here if the mimetype expects to get a codecs parameter,
900     // but didn't get one. If |mime_type| does not have a default codec
901     // the best we can do is say "maybe" because we don't have enough
902     // information.
903     Codec default_codec = INVALID_CODEC;
904     if (!GetDefaultCodec(mime_type, &default_codec))
905       return MayBeSupported;
906
907     return IsCodecSupported(default_codec) ? IsSupported : IsNotSupported;
908   }
909
910   return AreSupportedCodecs(it_strict_map->second, codecs);
911 }
912
913 void MimeUtil::RemoveProprietaryMediaTypesAndCodecsForTests() {
914   for (size_t i = 0; i < arraysize(proprietary_media_types); ++i) {
915     non_image_map_.erase(proprietary_media_types[i]);
916     media_map_.erase(proprietary_media_types[i]);
917   }
918   allow_proprietary_codecs_ = false;
919 }
920
921 static bool IsValidH264Level(const std::string& level_str) {
922   uint32 level;
923   if (level_str.size() != 2 || !base::HexStringToUInt(level_str, &level))
924     return false;
925
926   // Valid levels taken from Table A-1 in ISO-14496-10.
927   // Essentially |level_str| is toHex(10 * level).
928   return ((level >= 10 && level <= 13) ||
929           (level >= 20 && level <= 22) ||
930           (level >= 30 && level <= 32) ||
931           (level >= 40 && level <= 42) ||
932           (level >= 50 && level <= 51));
933 }
934
935 // Handle parsing H.264 codec IDs as outlined in RFC 6381
936 //   avc1.42E0xx - H.264 Baseline
937 //   avc1.4D40xx - H.264 Main
938 //   avc1.6400xx - H.264 High
939 //
940 //   avc1.xxxxxx & avc3.xxxxxx are considered ambiguous forms that
941 //   are trying to signal H.264 Baseline.
942 static bool ParseH264CodecID(const std::string& codec_id,
943                              MimeUtil::Codec* codec,
944                              bool* is_ambiguous) {
945   // Make sure we have avc1.xxxxxx or avc3.xxxxxx
946   if (codec_id.size() != 11 ||
947       (!StartsWithASCII(codec_id, "avc1.", true) &&
948        !StartsWithASCII(codec_id, "avc3.", true))) {
949     return false;
950   }
951
952   std::string profile = StringToUpperASCII(codec_id.substr(5, 4));
953   if (profile == "42E0") {
954     *codec = MimeUtil::H264_BASELINE;
955   } else if (profile == "4D40") {
956     *codec = MimeUtil::H264_MAIN;
957   } else if (profile == "6400") {
958     *codec = MimeUtil::H264_HIGH;
959   } else {
960     *codec = MimeUtil::H264_BASELINE;
961     *is_ambiguous = true;
962     return true;
963   }
964
965   *is_ambiguous = !IsValidH264Level(StringToUpperASCII(codec_id.substr(9)));
966   return true;
967 }
968
969 bool MimeUtil::StringToCodec(const std::string& codec_id,
970                              Codec* codec,
971                              bool* is_ambiguous) const {
972   StringToCodecMappings::const_iterator itr =
973       string_to_codec_map_.find(codec_id);
974   if (itr != string_to_codec_map_.end()) {
975     *codec = itr->second.codec;
976     *is_ambiguous = itr->second.is_ambiguous;
977     return true;
978   }
979
980   // If |codec_id| is not in |string_to_codec_map_|, then we assume that it is
981   // an H.264 codec ID because currently those are the only ones that can't be
982   // stored in the |string_to_codec_map_| and require parsing.
983   return ParseH264CodecID(codec_id, codec, is_ambiguous);
984 }
985
986 bool MimeUtil::IsCodecSupported(Codec codec) const {
987   DCHECK_NE(codec, INVALID_CODEC);
988
989 #if defined(OS_ANDROID)
990   if (!IsCodecSupportedOnAndroid(codec))
991     return false;
992 #endif
993
994   return allow_proprietary_codecs_ || !IsCodecProprietary(codec);
995 }
996
997 bool MimeUtil::IsCodecProprietary(Codec codec) const {
998   switch (codec) {
999     case INVALID_CODEC:
1000     case MP3:
1001     case MPEG2_AAC_LC:
1002     case MPEG2_AAC_MAIN:
1003     case MPEG2_AAC_SSR:
1004     case MPEG4_AAC_LC:
1005     case MPEG4_AAC_SBRv1:
1006     case H264_BASELINE:
1007     case H264_MAIN:
1008     case H264_HIGH:
1009       return true;
1010
1011     case PCM:
1012     case VORBIS:
1013     case OPUS:
1014     case VP8:
1015     case VP9:
1016     case THEORA:
1017       return false;
1018   }
1019
1020   return true;
1021 }
1022
1023 bool MimeUtil::GetDefaultCodec(const std::string& mime_type,
1024                                Codec* default_codec) const {
1025   if (mime_type == "audio/mpeg" ||
1026       mime_type == "audio/mp3" ||
1027       mime_type == "audio/x-mp3") {
1028     *default_codec = MimeUtil::MP3;
1029     return true;
1030   }
1031
1032   return false;
1033 }
1034
1035
1036 bool MimeUtil::IsDefaultCodecSupported(const std::string& mime_type) const {
1037   Codec default_codec = Codec::INVALID_CODEC;
1038   if (!GetDefaultCodec(mime_type, &default_codec))
1039     return false;
1040   return IsCodecSupported(default_codec);
1041 }
1042
1043 //----------------------------------------------------------------------------
1044 // Wrappers for the singleton
1045 //----------------------------------------------------------------------------
1046
1047 bool GetMimeTypeFromExtension(const base::FilePath::StringType& ext,
1048                               std::string* mime_type) {
1049   return g_mime_util.Get().GetMimeTypeFromExtension(ext, mime_type);
1050 }
1051
1052 bool GetMimeTypeFromFile(const base::FilePath& file_path,
1053                          std::string* mime_type) {
1054   return g_mime_util.Get().GetMimeTypeFromFile(file_path, mime_type);
1055 }
1056
1057 bool GetWellKnownMimeTypeFromExtension(const base::FilePath::StringType& ext,
1058                                        std::string* mime_type) {
1059   return g_mime_util.Get().GetWellKnownMimeTypeFromExtension(ext, mime_type);
1060 }
1061
1062 bool GetPreferredExtensionForMimeType(const std::string& mime_type,
1063                                       base::FilePath::StringType* extension) {
1064   return g_mime_util.Get().GetPreferredExtensionForMimeType(mime_type,
1065                                                             extension);
1066 }
1067
1068 bool IsSupportedImageMimeType(const std::string& mime_type) {
1069   return g_mime_util.Get().IsSupportedImageMimeType(mime_type);
1070 }
1071
1072 bool IsSupportedMediaMimeType(const std::string& mime_type) {
1073   return g_mime_util.Get().IsSupportedMediaMimeType(mime_type);
1074 }
1075
1076 bool IsSupportedNonImageMimeType(const std::string& mime_type) {
1077   return g_mime_util.Get().IsSupportedNonImageMimeType(mime_type);
1078 }
1079
1080 bool IsUnsupportedTextMimeType(const std::string& mime_type) {
1081   return g_mime_util.Get().IsUnsupportedTextMimeType(mime_type);
1082 }
1083
1084 bool IsSupportedJavascriptMimeType(const std::string& mime_type) {
1085   return g_mime_util.Get().IsSupportedJavascriptMimeType(mime_type);
1086 }
1087
1088 bool IsSupportedMimeType(const std::string& mime_type) {
1089   return g_mime_util.Get().IsSupportedMimeType(mime_type);
1090 }
1091
1092 bool MatchesMimeType(const std::string& mime_type_pattern,
1093                      const std::string& mime_type) {
1094   return g_mime_util.Get().MatchesMimeType(mime_type_pattern, mime_type);
1095 }
1096
1097 bool ParseMimeTypeWithoutParameter(const std::string& type_string,
1098                                    std::string* top_level_type,
1099                                    std::string* subtype) {
1100   return g_mime_util.Get().ParseMimeTypeWithoutParameter(
1101       type_string, top_level_type, subtype);
1102 }
1103
1104 bool IsValidTopLevelMimeType(const std::string& type_string) {
1105   return g_mime_util.Get().IsValidTopLevelMimeType(type_string);
1106 }
1107
1108 bool AreSupportedMediaCodecs(const std::vector<std::string>& codecs) {
1109   return g_mime_util.Get().AreSupportedMediaCodecs(codecs);
1110 }
1111
1112 bool IsStrictMediaMimeType(const std::string& mime_type) {
1113   return g_mime_util.Get().IsStrictMediaMimeType(mime_type);
1114 }
1115
1116 SupportsType IsSupportedStrictMediaMimeType(
1117     const std::string& mime_type,
1118     const std::vector<std::string>& codecs) {
1119   return g_mime_util.Get().IsSupportedStrictMediaMimeType(mime_type, codecs);
1120 }
1121
1122 void ParseCodecString(const std::string& codecs,
1123                       std::vector<std::string>* codecs_out,
1124                       const bool strip) {
1125   g_mime_util.Get().ParseCodecString(codecs, codecs_out, strip);
1126 }
1127
1128 namespace {
1129
1130 // From http://www.w3schools.com/media/media_mimeref.asp and
1131 // http://plugindoc.mozdev.org/winmime.php
1132 static const char* const kStandardImageTypes[] = {
1133   "image/bmp",
1134   "image/cis-cod",
1135   "image/gif",
1136   "image/ief",
1137   "image/jpeg",
1138   "image/webp",
1139   "image/pict",
1140   "image/pipeg",
1141   "image/png",
1142   "image/svg+xml",
1143   "image/tiff",
1144   "image/vnd.microsoft.icon",
1145   "image/x-cmu-raster",
1146   "image/x-cmx",
1147   "image/x-icon",
1148   "image/x-portable-anymap",
1149   "image/x-portable-bitmap",
1150   "image/x-portable-graymap",
1151   "image/x-portable-pixmap",
1152   "image/x-rgb",
1153   "image/x-xbitmap",
1154   "image/x-xpixmap",
1155   "image/x-xwindowdump"
1156 };
1157 static const char* const kStandardAudioTypes[] = {
1158   "audio/aac",
1159   "audio/aiff",
1160   "audio/amr",
1161   "audio/basic",
1162   "audio/midi",
1163   "audio/mp3",
1164   "audio/mp4",
1165   "audio/mpeg",
1166   "audio/mpeg3",
1167   "audio/ogg",
1168   "audio/vorbis",
1169   "audio/wav",
1170   "audio/webm",
1171   "audio/x-m4a",
1172   "audio/x-ms-wma",
1173   "audio/vnd.rn-realaudio",
1174   "audio/vnd.wave"
1175 };
1176 static const char* const kStandardVideoTypes[] = {
1177   "video/avi",
1178   "video/divx",
1179   "video/flc",
1180   "video/mp4",
1181   "video/mpeg",
1182   "video/ogg",
1183   "video/quicktime",
1184   "video/sd-video",
1185   "video/webm",
1186   "video/x-dv",
1187   "video/x-m4v",
1188   "video/x-mpeg",
1189   "video/x-ms-asf",
1190   "video/x-ms-wmv"
1191 };
1192
1193 struct StandardType {
1194   const char* leading_mime_type;
1195   const char* const* standard_types;
1196   size_t standard_types_len;
1197 };
1198 static const StandardType kStandardTypes[] = {
1199   { "image/", kStandardImageTypes, arraysize(kStandardImageTypes) },
1200   { "audio/", kStandardAudioTypes, arraysize(kStandardAudioTypes) },
1201   { "video/", kStandardVideoTypes, arraysize(kStandardVideoTypes) },
1202   { NULL, NULL, 0 }
1203 };
1204
1205 void GetExtensionsFromHardCodedMappings(
1206     const MimeInfo* mappings,
1207     size_t mappings_len,
1208     const std::string& leading_mime_type,
1209     base::hash_set<base::FilePath::StringType>* extensions) {
1210   base::FilePath::StringType extension;
1211   for (size_t i = 0; i < mappings_len; ++i) {
1212     if (StartsWithASCII(mappings[i].mime_type, leading_mime_type, false)) {
1213       std::vector<string> this_extensions;
1214       base::SplitString(mappings[i].extensions, ',', &this_extensions);
1215       for (size_t j = 0; j < this_extensions.size(); ++j) {
1216 #if defined(OS_WIN)
1217         base::FilePath::StringType extension(
1218             base::UTF8ToWide(this_extensions[j]));
1219 #else
1220         base::FilePath::StringType extension(this_extensions[j]);
1221 #endif
1222         extensions->insert(extension);
1223       }
1224     }
1225   }
1226 }
1227
1228 void GetExtensionsHelper(
1229     const char* const* standard_types,
1230     size_t standard_types_len,
1231     const std::string& leading_mime_type,
1232     base::hash_set<base::FilePath::StringType>* extensions) {
1233   for (size_t i = 0; i < standard_types_len; ++i) {
1234     g_mime_util.Get().GetPlatformExtensionsForMimeType(standard_types[i],
1235                                                        extensions);
1236   }
1237
1238   // Also look up the extensions from hard-coded mappings in case that some
1239   // supported extensions are not registered in the system registry, like ogg.
1240   GetExtensionsFromHardCodedMappings(primary_mappings,
1241                                      arraysize(primary_mappings),
1242                                      leading_mime_type,
1243                                      extensions);
1244
1245   GetExtensionsFromHardCodedMappings(secondary_mappings,
1246                                      arraysize(secondary_mappings),
1247                                      leading_mime_type,
1248                                      extensions);
1249 }
1250
1251 // Note that the elements in the source set will be appended to the target
1252 // vector.
1253 template<class T>
1254 void HashSetToVector(base::hash_set<T>* source, std::vector<T>* target) {
1255   size_t old_target_size = target->size();
1256   target->resize(old_target_size + source->size());
1257   size_t i = 0;
1258   for (typename base::hash_set<T>::iterator iter = source->begin();
1259        iter != source->end(); ++iter, ++i)
1260     (*target)[old_target_size + i] = *iter;
1261 }
1262 }
1263
1264 void GetExtensionsForMimeType(
1265     const std::string& unsafe_mime_type,
1266     std::vector<base::FilePath::StringType>* extensions) {
1267   if (unsafe_mime_type == "*/*" || unsafe_mime_type == "*")
1268     return;
1269
1270   const std::string mime_type = base::StringToLowerASCII(unsafe_mime_type);
1271   base::hash_set<base::FilePath::StringType> unique_extensions;
1272
1273   if (EndsWith(mime_type, "/*", true)) {
1274     std::string leading_mime_type = mime_type.substr(0, mime_type.length() - 1);
1275
1276     // Find the matching StandardType from within kStandardTypes, or fall
1277     // through to the last (default) StandardType.
1278     const StandardType* type = NULL;
1279     for (size_t i = 0; i < arraysize(kStandardTypes); ++i) {
1280       type = &(kStandardTypes[i]);
1281       if (type->leading_mime_type &&
1282           leading_mime_type == type->leading_mime_type)
1283         break;
1284     }
1285     DCHECK(type);
1286     GetExtensionsHelper(type->standard_types,
1287                         type->standard_types_len,
1288                         leading_mime_type,
1289                         &unique_extensions);
1290   } else {
1291     g_mime_util.Get().GetPlatformExtensionsForMimeType(mime_type,
1292                                                        &unique_extensions);
1293
1294     // Also look up the extensions from hard-coded mappings in case that some
1295     // supported extensions are not registered in the system registry, like ogg.
1296     GetExtensionsFromHardCodedMappings(primary_mappings,
1297                                        arraysize(primary_mappings),
1298                                        mime_type,
1299                                        &unique_extensions);
1300
1301     GetExtensionsFromHardCodedMappings(secondary_mappings,
1302                                        arraysize(secondary_mappings),
1303                                        mime_type,
1304                                        &unique_extensions);
1305   }
1306
1307   HashSetToVector(&unique_extensions, extensions);
1308 }
1309
1310 void RemoveProprietaryMediaTypesAndCodecsForTests() {
1311   g_mime_util.Get().RemoveProprietaryMediaTypesAndCodecsForTests();
1312 }
1313
1314 const std::string GetIANAMediaType(const std::string& mime_type) {
1315   for (size_t i = 0; i < arraysize(kIanaMediaTypes); ++i) {
1316     if (StartsWithASCII(mime_type, kIanaMediaTypes[i].matcher, true)) {
1317       return kIanaMediaTypes[i].name;
1318     }
1319   }
1320   return std::string();
1321 }
1322
1323 CertificateMimeType GetCertificateMimeTypeForMimeType(
1324     const std::string& mime_type) {
1325   // Don't create a map, there is only one entry in the table,
1326   // except on Android.
1327   for (size_t i = 0; i < arraysize(supported_certificate_types); ++i) {
1328     if (mime_type == net::supported_certificate_types[i].mime_type)
1329       return net::supported_certificate_types[i].cert_type;
1330   }
1331   return CERTIFICATE_MIME_TYPE_UNKNOWN;
1332 }
1333
1334 bool IsSupportedCertificateMimeType(const std::string& mime_type) {
1335   CertificateMimeType file_type =
1336       GetCertificateMimeTypeForMimeType(mime_type);
1337   return file_type != CERTIFICATE_MIME_TYPE_UNKNOWN;
1338 }
1339
1340 void AddMultipartValueForUpload(const std::string& value_name,
1341                                 const std::string& value,
1342                                 const std::string& mime_boundary,
1343                                 const std::string& content_type,
1344                                 std::string* post_data) {
1345   DCHECK(post_data);
1346   // First line is the boundary.
1347   post_data->append("--" + mime_boundary + "\r\n");
1348   // Next line is the Content-disposition.
1349   post_data->append("Content-Disposition: form-data; name=\"" +
1350                     value_name + "\"\r\n");
1351   if (!content_type.empty()) {
1352     // If Content-type is specified, the next line is that.
1353     post_data->append("Content-Type: " + content_type + "\r\n");
1354   }
1355   // Leave an empty line and append the value.
1356   post_data->append("\r\n" + value + "\r\n");
1357 }
1358
1359 void AddMultipartFinalDelimiterForUpload(const std::string& mime_boundary,
1360                                          std::string* post_data) {
1361   DCHECK(post_data);
1362   post_data->append("--" + mime_boundary + "--\r\n");
1363 }
1364
1365 }  // namespace net