1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
|
/*
* Copyright (C) 2006-2024 Apple Inc. All rights reserved.
* Copyright (C) 2010, 2011, 2012 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "FormController.h"
#include "FileChooser.h"
#include "HTMLFormElement.h"
#include "HTMLInputElement.h"
#include "HTMLMaybeFormAssociatedCustomElement.h"
#include "ScriptDisallowedScope.h"
#include "TypedElementDescendantIteratorInlines.h"
#include <wtf/NeverDestroyed.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/WeakHashMap.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/StringToIntegerConversion.h>
namespace WebCore {
WTF_MAKE_TZONE_ALLOCATED_IMPL(FormController);
HTMLFormElement* FormController::ownerForm(const FormListedElement& control)
{
// Assume controls with form attribute have no owners because we restore
// state during parsing and form owners of such controls might be
// indeterminate.
return control.asHTMLElement().hasAttributeWithoutSynchronization(HTMLNames::formAttr) ? nullptr : control.form();
}
struct AtomStringVectorReader {
const Vector<AtomString>& vector;
size_t index { 0 };
const AtomString& consumeString();
Vector<AtomString> consumeSubvector(size_t subvectorSize);
};
const AtomString& AtomStringVectorReader::consumeString()
{
if (index == vector.size())
return nullAtom();
return vector[index++];
}
Vector<AtomString> AtomStringVectorReader::consumeSubvector(size_t subvectorSize)
{
if (subvectorSize > vector.size() - index)
return { };
auto subvectorIndex = index;
index += subvectorSize;
return vector.subvector(subvectorIndex, subvectorSize);
}
// ----------------------------------------------------------------------------
// Serialized form of FormControlState:
// (',' means strings around it are separated in stateVector.)
//
// SerializedControlState ::= SkipState | RestoreState
// SkipState ::= '0'
// RestoreState ::= UnsignedNumber, ControlValue+
// UnsignedNumber ::= [0-9]+
// ControlValue ::= arbitrary string
//
// The UnsignedNumber in RestoreState is the length of the sequence of ControlValues.
static void appendSerializedFormControlState(Vector<AtomString>& vector, const FormControlState& state)
{
vector.append(AtomString::number(state.size()));
for (auto& value : state)
vector.append(value.isNull() ? emptyAtom() : value);
}
static std::optional<FormControlState> consumeSerializedFormControlState(AtomStringVectorReader& reader)
{
auto sizeString = reader.consumeString();
if (sizeString.isNull())
return std::nullopt;
return reader.consumeSubvector(parseInteger<size_t>(sizeString).value_or(0));
}
// ----------------------------------------------------------------------------
class FormController::SavedFormState {
public:
static SavedFormState consumeSerializedState(AtomStringVectorReader&);
bool isEmpty() const { return m_map.isEmpty(); }
using FormElementKey = std::pair<AtomString, AtomString>;
FormControlState takeControlState(const FormElementKey&);
void appendReferencedFilePaths(Vector<String>&) const;
private:
UncheckedKeyHashMap<FormElementKey, Deque<FormControlState>> m_map;
};
FormController::SavedFormState FormController::SavedFormState::consumeSerializedState(AtomStringVectorReader& reader)
{
auto isNotFormControlTypeCharacter = [](UChar character) {
return !(character == '-' || isASCIILower(character));
};
SavedFormState result;
auto count = parseInteger<size_t>(reader.consumeString()).value_or(0);
while (count--) {
auto& name = reader.consumeString();
auto& type = reader.consumeString();
if (type.isEmpty() || StringView { type }.contains(isNotFormControlTypeCharacter))
return { };
auto state = consumeSerializedFormControlState(reader);
if (!state)
return { };
result.m_map.add({ name, type }, Deque<FormControlState> { }).iterator->value.append(WTFMove(*state));
}
return result;
}
FormControlState FormController::SavedFormState::takeControlState(const FormElementKey& key)
{
auto iterator = m_map.find(key);
if (iterator == m_map.end())
return { };
auto state = iterator->value.takeFirst();
if (iterator->value.isEmpty())
m_map.remove(iterator);
return state;
}
void FormController::SavedFormState::appendReferencedFilePaths(Vector<String>& vector) const
{
for (auto& element : m_map) {
if (element.key.second != "file"_s) // type
continue;
for (auto& state : element.value) {
for (auto& file : HTMLInputElement::filesFromFileInputFormControlState(state))
vector.append(file.path);
}
}
}
// ----------------------------------------------------------------------------
class FormController::FormKeyGenerator {
typedef FormController::FormKeyGenerator FormControllerFormKeyGenerator;
WTF_MAKE_TZONE_ALLOCATED(FormKeyGenerator);
WTF_MAKE_NONCOPYABLE(FormKeyGenerator);
public:
FormKeyGenerator() = default;
String formKey(const ValidatedFormListedElement&);
void willDeleteForm(HTMLFormElement&);
private:
WeakHashMap<HTMLFormElement, String, WeakPtrImplWithEventTargetData> m_formToKeyMap;
UncheckedKeyHashMap<String, unsigned> m_formSignatureToNextIndexMap;
};
WTF_MAKE_TZONE_ALLOCATED_IMPL(FormController::FormKeyGenerator);
static bool shouldBeUsedForFormSignature(const Element& element)
{
if (auto* formControl = dynamicDowncast<HTMLFormControlElement>(element))
return formControl->shouldSaveAndRestoreFormControlState();
if (auto* customElement = dynamicDowncast<HTMLMaybeFormAssociatedCustomElement>(element))
return customElement->hasFormAssociatedInterface() || element.isCustomElementUpgradeCandidate();
return false;
}
static String formSignature(const HTMLFormElement& form)
{
StringBuilder builder;
// Remove the query part because it might contain volatile parameters such as a session key.
// FIXME: But leave the fragment identifier? Perhaps we should switch to removeQueryAndFragmentIdentifier.
URL actionURL = form.getURLAttribute(HTMLNames::actionAttr);
actionURL.setQuery({ });
builder.append(actionURL.string());
// Two named controls seems to be enough to distinguish similar but different forms.
constexpr unsigned maxNamedControlsToBeRecorded = 2;
ScriptDisallowedScope::InMainThread scriptDisallowedScope;
unsigned count = 0;
builder.append(" ["_s);
for (Ref element : descendantsOfType<Element>(form)) {
if (!shouldBeUsedForFormSignature(element.get()) || element->hasAttributeWithoutSynchronization(HTMLNames::formAttr))
continue;
auto& name = element->getNameAttribute();
if (name.isNull() || name.isEmpty())
continue;
builder.append(name, ' ');
if (++count >= maxNamedControlsToBeRecorded)
break;
}
builder.append(']');
return builder.toString();
}
String FormController::FormKeyGenerator::formKey(const ValidatedFormListedElement& control)
{
RefPtr form = ownerForm(control);
if (!form) {
static MainThreadNeverDestroyed<String> formKeyForNoOwner(MAKE_STATIC_STRING_IMPL("No owner"));
return formKeyForNoOwner;
}
return m_formToKeyMap.ensure(*form, [this, form] {
auto signature = formSignature(*form);
auto nextIndex = m_formSignatureToNextIndexMap.add(signature, 0).iterator->value++;
return makeString(signature, " #"_s, nextIndex);
}).iterator->value;
}
void FormController::FormKeyGenerator::willDeleteForm(HTMLFormElement& form)
{
m_formToKeyMap.remove(form);
}
// ----------------------------------------------------------------------------
FormController::FormController() = default;
FormController::~FormController() = default;
static String formStateSignature()
{
// In the legacy version of serialized state, the first item was a name attribute
// value of a form control. The following string literal contains some characters
// which are rarely used for name attribute values so it won't match.
static MainThreadNeverDestroyed<String> signature(MAKE_STATIC_STRING_IMPL("\n\r?% WebKit serialized form state version 8 \n\r=&"));
return signature;
}
Vector<AtomString> FormController::formElementsState(const Document& document) const
{
UncheckedKeyHashMap<AtomString, Vector<Ref<const ValidatedFormListedElement>>> formKeyToControlsMap;
{
// FIXME: We should be saving the state of form controls in shadow trees, too.
FormKeyGenerator keyGenerator;
for (Ref element : descendantsOfType<Element>(document)) {
RefPtr control = const_cast<Element&>(element.get()).asValidatedFormListedElement();
if (!control || !control->isCandidateForSavingAndRestoringState())
continue;
AtomString formKey { keyGenerator.formKey(*control) };
auto& vector = formKeyToControlsMap.ensure(formKey, [] {
return Vector<Ref<const ValidatedFormListedElement>> { };
}).iterator->value;
vector.append(control.releaseNonNull());
}
}
if (formKeyToControlsMap.isEmpty())
return { };
Vector<AtomString> stateVector;
stateVector.append(formStateSignature());
for (const auto& entry : formKeyToControlsMap) {
stateVector.append(entry.key);
stateVector.append(AtomString::number(entry.value.size()));
for (const auto& control : entry.value) {
stateVector.append(control->name());
stateVector.append(control->formControlType());
appendSerializedFormControlState(stateVector, control->saveFormControlState());
}
}
stateVector.shrinkToFit();
return stateVector;
}
void FormController::setStateForNewFormElements(const Vector<AtomString>& stateVector)
{
m_savedFormStateMap = parseStateVector(stateVector);
}
FormControlState FormController::takeStateForFormElement(const ValidatedFormListedElement& control)
{
if (m_savedFormStateMap.isEmpty())
return { };
if (!m_formKeyGenerator)
m_formKeyGenerator = makeUnique<FormKeyGenerator>();
auto iterator = m_savedFormStateMap.find(m_formKeyGenerator->formKey(control));
if (iterator == m_savedFormStateMap.end())
return { };
auto state = iterator->value.takeControlState({ control.name(), control.formControlType() });
if (iterator->value.isEmpty())
m_savedFormStateMap.remove(iterator);
return state;
}
FormController::SavedFormStateMap FormController::parseStateVector(const Vector<AtomString>& stateVector)
{
AtomStringVectorReader reader { stateVector };
if (reader.consumeString() != formStateSignature())
return { };
SavedFormStateMap map;
while (true) {
auto formKey = reader.consumeString();
if (formKey.isNull())
return map;
auto state = SavedFormState::consumeSerializedState(reader);
if (state.isEmpty())
return { };
map.add(formKey, WTFMove(state));
}
}
void FormController::willDeleteForm(HTMLFormElement& form)
{
if (m_formKeyGenerator)
m_formKeyGenerator->willDeleteForm(form);
}
void FormController::restoreControlStateFor(ValidatedFormListedElement& control)
{
// We don't save state of a control when shouldSaveAndRestoreFormControlState()
// is false. But we need to skip restoring process too because a control in
// another form might have the same pair of name and type and saved its state.
if (!control.isCandidateForSavingAndRestoringState())
return;
auto state = takeStateForFormElement(control);
if (!state.isEmpty())
control.restoreFormControlState(state);
}
void FormController::restoreControlStateIn(HTMLFormElement& form)
{
for (Ref element : form.copyValidatedListedElementsVector()) {
if (!element->isCandidateForSavingAndRestoringState() || ownerForm(element) != &form)
continue;
auto state = takeStateForFormElement(element);
if (!state.isEmpty())
element->restoreFormControlState(state);
}
}
bool FormController::hasFormStateToRestore() const
{
return !m_savedFormStateMap.isEmpty();
}
Vector<String> FormController::referencedFilePaths(const Vector<AtomString>& stateVector)
{
Vector<String> paths;
auto parsedState = parseStateVector(stateVector);
for (auto& state : parsedState.values())
state.appendReferencedFilePaths(paths);
return paths;
}
} // namespace WebCore
|