2 * Copyright (C) 2010 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
32 #include "core/loader/FormSubmission.h"
34 #include "HTMLNames.h"
35 #include "RuntimeEnabledFeatures.h"
36 #include "core/dom/Document.h"
37 #include "core/events/Event.h"
38 #include "core/html/DOMFormData.h"
39 #include "core/html/HTMLFormControlElement.h"
40 #include "core/html/HTMLFormElement.h"
41 #include "core/html/HTMLInputElement.h"
42 #include "core/html/parser/HTMLParserIdioms.h"
43 #include "core/loader/FrameLoadRequest.h"
44 #include "core/loader/FrameLoader.h"
45 #include "platform/network/FormData.h"
46 #include "platform/network/FormDataBuilder.h"
47 #include "wtf/CurrentTime.h"
48 #include "wtf/text/StringBuilder.h"
49 #include "wtf/text/TextEncoding.h"
53 using namespace HTMLNames;
55 static int64_t generateFormDataIdentifier()
57 // Initialize to the current time to reduce the likelihood of generating
58 // identifiers that overlap with those from past/future browser sessions.
59 static int64_t nextIdentifier = static_cast<int64_t>(currentTime() * 1000000.0);
60 return ++nextIdentifier;
63 static void appendMailtoPostFormDataToURL(KURL& url, const FormData& data, const String& encodingType)
65 String body = data.flattenToString();
67 if (equalIgnoringCase(encodingType, "text/plain")) {
68 // Convention seems to be to decode, and s/&/\r\n/. Also, spaces are encoded as %20.
69 body = decodeURLEscapeSequences(body.replaceWithLiteral('&', "\r\n").replace('+', ' ') + "\r\n");
72 Vector<char> bodyData;
73 bodyData.append("body=", 5);
74 FormDataBuilder::encodeStringAsFormData(bodyData, body.utf8());
75 body = String(bodyData.data(), bodyData.size()).replaceWithLiteral('+', "%20");
78 query.append(url.query());
82 url.setQuery(query.toString());
85 void FormSubmission::Attributes::parseAction(const String& action)
87 // FIXME: Can we parse into a KURL?
88 m_action = stripLeadingAndTrailingHTMLSpaces(action);
91 AtomicString FormSubmission::Attributes::parseEncodingType(const String& type)
93 if (equalIgnoringCase(type, "multipart/form-data"))
94 return AtomicString("multipart/form-data", AtomicString::ConstructFromLiteral);
95 if (equalIgnoringCase(type, "text/plain"))
96 return AtomicString("text/plain", AtomicString::ConstructFromLiteral);
97 return AtomicString("application/x-www-form-urlencoded", AtomicString::ConstructFromLiteral);
100 void FormSubmission::Attributes::updateEncodingType(const String& type)
102 m_encodingType = parseEncodingType(type);
103 m_isMultiPartForm = (m_encodingType == "multipart/form-data");
106 FormSubmission::Method FormSubmission::Attributes::parseMethodType(const String& type)
108 if (equalIgnoringCase(type, "post"))
109 return FormSubmission::PostMethod;
110 if (RuntimeEnabledFeatures::dialogElementEnabled() && equalIgnoringCase(type, "dialog"))
111 return FormSubmission::DialogMethod;
112 return FormSubmission::GetMethod;
115 void FormSubmission::Attributes::updateMethodType(const String& type)
117 m_method = parseMethodType(type);
120 String FormSubmission::Attributes::methodString(Method method)
130 ASSERT_NOT_REACHED();
131 return emptyString();
134 void FormSubmission::Attributes::copyFrom(const Attributes& other)
136 m_method = other.m_method;
137 m_isMultiPartForm = other.m_isMultiPartForm;
139 m_action = other.m_action;
140 m_target = other.m_target;
141 m_encodingType = other.m_encodingType;
142 m_acceptCharset = other.m_acceptCharset;
145 inline FormSubmission::FormSubmission(Method method, const KURL& action, const AtomicString& target, const AtomicString& contentType, PassRefPtr<FormState> state, PassRefPtr<FormData> data, const String& boundary, PassRefPtr<Event> event)
149 , m_contentType(contentType)
152 , m_boundary(boundary)
157 inline FormSubmission::FormSubmission(const String& result)
158 : m_method(DialogMethod)
163 PassRefPtr<FormSubmission> FormSubmission::create(HTMLFormElement* form, const Attributes& attributes, PassRefPtr<Event> event, FormSubmissionTrigger trigger)
167 HTMLFormControlElement* submitButton = 0;
168 if (event && event->target()) {
169 for (Node* node = event->target()->toNode(); node; node = node->parentOrShadowHostNode()) {
170 if (node->isElementNode() && toElement(node)->isFormControlElement()) {
171 submitButton = toHTMLFormControlElement(node);
177 FormSubmission::Attributes copiedAttributes;
178 copiedAttributes.copyFrom(attributes);
180 AtomicString attributeValue;
181 if (!(attributeValue = submitButton->fastGetAttribute(formactionAttr)).isNull())
182 copiedAttributes.parseAction(attributeValue);
183 if (!(attributeValue = submitButton->fastGetAttribute(formenctypeAttr)).isNull())
184 copiedAttributes.updateEncodingType(attributeValue);
185 if (!(attributeValue = submitButton->fastGetAttribute(formmethodAttr)).isNull())
186 copiedAttributes.updateMethodType(attributeValue);
187 if (!(attributeValue = submitButton->fastGetAttribute(formtargetAttr)).isNull())
188 copiedAttributes.setTarget(attributeValue);
191 if (copiedAttributes.method() == DialogMethod)
192 return adoptRef(new FormSubmission(submitButton->resultForDialogSubmit()));
194 Document& document = form->document();
195 KURL actionURL = document.completeURL(copiedAttributes.action().isEmpty() ? document.url().string() : copiedAttributes.action());
196 bool isMailtoForm = actionURL.protocolIs("mailto");
197 bool isMultiPartForm = false;
198 AtomicString encodingType = copiedAttributes.encodingType();
200 if (copiedAttributes.method() == PostMethod) {
201 isMultiPartForm = copiedAttributes.isMultiPartForm();
202 if (isMultiPartForm && isMailtoForm) {
203 encodingType = AtomicString("application/x-www-form-urlencoded", AtomicString::ConstructFromLiteral);
204 isMultiPartForm = false;
207 WTF::TextEncoding dataEncoding = isMailtoForm ? UTF8Encoding() : FormDataBuilder::encodingFromAcceptCharset(copiedAttributes.acceptCharset(), document.inputEncoding(), document.defaultCharset());
208 RefPtr<DOMFormData> domFormData = DOMFormData::create(dataEncoding.encodingForFormSubmission());
209 Vector<pair<String, String> > formValues;
211 bool containsPasswordData = false;
212 for (unsigned i = 0; i < form->associatedElements().size(); ++i) {
213 FormAssociatedElement* control = form->associatedElements()[i];
214 HTMLElement* element = toHTMLElement(control);
215 if (!element->isDisabledFormControl())
216 control->appendFormData(*domFormData, isMultiPartForm);
217 if (element->hasTagName(inputTag)) {
218 HTMLInputElement* input = toHTMLInputElement(element);
219 if (input->isTextField())
220 formValues.append(pair<String, String>(input->name().string(), input->value()));
221 if (input->isPasswordField() && !input->value().isEmpty())
222 containsPasswordData = true;
226 RefPtr<FormData> formData;
229 if (isMultiPartForm) {
230 formData = domFormData->createMultiPartFormData(domFormData->encoding());
231 boundary = formData->boundary().data();
233 formData = domFormData->createFormData(domFormData->encoding(), attributes.method() == GetMethod ? FormData::FormURLEncoded : FormData::parseEncodingType(encodingType));
234 if (copiedAttributes.method() == PostMethod && isMailtoForm) {
235 // Convert the form data into a string that we put into the URL.
236 appendMailtoPostFormDataToURL(actionURL, *formData, encodingType);
237 formData = FormData::create();
241 formData->setIdentifier(generateFormDataIdentifier());
242 formData->setContainsPasswordData(containsPasswordData);
243 AtomicString targetOrBaseTarget = copiedAttributes.target().isEmpty() ? document.baseTarget() : copiedAttributes.target();
244 RefPtr<FormState> formState = FormState::create(form, formValues, &document, trigger);
245 return adoptRef(new FormSubmission(copiedAttributes.method(), actionURL, targetOrBaseTarget, encodingType, formState.release(), formData.release(), boundary, event));
248 KURL FormSubmission::requestURL() const
250 if (m_method == FormSubmission::PostMethod)
253 KURL requestURL(m_action);
254 requestURL.setQuery(m_formData->flattenToString());
258 void FormSubmission::populateFrameLoadRequest(FrameLoadRequest& frameRequest)
260 if (!m_target.isEmpty())
261 frameRequest.setFrameName(m_target);
263 if (!m_referrer.referrer.isEmpty())
264 frameRequest.resourceRequest().setHTTPReferrer(m_referrer);
266 if (m_method == FormSubmission::PostMethod) {
267 frameRequest.resourceRequest().setHTTPMethod("POST");
268 frameRequest.resourceRequest().setHTTPBody(m_formData);
270 // construct some user headers if necessary
271 if (m_boundary.isEmpty())
272 frameRequest.resourceRequest().setHTTPContentType(m_contentType);
274 frameRequest.resourceRequest().setHTTPContentType(m_contentType + "; boundary=" + m_boundary);
277 frameRequest.resourceRequest().setURL(requestURL());
278 FrameLoader::addHTTPOriginIfNeeded(frameRequest.resourceRequest(), AtomicString(m_origin));