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 "FormSubmission.h"
34 #include "DOMFormData.h"
38 #include "FormDataBuilder.h"
39 #include "FormState.h"
41 #include "FrameLoadRequest.h"
42 #include "FrameLoader.h"
43 #include "HTMLFormControlElement.h"
44 #include "HTMLFormElement.h"
45 #include "HTMLInputElement.h"
46 #include "HTMLNames.h"
47 #include "HTMLParserIdioms.h"
48 #include "TextEncoding.h"
49 #include <wtf/CurrentTime.h>
50 #include <wtf/RandomNumber.h>
54 using namespace HTMLNames;
56 static int64_t generateFormDataIdentifier()
58 // Initialize to the current time to reduce the likelihood of generating
59 // identifiers that overlap with those from past/future browser sessions.
60 static int64_t nextIdentifier = static_cast<int64_t>(currentTime() * 1000000.0);
61 return ++nextIdentifier;
64 static void appendMailtoPostFormDataToURL(KURL& url, const FormData& data, const String& encodingType)
66 String body = data.flattenToString();
68 if (equalIgnoringCase(encodingType, "text/plain")) {
69 // Convention seems to be to decode, and s/&/\r\n/. Also, spaces are encoded as %20.
70 body = decodeURLEscapeSequences(body.replace('&', "\r\n").replace('+', ' ') + "\r\n");
73 Vector<char> bodyData;
74 bodyData.append("body=", 5);
75 FormDataBuilder::encodeStringAsFormData(bodyData, body.utf8());
76 body = String(bodyData.data(), bodyData.size()).replace('+', "%20");
78 String query = url.query();
85 void FormSubmission::Attributes::parseAction(const String& action)
87 // FIXME: Can we parse into a KURL?
88 m_action = stripLeadingAndTrailingHTMLSpaces(action);
91 String FormSubmission::Attributes::parseEncodingType(const String& type)
93 if (equalIgnoringCase(type, "multipart/form-data"))
94 return "multipart/form-data";
95 if (equalIgnoringCase(type, "text/plain"))
97 return "application/x-www-form-urlencoded";
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 return equalIgnoringCase(type, "post") ? FormSubmission::PostMethod : FormSubmission::GetMethod;
111 void FormSubmission::Attributes::updateMethodType(const String& type)
113 m_method = parseMethodType(type);
116 void FormSubmission::Attributes::copyFrom(const Attributes& other)
118 m_method = other.m_method;
119 m_isMultiPartForm = other.m_isMultiPartForm;
121 m_action = other.m_action;
122 m_target = other.m_target;
123 m_encodingType = other.m_encodingType;
124 m_acceptCharset = other.m_acceptCharset;
127 inline FormSubmission::FormSubmission(Method method, const KURL& action, const String& target, const String& contentType, PassRefPtr<FormState> state, PassRefPtr<FormData> data, const String& boundary, bool lockHistory, PassRefPtr<Event> event)
131 , m_contentType(contentType)
134 , m_boundary(boundary)
135 , m_lockHistory(lockHistory)
140 PassRefPtr<FormSubmission> FormSubmission::create(HTMLFormElement* form, const Attributes& attributes, PassRefPtr<Event> event, bool lockHistory, FormSubmissionTrigger trigger)
144 HTMLFormControlElement* submitButton = 0;
145 if (event && event->target()) {
146 Node* node = event->target()->toNode();
147 if (node && node->isElementNode() && toElement(node)->isFormControlElement())
148 submitButton = static_cast<HTMLFormControlElement*>(node);
151 FormSubmission::Attributes copiedAttributes;
152 copiedAttributes.copyFrom(attributes);
154 String attributeValue;
155 if (!(attributeValue = submitButton->getAttribute(formactionAttr)).isNull())
156 copiedAttributes.parseAction(attributeValue);
157 if (!(attributeValue = submitButton->getAttribute(formenctypeAttr)).isNull())
158 copiedAttributes.updateEncodingType(attributeValue);
159 if (!(attributeValue = submitButton->getAttribute(formmethodAttr)).isNull())
160 copiedAttributes.updateMethodType(attributeValue);
161 if (!(attributeValue = submitButton->getAttribute(formtargetAttr)).isNull())
162 copiedAttributes.setTarget(attributeValue);
165 Document* document = form->document();
166 KURL actionURL = document->completeURL(copiedAttributes.action().isEmpty() ? document->url().string() : copiedAttributes.action());
167 bool isMailtoForm = actionURL.protocolIs("mailto");
168 bool isMultiPartForm = false;
169 String encodingType = copiedAttributes.encodingType();
171 if (copiedAttributes.method() == PostMethod) {
172 isMultiPartForm = copiedAttributes.isMultiPartForm();
173 if (isMultiPartForm && isMailtoForm) {
174 encodingType = "application/x-www-form-urlencoded";
175 isMultiPartForm = false;
179 TextEncoding dataEncoding = isMailtoForm ? UTF8Encoding() : FormDataBuilder::encodingFromAcceptCharset(copiedAttributes.acceptCharset(), document);
180 RefPtr<DOMFormData> domFormData = DOMFormData::create(dataEncoding.encodingForFormSubmission());
181 Vector<pair<String, String> > formValues;
183 bool containsPasswordData = false;
184 for (unsigned i = 0; i < form->associatedElements().size(); ++i) {
185 FormAssociatedElement* control = form->associatedElements()[i];
186 HTMLElement* element = toHTMLElement(control);
187 if (!element->disabled())
188 control->appendFormData(*domFormData, isMultiPartForm);
189 if (element->hasLocalName(inputTag)) {
190 HTMLInputElement* input = static_cast<HTMLInputElement*>(control);
191 if (input->isTextField()) {
192 formValues.append(pair<String, String>(input->name().string(), input->value()));
193 if (input->isSearchField())
194 input->addSearchResult();
196 if (input->isPasswordField() && !input->value().isEmpty())
197 containsPasswordData = true;
201 RefPtr<FormData> formData;
204 if (isMultiPartForm) {
205 formData = FormData::createMultiPart(*(static_cast<FormDataList*>(domFormData.get())), domFormData->encoding(), document);
206 boundary = formData->boundary().data();
208 formData = FormData::create(*(static_cast<FormDataList*>(domFormData.get())), domFormData->encoding(), attributes.method() == GetMethod ? FormData::FormURLEncoded : FormData::parseEncodingType(encodingType));
209 if (copiedAttributes.method() == PostMethod && isMailtoForm) {
210 // Convert the form data into a string that we put into the URL.
211 appendMailtoPostFormDataToURL(actionURL, *formData, encodingType);
212 formData = FormData::create();
216 formData->setIdentifier(generateFormDataIdentifier());
217 formData->setContainsPasswordData(containsPasswordData);
218 String targetOrBaseTarget = copiedAttributes.target().isEmpty() ? document->baseTarget() : copiedAttributes.target();
219 RefPtr<FormState> formState = FormState::create(form, formValues, document->frame(), trigger);
220 return adoptRef(new FormSubmission(copiedAttributes.method(), actionURL, targetOrBaseTarget, encodingType, formState.release(), formData.release(), boundary, lockHistory, event));
223 KURL FormSubmission::requestURL() const
225 if (m_method == FormSubmission::PostMethod)
228 KURL requestURL(m_action);
229 requestURL.setQuery(m_formData->flattenToString());
233 void FormSubmission::populateFrameLoadRequest(FrameLoadRequest& frameRequest)
235 if (!m_target.isEmpty())
236 frameRequest.setFrameName(m_target);
238 if (!m_referrer.isEmpty())
239 frameRequest.resourceRequest().setHTTPReferrer(m_referrer);
241 if (m_method == FormSubmission::PostMethod) {
242 frameRequest.resourceRequest().setHTTPMethod("POST");
243 frameRequest.resourceRequest().setHTTPBody(m_formData);
245 // construct some user headers if necessary
246 if (m_contentType.isNull() || m_contentType == "application/x-www-form-urlencoded")
247 frameRequest.resourceRequest().setHTTPContentType(m_contentType);
248 else // contentType must be "multipart/form-data"
249 frameRequest.resourceRequest().setHTTPContentType(m_contentType + "; boundary=" + m_boundary);
252 frameRequest.resourceRequest().setURL(requestURL());
253 FrameLoader::addHTTPOriginIfNeeded(frameRequest.resourceRequest(), m_origin);