Replace WTF::move with WTFMove
[WebKit-https.git] / Source / WebCore / html / FormController.cpp
1 /*
2  * Copyright (C) 2006, 2008, 2009, 2010 Apple Inc. All rights reserved.
3  * Copyright (C) 2010, 2011, 2012 Google Inc. All rights reserved.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public License
16  * along with this library; see the file COPYING.LIB.  If not, write to
17  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20
21 #include "config.h"
22 #include "FormController.h"
23
24 #include "HTMLFormElement.h"
25 #include "HTMLInputElement.h"
26 #include <wtf/text/StringBuilder.h>
27
28 namespace WebCore {
29
30 using namespace HTMLNames;
31
32 static inline HTMLFormElement* ownerFormForState(const HTMLFormControlElementWithState& control)
33 {
34     // Assume controls with form attribute have no owners because we restore
35     // state during parsing and form owners of such controls might be
36     // indeterminate.
37     return control.fastHasAttribute(formAttr) ? 0 : control.form();
38 }
39
40 // ----------------------------------------------------------------------------
41
42 // Serilized form of FormControlState:
43 //  (',' means strings around it are separated in stateVector.)
44 //
45 // SerializedControlState ::= SkipState | RestoreState
46 // SkipState ::= '0'
47 // RestoreState ::= UnsignedNumber, ControlValue+
48 // UnsignedNumber ::= [0-9]+
49 // ControlValue ::= arbitrary string
50 //
51 // RestoreState has a sequence of ControlValues. The length of the
52 // sequence is represented by UnsignedNumber.
53
54 void FormControlState::serializeTo(Vector<String>& stateVector) const
55 {
56     ASSERT(!isFailure());
57     stateVector.append(String::number(m_values.size()));
58     for (auto& value : m_values)
59         stateVector.append(value.isNull() ? emptyString() : value);
60 }
61
62 FormControlState FormControlState::deserialize(const Vector<String>& stateVector, size_t& index)
63 {
64     if (index >= stateVector.size())
65         return FormControlState(TypeFailure);
66     size_t valueSize = stateVector[index++].toUInt();
67     if (!valueSize)
68         return FormControlState();
69     if (index + valueSize > stateVector.size())
70         return FormControlState(TypeFailure);
71     FormControlState state;
72     state.m_values.reserveCapacity(valueSize);
73     for (size_t i = 0; i < valueSize; ++i)
74         state.append(stateVector[index++]);
75     return state;
76 }
77
78 // ----------------------------------------------------------------------------
79
80 class FormElementKey {
81 public:
82     FormElementKey(AtomicStringImpl* = 0, AtomicStringImpl* = 0);
83     ~FormElementKey();
84     FormElementKey(const FormElementKey&);
85     FormElementKey& operator=(const FormElementKey&);
86
87     AtomicStringImpl* name() const { return m_name; }
88     AtomicStringImpl* type() const { return m_type; }
89
90     // Hash table deleted values, which are only constructed and never copied or destroyed.
91     FormElementKey(WTF::HashTableDeletedValueType) : m_name(hashTableDeletedValue()) { }
92     bool isHashTableDeletedValue() const { return m_name == hashTableDeletedValue(); }
93
94 private:
95     void ref() const;
96     void deref() const;
97
98     static AtomicStringImpl* hashTableDeletedValue() { return reinterpret_cast<AtomicStringImpl*>(-1); }
99
100     AtomicStringImpl* m_name;
101     AtomicStringImpl* m_type;
102 };
103
104 FormElementKey::FormElementKey(AtomicStringImpl* name, AtomicStringImpl* type)
105     : m_name(name)
106     , m_type(type)
107 {
108     ref();
109 }
110
111 FormElementKey::~FormElementKey()
112 {
113     deref();
114 }
115
116 FormElementKey::FormElementKey(const FormElementKey& other)
117     : m_name(other.name())
118     , m_type(other.type())
119 {
120     ref();
121 }
122
123 FormElementKey& FormElementKey::operator=(const FormElementKey& other)
124 {
125     other.ref();
126     deref();
127     m_name = other.name();
128     m_type = other.type();
129     return *this;
130 }
131
132 void FormElementKey::ref() const
133 {
134     if (name())
135         name()->ref();
136     if (type())
137         type()->ref();
138 }
139
140 void FormElementKey::deref() const
141 {
142     if (name())
143         name()->deref();
144     if (type())
145         type()->deref();
146 }
147
148 inline bool operator==(const FormElementKey& a, const FormElementKey& b)
149 {
150     return a.name() == b.name() && a.type() == b.type();
151 }
152
153 struct FormElementKeyHash {
154     static unsigned hash(const FormElementKey&);
155     static bool equal(const FormElementKey& a, const FormElementKey& b) { return a == b; }
156     static const bool safeToCompareToEmptyOrDeleted = true;
157 };
158
159 unsigned FormElementKeyHash::hash(const FormElementKey& key)
160 {
161     return StringHasher::hashMemory<sizeof(FormElementKey)>(&key);
162 }
163
164 struct FormElementKeyHashTraits : WTF::GenericHashTraits<FormElementKey> {
165     static void constructDeletedValue(FormElementKey& slot) { new (NotNull, &slot) FormElementKey(WTF::HashTableDeletedValue); }
166     static bool isDeletedValue(const FormElementKey& value) { return value.isHashTableDeletedValue(); }
167 };
168
169 // ----------------------------------------------------------------------------
170
171 class SavedFormState {
172     WTF_MAKE_NONCOPYABLE(SavedFormState);
173     WTF_MAKE_FAST_ALLOCATED;
174
175 public:
176     SavedFormState()
177         : m_controlStateCount(0)
178     {
179     }
180
181     static std::unique_ptr<SavedFormState> deserialize(const Vector<String>&, size_t& index);
182     void serializeTo(Vector<String>&) const;
183     bool isEmpty() const { return m_stateForNewFormElements.isEmpty(); }
184     void appendControlState(const AtomicString& name, const AtomicString& type, const FormControlState&);
185     FormControlState takeControlState(const AtomicString& name, const AtomicString& type);
186
187     Vector<String> getReferencedFilePaths() const;
188
189 private:
190     typedef HashMap<FormElementKey, Deque<FormControlState>, FormElementKeyHash, FormElementKeyHashTraits> FormElementStateMap;
191     FormElementStateMap m_stateForNewFormElements;
192     size_t m_controlStateCount;
193 };
194
195 static bool isNotFormControlTypeCharacter(UChar ch)
196 {
197     return ch != '-' && (ch > 'z' || ch < 'a');
198 }
199
200 std::unique_ptr<SavedFormState> SavedFormState::deserialize(const Vector<String>& stateVector, size_t& index)
201 {
202     if (index >= stateVector.size())
203         return nullptr;
204     // FIXME: We need String::toSizeT().
205     size_t itemCount = stateVector[index++].toUInt();
206     if (!itemCount)
207         return nullptr;
208     auto savedFormState = std::make_unique<SavedFormState>();
209     while (itemCount--) {
210         if (index + 1 >= stateVector.size())
211             return nullptr;
212         String name = stateVector[index++];
213         String type = stateVector[index++];
214         FormControlState state = FormControlState::deserialize(stateVector, index);
215         if (type.isEmpty() || type.find(isNotFormControlTypeCharacter) != notFound || state.isFailure())
216             return nullptr;
217         savedFormState->appendControlState(name, type, state);
218     }
219     return savedFormState;
220 }
221
222 void SavedFormState::serializeTo(Vector<String>& stateVector) const
223 {
224     stateVector.append(String::number(m_controlStateCount));
225     for (auto& element : m_stateForNewFormElements) {
226         const FormElementKey& key = element.key;
227         for (auto& state : element.value) {
228             stateVector.append(key.name());
229             stateVector.append(key.type());
230             state.serializeTo(stateVector);
231         }
232     }
233 }
234
235 void SavedFormState::appendControlState(const AtomicString& name, const AtomicString& type, const FormControlState& state)
236 {
237     FormElementKey key(name.impl(), type.impl());
238     FormElementStateMap::iterator it = m_stateForNewFormElements.find(key);
239     if (it != m_stateForNewFormElements.end())
240         it->value.append(state);
241     else {
242         Deque<FormControlState> stateList;
243         stateList.append(state);
244         m_stateForNewFormElements.set(key, stateList);
245     }
246     m_controlStateCount++;
247 }
248
249 FormControlState SavedFormState::takeControlState(const AtomicString& name, const AtomicString& type)
250 {
251     if (m_stateForNewFormElements.isEmpty())
252         return FormControlState();
253     FormElementStateMap::iterator it = m_stateForNewFormElements.find(FormElementKey(name.impl(), type.impl()));
254     if (it == m_stateForNewFormElements.end())
255         return FormControlState();
256     ASSERT(it->value.size());
257     FormControlState state = it->value.takeFirst();
258     m_controlStateCount--;
259     if (!it->value.size())
260         m_stateForNewFormElements.remove(it);
261     return state;
262 }
263
264 Vector<String> SavedFormState::getReferencedFilePaths() const
265 {
266     Vector<String> toReturn;
267     for (auto& element : m_stateForNewFormElements) {
268         if (!equal(element.key.type(), "file", 4))
269             continue;
270         for (auto& state : element.value) {
271             for (auto& file : HTMLInputElement::filesFromFileInputFormControlState(state))
272                 toReturn.append(file.path);
273         }
274     }
275     return toReturn;
276 }
277
278 // ----------------------------------------------------------------------------
279
280 class FormKeyGenerator {
281     WTF_MAKE_NONCOPYABLE(FormKeyGenerator);
282     WTF_MAKE_FAST_ALLOCATED;
283
284 public:
285     FormKeyGenerator() = default;
286     AtomicString formKey(const HTMLFormControlElementWithState&);
287     void willDeleteForm(HTMLFormElement*);
288
289 private:
290     typedef HashMap<HTMLFormElement*, AtomicString> FormToKeyMap;
291     typedef HashMap<String, unsigned> FormSignatureToNextIndexMap;
292     FormToKeyMap m_formToKeyMap;
293     FormSignatureToNextIndexMap m_formSignatureToNextIndexMap;
294 };
295
296 static inline void recordFormStructure(const HTMLFormElement& form, StringBuilder& builder)
297 {
298     // 2 is enough to distinguish forms in webkit.org/b/91209#c0
299     const size_t namedControlsToBeRecorded = 2;
300     const Vector<FormAssociatedElement*>& controls = form.associatedElements();
301     builder.appendLiteral(" [");
302     for (size_t i = 0, namedControls = 0; i < controls.size() && namedControls < namedControlsToBeRecorded; ++i) {
303         if (!controls[i]->isFormControlElementWithState())
304             continue;
305         HTMLFormControlElementWithState* control = static_cast<HTMLFormControlElementWithState*>(controls[i]);
306         if (!ownerFormForState(*control))
307             continue;
308         AtomicString name = control->name();
309         if (name.isEmpty())
310             continue;
311         namedControls++;
312         builder.append(name);
313         builder.append(' ');
314     }
315     builder.append(']');
316 }
317
318 static inline String formSignature(const HTMLFormElement& form)
319 {
320     URL actionURL = form.getURLAttribute(actionAttr);
321     // Remove the query part because it might contain volatile parameters such
322     // as a session key.
323     actionURL.setQuery(String());
324     StringBuilder builder;
325     if (!actionURL.isEmpty())
326         builder.append(actionURL.string());
327
328     recordFormStructure(form, builder);
329     return builder.toString();
330 }
331
332 AtomicString FormKeyGenerator::formKey(const HTMLFormControlElementWithState& control)
333 {
334     HTMLFormElement* form = ownerFormForState(control);
335     if (!form) {
336         DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, formKeyForNoOwner, ("No owner", AtomicString::ConstructFromLiteral));
337         return formKeyForNoOwner;
338     }
339     FormToKeyMap::const_iterator it = m_formToKeyMap.find(form);
340     if (it != m_formToKeyMap.end())
341         return it->value;
342
343     String signature = formSignature(*form);
344     ASSERT(!signature.isNull());
345     FormSignatureToNextIndexMap::AddResult result = m_formSignatureToNextIndexMap.add(signature, 0);
346     unsigned nextIndex = result.iterator->value++;
347
348     StringBuilder builder;
349     builder.append(signature);
350     builder.appendLiteral(" #");
351     builder.appendNumber(nextIndex);
352     AtomicString formKey = builder.toAtomicString();
353     m_formToKeyMap.add(form, formKey);
354     return formKey;
355 }
356
357 void FormKeyGenerator::willDeleteForm(HTMLFormElement* form)
358 {
359     ASSERT(form);
360     m_formToKeyMap.remove(form);
361 }
362
363 // ----------------------------------------------------------------------------
364
365 FormController::FormController()
366 {
367 }
368
369 FormController::~FormController()
370 {
371 }
372
373 unsigned FormController::formElementsCharacterCount() const
374 {
375     unsigned count = 0;
376     for (auto& element : m_formElementsWithState) {
377         FormControlState state = element->saveFormControlState();
378         if (state.valueSize() && element->isTextFormControl())
379             count += state[0].length();
380     }
381     return count;
382 }
383
384 static String formStateSignature()
385 {
386     // In the legacy version of serialized state, the first item was a name
387     // attribute value of a form control. The following string literal should
388     // contain some characters which are rarely used for name attribute values.
389     DEPRECATED_DEFINE_STATIC_LOCAL(String, signature, (ASCIILiteral("\n\r?% WebKit serialized form state version 8 \n\r=&")));
390     return signature;
391 }
392
393 std::unique_ptr<FormController::SavedFormStateMap> FormController::createSavedFormStateMap(const FormElementListHashSet& controlList)
394 {
395     FormKeyGenerator keyGenerator;
396     auto stateMap = std::make_unique<SavedFormStateMap>();
397     for (auto& control : controlList) {
398         if (!control->shouldSaveAndRestoreFormControlState())
399             continue;
400         auto& formState = stateMap->add(keyGenerator.formKey(*control).impl(), nullptr).iterator->value;
401         if (!formState)
402             formState = std::make_unique<SavedFormState>();
403         formState->appendControlState(control->name(), control->type(), control->saveFormControlState());
404     }
405     return stateMap;
406 }
407
408 Vector<String> FormController::formElementsState() const
409 {
410     std::unique_ptr<SavedFormStateMap> stateMap = createSavedFormStateMap(m_formElementsWithState);
411     Vector<String> stateVector;
412     stateVector.reserveInitialCapacity(m_formElementsWithState.size() * 4);
413     stateVector.append(formStateSignature());
414     for (auto& state : *stateMap) {
415         stateVector.append(state.key.get());
416         state.value->serializeTo(stateVector);
417     }
418     bool hasOnlySignature = stateVector.size() == 1;
419     if (hasOnlySignature)
420         stateVector.clear();
421     return stateVector;
422 }
423
424 void FormController::setStateForNewFormElements(const Vector<String>& stateVector)
425 {
426     formStatesFromStateVector(stateVector, m_savedFormStateMap);
427 }
428
429 FormControlState FormController::takeStateForFormElement(const HTMLFormControlElementWithState& control)
430 {
431     if (m_savedFormStateMap.isEmpty())
432         return FormControlState();
433     if (!m_formKeyGenerator)
434         m_formKeyGenerator = std::make_unique<FormKeyGenerator>();
435     SavedFormStateMap::iterator it = m_savedFormStateMap.find(m_formKeyGenerator->formKey(control).impl());
436     if (it == m_savedFormStateMap.end())
437         return FormControlState();
438     FormControlState state = it->value->takeControlState(control.name(), control.type());
439     if (it->value->isEmpty())
440         m_savedFormStateMap.remove(it);
441     return state;
442 }
443
444 void FormController::formStatesFromStateVector(const Vector<String>& stateVector, SavedFormStateMap& map)
445 {
446     map.clear();
447
448     size_t i = 0;
449     if (stateVector.size() < 1 || stateVector[i++] != formStateSignature())
450         return;
451
452     while (i + 1 < stateVector.size()) {
453         AtomicString formKey = stateVector[i++];
454         auto state = SavedFormState::deserialize(stateVector, i);
455         if (!state) {
456             i = 0;
457             break;
458         }
459         map.add(formKey.impl(), WTFMove(state));
460     }
461     if (i != stateVector.size())
462         map.clear();
463 }
464
465 void FormController::willDeleteForm(HTMLFormElement* form)
466 {
467     if (m_formKeyGenerator)
468         m_formKeyGenerator->willDeleteForm(form);
469 }
470
471 void FormController::restoreControlStateFor(HTMLFormControlElementWithState& control)
472 {
473     // We don't save state of a control with shouldSaveAndRestoreFormControlState()
474     // == false. But we need to skip restoring process too because a control in
475     // another form might have the same pair of name and type and saved its state.
476     if (!control.shouldSaveAndRestoreFormControlState())
477         return;
478     if (ownerFormForState(control))
479         return;
480     FormControlState state = takeStateForFormElement(control);
481     if (state.valueSize() > 0)
482         control.restoreFormControlState(state);
483 }
484
485 void FormController::restoreControlStateIn(HTMLFormElement& form)
486 {
487     for (auto& element : form.associatedElements()) {
488         if (!element->isFormControlElementWithState())
489             continue;
490         HTMLFormControlElementWithState* control = static_cast<HTMLFormControlElementWithState*>(element);
491         if (!control->shouldSaveAndRestoreFormControlState())
492             continue;
493         if (ownerFormForState(*control) != &form)
494             continue;
495         FormControlState state = takeStateForFormElement(*control);
496         if (state.valueSize() > 0)
497             control->restoreFormControlState(state);
498     }
499 }
500
501 Vector<String> FormController::getReferencedFilePaths(const Vector<String>& stateVector)
502 {
503     Vector<String> toReturn;
504     SavedFormStateMap map;
505     formStatesFromStateVector(stateVector, map);
506     for (auto& state : map.values())
507         toReturn.appendVector(state->getReferencedFilePaths());
508     return toReturn;
509 }
510
511 void FormController::registerFormElementWithState(HTMLFormControlElementWithState* control)
512 {
513     ASSERT(!m_formElementsWithState.contains(control));
514     m_formElementsWithState.add(control);
515 }
516
517 void FormController::unregisterFormElementWithState(HTMLFormControlElementWithState* control)
518 {
519     ASSERT(m_formElementsWithState.contains(control));
520     m_formElementsWithState.remove(control);
521 }
522
523 } // namespace WebCore