initial import
[vuplus_webkit] / Source / WebCore / html / parser / HTMLMetaCharsetParser.cpp
1 /*
2  * Copyright (C) 2010 Google Inc. All Rights Reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "HTMLMetaCharsetParser.h"
28
29 #include "HTMLNames.h"
30 #include "HTMLParserIdioms.h"
31 #include "HTMLTokenizer.h"
32 #include "PlatformString.h"
33 #include "TextCodec.h"
34 #include "TextEncodingRegistry.h"
35
36 using namespace WTF;
37
38 namespace WebCore {
39
40 using namespace HTMLNames;
41
42 HTMLMetaCharsetParser::HTMLMetaCharsetParser()
43     : m_tokenizer(HTMLTokenizer::create(false)) // No pre-HTML5 parser quirks.
44     , m_assumedCodec(newTextCodec(Latin1Encoding()))
45     , m_inHeadSection(true)
46     , m_doneChecking(false)
47 {
48 }
49
50 HTMLMetaCharsetParser::~HTMLMetaCharsetParser()
51 {
52 }
53
54 static const char charsetString[] = "charset";
55 static const size_t charsetLength = sizeof("charset") - 1;
56
57 String HTMLMetaCharsetParser::extractCharset(const String& value)
58 {
59     size_t pos = 0;
60     unsigned length = value.length();
61
62     while (pos < length) {
63         pos = value.find(charsetString, pos, false);
64         if (pos == notFound)
65             break;
66
67         pos += charsetLength;
68
69         // Skip whitespace.
70         while (pos < length && value[pos] <= ' ')
71             ++pos;
72
73         if (value[pos] != '=')
74             continue;
75
76         ++pos;
77
78         while (pos < length && value[pos] <= ' ')
79             ++pos;
80
81         char quoteMark = 0;
82         if (pos < length && (value[pos] == '"' || value[pos] == '\'')) {
83             quoteMark = static_cast<char>(value[pos++]);
84             ASSERT(!(quoteMark & 0x80));
85         }
86             
87         if (pos == length)
88             break;
89
90         unsigned end = pos;
91         while (end < length && ((quoteMark && value[end] != quoteMark) || (!quoteMark && value[end] > ' ' && value[end] != '"' && value[end] != '\'' && value[end] != ';')))
92             ++end;
93
94         if (quoteMark && (end == length))
95             break; // Close quote not found.
96
97         return value.substring(pos, end - pos);
98     }
99
100     return "";
101 }
102
103 bool HTMLMetaCharsetParser::processMeta()
104 {
105     const HTMLToken::AttributeList& tokenAttributes = m_token.attributes();
106     AttributeList attributes;
107     for (HTMLToken::AttributeList::const_iterator iter = tokenAttributes.begin(); iter != tokenAttributes.end(); ++iter) {
108         String attributeName(iter->m_name.data(), iter->m_name.size());
109         String attributeValue(iter->m_value.data(), iter->m_value.size());
110         attributes.append(make_pair(attributeName, attributeValue));
111     }
112
113     m_encoding = encodingFromMetaAttributes(attributes);
114     return m_encoding.isValid();
115 }
116
117 TextEncoding HTMLMetaCharsetParser::encodingFromMetaAttributes(const AttributeList& attributes)
118 {
119     bool gotPragma = false;
120     Mode mode = None;
121     String charset;
122
123     for (AttributeList::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter) {
124         const AtomicString& attributeName = iter->first;
125         const String& attributeValue = iter->second;
126
127         if (attributeName == http_equivAttr) {
128             if (equalIgnoringCase(attributeValue, "content-type"))
129                 gotPragma = true;
130         } else if (charset.isEmpty()) {
131             if (attributeName == charsetAttr) {
132                 charset = attributeValue;
133                 mode = Charset;
134             } else if (attributeName == contentAttr) {
135                 charset = extractCharset(attributeValue);
136                 if (charset.length())
137                     mode = Pragma;
138             }
139         }
140     }
141
142     if (mode == Charset || (mode == Pragma && gotPragma))
143         return TextEncoding(stripLeadingAndTrailingHTMLSpaces(charset));
144
145     return TextEncoding();
146 }
147
148 static const int bytesToCheckUnconditionally = 1024; // That many input bytes will be checked for meta charset even if <head> section is over.
149
150 bool HTMLMetaCharsetParser::checkForMetaCharset(const char* data, size_t length)
151 {
152     if (m_doneChecking)
153         return true;
154
155     ASSERT(!m_encoding.isValid());
156
157     // We still don't have an encoding, and are in the head.
158     // The following tags are allowed in <head>:
159     // SCRIPT|STYLE|META|LINK|OBJECT|TITLE|BASE
160
161     // We stop scanning when a tag that is not permitted in <head>
162     // is seen, rather when </head> is seen, because that more closely
163     // matches behavior in other browsers; more details in
164     // <http://bugs.webkit.org/show_bug.cgi?id=3590>.
165
166     // Additionally, we ignore things that looks like tags in <title>, <script>
167     // and <noscript>; see <http://bugs.webkit.org/show_bug.cgi?id=4560>,
168     // <http://bugs.webkit.org/show_bug.cgi?id=12165> and
169     // <http://bugs.webkit.org/show_bug.cgi?id=12389>.
170
171     // Since many sites have charset declarations after <body> or other tags
172     // that are disallowed in <head>, we don't bail out until we've checked at
173     // least bytesToCheckUnconditionally bytes of input.
174
175     m_input.append(SegmentedString(m_assumedCodec->decode(data, length)));
176
177     while (m_tokenizer->nextToken(m_input, m_token)) {
178         bool end = m_token.type() == HTMLTokenTypes::EndTag;
179         if (end || m_token.type() == HTMLTokenTypes::StartTag) {
180             AtomicString tagName(m_token.name().data(), m_token.name().size());
181             if (!end) {
182                 m_tokenizer->updateStateFor(tagName, 0);
183                 if (tagName == metaTag && processMeta()) {
184                     m_doneChecking = true;
185                     return true;
186                 }
187             }
188
189             if (tagName != scriptTag && tagName != noscriptTag
190                 && tagName != styleTag && tagName != linkTag
191                 && tagName != metaTag && tagName != objectTag
192                 && tagName != titleTag && tagName != baseTag
193                 && (end || tagName != htmlTag) && (end || tagName != headTag)) {
194                 m_inHeadSection = false;
195             }
196         }
197
198         if (!m_inHeadSection && m_input.numberOfCharactersConsumed() >= bytesToCheckUnconditionally) {
199             m_doneChecking = true;
200             return true;
201         }
202
203         m_token.clear();
204     }
205
206     return false;
207 }
208
209 }