initial import
[vuplus_webkit] / Source / WebCore / platform / network / ContentTypeParser.cpp
1  /*
2  * Copyright (C) 2011 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 are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "ContentTypeParser.h"
33
34 #include <wtf/text/CString.h>
35 #include <wtf/text/StringBuilder.h>
36
37 namespace WebCore {
38
39 static void skipSpaces(const String& input, size_t& startIndex)
40 {
41     while (startIndex < input.length() && input[startIndex] == ' ')
42         ++startIndex;
43 }
44
45 static bool isTokenCharacter(char c)
46 {
47     return isASCII(c) && c > ' ' && c != '"' && c != '(' && c != ')' && c != ',' && c != '/' && (c < ':' || c > '@') && (c < '[' || c > ']');
48 }
49
50 static String parseToken(const String& input, size_t& startIndex)
51 {
52     if (startIndex >= input.length())
53         return String();
54
55     StringBuilder stringBuilder;
56     while (startIndex < input.length()) {
57         char currentCharacter = input[startIndex];
58         if (!isTokenCharacter(currentCharacter))
59             return stringBuilder.toString();
60         stringBuilder.append(currentCharacter);
61         ++startIndex;
62     }
63     return stringBuilder.toString();
64 }
65
66 static String parseQuotedString(const String& input, size_t& startIndex)
67 {
68     if (startIndex >= input.length())
69         return String();
70
71     if (input[startIndex++] != '"' || startIndex >= input.length())
72         return String();
73
74     StringBuilder stringBuilder;
75     bool lastCharacterWasBackslash = false;
76     char currentCharacter;
77     while ((currentCharacter = input[startIndex++]) != '"' || lastCharacterWasBackslash) {
78         if (startIndex >= input.length())
79             return String();
80         if (currentCharacter == '\\' && !lastCharacterWasBackslash) {
81             lastCharacterWasBackslash = true;
82             continue;
83         }
84         if (lastCharacterWasBackslash)
85             lastCharacterWasBackslash = false;
86         stringBuilder.append(currentCharacter);
87     }
88     return stringBuilder.toString();
89 }
90
91 ContentTypeParser::ContentTypeParser(const String& contentType)
92     : m_contentType(contentType.stripWhiteSpace())
93 {
94     parse();
95 }
96
97 String ContentTypeParser::charset() const
98 {
99     return parameterValueForName("charset");
100 }
101
102 String ContentTypeParser::parameterValueForName(const String& name) const
103 {
104     return m_parameters.get(name);
105 }
106
107 size_t ContentTypeParser::parameterCount() const
108 {
109     return m_parameters.size();
110 }
111
112 // From http://tools.ietf.org/html/rfc2045#section-5.1:
113 //
114 // content := "Content-Type" ":" type "/" subtype
115 //            *(";" parameter)
116 //            ; Matching of media type and subtype
117 //            ; is ALWAYS case-insensitive.
118 //
119 // type := discrete-type / composite-type
120 //
121 // discrete-type := "text" / "image" / "audio" / "video" /
122 //                  "application" / extension-token
123 //
124 // composite-type := "message" / "multipart" / extension-token
125 //
126 // extension-token := ietf-token / x-token
127 //
128 // ietf-token := <An extension token defined by a
129 //                standards-track RFC and registered
130 //                with IANA.>
131 //
132 // x-token := <The two characters "X-" or "x-" followed, with
133 //             no intervening white space, by any token>
134 //
135 // subtype := extension-token / iana-token
136 //
137 // iana-token := <A publicly-defined extension token. Tokens
138 //                of this form must be registered with IANA
139 //                as specified in RFC 2048.>
140 //
141 // parameter := attribute "=" value
142 //
143 // attribute := token
144 //              ; Matching of attributes
145 //              ; is ALWAYS case-insensitive.
146 //
147 // value := token / quoted-string
148 //
149 // token := 1*<any (US-ASCII) CHAR except SPACE, CTLs,
150 //             or tspecials>
151 //
152 // tspecials :=  "(" / ")" / "<" / ">" / "@" /
153 //               "," / ";" / ":" / "\" / <">
154 //               "/" / "[" / "]" / "?" / "="
155 //               ; Must be in quoted-string,
156 //               ; to use within parameter values
157
158 void ContentTypeParser::parse()
159 {
160     DEFINE_STATIC_LOCAL(const String, contentTypeParameterName, ("Content-Type"));
161
162     if (!m_contentType.startsWith(contentTypeParameterName)) {
163         LOG_ERROR("Invalid Content-Type string '%s'", m_contentType.ascii().data());
164         return;
165     }
166     size_t contentTypeLength = m_contentType.length();
167     size_t index = contentTypeParameterName.length();
168     skipSpaces(m_contentType, index);
169     if (index >= contentTypeLength || m_contentType[index] != ':' || ++index >= contentTypeLength)  {
170         LOG_ERROR("Invalid Content-Type string '%s'", m_contentType.ascii().data());
171         return;
172     }
173
174     // There should not be any quoted strings until we reach the parameters.
175     size_t semiColonIndex = m_contentType.find(';', index);
176     if (semiColonIndex == notFound) {
177         m_mimeType = m_contentType.substring(index).stripWhiteSpace();
178         return;
179     }
180
181     m_mimeType = m_contentType.substring(index, semiColonIndex - index).stripWhiteSpace();
182     index = semiColonIndex + 1;
183     while (true) {
184         skipSpaces(m_contentType, index);
185         String key = parseToken(m_contentType, index);
186         if (key.isEmpty() || index >= contentTypeLength) {
187             LOG_ERROR("Invalid Content-Type parameter name.");
188             return;
189         }
190         // Should we tolerate spaces here?
191         if (m_contentType[index++] != '=' || index >= contentTypeLength) {
192             LOG_ERROR("Invalid Content-Type malformed parameter.");
193             return;
194         }
195
196         // Should we tolerate spaces here?
197         String value;
198         if (m_contentType[index] == '"')
199             value = parseQuotedString(m_contentType, index);
200         else
201             value = parseToken(m_contentType, index);
202
203         if (value.isNull()) {
204             LOG_ERROR("Invalid Content-Type, invalid parameter value.");
205             return;
206         }
207
208         // Should we tolerate spaces here?
209         if (index < contentTypeLength && m_contentType[index++] != ';') {
210             LOG_ERROR("Invalid Content-Type, invalid character at the end of key/value parameter.");
211             return;
212         }
213
214         m_parameters.set(key, value);
215
216         if (index >= contentTypeLength)
217             return;
218     }
219 }
220
221 }