1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.host;
16
17 import static org.htmlunit.BrowserVersionFeatures.JS_STORAGE_PRESERVED_INCLUDED;
18
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Map;
24
25 import org.htmlunit.Page;
26 import org.htmlunit.StorageHolder;
27 import org.htmlunit.StorageHolder.Type;
28 import org.htmlunit.WebClient;
29 import org.htmlunit.WebWindow;
30 import org.htmlunit.corejs.javascript.CompoundOperationMap;
31 import org.htmlunit.corejs.javascript.Context;
32 import org.htmlunit.corejs.javascript.Function;
33 import org.htmlunit.corejs.javascript.Scriptable;
34 import org.htmlunit.corejs.javascript.ScriptableObject;
35 import org.htmlunit.corejs.javascript.VarScope;
36 import org.htmlunit.html.HtmlPage;
37 import org.htmlunit.javascript.AbstractJavaScriptEngine;
38 import org.htmlunit.javascript.HtmlUnitContextFactory;
39 import org.htmlunit.javascript.HtmlUnitScriptable;
40 import org.htmlunit.javascript.JavaScriptEngine;
41 import org.htmlunit.javascript.PostponedAction;
42 import org.htmlunit.javascript.configuration.JsxClass;
43 import org.htmlunit.javascript.configuration.JsxConstructor;
44 import org.htmlunit.javascript.configuration.JsxFunction;
45 import org.htmlunit.javascript.configuration.JsxGetter;
46 import org.htmlunit.javascript.host.dom.DOMException;
47 import org.htmlunit.javascript.host.event.Event;
48 import org.htmlunit.javascript.host.event.StorageEvent;
49
50
51
52
53
54
55
56
57
58
59
60
61 @JsxClass
62 public class Storage extends HtmlUnitScriptable {
63
64 private static final HashSet<String> RESERVED_NAMES_ = new HashSet<>(Arrays.asList(
65 "clear", "key", "getItem", "length", "removeItem",
66 "setItem", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "propertyIsEnumerable",
67 "isPrototypeOf", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"));
68
69
70 private static final long STORE_SIZE_LIMIT = 5L * 1024 * 1024;
71
72 private final Map<String, String> store_;
73 private final Type type_;
74
75
76
77
78 public Storage() {
79 super();
80 store_ = null;
81 type_ = null;
82 }
83
84
85
86
87 @JsxConstructor
88 public void jsConstructor() {
89
90 }
91
92
93
94
95
96
97
98
99 public Storage(final Window window, final Map<String, String> store) {
100 this(window, store, null);
101 }
102
103
104
105
106
107
108
109
110
111 public Storage(final Window window, final Map<String, String> store, final Type type) {
112 super();
113 store_ = store;
114 type_ = type;
115 setParentScope(getTopLevelScope(window.getParentScope()));
116 setPrototype(window.getPrototype(Storage.class));
117 }
118
119
120
121
122 @Override
123 public void put(final String name, final Scriptable start, final Object value) {
124 final boolean isReserved = RESERVED_NAMES_.contains(name);
125 if (store_ == null || isReserved) {
126 super.put(name, start, value);
127 }
128 if (store_ != null && (!isReserved || getBrowserVersion().hasFeature(JS_STORAGE_PRESERVED_INCLUDED))) {
129 setItem(name, JavaScriptEngine.toString(value));
130 }
131 }
132
133
134
135
136 @Override
137 public Object get(final String name, final Scriptable start) {
138 if (store_ == null || RESERVED_NAMES_.contains(name)) {
139 return super.get(name, start);
140 }
141 final Object value = getItem(name);
142 if (value != null) {
143 return value;
144 }
145 return super.get(name, start);
146 }
147
148
149
150
151
152 @Override
153 public boolean has(final String name, final Scriptable start) {
154 return isItem(name) || super.has(name, start);
155 }
156
157
158
159
160
161 @Override
162 public void delete(final String name) {
163 if (isItem(name) && !super.has(name, this)) {
164 removeItem(name);
165 return;
166 }
167 super.delete(name);
168 }
169
170
171
172
173
174
175 @Override
176 protected Object[] getIds(final CompoundOperationMap<Scriptable> map,
177 final boolean getNonEnumerable, final boolean getSymbols) {
178 return addItemIds(super.getIds(map, getNonEnumerable, getSymbols));
179 }
180
181
182
183
184
185 @Override
186 protected DescriptorInfo getOwnPropertyDescriptor(final Context cx, final Object id) {
187 final DescriptorInfo descInfo = super.getOwnPropertyDescriptor(cx, id);
188 if (descInfo != null) {
189 return descInfo;
190 }
191
192 if (id instanceof CharSequence) {
193 final String name = id.toString();
194 if (isItem(name)) {
195 final Object value = getItem(name);
196 if (value != null) {
197 return ScriptableObject.buildDataDescriptor(value, ScriptableObject.EMPTY);
198 }
199 }
200 }
201 return null;
202 }
203
204 private boolean isItem(final String name) {
205 if (store_ == null || RESERVED_NAMES_.contains(name)) {
206 return false;
207 }
208 synchronized (store_) {
209 return store_.containsKey(name);
210 }
211 }
212
213 private Object[] addItemIds(final Object[] ids) {
214 if (store_ == null) {
215 return ids;
216 }
217
218 final List<Object> result = new ArrayList<>();
219 synchronized (store_) {
220 for (final String key : store_.keySet()) {
221 if (!RESERVED_NAMES_.contains(key)) {
222 result.add(key);
223 }
224 }
225 }
226 for (final Object id : ids) {
227 if (!result.contains(id)) {
228 result.add(id);
229 }
230 }
231 return result.toArray();
232 }
233
234
235
236
237
238
239 @JsxGetter
240 public int getLength() {
241 synchronized (store_) {
242 return store_.size();
243 }
244 }
245
246
247
248
249
250
251 public void removeItem(final String key) {
252 final String removed;
253 synchronized (store_) {
254 removed = store_.remove(key);
255 }
256 if (removed != null) {
257 fireStorageEvent(key, removed, null);
258 }
259 }
260
261
262
263
264
265
266
267
268
269
270 @JsxFunction(functionName = "removeItem")
271 public static void jsRemoveItem(final Context context, final VarScope scope,
272 final Scriptable thisObj, final Object[] args, final Function function) {
273 checkArguments(args, 1, "removeItem");
274 getStorage(thisObj).removeItem(JavaScriptEngine.toString(args[0]));
275 }
276
277
278
279
280
281
282
283 public String key(final int index) {
284 if (index >= 0) {
285 synchronized (store_) {
286 int counter = 0;
287 for (final String key : store_.keySet()) {
288 if (counter == index) {
289 return key;
290 }
291 counter++;
292 }
293 }
294 }
295 return null;
296 }
297
298
299
300
301
302
303
304
305
306
307
308 @JsxFunction(functionName = "key")
309 public static String jsKey(final Context context, final VarScope scope,
310 final Scriptable thisObj, final Object[] args, final Function function) {
311 checkArguments(args, 1, "key");
312 final Storage storage = getStorage(thisObj);
313 final long index = JavaScriptEngine.toUint32(args[0]);
314 if (index > Integer.MAX_VALUE) {
315 return null;
316 }
317 return storage.key((int) index);
318 }
319
320
321
322
323
324
325
326 public Object getItem(final String key) {
327 synchronized (store_) {
328 return store_.get(key);
329 }
330 }
331
332
333
334
335
336
337
338
339
340
341
342 @JsxFunction(functionName = "getItem")
343 public static Object jsGetItem(final Context context, final VarScope scope,
344 final Scriptable thisObj, final Object[] args, final Function function) {
345 checkArguments(args, 1, "getItem");
346 return getStorage(thisObj).getItem(JavaScriptEngine.toString(args[0]));
347 }
348
349
350
351
352
353
354
355
356
357 public void setItem(final String key, final String data) {
358 final String oldData;
359 synchronized (store_) {
360 oldData = store_.get(key);
361 if (data.equals(oldData)) {
362 return;
363 }
364
365 long storeSize = key.length() + data.length();
366 for (final Map.Entry<String, String> entry : store_.entrySet()) {
367 if (!key.equals(entry.getKey())) {
368 storeSize += entry.getKey().length() + entry.getValue().length();
369 }
370 }
371 if (storeSize > STORE_SIZE_LIMIT) {
372 throw JavaScriptEngine.asJavaScriptException(this,
373 "Failed to execute 'setItem' on 'Storage': "
374 + "Setting the value of '" + key + "' exceeded the quota.",
375 DOMException.QUOTA_EXCEEDED_ERR);
376 }
377 store_.put(key, data);
378 }
379 fireStorageEvent(key, oldData, data);
380 }
381
382
383
384
385
386
387
388
389
390
391 @JsxFunction(functionName = "setItem")
392 public static void jsSetItem(final Context context, final VarScope scope,
393 final Scriptable thisObj, final Object[] args, final Function function) {
394 checkArguments(args, 2, "setItem");
395 getStorage(thisObj).setItem(JavaScriptEngine.toString(args[0]), JavaScriptEngine.toString(args[1]));
396 }
397
398
399
400
401 @JsxFunction
402 public void clear() {
403 synchronized (store_) {
404 if (store_.isEmpty()) {
405 return;
406 }
407 store_.clear();
408 }
409 fireStorageEvent(null, null, null);
410 }
411
412 private static Storage getStorage(final Scriptable thisObj) {
413 if (thisObj instanceof Storage storage && storage.store_ != null) {
414 return storage;
415 }
416 throw JavaScriptEngine.typeError("Illegal invocation");
417 }
418
419 private static void checkArguments(final Object[] args, final int required, final String functionName) {
420 if (args.length < required) {
421 throw JavaScriptEngine.typeError("Failed to execute '" + functionName + "' on 'Storage': "
422 + required + " argument" + (required > 1 ? "s" : "") + " required, but only "
423 + args.length + " present.");
424 }
425 }
426
427
428
429
430
431
432
433
434
435 private void fireStorageEvent(final String key, final String oldValue, final String newValue) {
436 if (type_ == null) {
437 return;
438 }
439
440 final Window window = getWindow();
441 final WebWindow sourceWindow = window.getWebWindow();
442 final Page sourcePage = sourceWindow.getEnclosedPage();
443 if (sourcePage == null || sourcePage.getUrl() == null) {
444 return;
445 }
446 final String url = sourcePage.getUrl().toExternalForm();
447
448 final WebClient webClient = sourceWindow.getWebClient();
449 final StorageHolder storageHolder = webClient.getStorageHolder();
450 final AbstractJavaScriptEngine<?> jsEngine = webClient.getJavaScriptEngine();
451
452 for (final WebWindow webWindow : webClient.getWebWindows()) {
453 if (webWindow == sourceWindow) {
454 continue;
455 }
456 if (type_ == Type.SESSION_STORAGE && webWindow.getTopWindow() != sourceWindow.getTopWindow()) {
457 continue;
458 }
459 if (!(webWindow.getEnclosedPage() instanceof HtmlPage page)) {
460 continue;
461 }
462 if (storageHolder.getStore(type_, page) != store_) {
463 continue;
464 }
465 final Window receiver = webWindow.getScriptableObject();
466 if (receiver == null) {
467 continue;
468 }
469
470 final PostponedAction action = new PostponedAction(page, "Storage event") {
471 @Override
472 public void execute() {
473 final StorageEvent event = new StorageEvent();
474 event.setParentScope(getTopLevelScope(receiver.getParentScope()));
475 event.setPrototype(receiver.getPrototype(StorageEvent.class));
476 event.initStorageEvent(Event.TYPE_STORAGE, false, false,
477 key, oldValue, newValue, url, receiver.getStorage(type_));
478
479 final HtmlUnitContextFactory cf = jsEngine.getContextFactory();
480 cf.call(cx -> receiver.dispatchEvent(event));
481 }
482 };
483 jsEngine.addPostponedAction(action);
484 }
485 }
486 }