Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / loader / FormSubmission.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 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 "core/loader/FormSubmission.h"
33
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"
50
51 namespace WebCore {
52
53 using namespace HTMLNames;
54
55 static int64_t generateFormDataIdentifier()
56 {
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;
61 }
62
63 static void appendMailtoPostFormDataToURL(KURL& url, const FormData& data, const String& encodingType)
64 {
65     String body = data.flattenToString();
66
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");
70     }
71
72     Vector<char> bodyData;
73     bodyData.append("body=", 5);
74     FormDataBuilder::encodeStringAsFormData(bodyData, body.utf8());
75     body = String(bodyData.data(), bodyData.size()).replaceWithLiteral('+', "%20");
76
77     StringBuilder query;
78     query.append(url.query());
79     if (!query.isEmpty())
80         query.append('&');
81     query.append(body);
82     url.setQuery(query.toString());
83 }
84
85 void FormSubmission::Attributes::parseAction(const String& action)
86 {
87     // FIXME: Can we parse into a KURL?
88     m_action = stripLeadingAndTrailingHTMLSpaces(action);
89 }
90
91 AtomicString FormSubmission::Attributes::parseEncodingType(const String& type)
92 {
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);
98 }
99
100 void FormSubmission::Attributes::updateEncodingType(const String& type)
101 {
102     m_encodingType = parseEncodingType(type);
103     m_isMultiPartForm = (m_encodingType == "multipart/form-data");
104 }
105
106 FormSubmission::Method FormSubmission::Attributes::parseMethodType(const String& type)
107 {
108     if (equalIgnoringCase(type, "post"))
109         return FormSubmission::PostMethod;
110     if (RuntimeEnabledFeatures::dialogElementEnabled() && equalIgnoringCase(type, "dialog"))
111         return FormSubmission::DialogMethod;
112     return FormSubmission::GetMethod;
113 }
114
115 void FormSubmission::Attributes::updateMethodType(const String& type)
116 {
117     m_method = parseMethodType(type);
118 }
119
120 String FormSubmission::Attributes::methodString(Method method)
121 {
122     switch (method) {
123     case GetMethod:
124         return "get";
125     case PostMethod:
126         return "post";
127     case DialogMethod:
128         return "dialog";
129     }
130     ASSERT_NOT_REACHED();
131     return emptyString();
132 }
133
134 void FormSubmission::Attributes::copyFrom(const Attributes& other)
135 {
136     m_method = other.m_method;
137     m_isMultiPartForm = other.m_isMultiPartForm;
138
139     m_action = other.m_action;
140     m_target = other.m_target;
141     m_encodingType = other.m_encodingType;
142     m_acceptCharset = other.m_acceptCharset;
143 }
144
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)
146     : m_method(method)
147     , m_action(action)
148     , m_target(target)
149     , m_contentType(contentType)
150     , m_formState(state)
151     , m_formData(data)
152     , m_boundary(boundary)
153     , m_event(event)
154 {
155 }
156
157 inline FormSubmission::FormSubmission(const String& result)
158     : m_method(DialogMethod)
159     , m_result(result)
160 {
161 }
162
163 PassRefPtr<FormSubmission> FormSubmission::create(HTMLFormElement* form, const Attributes& attributes, PassRefPtr<Event> event, FormSubmissionTrigger trigger)
164 {
165     ASSERT(form);
166
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);
172                 break;
173             }
174         }
175     }
176
177     FormSubmission::Attributes copiedAttributes;
178     copiedAttributes.copyFrom(attributes);
179     if (submitButton) {
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);
189     }
190
191     if (copiedAttributes.method() == DialogMethod)
192         return adoptRef(new FormSubmission(submitButton->resultForDialogSubmit()));
193
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();
199
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;
205         }
206     }
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;
210
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;
223         }
224     }
225
226     RefPtr<FormData> formData;
227     String boundary;
228
229     if (isMultiPartForm) {
230         formData = domFormData->createMultiPartFormData(domFormData->encoding());
231         boundary = formData->boundary().data();
232     } else {
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();
238         }
239     }
240
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));
246 }
247
248 KURL FormSubmission::requestURL() const
249 {
250     if (m_method == FormSubmission::PostMethod)
251         return m_action;
252
253     KURL requestURL(m_action);
254     requestURL.setQuery(m_formData->flattenToString());
255     return requestURL;
256 }
257
258 void FormSubmission::populateFrameLoadRequest(FrameLoadRequest& frameRequest)
259 {
260     if (!m_target.isEmpty())
261         frameRequest.setFrameName(m_target);
262
263     if (!m_referrer.referrer.isEmpty())
264         frameRequest.resourceRequest().setHTTPReferrer(m_referrer);
265
266     if (m_method == FormSubmission::PostMethod) {
267         frameRequest.resourceRequest().setHTTPMethod("POST");
268         frameRequest.resourceRequest().setHTTPBody(m_formData);
269
270         // construct some user headers if necessary
271         if (m_boundary.isEmpty())
272             frameRequest.resourceRequest().setHTTPContentType(m_contentType);
273         else
274             frameRequest.resourceRequest().setHTTPContentType(m_contentType + "; boundary=" + m_boundary);
275     }
276
277     frameRequest.resourceRequest().setURL(requestURL());
278     FrameLoader::addHTTPOriginIfNeeded(frameRequest.resourceRequest(), AtomicString(m_origin));
279 }
280
281 }