Coverage Report

Created: 2018-09-25 14:53

/work/obj-fuzz/dist/include/nsContentUtils.h
Line
Count
Source (jump to first uncovered line)
1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
 * License, v. 2.0. If a copy of the MPL was not distributed with this
5
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
/* A namespace class for static content utilities. */
8
9
#ifndef nsContentUtils_h___
10
#define nsContentUtils_h___
11
12
#if defined(XP_WIN)
13
#include <float.h>
14
#endif
15
16
#if defined(SOLARIS)
17
#include <ieeefp.h>
18
#endif
19
20
#include "js/TypeDecls.h"
21
#include "js/Value.h"
22
#include "js/RootingAPI.h"
23
#include "mozilla/dom/FromParser.h"
24
#include "mozilla/BasicEvents.h"
25
#include "mozilla/CORSMode.h"
26
#include "mozilla/EventForwards.h"
27
#include "mozilla/GuardObjects.h"
28
#include "mozilla/StaticPtr.h"
29
#include "mozilla/TaskCategory.h"
30
#include "mozilla/TimeStamp.h"
31
#include "nsContentListDeclarations.h"
32
#include "nsMathUtils.h"
33
#include "nsTArrayForwardDeclare.h"
34
#include "Units.h"
35
#include "mozilla/dom/AutocompleteInfoBinding.h"
36
#include "mozilla/dom/BindingDeclarations.h" // For CallerType
37
#include "mozilla/dom/ScriptSettings.h"
38
#include "mozilla/FloatingPoint.h"
39
#include "mozilla/intl/LineBreaker.h"
40
#include "mozilla/intl/WordBreaker.h"
41
#include "mozilla/net/ReferrerPolicy.h"
42
#include "mozilla/Logging.h"
43
#include "mozilla/NotNull.h"
44
#include "mozilla/Maybe.h"
45
#include "mozilla/RangeBoundary.h"
46
#include "nsIContentPolicy.h"
47
#include "nsIDocument.h"
48
#include "nsPIDOMWindow.h"
49
#include "nsRFPService.h"
50
51
#if defined(XP_WIN)
52
// Undefine LoadImage to prevent naming conflict with Windows.
53
#undef LoadImage
54
#endif
55
56
class imgICache;
57
class imgIContainer;
58
class imgINotificationObserver;
59
class imgIRequest;
60
class imgLoader;
61
class imgRequestProxy;
62
class nsAutoScriptBlockerSuppressNodeRemoved;
63
class nsCacheableFuncStringHTMLCollection;
64
class nsHtml5StringParser;
65
class nsAtom;
66
class nsIChannel;
67
class nsIConsoleService;
68
class nsIContent;
69
class nsIContentPolicy;
70
class nsIContentSecurityPolicy;
71
class nsIDocShellTreeItem;
72
class nsIDocumentLoaderFactory;
73
class nsIDragSession;
74
class nsIEventTarget;
75
class nsIFragmentContentSink;
76
class nsIFrame;
77
class nsIImageLoadingContent;
78
class nsIInterfaceRequestor;
79
class nsIIOService;
80
class nsILoadInfo;
81
class nsILoadGroup;
82
class nsNameSpaceManager;
83
class nsIObserver;
84
class nsIParser;
85
class nsIPluginTag;
86
class nsIPresShell;
87
class nsIPrincipal;
88
class nsIRequest;
89
class nsIRunnable;
90
class nsIScriptContext;
91
class nsIScriptSecurityManager;
92
class nsIStringBundle;
93
class nsIStringBundleService;
94
class nsISupportsHashKey;
95
class nsIURI;
96
class nsIUUIDGenerator;
97
class nsIWidget;
98
class nsIXPConnect;
99
class nsNodeInfoManager;
100
class nsPIDOMWindowInner;
101
class nsPIDOMWindowOuter;
102
class nsPresContext;
103
class nsStringBuffer;
104
class nsStringHashKey;
105
class nsTextFragment;
106
class nsView;
107
class nsViewportInfo;
108
class nsWrapperCache;
109
class nsAttrValue;
110
class nsITransferable;
111
class nsPIWindowRoot;
112
class nsIWindowProvider;
113
114
struct JSRuntime;
115
116
template<class E> class nsCOMArray;
117
template<class K, class V> class nsDataHashtable;
118
template<class K, class V> class nsRefPtrHashtable;
119
template<class T> class nsReadingIterator;
120
121
namespace mozilla {
122
class Dispatcher;
123
class ErrorResult;
124
class EventListenerManager;
125
class HTMLEditor;
126
127
namespace dom {
128
class ContentFrameMessageManager;
129
struct CustomElementDefinition;
130
class DocumentFragment;
131
class Element;
132
class Event;
133
class EventTarget;
134
class HTMLInputElement;
135
class IPCDataTransfer;
136
class IPCDataTransferItem;
137
struct LifecycleCallbackArgs;
138
struct LifecycleAdoptedCallbackArgs;
139
class MessageBroadcaster;
140
class NodeInfo;
141
class nsIContentChild;
142
class nsIContentParent;
143
class TabChild;
144
class Selection;
145
class TabParent;
146
} // namespace dom
147
148
namespace ipc {
149
class Shmem;
150
class IShmemAllocator;
151
}
152
153
namespace gfx {
154
class DataSourceSurface;
155
} // namespace gfx
156
157
namespace layers {
158
class LayerManager;
159
} // namespace layers
160
161
} // namespace mozilla
162
163
class nsIBidiKeyboard;
164
165
extern const char kLoadAsData[];
166
167
// Stolen from nsReadableUtils, but that's OK, since we can declare the same
168
// name multiple times.
169
const nsString& EmptyString();
170
const nsCString& EmptyCString();
171
172
enum EventNameType {
173
  EventNameType_None = 0x0000,
174
  EventNameType_HTML = 0x0001,
175
  EventNameType_XUL = 0x0002,
176
  EventNameType_SVGGraphic = 0x0004, // svg graphic elements
177
  EventNameType_SVGSVG = 0x0008, // the svg element
178
  EventNameType_SMIL = 0x0010, // smil elements
179
  EventNameType_HTMLBodyOrFramesetOnly = 0x0020,
180
181
  EventNameType_HTMLXUL = 0x0003,
182
  EventNameType_All = 0xFFFF
183
};
184
185
struct EventNameMapping
186
{
187
  // This holds pointers to nsGkAtoms members, and is therefore safe as a
188
  // non-owning reference.
189
  nsAtom* MOZ_NON_OWNING_REF mAtom;
190
  int32_t  mType;
191
  mozilla::EventMessage mMessage;
192
  mozilla::EventClassID mEventClassID;
193
  // True if mAtom is possibly used by special SVG/SMIL events, but
194
  // mMessage is eUnidentifiedEvent. See EventNameList.h
195
  bool mMaybeSpecialSVGorSMILEvent;
196
};
197
198
typedef bool (*CallOnRemoteChildFunction) (mozilla::dom::TabParent* aTabParent,
199
                                           void* aArg);
200
201
class nsContentUtils
202
{
203
  friend class nsAutoScriptBlockerSuppressNodeRemoved;
204
  typedef mozilla::dom::Element Element;
205
  typedef mozilla::Cancelable Cancelable;
206
  typedef mozilla::CanBubble CanBubble;
207
  typedef mozilla::Composed Composed;
208
  typedef mozilla::ChromeOnlyDispatch ChromeOnlyDispatch;
209
  typedef mozilla::EventMessage EventMessage;
210
  typedef mozilla::TimeDuration TimeDuration;
211
  typedef mozilla::Trusted Trusted;
212
213
public:
214
  static nsresult Init();
215
216
  // Strip off "wyciwyg://n/" part of a URL. aURI must have "wyciwyg" scheme.
217
  static nsresult RemoveWyciwygScheme(nsIURI* aURI, nsIURI** aReturn);
218
219
  static bool     IsCallerChrome();
220
  static bool     ThreadsafeIsCallerChrome();
221
  static bool     IsCallerContentXBL();
222
223
  // The APIs for checking whether the caller is system (in the sense of system
224
  // principal) should only be used when the JSContext is known to accurately
225
  // represent the caller.  In practice, that means you should only use them in
226
  // two situations at the moment:
227
  //
228
  // 1) Functions used in WebIDL Func annotations.
229
  // 2) Bindings code or other code called directly from the JS engine.
230
  //
231
  // Use pretty much anywhere else is almost certainly wrong and should be
232
  // replaced with [NeedsCallerType] annotations in bindings.
233
234
  // Check whether the caller is system if you know you're on the main thread.
235
  static bool IsSystemCaller(JSContext* aCx);
236
237
  // Check whether the caller is system if you might be on a worker or worklet
238
  // thread.
239
  static bool ThreadsafeIsSystemCaller(JSContext* aCx);
240
241
  // In the traditional Gecko architecture, both C++ code and untrusted JS code
242
  // needed to rely on the same XPCOM method/getter/setter to get work done.
243
  // This required lots of security checks in the various exposed methods, which
244
  // in turn created difficulty in determining whether the caller was script
245
  // (whose access needed to be checked) and internal C++ platform code (whose
246
  // access did not need to be checked). To address this problem, Gecko had a
247
  // convention whereby the absence of script on the stack was interpretted as
248
  // "System Caller" and always granted unfettered access.
249
  //
250
  // Unfortunately, this created a bunch of footguns. For example, when the
251
  // implementation of a DOM method wanted to perform a privileged
252
  // sub-operation, it needed to "hide" the presence of script on the stack in
253
  // order for that sub-operation to be allowed. Additionally, if script could
254
  // trigger an API entry point to be invoked in some asynchronous way without
255
  // script on the stack, it could potentially perform privilege escalation.
256
  //
257
  // In the modern world, untrusted script should interact with the platform
258
  // exclusively over WebIDL APIs, and platform code has a lot more flexibility
259
  // in deciding whether or not to use XPCOM. This gives us the flexibility to
260
  // do something better.
261
  //
262
  // Going forward, APIs should be designed such that any security checks that
263
  // ask the question "is my caller allowed to do this?" should live in WebIDL
264
  // API entry points, with a separate method provided for internal callers
265
  // that just want to get the job done.
266
  //
267
  // To enforce this and catch bugs, nsContentUtils::SubjectPrincipal will crash
268
  // if it is invoked without script on the stack. To land that transition, it
269
  // was necessary to go through and whitelist a bunch of callers that were
270
  // depending on the old behavior. Those callers should be fixed up, and these
271
  // methods should not be used by new code without review from bholley or bz.
272
0
  static bool     LegacyIsCallerNativeCode() { return !GetCurrentJSContext(); }
273
0
  static bool     LegacyIsCallerChromeOrNativeCode() { return LegacyIsCallerNativeCode() || IsCallerChrome(); }
274
  static nsIPrincipal* SubjectPrincipalOrSystemIfNativeCaller()
275
0
  {
276
0
    if (!GetCurrentJSContext()) {
277
0
      return GetSystemPrincipal();
278
0
    }
279
0
    return SubjectPrincipal();
280
0
  }
281
282
  static bool LookupBindingMember(JSContext* aCx, nsIContent *aContent,
283
                                  JS::Handle<jsid> aId,
284
                                  JS::MutableHandle<JS::PropertyDescriptor> aDesc);
285
286
  // Check whether we should avoid leaking distinguishing information to JS/CSS.
287
  // This function can be called both in the main thread and worker threads.
288
  static bool ShouldResistFingerprinting();
289
  static bool ShouldResistFingerprinting(nsIDocShell* aDocShell);
290
  static bool ShouldResistFingerprinting(nsIDocument* aDoc);
291
292
  // A helper function to calculate the rounded window size for fingerprinting
293
  // resistance. The rounded size is based on the chrome UI size and available
294
  // screen size. If the inputWidth/Height is greater than the available content
295
  // size, this will report the available content size. Otherwise, it will
296
  // round the size to the nearest upper 200x100.
297
  static void CalcRoundedWindowSizeForResistingFingerprinting(int32_t  aChromeWidth,
298
                                                              int32_t  aChromeHeight,
299
                                                              int32_t  aScreenWidth,
300
                                                              int32_t  aScreenHeight,
301
                                                              int32_t  aInputWidth,
302
                                                              int32_t  aInputHeight,
303
                                                              bool     aSetOuterWidth,
304
                                                              bool     aSetOuterHeight,
305
                                                              int32_t* aOutputWidth,
306
                                                              int32_t* aOutputHeight);
307
308
  /**
309
   * Returns the parent node of aChild crossing document boundaries.
310
   * Uses the parent node in the composed document.
311
   */
312
  static nsINode* GetCrossDocParentNode(nsINode* aChild);
313
314
  /**
315
   * Do not ever pass null pointers to this method.  If one of your
316
   * nsIContents is null, you have to decide for yourself what
317
   * "IsDescendantOf" really means.
318
   *
319
   * @param  aPossibleDescendant node to test for being a descendant of
320
   *         aPossibleAncestor
321
   * @param  aPossibleAncestor node to test for being an ancestor of
322
   *         aPossibleDescendant
323
   * @return true if aPossibleDescendant is a descendant of
324
   *         aPossibleAncestor (or is aPossibleAncestor).  false
325
   *         otherwise.
326
   */
327
  static bool ContentIsDescendantOf(const nsINode* aPossibleDescendant,
328
                                      const nsINode* aPossibleAncestor);
329
330
  /**
331
   * Similar to ContentIsDescendantOf, except will treat an HTMLTemplateElement
332
   * or ShadowRoot as an ancestor of things in the corresponding DocumentFragment.
333
   * See the concept of "host-including inclusive ancestor" in the DOM
334
   * specification.
335
   */
336
  static bool ContentIsHostIncludingDescendantOf(
337
    const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
338
339
  /**
340
   * Similar to above, but does special case only ShadowRoot,
341
   * not HTMLTemplateElement.
342
   */
343
  static bool ContentIsShadowIncludingDescendantOf(
344
    const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor);
345
346
  /**
347
   * Similar to ContentIsDescendantOf except it crosses document boundaries,
348
   * this function uses ancestor/descendant relations in the composed document
349
   * (see shadow DOM spec).
350
   */
351
  static bool ContentIsCrossDocDescendantOf(nsINode* aPossibleDescendant,
352
                                              nsINode* aPossibleAncestor);
353
354
  /**
355
   * As with ContentIsCrossDocDescendantOf but crosses shadow boundaries but not
356
   * cross document boundaries.
357
   *
358
   * @see nsINode::GetFlattenedTreeParentNode()
359
   */
360
  static bool
361
  ContentIsFlattenedTreeDescendantOf(const nsINode* aPossibleDescendant,
362
                                     const nsINode* aPossibleAncestor);
363
364
  /**
365
   * Same as `ContentIsFlattenedTreeDescendantOf`, but from the flattened tree
366
   * point of view of the style system
367
   *
368
   * @see nsINode::GetFlattenedTreeParentNodeForStyle()
369
   */
370
  static bool
371
  ContentIsFlattenedTreeDescendantOfForStyle(const nsINode* aPossibleDescendant,
372
                                             const nsINode* aPossibleAncestor);
373
374
  /**
375
   * Retarget an object A against an object B
376
   * @see https://dom.spec.whatwg.org/#retarget
377
   */
378
  static nsINode*
379
  Retarget(nsINode* aTargetA, nsINode* aTargetB);
380
381
  /*
382
   * This method fills the |aArray| with all ancestor nodes of |aNode|
383
   * including |aNode| at the zero index.
384
   */
385
  static nsresult GetAncestors(nsINode* aNode,
386
                               nsTArray<nsINode*>& aArray);
387
388
  /*
389
   * This method fills |aAncestorNodes| with all ancestor nodes of |aNode|
390
   * including |aNode| (QI'd to nsIContent) at the zero index.
391
   * For each ancestor, there is a corresponding element in |aAncestorOffsets|
392
   * which is the IndexOf the child in relation to its parent.
393
   *
394
   * This method just sucks.
395
   */
396
  static nsresult GetAncestorsAndOffsets(nsINode* aNode,
397
                                         int32_t aOffset,
398
                                         nsTArray<nsIContent*>* aAncestorNodes,
399
                                         nsTArray<int32_t>* aAncestorOffsets);
400
401
  /**
402
   * Returns the common ancestor, if any, for two nodes.
403
   *
404
   * Returns null if the nodes are disconnected.
405
   */
406
  static nsINode* GetCommonAncestor(nsINode* aNode1, nsINode* aNode2)
407
0
  {
408
0
    if (aNode1 == aNode2) {
409
0
      return aNode1;
410
0
    }
411
0
412
0
    return GetCommonAncestorHelper(aNode1, aNode2);
413
0
  }
414
415
  /**
416
   * Returns the common flattened tree ancestor, if any, for two given content
417
   * nodes.
418
   */
419
  static nsIContent* GetCommonFlattenedTreeAncestor(nsIContent* aContent1,
420
                                                    nsIContent* aContent2)
421
0
  {
422
0
    if (aContent1 == aContent2) {
423
0
      return aContent1;
424
0
    }
425
0
426
0
    return GetCommonFlattenedTreeAncestorHelper(aContent1, aContent2);
427
0
  }
428
429
  /**
430
   * Returns the common flattened tree ancestor from the point of view of the
431
   * style system, if any, for two given content nodes.
432
   */
433
  static Element* GetCommonFlattenedTreeAncestorForStyle(
434
      Element* aElement1, Element* aElement2);
435
436
  /**
437
   * Returns true if aNode1 is before aNode2 in the same connected
438
   * tree.
439
   * aNode1Index and aNode2Index are in/out arguments. If non-null, and value is
440
   * not -1, that value is used instead of calling slow ComputeIndexOf on the
441
   * parent node. If value is -1, the value will be set to the return value of
442
   * ComputeIndexOf.
443
   */
444
  static bool PositionIsBefore(nsINode* aNode1, nsINode* aNode2,
445
                               int32_t* aNode1Index = nullptr,
446
                               int32_t* aNode2Index = nullptr);
447
448
  /**
449
   *  Utility routine to compare two "points", where a point is a
450
   *  node/offset pair
451
   *  Returns -1 if point1 < point2, 1, if point1 > point2,
452
   *  0 if error or if point1 == point2.
453
   *  NOTE! If the two nodes aren't in the same connected subtree,
454
   *  the result is 1, and the optional aDisconnected parameter
455
   *  is set to true.
456
   *
457
   *  XXX aOffset1 and aOffset2 should be uint32_t since valid offset value is
458
   *      between 0 - UINT32_MAX.  However, these methods work even with
459
   *      negative offset values!  E.g., when aOffset1 is -1 and aOffset is 0,
460
   *      these methods return -1.  Some root callers depend on this behavior.
461
   *      On the other hand, nsINode can have ATTRCHILD_ARRAY_MAX_CHILD_COUN
462
   *      (0x3FFFFF) at most.  Therefore, they can be int32_t for now.
463
   */
464
  static int32_t ComparePoints(nsINode* aParent1, int32_t aOffset1,
465
                               nsINode* aParent2, int32_t aOffset2,
466
                               bool* aDisconnected = nullptr);
467
  static int32_t ComparePoints(const mozilla::RawRangeBoundary& aFirst,
468
                               const mozilla::RawRangeBoundary& aSecond,
469
                               bool* aDisconnected = nullptr);
470
471
  /**
472
   * Brute-force search of the element subtree rooted at aContent for
473
   * an element with the given id.  aId must be nonempty, otherwise
474
   * this method may return nodes even if they have no id!
475
   */
476
  static Element* MatchElementId(nsIContent *aContent, const nsAString& aId);
477
478
  /**
479
   * Similar to above, but to be used if one already has an atom for the ID
480
   */
481
  static Element* MatchElementId(nsIContent *aContent, const nsAtom* aId);
482
483
  /**
484
   * Reverses the document position flags passed in.
485
   *
486
   * @param   aDocumentPosition   The document position flags to be reversed.
487
   *
488
   * @return  The reversed document position flags.
489
   *
490
   * @see Node
491
   */
492
  static uint16_t ReverseDocumentPosition(uint16_t aDocumentPosition);
493
494
  /**
495
   * Returns a subdocument for aDocument with a particular outer window ID.
496
   *
497
   * @param aDocument
498
   *        The document whose subdocuments will be searched.
499
   * @param aOuterWindowID
500
   *        The outer window ID for the subdocument to be found. This must
501
   *        be a value greater than 0.
502
   * @return nsIDocument*
503
   *        A pointer to the found nsIDocument. nullptr if the subdocument
504
   *        cannot be found, or if either aDocument or aOuterWindowId were
505
   *        invalid. If the outer window ID belongs to aDocument itself, this
506
   *        will return a pointer to aDocument.
507
   */
508
  static nsIDocument* GetSubdocumentWithOuterWindowId(nsIDocument *aDocument,
509
                                                      uint64_t aOuterWindowId);
510
511
  static const nsDependentSubstring TrimCharsInSet(const char* aSet,
512
                                                   const nsAString& aValue);
513
514
  template<bool IsWhitespace(char16_t)>
515
  static const nsDependentSubstring TrimWhitespace(const nsAString& aStr,
516
                                                   bool aTrimTrailing = true);
517
518
  /**
519
   * Returns true if aChar is of class Ps, Pi, Po, Pf, or Pe.
520
   */
521
  static bool IsFirstLetterPunctuation(uint32_t aChar);
522
  static bool IsFirstLetterPunctuationAt(const nsTextFragment* aFrag, uint32_t aOffset);
523
524
  /**
525
   * Returns true if aChar is of class Lu, Ll, Lt, Lm, Lo, Nd, Nl or No
526
   */
527
  static bool IsAlphanumeric(uint32_t aChar);
528
  static bool IsAlphanumericAt(const nsTextFragment* aFrag, uint32_t aOffset);
529
530
  /*
531
   * Is the character an HTML whitespace character?
532
   *
533
   * We define whitespace using the list in HTML5 and css3-selectors:
534
   * U+0009, U+000A, U+000C, U+000D, U+0020
535
   *
536
   * HTML 4.01 also lists U+200B (zero-width space).
537
   */
538
  static bool IsHTMLWhitespace(char16_t aChar);
539
540
  /*
541
   * Returns whether the character is an HTML whitespace (see IsHTMLWhitespace)
542
   * or a nbsp character (U+00A0).
543
   */
544
  static bool IsHTMLWhitespaceOrNBSP(char16_t aChar);
545
546
  /**
547
   * Is the HTML local name a block element?
548
   */
549
  static bool IsHTMLBlock(nsIContent* aContent);
550
551
  enum ParseHTMLIntegerResultFlags {
552
    eParseHTMLInteger_NoFlags               = 0,
553
    eParseHTMLInteger_IsPercent             = 1 << 0,
554
    // eParseHTMLInteger_NonStandard is set if the string representation of the
555
    // integer was not the canonical one (e.g. had extra leading '+' or '0').
556
    eParseHTMLInteger_NonStandard           = 1 << 1,
557
    eParseHTMLInteger_DidNotConsumeAllInput = 1 << 2,
558
    // Set if one or more error flags were set.
559
    eParseHTMLInteger_Error                 = 1 << 3,
560
    eParseHTMLInteger_ErrorNoValue          = 1 << 4,
561
    eParseHTMLInteger_ErrorOverflow         = 1 << 5,
562
    // Use this flag to detect the difference between overflow and underflow
563
    eParseHTMLInteger_Negative              = 1 << 6,
564
  };
565
  static int32_t ParseHTMLInteger(const nsAString& aValue,
566
                                  ParseHTMLIntegerResultFlags *aResult);
567
568
  /**
569
   * Parse a margin string of format 'top, right, bottom, left' into
570
   * an nsIntMargin.
571
   *
572
   * @param aString the string to parse
573
   * @param aResult the resulting integer
574
   * @return whether the value could be parsed
575
   */
576
  static bool ParseIntMarginValue(const nsAString& aString, nsIntMargin& aResult);
577
578
  /**
579
   * Parse the value of the <font size=""> attribute according to the HTML5
580
   * spec as of April 16, 2012.
581
   *
582
   * @param aValue the value to parse
583
   * @return 1 to 7, or 0 if the value couldn't be parsed
584
   */
585
  static int32_t ParseLegacyFontSize(const nsAString& aValue);
586
587
  static void Shutdown();
588
589
  /**
590
   * Checks whether two nodes come from the same origin.
591
   */
592
  static nsresult CheckSameOrigin(const nsINode* aTrustedNode,
593
                                  const nsINode* unTrustedNode);
594
595
  // Check if the (JS) caller can access aNode.
596
  static bool CanCallerAccess(nsINode* aNode);
597
598
  // Check if the (JS) caller can access aWindow.
599
  // aWindow can be either outer or inner window.
600
  static bool CanCallerAccess(nsPIDOMWindowInner* aWindow);
601
602
  // Check if the principal is chrome or an addon with the permission.
603
  static bool PrincipalHasPermission(nsIPrincipal* aPrincipal, const nsAtom* aPerm);
604
605
  // Check if the JS caller is chrome or an addon with the permission.
606
  static bool CallerHasPermission(JSContext* aCx, const nsAtom* aPerm);
607
608
  /**
609
   * Returns the triggering principal which should be used for the given URL
610
   * attribute value with the given subject principal.
611
   *
612
   * If the attribute value is not an absolute URL, the subject principal will
613
   * be ignored, and the node principal of aContent will be used instead.
614
   * If aContent is non-null, this function will always return a principal.
615
   * Otherewise, it may return null if aSubjectPrincipal is null or is rejected
616
   * based on the attribute value.
617
   *
618
   * @param aContent The content on which the attribute is being set.
619
   * @param aAttrValue The URL value of the attribute. For parsed attribute
620
   *        values, such as `srcset`, this function should be called separately
621
   *        for each URL value it contains.
622
   * @param aSubjectPrincipal The subject principal of the scripted caller
623
   *        responsible for setting the attribute, or null if no scripted caller
624
   *        can be determined.
625
   */
626
  static nsIPrincipal* GetAttrTriggeringPrincipal(nsIContent* aContent,
627
                                                  const nsAString& aAttrValue,
628
                                                  nsIPrincipal* aSubjectPrincipal);
629
630
  /**
631
   * Returns true if the given string is guaranteed to be treated as an absolute
632
   * URL, rather than a relative URL. In practice, this means any complete URL
633
   * as supported by nsStandardURL, or any string beginning with a valid scheme
634
   * which is known to the IO service, and has the URI_NORELATIVE flag.
635
   *
636
   * If the URL may be treated as absolute in some cases, but relative in others
637
   * (for instance, "http:foo", which can be either an absolute or relative URL,
638
   * depending on the context), this function returns false.
639
   */
640
  static bool IsAbsoluteURL(const nsACString& aURL);
641
642
  // Check if a node is in the document prolog, i.e. before the document
643
  // element.
644
  static bool InProlog(nsINode *aNode);
645
646
  static nsNameSpaceManager* NameSpaceManager()
647
18
  {
648
18
    return sNameSpaceManager;
649
18
  }
650
651
  static nsIIOService* GetIOService()
652
  {
653
    return sIOService;
654
  }
655
656
  static nsIBidiKeyboard* GetBidiKeyboard();
657
658
  /**
659
   * Get the cache security manager service. Can return null if the layout
660
   * module has been shut down.
661
   */
662
  static nsIScriptSecurityManager* GetSecurityManager()
663
0
  {
664
0
    return sSecurityManager;
665
0
  }
666
667
  // Returns the subject principal from the JSContext. May only be called
668
  // from the main thread and assumes an existing compartment.
669
  static nsIPrincipal* SubjectPrincipal(JSContext* aCx);
670
671
  // Returns the subject principal. Guaranteed to return non-null. May only
672
  // be called when nsContentUtils is initialized.
673
  static nsIPrincipal* SubjectPrincipal();
674
675
  // Returns the prinipal of the given JS object. This may only be called on
676
  // the main thread for objects from the main thread's JSRuntime. The object
677
  // must not be a cross-compartment wrapper, because CCWs are not associated
678
  // with a single realm.
679
  static nsIPrincipal* ObjectPrincipal(JSObject* aObj);
680
681
  static nsresult GenerateStateKey(nsIContent* aContent,
682
                                   nsIDocument* aDocument,
683
                                   nsACString& aKey);
684
685
  /**
686
   * Create a new nsIURI from aSpec, using aBaseURI as the base.  The
687
   * origin charset of the new nsIURI will be the document charset of
688
   * aDocument.
689
   */
690
  static nsresult NewURIWithDocumentCharset(nsIURI** aResult,
691
                                            const nsAString& aSpec,
692
                                            nsIDocument* aDocument,
693
                                            nsIURI* aBaseURI);
694
695
  /**
696
   * Returns true if |aName| is a name with dashes.
697
   */
698
  static bool IsNameWithDash(nsAtom* aName);
699
700
  /**
701
   * Returns true if |aName| is a valid name to be registered via
702
   * customElements.define.
703
   */
704
  static bool IsCustomElementName(nsAtom* aName, uint32_t aNameSpaceID);
705
706
  static nsresult CheckQName(const nsAString& aQualifiedName,
707
                             bool aNamespaceAware = true,
708
                             const char16_t** aColon = nullptr);
709
710
  static nsresult SplitQName(const nsIContent* aNamespaceResolver,
711
                             const nsString& aQName,
712
                             int32_t *aNamespace, nsAtom **aLocalName);
713
714
  static nsresult GetNodeInfoFromQName(const nsAString& aNamespaceURI,
715
                                       const nsAString& aQualifiedName,
716
                                       nsNodeInfoManager* aNodeInfoManager,
717
                                       uint16_t aNodeType,
718
                                       mozilla::dom::NodeInfo** aNodeInfo);
719
720
  static void SplitExpatName(const char16_t *aExpatName, nsAtom **aPrefix,
721
                             nsAtom **aTagName, int32_t *aNameSpaceID);
722
723
  // Get a permission-manager setting for the given principal and type.
724
  // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
725
  // returned, otherwise true is returned. Always returns true for the
726
  // system principal, and false for a null principal.
727
  static bool IsSitePermAllow(nsIPrincipal* aPrincipal, const char* aType);
728
729
  // Get a permission-manager setting for the given principal and type.
730
  // If the pref doesn't exist or if it isn't DENY_ACTION, false is
731
  // returned, otherwise true is returned. Always returns false for the
732
  // system principal, and true for a null principal.
733
  static bool IsSitePermDeny(nsIPrincipal* aPrincipal, const char* aType);
734
735
  // Get a permission-manager setting for the given principal and type.
736
  // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is
737
  // returned, otherwise true is returned. Always returns true for the
738
  // system principal, and false for a null principal.
739
  // This version checks the permission for an exact host match on
740
  // the principal
741
  static bool IsExactSitePermAllow(nsIPrincipal* aPrincipal, const char* aType);
742
743
  // Get a permission-manager setting for the given principal and type.
744
  // If the pref doesn't exist or if it isn't DENY_ACTION, false is
745
  // returned, otherwise true is returned. Always returns false for the
746
  // system principal, and true for a null principal.
747
  // This version checks the permission for an exact host match on
748
  // the principal
749
  static bool IsExactSitePermDeny(nsIPrincipal* aPrincipal, const char* aType);
750
751
  // Returns true if aDoc1 and aDoc2 have equal NodePrincipal()s.
752
  static bool HaveEqualPrincipals(nsIDocument* aDoc1, nsIDocument* aDoc2);
753
754
  static mozilla::intl::LineBreaker* LineBreaker()
755
0
  {
756
0
    return sLineBreaker.get();
757
0
  }
758
759
  static mozilla::intl::WordBreaker* WordBreaker()
760
0
  {
761
0
    return sWordBreaker.get();
762
0
  }
763
764
  /**
765
   * Regster aObserver as a shutdown observer. A strong reference is held
766
   * to aObserver until UnregisterShutdownObserver is called.
767
   */
768
  static void RegisterShutdownObserver(nsIObserver* aObserver);
769
  static void UnregisterShutdownObserver(nsIObserver* aObserver);
770
771
  /**
772
   * @return true if aContent has an attribute aName in namespace aNameSpaceID,
773
   * and the attribute value is non-empty.
774
   */
775
  static bool HasNonEmptyAttr(const nsIContent* aContent, int32_t aNameSpaceID,
776
                                nsAtom* aName);
777
778
  /**
779
   * Method that gets the primary presContext for the node.
780
   *
781
   * @param aContent The content node.
782
   * @return the presContext, or nullptr if the content is not in a document
783
   *         (if GetComposedDoc returns nullptr)
784
   */
785
  static nsPresContext* GetContextForContent(const nsIContent* aContent);
786
787
788
  /**
789
   * Method that gets the pres shell for the node.
790
   *
791
   * @param aContent The content node.
792
   * @return the pres shell, or nullptr if the content is not in a document
793
   *         (if GetComposedDoc returns nullptr)
794
   */
795
  static nsIPresShell* GetPresShellForContent(const nsIContent* aContent);
796
797
  /**
798
   * Method to do security and content policy checks on the image URI
799
   *
800
   * @param aURI uri of the image to be loaded
801
   * @param aNode, the context the image is loaded in (eg an element)
802
   * @param aLoadingDocument the document we belong to
803
   * @param aLoadingPrincipal the principal doing the load
804
   * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE] (Optional)
805
   *        The CP content type to use
806
   * @param aImageBlockingStatus the nsIContentPolicy blocking status for this
807
   *        image.  This will be set even if a security check fails for the
808
   *        image, to some reasonable REJECT_* value.  This out param will only
809
   *        be set if it's non-null.
810
   * @return true if the load can proceed, or false if it is blocked.
811
   *         Note that aImageBlockingStatus, if set will always be an ACCEPT
812
   *         status if true is returned and always be a REJECT_* status if
813
   *         false is returned.
814
   */
815
  static bool CanLoadImage(nsIURI* aURI,
816
                           nsINode* aNode,
817
                           nsIDocument* aLoadingDocument,
818
                           nsIPrincipal* aLoadingPrincipal);
819
820
  /**
821
   * Returns true if objects in aDocument shouldn't initiate image loads.
822
   */
823
  static bool DocumentInactiveForImageLoads(nsIDocument* aDocument);
824
825
  /**
826
   * Convert a CORSMode into the corresponding imgILoader flags for
827
   * passing to LoadImage.
828
   * @param aMode CORS mode to convert
829
   * @return a bitfield suitable to bitwise OR with other nsIRequest flags
830
   */
831
  static int32_t CORSModeToLoadImageFlags(mozilla::CORSMode aMode);
832
833
  /**
834
   * Method to start an image load.  This does not do any security checks.
835
   * This method will attempt to make aURI immutable; a caller that wants to
836
   * keep a mutable version around should pass in a clone.
837
   *
838
   * @param aURI uri of the image to be loaded
839
   * @param aContext element of document where the result of this request
840
   *                 will be used.
841
   * @param aLoadingDocument the document we belong to
842
   * @param aLoadingPrincipal the principal doing the load
843
   * @param aReferrer the referrer URI
844
   * @param aReferrerPolicy the referrer-sending policy to use on channel
845
   *         creation
846
   * @param aObserver the observer for the image load
847
   * @param aLoadFlags the load flags to use.  See nsIRequest
848
   * @param [aContentPolicyType=nsIContentPolicy::TYPE_INTERNAL_IMAGE] (Optional)
849
   *        The CP content type to use
850
   * @param aUseUrgentStartForChannel,(Optional) a flag to mark on channel if it
851
   *        is triggered by user input events.
852
   * @return the imgIRequest for the image load
853
   */
854
  static nsresult LoadImage(nsIURI* aURI,
855
                            nsINode* aContext,
856
                            nsIDocument* aLoadingDocument,
857
                            nsIPrincipal* aLoadingPrincipal,
858
                            uint64_t aRequestContextID,
859
                            nsIURI* aReferrer,
860
                            mozilla::net::ReferrerPolicy aReferrerPolicy,
861
                            imgINotificationObserver* aObserver,
862
                            int32_t aLoadFlags,
863
                            const nsAString& initiatorType,
864
                            imgRequestProxy** aRequest,
865
                            uint32_t aContentPolicyType = nsIContentPolicy::TYPE_INTERNAL_IMAGE,
866
                            bool aUseUrgentStartForChannel = false);
867
868
  /**
869
   * Obtain an image loader that respects the given document/channel's privacy status.
870
   * Null document/channel arguments return the public image loader.
871
   */
872
  static imgLoader* GetImgLoaderForDocument(nsIDocument* aDoc);
873
  static imgLoader* GetImgLoaderForChannel(nsIChannel* aChannel,
874
                                           nsIDocument* aContext);
875
876
  /**
877
   * Returns whether the given URI is in the image cache.
878
   */
879
  static bool IsImageInCache(nsIURI* aURI, nsIDocument* aDocument);
880
881
  /**
882
   * Method to get an imgIContainer from an image loading content
883
   *
884
   * @param aContent The image loading content.  Must not be null.
885
   * @param aRequest The image request [out]
886
   * @return the imgIContainer corresponding to the first frame of the image
887
   */
888
  static already_AddRefed<imgIContainer> GetImageFromContent(nsIImageLoadingContent* aContent, imgIRequest **aRequest = nullptr);
889
890
  /**
891
   * Helper method to call imgIRequest::GetStaticRequest.
892
   */
893
  static already_AddRefed<imgRequestProxy> GetStaticRequest(nsIDocument* aLoadingDocument,
894
                                                            imgRequestProxy* aRequest);
895
896
  /**
897
   * Method that decides whether a content node is draggable
898
   *
899
   * @param aContent The content node to test.
900
   * @return whether it's draggable
901
   */
902
  static bool ContentIsDraggable(nsIContent* aContent);
903
904
  /**
905
   * Method that decides whether a content node is a draggable image
906
   *
907
   * @param aContent The content node to test.
908
   * @return whether it's a draggable image
909
   */
910
  static bool IsDraggableImage(nsIContent* aContent);
911
912
  /**
913
   * Method that decides whether a content node is a draggable link
914
   *
915
   * @param aContent The content node to test.
916
   * @return whether it's a draggable link
917
   */
918
  static bool IsDraggableLink(const nsIContent* aContent);
919
920
  /**
921
   * Convenience method to create a new nodeinfo that differs only by prefix and
922
   * name from aNodeInfo. The new nodeinfo's name is set to aName, and prefix is
923
   * set to null.
924
   */
925
  static nsresult QNameChanged(mozilla::dom::NodeInfo* aNodeInfo,
926
                               nsAtom* aName,
927
                               mozilla::dom::NodeInfo** aResult);
928
929
  /**
930
   * Returns the appropriate event argument names for the specified
931
   * namespace and event name.  Added because we need to switch between
932
   * SVG's "evt" and the rest of the world's "event", and because onerror
933
   * on window takes 5 args.
934
   */
935
  static void GetEventArgNames(int32_t aNameSpaceID, nsAtom *aEventName,
936
                               bool aIsForWindow,
937
                               uint32_t *aArgCount, const char*** aArgNames);
938
939
  /**
940
   * Returns origin attributes of the document.
941
   **/
942
  static mozilla::OriginAttributes
943
  GetOriginAttributes(nsIDocument* aDoc);
944
945
  /**
946
   * Returns origin attributes of the load group.
947
   **/
948
  static mozilla::OriginAttributes
949
  GetOriginAttributes(nsILoadGroup* aLoadGroup);
950
951
  /**
952
   * Returns true if this document is in a Private Browsing window.
953
   */
954
  static bool IsInPrivateBrowsing(nsIDocument* aDoc);
955
956
  /**
957
   * Returns true if this loadGroup uses Private Browsing.
958
   */
959
  static bool IsInPrivateBrowsing(nsILoadGroup* aLoadGroup);
960
961
  /**
962
   * If aNode is not an element, return true exactly when aContent's binding
963
   * parent is null.
964
   *
965
   * If aNode is an element, return true exactly when aContent's binding parent
966
   * is the same as aNode's.
967
   *
968
   * This method is particularly useful for callers who are trying to ensure
969
   * that they are working with a non-anonymous descendant of a given node.  If
970
   * aContent is a descendant of aNode, a return value of false from this
971
   * method means that it's an anonymous descendant from aNode's point of view.
972
   *
973
   * Both arguments to this method must be non-null.
974
   */
975
  static bool IsInSameAnonymousTree(const nsINode* aNode, const nsIContent* aContent);
976
977
  /**
978
   * Return the nsIXPConnect service.
979
   */
980
  static nsIXPConnect *XPConnect()
981
0
  {
982
0
    return sXPConnect;
983
0
  }
984
985
  /**
986
   * Report simple error message to the browser console
987
   *   @param aErrorText the error message
988
   *   @param classification Name of the module reporting error
989
   */
990
  static void LogSimpleConsoleError(const nsAString& aErrorText,
991
                                    const char * classification,
992
                                    bool aFromPrivateWindow);
993
994
  /**
995
   * Report a non-localized error message to the error console.
996
   *   @param aErrorText the error message
997
   *   @param aErrorFlags See nsIScriptError.
998
   *   @param aCategory Name of module reporting error.
999
   *   @param aDocument Reference to the document which triggered the message.
1000
   *   @param [aURI=nullptr] (Optional) URI of resource containing error.
1001
   *   @param [aSourceLine=EmptyString()] (Optional) The text of the line that
1002
              contains the error (may be empty).
1003
   *   @param [aLineNumber=0] (Optional) Line number within resource
1004
              containing error.
1005
   *   @param [aColumnNumber=0] (Optional) Column number within resource
1006
              containing error.
1007
              If aURI is null, then aDocument->GetDocumentURI() is used.
1008
   *   @param [aLocationMode] (Optional) Specifies the behavior if
1009
              error location information is omitted.
1010
   */
1011
  enum MissingErrorLocationMode {
1012
    // Don't show location information in the error console.
1013
    eOMIT_LOCATION,
1014
    // Get location information from the currently executing script.
1015
    eUSE_CALLING_LOCATION
1016
  };
1017
  static nsresult ReportToConsoleNonLocalized(const nsAString& aErrorText,
1018
                                              uint32_t aErrorFlags,
1019
                                              const nsACString& aCategory,
1020
                                              const nsIDocument* aDocument,
1021
                                              nsIURI* aURI = nullptr,
1022
                                              const nsString& aSourceLine
1023
                                                = EmptyString(),
1024
                                              uint32_t aLineNumber = 0,
1025
                                              uint32_t aColumnNumber = 0,
1026
                                              MissingErrorLocationMode aLocationMode
1027
                                                = eUSE_CALLING_LOCATION);
1028
1029
  /**
1030
   * Report a non-localized error message to the error console base on the
1031
   * innerWindowID.
1032
   *   @param aErrorText the error message
1033
   *   @param aErrorFlags See nsIScriptError.
1034
   *   @param aCategory Name of module reporting error.
1035
   *   @param [aInnerWindowID] Inner window ID for document which triggered the
1036
   *          message.
1037
   *   @param [aURI=nullptr] (Optional) URI of resource containing error.
1038
   *   @param [aSourceLine=EmptyString()] (Optional) The text of the line that
1039
              contains the error (may be empty).
1040
   *   @param [aLineNumber=0] (Optional) Line number within resource
1041
              containing error.
1042
   *   @param [aColumnNumber=0] (Optional) Column number within resource
1043
              containing error.
1044
              If aURI is null, then aDocument->GetDocumentURI() is used.
1045
   *   @param [aLocationMode] (Optional) Specifies the behavior if
1046
              error location information is omitted.
1047
   */
1048
  static nsresult ReportToConsoleByWindowID(const nsAString& aErrorText,
1049
                                            uint32_t aErrorFlags,
1050
                                            const nsACString& aCategory,
1051
                                            uint64_t aInnerWindowID,
1052
                                            nsIURI* aURI = nullptr,
1053
                                            const nsString& aSourceLine
1054
                                              = EmptyString(),
1055
                                            uint32_t aLineNumber = 0,
1056
                                            uint32_t aColumnNumber = 0,
1057
                                            MissingErrorLocationMode aLocationMode
1058
                                              = eUSE_CALLING_LOCATION);
1059
1060
  /**
1061
   * Report a localized error message to the error console.
1062
   *   @param aErrorFlags See nsIScriptError.
1063
   *   @param aCategory Name of module reporting error.
1064
   *   @param aDocument Reference to the document which triggered the message.
1065
   *   @param aFile Properties file containing localized message.
1066
   *   @param aMessageName Name of localized message.
1067
   *   @param [aParams=nullptr] (Optional) Parameters to be substituted into
1068
              localized message.
1069
   *   @param [aParamsLength=0] (Optional) Length of aParams.
1070
   *   @param [aURI=nullptr] (Optional) URI of resource containing error.
1071
   *   @param [aSourceLine=EmptyString()] (Optional) The text of the line that
1072
              contains the error (may be empty).
1073
   *   @param [aLineNumber=0] (Optional) Line number within resource
1074
              containing error.
1075
   *   @param [aColumnNumber=0] (Optional) Column number within resource
1076
              containing error.
1077
              If aURI is null, then aDocument->GetDocumentURI() is used.
1078
   */
1079
  enum PropertiesFile {
1080
    eCSS_PROPERTIES,
1081
    eXBL_PROPERTIES,
1082
    eXUL_PROPERTIES,
1083
    eLAYOUT_PROPERTIES,
1084
    eFORMS_PROPERTIES,
1085
    ePRINTING_PROPERTIES,
1086
    eDOM_PROPERTIES,
1087
    eHTMLPARSER_PROPERTIES,
1088
    eSVG_PROPERTIES,
1089
    eBRAND_PROPERTIES,
1090
    eCOMMON_DIALOG_PROPERTIES,
1091
    eMATHML_PROPERTIES,
1092
    eSECURITY_PROPERTIES,
1093
    eNECKO_PROPERTIES,
1094
    PropertiesFile_COUNT
1095
  };
1096
  static nsresult ReportToConsole(uint32_t aErrorFlags,
1097
                                  const nsACString& aCategory,
1098
                                  const nsIDocument* aDocument,
1099
                                  PropertiesFile aFile,
1100
                                  const char *aMessageName,
1101
                                  const char16_t **aParams = nullptr,
1102
                                  uint32_t aParamsLength = 0,
1103
                                  nsIURI* aURI = nullptr,
1104
                                  const nsString& aSourceLine
1105
                                    = EmptyString(),
1106
                                  uint32_t aLineNumber = 0,
1107
                                  uint32_t aColumnNumber = 0);
1108
1109
  static void ReportEmptyGetElementByIdArg(const nsIDocument* aDoc);
1110
1111
  static void LogMessageToConsole(const char* aMsg);
1112
1113
  /**
1114
   * Get the localized string named |aKey| in properties file |aFile|.
1115
   */
1116
  static nsresult GetLocalizedString(PropertiesFile aFile,
1117
                                     const char* aKey,
1118
                                     nsAString& aResult);
1119
1120
  /**
1121
   * A helper function that parses a sandbox attribute (of an <iframe> or a CSP
1122
   * directive) and converts it to the set of flags used internally.
1123
   *
1124
   * @param aSandboxAttr  the sandbox attribute
1125
   * @return              the set of flags (SANDBOXED_NONE if aSandboxAttr is
1126
   *                      null)
1127
   */
1128
  static uint32_t ParseSandboxAttributeToFlags(const nsAttrValue* aSandboxAttr);
1129
1130
  /**
1131
   * A helper function that checks if a string matches a valid sandbox flag.
1132
   *
1133
   * @param aFlag   the potential sandbox flag.
1134
   * @return        true if the flag is a sandbox flag.
1135
   */
1136
  static bool IsValidSandboxFlag(const nsAString& aFlag);
1137
1138
  /**
1139
   * A helper function that returns a string attribute corresponding to the
1140
   * sandbox flags.
1141
   *
1142
   * @param aFlags    the sandbox flags
1143
   * @param aString   the attribute corresponding to the flags (null if aFlags
1144
   *                  is zero)
1145
   */
1146
  static void SandboxFlagsToString(uint32_t aFlags, nsAString& aString);
1147
1148
  /**
1149
   * Helper function that generates a UUID.
1150
   */
1151
  static nsresult GenerateUUIDInPlace(nsID& aUUID);
1152
1153
  static bool PrefetchPreloadEnabled(nsIDocShell* aDocShell);
1154
1155
  static void
1156
  ExtractErrorValues(JSContext* aCx, JS::Handle<JS::Value> aValue,
1157
                     nsAString& aSourceSpecOut, uint32_t *aLineOut,
1158
                     uint32_t *aColumnOut, nsString& aMessageOut);
1159
1160
  // Variant on `ExtractErrorValues` with a `nsACString`. This
1161
  // method is provided for backwards compatibility. Prefer the
1162
  // faster method above for your code.
1163
  static void
1164
  ExtractErrorValues(JSContext* aCx, JS::Handle<JS::Value> aValue,
1165
                     nsACString& aSourceSpecOut, uint32_t *aLineOut,
1166
                     uint32_t *aColumnOut, nsString& aMessageOut);
1167
1168
  static nsresult CalculateBufferSizeForImage(const uint32_t& aStride,
1169
                                            const mozilla::gfx::IntSize& aImageSize,
1170
                                            const mozilla::gfx::SurfaceFormat& aFormat,
1171
                                            size_t* aMaxBufferSize,
1172
                                            size_t* aUsedBufferSize);
1173
1174
private:
1175
  /**
1176
   * Fill (with the parameters given) the localized string named |aKey| in
1177
   * properties file |aFile|.
1178
   */
1179
  static nsresult FormatLocalizedString(PropertiesFile aFile,
1180
                                        const char* aKey,
1181
                                        const char16_t** aParams,
1182
                                        uint32_t aParamsLength,
1183
                                        nsAString& aResult);
1184
1185
public:
1186
  template<uint32_t N>
1187
  static nsresult FormatLocalizedString(PropertiesFile aFile,
1188
                                        const char* aKey,
1189
                                        const char16_t* (&aParams)[N],
1190
                                        nsAString& aResult)
1191
0
  {
1192
0
    return FormatLocalizedString(aFile, aKey, aParams, N, aResult);
1193
0
  }
Unexecuted instantiation: nsresult nsContentUtils::FormatLocalizedString<2u>(nsContentUtils::PropertiesFile, char const*, char16_t const* (&) [2u], nsTSubstring<char16_t>&)
Unexecuted instantiation: nsresult nsContentUtils::FormatLocalizedString<1u>(nsContentUtils::PropertiesFile, char const*, char16_t const* (&) [1u], nsTSubstring<char16_t>&)
1194
1195
  /**
1196
   * Fill (with the parameters given) the localized string named |aKey| in
1197
   * properties file |aFile| consuming an nsTArray of nsString parameters rather
1198
   * than a char16_t** for the sake of avoiding use-after-free errors involving
1199
   * temporaries.
1200
   */
1201
  static nsresult FormatLocalizedString(PropertiesFile aFile,
1202
                                        const char* aKey,
1203
                                        const nsTArray<nsString>& aParamArray,
1204
                                        nsAString& aResult);
1205
1206
  /**
1207
   * Returns true if aDocument is a chrome document
1208
   */
1209
  static bool IsChromeDoc(nsIDocument *aDocument);
1210
1211
  /**
1212
   * Returns true if aDocument is in a docshell whose parent is the same type
1213
   */
1214
  static bool IsChildOfSameType(nsIDocument* aDoc);
1215
1216
  /**
1217
   * Returns true if the content-type will be rendered as plain-text.
1218
   */
1219
  static bool IsPlainTextType(const nsACString& aContentType);
1220
1221
  /**
1222
   * Returns true iff the type is rendered as plain text and doesn't support
1223
   * non-UTF-8 encodings.
1224
   */
1225
  static bool IsUtf8OnlyPlainTextType(const nsACString& aContentType);
1226
1227
  /**
1228
   * Get the script file name to use when compiling the script
1229
   * referenced by aURI. In cases where there's no need for any extra
1230
   * security wrapper automation the script file name that's returned
1231
   * will be the spec in aURI, else it will be the spec in aDocument's
1232
   * URI followed by aURI's spec, separated by " -> ". Returns true
1233
   * if the script file name was modified, false if it's aURI's
1234
   * spec.
1235
   */
1236
  static bool GetWrapperSafeScriptFilename(nsIDocument *aDocument,
1237
                                             nsIURI *aURI,
1238
                                             nsACString& aScriptURI,
1239
                                             nsresult* aRv);
1240
1241
1242
  /**
1243
   * Returns true if aDocument belongs to a chrome docshell for
1244
   * display purposes.  Returns false for null documents or documents
1245
   * which do not belong to a docshell.
1246
   */
1247
  static bool IsInChromeDocshell(nsIDocument *aDocument);
1248
1249
  /**
1250
   * Return the content policy service
1251
   */
1252
  static nsIContentPolicy *GetContentPolicy();
1253
1254
  /**
1255
   * Map internal content policy types to external ones.
1256
   */
1257
  static inline nsContentPolicyType
1258
    InternalContentPolicyTypeToExternal(nsContentPolicyType aType);
1259
1260
  /**
1261
   * Map internal content policy types to external ones or preload types:
1262
   *   * TYPE_INTERNAL_SCRIPT_PRELOAD
1263
   *   * TYPE_INTERNAL_IMAGE_PRELOAD
1264
   *   * TYPE_INTERNAL_STYLESHEET_PRELOAD
1265
   *
1266
   * Note: DO NOT call this function unless you know what you're doing!
1267
   */
1268
  static inline nsContentPolicyType
1269
    InternalContentPolicyTypeToExternalOrPreload(nsContentPolicyType aType);
1270
1271
  /**
1272
   * Map internal content policy types to external ones, worker, or preload types:
1273
   *   * TYPE_INTERNAL_WORKER
1274
   *   * TYPE_INTERNAL_SHARED_WORKER
1275
   *   * TYPE_INTERNAL_SERVICE_WORKER
1276
   *
1277
   * Note: DO NOT call this function unless you know what you're doing!
1278
   */
1279
  static nsContentPolicyType InternalContentPolicyTypeToExternalOrWorker(nsContentPolicyType aType);
1280
1281
  /**
1282
   * Returns true if the content policy type is any of:
1283
   *   * TYPE_INTERNAL_SCRIPT_PRELOAD
1284
   *   * TYPE_INTERNAL_IMAGE_PRELOAD
1285
   *   * TYPE_INTERNAL_STYLESHEET_PRELOAD
1286
   */
1287
  static bool IsPreloadType(nsContentPolicyType aType);
1288
1289
  /**
1290
   * Returns true if the pref "security.mixed_content.upgrade_display_content" is true
1291
   * and the content policy type is any of:
1292
   *   * TYPE_IMAGE
1293
   *   * TYPE_MEDIA
1294
   */
1295
  static bool IsUpgradableDisplayType(nsContentPolicyType aType);
1296
1297
  /**
1298
   * Quick helper to determine whether there are any mutation listeners
1299
   * of a given type that apply to this content or any of its ancestors.
1300
   * The method has the side effect to call document's MayDispatchMutationEvent
1301
   * using aTargetForSubtreeModified as the parameter.
1302
   *
1303
   * @param aNode  The node to search for listeners
1304
   * @param aType  The type of listener (NS_EVENT_BITS_MUTATION_*)
1305
   * @param aTargetForSubtreeModified The node which is the target of the
1306
   *                                  possible DOMSubtreeModified event.
1307
   *
1308
   * @return true if there are mutation listeners of the specified type
1309
   */
1310
  static bool HasMutationListeners(nsINode* aNode,
1311
                                     uint32_t aType,
1312
                                     nsINode* aTargetForSubtreeModified);
1313
1314
  /**
1315
   * Quick helper to determine whether there are any mutation listeners
1316
   * of a given type that apply to any content in this document. It is valid
1317
   * to pass null for aDocument here, in which case this function always
1318
   * returns true.
1319
   *
1320
   * @param aDocument The document to search for listeners
1321
   * @param aType     The type of listener (NS_EVENT_BITS_MUTATION_*)
1322
   *
1323
   * @return true if there are mutation listeners of the specified type
1324
   */
1325
  static bool HasMutationListeners(nsIDocument* aDocument,
1326
                                     uint32_t aType);
1327
  /**
1328
   * Synchronously fire DOMNodeRemoved on aChild. Only fires the event if
1329
   * there really are listeners by checking using the HasMutationListeners
1330
   * function above. The function makes sure to hold the relevant objects alive
1331
   * for the duration of the event firing. However there are no guarantees
1332
   * that any of the objects are alive by the time the function returns.
1333
   * If you depend on that you need to hold references yourself.
1334
   *
1335
   * @param aChild    The node to fire DOMNodeRemoved at.
1336
   * @param aParent   The parent of aChild.
1337
   */
1338
  static void MaybeFireNodeRemoved(nsINode* aChild, nsINode* aParent);
1339
1340
  /**
1341
   * This method creates and dispatches a trusted event.
1342
   * Works only with events which can be created by calling
1343
   * nsIDocument::CreateEvent() with parameter "Events".
1344
   * @param aDoc           The document which will be used to create the event.
1345
   * @param aTarget        The target of the event, should be QIable to
1346
   *                       EventTarget.
1347
   * @param aEventName     The name of the event.
1348
   * @param aCanBubble     Whether the event can bubble.
1349
   * @param aCancelable    Is the event cancelable.
1350
   * @param aCopmosed      Is the event composed.
1351
   * @param aDefaultAction Set to true if default action should be taken,
1352
   *                       see EventTarget::DispatchEvent.
1353
   */
1354
  static nsresult DispatchTrustedEvent(nsIDocument* aDoc,
1355
                                       nsISupports* aTarget,
1356
                                       const nsAString& aEventName,
1357
                                       CanBubble,
1358
                                       Cancelable,
1359
                                       Composed aComposed = Composed::eDefault,
1360
                                       bool* aDefaultAction = nullptr);
1361
1362
  static nsresult DispatchTrustedEvent(nsIDocument* aDoc,
1363
                                       nsISupports* aTarget,
1364
                                       const nsAString& aEventName,
1365
                                       CanBubble aCanBubble,
1366
                                       Cancelable aCancelable,
1367
                                       bool* aDefaultAction)
1368
0
  {
1369
0
    return DispatchTrustedEvent(aDoc, aTarget, aEventName,
1370
0
                                aCanBubble, aCancelable,
1371
0
                                Composed::eDefault, aDefaultAction);
1372
0
  }
1373
1374
  /**
1375
   * This method creates and dispatches a trusted event using an event message.
1376
   * @param aDoc           The document which will be used to create the event.
1377
   * @param aTarget        The target of the event, should be QIable to
1378
   *                       EventTarget.
1379
   * @param aEventMessage  The event message.
1380
   * @param aCanBubble     Whether the event can bubble.
1381
   * @param aCancelable    Is the event cancelable.
1382
   * @param aDefaultAction Set to true if default action should be taken,
1383
   *                       see EventTarget::DispatchEvent.
1384
   */
1385
  template <class WidgetEventType>
1386
  static nsresult DispatchTrustedEvent(
1387
    nsIDocument* aDoc,
1388
    nsISupports* aTarget,
1389
    EventMessage aEventMessage,
1390
    CanBubble aCanBubble,
1391
    Cancelable aCancelable,
1392
    bool* aDefaultAction = nullptr,
1393
    ChromeOnlyDispatch aOnlyChromeDispatch = ChromeOnlyDispatch::eNo)
1394
0
  {
1395
0
    WidgetEventType event(true, aEventMessage);
1396
0
    MOZ_ASSERT(GetEventClassIDFromMessage(aEventMessage) == event.mClass);
1397
0
    return DispatchEvent(aDoc, aTarget, event, aEventMessage,
1398
0
                         aCanBubble, aCancelable, Trusted::eYes,
1399
0
                         aDefaultAction, aOnlyChromeDispatch);
1400
0
  }
Unexecuted instantiation: nsresult nsContentUtils::DispatchTrustedEvent<mozilla::WidgetEvent>(nsIDocument*, nsISupports*, mozilla::EventMessage, mozilla::CanBubble, mozilla::Cancelable, bool*, mozilla::ChromeOnlyDispatch)
Unexecuted instantiation: nsresult nsContentUtils::DispatchTrustedEvent<mozilla::InternalEditorInputEvent>(nsIDocument*, nsISupports*, mozilla::EventMessage, mozilla::CanBubble, mozilla::Cancelable, bool*, mozilla::ChromeOnlyDispatch)
1401
1402
  /**
1403
   * This method creates and dispatches a untrusted event.
1404
   * Works only with events which can be created by calling
1405
   * nsIDocument::CreateEvent() with parameter "Events".
1406
   * @param aDoc           The document which will be used to create the event.
1407
   * @param aTarget        The target of the event, should be QIable to
1408
   *                       EventTarget.
1409
   * @param aEventName     The name of the event.
1410
   * @param aCanBubble     Whether the event can bubble.
1411
   * @param aCancelable    Is the event cancelable.
1412
   * @param aDefaultAction Set to true if default action should be taken,
1413
   *                       see EventTarget::DispatchEvent.
1414
   */
1415
  static nsresult DispatchUntrustedEvent(nsIDocument* aDoc,
1416
                                         nsISupports* aTarget,
1417
                                         const nsAString& aEventName,
1418
                                         CanBubble,
1419
                                         Cancelable,
1420
                                         bool* aDefaultAction = nullptr);
1421
1422
1423
  /**
1424
   * This method creates and dispatches a untrusted event using an event message.
1425
   * @param aDoc           The document which will be used to create the event.
1426
   * @param aTarget        The target of the event, should be QIable to
1427
   *                       EventTarget.
1428
   * @param aEventMessage  The event message.
1429
   * @param aCanBubble     Whether the event can bubble.
1430
   * @param aCancelable    Is the event cancelable.
1431
   * @param aDefaultAction Set to true if default action should be taken,
1432
   *                       see EventTarget::DispatchEvent.
1433
   */
1434
  template <class WidgetEventType>
1435
  static nsresult DispatchUntrustedEvent(
1436
    nsIDocument* aDoc,
1437
    nsISupports* aTarget,
1438
    EventMessage aEventMessage,
1439
    CanBubble aCanBubble,
1440
    Cancelable aCancelable,
1441
    bool* aDefaultAction = nullptr,
1442
    ChromeOnlyDispatch aOnlyChromeDispatch = ChromeOnlyDispatch::eNo)
1443
  {
1444
    WidgetEventType event(false, aEventMessage);
1445
    MOZ_ASSERT(GetEventClassIDFromMessage(aEventMessage) == event.mClass);
1446
    return DispatchEvent(aDoc, aTarget, event, aEventMessage,
1447
                         aCanBubble, aCancelable, Trusted::eNo,
1448
                         aDefaultAction, aOnlyChromeDispatch);
1449
  }
1450
1451
  /**
1452
   * This method creates and dispatches a trusted event to the chrome
1453
   * event handler (the parent object of the DOM Window in the event target
1454
   * chain). Note, chrome event handler is used even if aTarget is a chrome
1455
   * object. Use DispatchEventOnlyToChrome if the normal event dispatching is
1456
   * wanted in case aTarget is a chrome object.
1457
   * Works only with events which can be created by calling
1458
   * nsIDocument::CreateEvent() with parameter "Events".
1459
   * @param aDocument      The document which will be used to create the event,
1460
   *                       and whose window's chrome handler will be used to
1461
   *                       dispatch the event.
1462
   * @param aTarget        The target of the event, used for event->SetTarget()
1463
   * @param aEventName     The name of the event.
1464
   * @param aCanBubble     Whether the event can bubble.
1465
   * @param aCancelable    Is the event cancelable.
1466
   * @param aDefaultAction Set to true if default action should be taken,
1467
   *                       see EventTarget::DispatchEvent.
1468
   */
1469
  static nsresult DispatchChromeEvent(nsIDocument* aDoc,
1470
                                      nsISupports* aTarget,
1471
                                      const nsAString& aEventName,
1472
                                      CanBubble,
1473
                                      Cancelable,
1474
                                      bool* aDefaultAction = nullptr);
1475
1476
  /**
1477
   * Helper function for dispatching a "DOMWindowFocus" event to
1478
   * the chrome event handler of the given DOM Window. This has the effect
1479
   * of focusing the corresponding tab and bringing the browser window
1480
   * to the foreground.
1481
   */
1482
  static nsresult DispatchFocusChromeEvent(nsPIDOMWindowOuter* aWindow);
1483
1484
  /**
1485
   * This method creates and dispatches a trusted event.
1486
   * If aTarget is not a chrome object, the nearest chrome object in the
1487
   * propagation path will be used as the start of the event target chain.
1488
   * This method is different than DispatchChromeEvent, which always dispatches
1489
   * events to chrome event handler. DispatchEventOnlyToChrome works like
1490
   * DispatchTrustedEvent in the case aTarget is a chrome object.
1491
   * Works only with events which can be created by calling
1492
   * nsIDocument::CreateEvent() with parameter "Events".
1493
   * @param aDoc           The document which will be used to create the event.
1494
   * @param aTarget        The target of the event, should be QIable to
1495
   *                       EventTarget.
1496
   * @param aEventName     The name of the event.
1497
   * @param aCanBubble     Whether the event can bubble.
1498
   * @param aCancelable    Is the event cancelable.
1499
   * @param aDefaultAction Set to true if default action should be taken,
1500
   *                       see EventTarget::DispatchEvent.
1501
   */
1502
  static nsresult DispatchEventOnlyToChrome(nsIDocument* aDoc,
1503
                                            nsISupports* aTarget,
1504
                                            const nsAString& aEventName,
1505
                                            CanBubble,
1506
                                            Cancelable,
1507
                                            bool* aDefaultAction = nullptr);
1508
1509
  /**
1510
   * Determines if an event attribute name (such as onclick) is valid for
1511
   * a given element type. Types are from the EventNameType enumeration
1512
   * defined above.
1513
   *
1514
   * @param aName the event name to look up
1515
   * @param aType the type of content
1516
   */
1517
  static bool IsEventAttributeName(nsAtom* aName, int32_t aType);
1518
1519
  /**
1520
   * Return the event message for the event with the given name. The name is
1521
   * the event name with the 'on' prefix. Returns eUnidentifiedEvent if the
1522
   * event doesn't match a known event name.
1523
   *
1524
   * @param aName the event name to look up
1525
   */
1526
  static EventMessage GetEventMessage(nsAtom* aName);
1527
1528
  /**
1529
   * Returns the EventMessage and nsAtom to be used for event listener
1530
   * registration.
1531
   */
1532
  static EventMessage
1533
  GetEventMessageAndAtomForListener(const nsAString& aName, nsAtom** aOnName);
1534
1535
  /**
1536
   * Return the EventClassID for the event with the given name. The name is the
1537
   * event name *without* the 'on' prefix. Returns eBasicEventClass if the event
1538
   * is not known to be of any particular event class.
1539
   *
1540
   * @param aName the event name to look up
1541
   */
1542
  static mozilla::EventClassID GetEventClassID(const nsAString& aName);
1543
1544
  /**
1545
   * Return the event message and atom for the event with the given name.
1546
   * The name is the event name *without* the 'on' prefix.
1547
   * Returns eUnidentifiedEvent on the aEventID if the
1548
   * event doesn't match a known event name in the category.
1549
   *
1550
   * @param aName the event name to look up
1551
   * @param aEventClassID only return event id for aEventClassID
1552
   */
1553
  static nsAtom* GetEventMessageAndAtom(const nsAString& aName,
1554
                                        mozilla::EventClassID aEventClassID,
1555
                                        EventMessage* aEventMessage);
1556
1557
  /**
1558
   * Used only during traversal of the XPCOM graph by the cycle
1559
   * collector: push a pointer to the listener manager onto the
1560
   * children deque, if it exists. Do nothing if there is no listener
1561
   * manager.
1562
   *
1563
   * Crucially: does not perform any refcounting operations.
1564
   *
1565
   * @param aNode The node to traverse.
1566
   * @param children The buffer to push a listener manager pointer into.
1567
   */
1568
  static void TraverseListenerManager(nsINode *aNode,
1569
                                      nsCycleCollectionTraversalCallback &cb);
1570
1571
  /**
1572
   * Get the eventlistener manager for aNode, creating it if it does not
1573
   * already exist.
1574
   *
1575
   * @param aNode The node for which to get the eventlistener manager.
1576
   */
1577
  static mozilla::EventListenerManager*
1578
    GetListenerManagerForNode(nsINode* aNode);
1579
  /**
1580
   * Get the eventlistener manager for aNode, returning null if it does not
1581
   * already exist.
1582
   *
1583
   * @param aNode The node for which to get the eventlistener manager.
1584
   */
1585
  static mozilla::EventListenerManager*
1586
    GetExistingListenerManagerForNode(const nsINode* aNode);
1587
1588
  static void UnmarkGrayJSListenersInCCGenerationDocuments();
1589
1590
  /**
1591
   * Remove the eventlistener manager for aNode.
1592
   *
1593
   * @param aNode The node for which to remove the eventlistener manager.
1594
   */
1595
  static void RemoveListenerManager(nsINode *aNode);
1596
1597
  static bool IsInitialized()
1598
  {
1599
    return sInitialized;
1600
  }
1601
1602
  /**
1603
   * Checks if the localname/prefix/namespace triple is valid wrt prefix
1604
   * and namespace according to the Namespaces in XML and DOM Code
1605
   * specfications.
1606
   *
1607
   * @param aLocalname localname of the node
1608
   * @param aPrefix prefix of the node
1609
   * @param aNamespaceID namespace of the node
1610
   */
1611
  static bool IsValidNodeName(nsAtom *aLocalName, nsAtom *aPrefix,
1612
                                int32_t aNamespaceID);
1613
1614
  /**
1615
   * Creates a DocumentFragment from text using a context node to resolve
1616
   * namespaces.
1617
   *
1618
   * Please note that for safety reasons, if the node principal of
1619
   * aContextNode is the system principal, this function will automatically
1620
   * sanitize its input using nsTreeSanitizer.
1621
   *
1622
   * Note! In the HTML case with the HTML5 parser enabled, this is only called
1623
   * from Range.createContextualFragment() and the implementation here is
1624
   * quirky accordingly (html context node behaves like a body context node).
1625
   * If you don't want that quirky behavior, don't use this method as-is!
1626
   *
1627
   * @param aContextNode the node which is used to resolve namespaces
1628
   * @param aFragment the string which is parsed to a DocumentFragment
1629
   * @param aReturn the resulting fragment
1630
   * @param aPreventScriptExecution whether to mark scripts as already started
1631
   */
1632
  static already_AddRefed<mozilla::dom::DocumentFragment>
1633
  CreateContextualFragment(nsINode* aContextNode, const nsAString& aFragment,
1634
                           bool aPreventScriptExecution,
1635
                           mozilla::ErrorResult& aRv);
1636
1637
  /**
1638
   * Invoke the fragment parsing algorithm (innerHTML) using the HTML parser.
1639
   *
1640
   * Please note that for safety reasons, if the node principal of aTargetNode
1641
   * is the system principal, this function will automatically sanitize its
1642
   * input using nsTreeSanitizer.
1643
   *
1644
   * @param aSourceBuffer the string being set as innerHTML
1645
   * @param aTargetNode the target container
1646
   * @param aContextLocalName local name of context node
1647
   * @param aContextNamespace namespace of context node
1648
   * @param aQuirks true to make <table> not close <p>
1649
   * @param aPreventScriptExecution true to prevent scripts from executing;
1650
   *        don't set to false when parsing into a target node that has been
1651
   *        bound to tree.
1652
   * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1653
   *         fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1654
   *         long and NS_OK otherwise.
1655
   */
1656
  static nsresult ParseFragmentHTML(const nsAString& aSourceBuffer,
1657
                                    nsIContent* aTargetNode,
1658
                                    nsAtom* aContextLocalName,
1659
                                    int32_t aContextNamespace,
1660
                                    bool aQuirks,
1661
                                    bool aPreventScriptExecution);
1662
1663
  /**
1664
   * Invoke the fragment parsing algorithm (innerHTML) using the XML parser.
1665
   *
1666
   * Please note that for safety reasons, if the node principal of aDocument
1667
   * is the system principal, this function will automatically sanitize its
1668
   * input using nsTreeSanitizer.
1669
   *
1670
   * @param aSourceBuffer the string being set as innerHTML
1671
   * @param aDocument the target document
1672
   * @param aTagStack the namespace mapping context
1673
   * @param aPreventExecution whether to mark scripts as already started
1674
   * @param aReturn the result fragment
1675
   * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1676
   *         fragments is made, a return code from the XML parser.
1677
   */
1678
  static nsresult ParseFragmentXML(const nsAString& aSourceBuffer,
1679
                                   nsIDocument* aDocument,
1680
                                   nsTArray<nsString>& aTagStack,
1681
                                   bool aPreventScriptExecution,
1682
                                   mozilla::dom::DocumentFragment** aReturn);
1683
1684
  /**
1685
   * Parse a string into a document using the HTML parser.
1686
   * Script elements are marked unexecutable.
1687
   *
1688
   * @param aSourceBuffer the string to parse as an HTML document
1689
   * @param aTargetDocument the document object to parse into. Must not have
1690
   *                        child nodes.
1691
   * @param aScriptingEnabledForNoscriptParsing whether <noscript> is parsed
1692
   *                                            as if scripting was enabled
1693
   * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1694
   *         fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1695
   *         long and NS_OK otherwise.
1696
   */
1697
  static nsresult ParseDocumentHTML(const nsAString& aSourceBuffer,
1698
                                    nsIDocument* aTargetDocument,
1699
                                    bool aScriptingEnabledForNoscriptParsing);
1700
1701
  /**
1702
   * Converts HTML source to plain text by parsing the source and using the
1703
   * plain text serializer on the resulting tree.
1704
   *
1705
   * @param aSourceBuffer the string to parse as an HTML document
1706
   * @param aResultBuffer the string where the plain text result appears;
1707
   *                      may be the same string as aSourceBuffer
1708
   * @param aFlags Flags from nsIDocumentEncoder.
1709
   * @param aWrapCol Number of columns after which to line wrap; 0 for no
1710
   *                 auto-wrapping
1711
   * @return NS_ERROR_DOM_INVALID_STATE_ERR if a re-entrant attempt to parse
1712
   *         fragments is made, NS_ERROR_OUT_OF_MEMORY if aSourceBuffer is too
1713
   *         long and NS_OK otherwise.
1714
   */
1715
  static nsresult ConvertToPlainText(const nsAString& aSourceBuffer,
1716
                                     nsAString& aResultBuffer,
1717
                                     uint32_t aFlags,
1718
                                     uint32_t aWrapCol);
1719
1720
  /**
1721
   * Sets the text contents of a node by replacing all existing children
1722
   * with a single text child.
1723
   *
1724
   * The function always notifies.
1725
   *
1726
   * Will reuse the first text child if one is available. Will not reuse
1727
   * existing cdata children.
1728
   *
1729
   * @param aContent Node to set contents of.
1730
   * @param aValue   Value to set contents to.
1731
   * @param aTryReuse When true, the function will try to reuse an existing
1732
   *                  textnodes rather than always creating a new one.
1733
   */
1734
  static nsresult SetNodeTextContent(nsIContent* aContent,
1735
                                     const nsAString& aValue,
1736
                                     bool aTryReuse);
1737
1738
  /**
1739
   * Get the textual contents of a node. This is a concatenation of all
1740
   * textnodes that are direct or (depending on aDeep) indirect children
1741
   * of the node.
1742
   *
1743
   * NOTE! No serialization takes place and <br> elements
1744
   * are not converted into newlines. Only textnodes and cdata nodes are
1745
   * added to the result.
1746
   *
1747
   * @see nsLayoutUtils::GetFrameTextContent
1748
   *
1749
   * @param aNode Node to get textual contents of.
1750
   * @param aDeep If true child elements of aNode are recursivly descended
1751
   *              into to find text children.
1752
   * @param aResult the result. Out param.
1753
   * @return false on out of memory errors, true otherwise.
1754
   */
1755
  MOZ_MUST_USE
1756
  static bool GetNodeTextContent(nsINode* aNode, bool aDeep,
1757
                                 nsAString& aResult, const mozilla::fallible_t&);
1758
1759
  static void GetNodeTextContent(nsINode* aNode, bool aDeep,
1760
                                 nsAString& aResult);
1761
1762
  /**
1763
   * Same as GetNodeTextContents but appends the result rather than sets it.
1764
   */
1765
  static bool AppendNodeTextContent(nsINode* aNode, bool aDeep,
1766
                                    nsAString& aResult, const mozilla::fallible_t&);
1767
1768
  /**
1769
   * Utility method that checks if a given node has any non-empty children. This
1770
   * method does not descend recursively into children by default.
1771
   *
1772
   * @param aDiscoverMode Set to eRecurseIntoChildren to descend recursively
1773
   * into children.
1774
   */
1775
  enum TextContentDiscoverMode : uint8_t {
1776
    eRecurseIntoChildren, eDontRecurseIntoChildren
1777
  };
1778
1779
  static bool HasNonEmptyTextContent(
1780
    nsINode* aNode,
1781
    TextContentDiscoverMode aDiscoverMode = eDontRecurseIntoChildren);
1782
1783
  /**
1784
   * Delete strings allocated for nsContentList matches
1785
   */
1786
  static void DestroyMatchString(void* aData);
1787
1788
  /*
1789
   * Notify when the first XUL menu is opened and when the all XUL menus are
1790
   * closed. At opening, aInstalling should be TRUE, otherwise, it should be
1791
   * FALSE.
1792
   */
1793
  static void NotifyInstalledMenuKeyboardListener(bool aInstalling);
1794
1795
  /**
1796
   * Check whether the nsIURI uses the given scheme.
1797
   *
1798
   * Note that this will check the innermost URI rather than that of
1799
   * the nsIURI itself.
1800
   */
1801
  static bool SchemeIs(nsIURI* aURI, const char* aScheme);
1802
1803
  /**
1804
   * Returns true if aPrincipal is the system principal.
1805
   */
1806
  static bool IsSystemPrincipal(nsIPrincipal* aPrincipal);
1807
1808
  /**
1809
   * Returns true if aPrincipal is an ExpandedPrincipal.
1810
   */
1811
  static bool IsExpandedPrincipal(nsIPrincipal* aPrincipal);
1812
1813
  /**
1814
   * Returns true if aPrincipal is the system or an ExpandedPrincipal.
1815
   */
1816
  static bool IsSystemOrExpandedPrincipal(nsIPrincipal* aPrincipal)
1817
  {
1818
    return IsSystemPrincipal(aPrincipal) || IsExpandedPrincipal(aPrincipal);
1819
  }
1820
1821
  /**
1822
   * Gets the system principal from the security manager.
1823
   */
1824
  static nsIPrincipal* GetSystemPrincipal();
1825
1826
  /**
1827
   * Gets the null subject principal singleton. This is only useful for
1828
   * assertions.
1829
   */
1830
  static nsIPrincipal* GetNullSubjectPrincipal() { return sNullSubjectPrincipal; }
1831
1832
  /**
1833
   * *aResourcePrincipal is a principal describing who may access the contents
1834
   * of a resource. The resource can only be consumed by a principal that
1835
   * subsumes *aResourcePrincipal. MAKE SURE THAT NOTHING EVER ACTS WITH THE
1836
   * AUTHORITY OF *aResourcePrincipal.
1837
   * It may be null to indicate that the resource has no data from any origin
1838
   * in it yet and anything may access the resource.
1839
   * Additional data is being mixed into the resource from aExtraPrincipal
1840
   * (which may be null; if null, no data is being mixed in and this function
1841
   * will do nothing). Update *aResourcePrincipal to reflect the new data.
1842
   * If *aResourcePrincipal subsumes aExtraPrincipal, nothing needs to change,
1843
   * otherwise *aResourcePrincipal is replaced with the system principal.
1844
   * Returns true if *aResourcePrincipal changed.
1845
   */
1846
  static bool CombineResourcePrincipals(nsCOMPtr<nsIPrincipal>* aResourcePrincipal,
1847
                                        nsIPrincipal* aExtraPrincipal);
1848
1849
  /**
1850
   * Trigger a link with uri aLinkURI. If aClick is false, this triggers a
1851
   * mouseover on the link, otherwise it triggers a load after doing a
1852
   * security check using aContent's principal.
1853
   *
1854
   * @param aContent the node on which a link was triggered.
1855
   * @param aPresContext the pres context, must be non-null.
1856
   * @param aLinkURI the URI of the link, must be non-null.
1857
   * @param aTargetSpec the target (like target=, may be empty).
1858
   * @param aClick whether this was a click or not (if false, this method
1859
   *               assumes you just hovered over the link).
1860
   * @param aIsTrusted If false, JS Context will be pushed to stack
1861
   *                   when the link is triggered.
1862
   */
1863
  static void TriggerLink(nsIContent *aContent, nsPresContext *aPresContext,
1864
                          nsIURI *aLinkURI, const nsString& aTargetSpec,
1865
                          bool aClick, bool aIsTrusted);
1866
1867
  /**
1868
   * Get the link location.
1869
   */
1870
  static void GetLinkLocation(mozilla::dom::Element* aElement,
1871
                              nsString& aLocationString);
1872
1873
  /**
1874
   * Return top-level widget in the parent chain.
1875
   */
1876
  static nsIWidget* GetTopLevelWidget(nsIWidget* aWidget);
1877
1878
  /**
1879
   * Return the localized ellipsis for UI.
1880
   */
1881
  static const nsDependentString GetLocalizedEllipsis();
1882
1883
  /**
1884
   * Hide any XUL popups associated with aDocument, including any documents
1885
   * displayed in child frames. Does nothing if aDocument is null.
1886
   */
1887
  static void HidePopupsInDocument(nsIDocument* aDocument);
1888
1889
  /**
1890
   * Retrieve the current drag session, or null if no drag is currently occuring
1891
   */
1892
  static already_AddRefed<nsIDragSession> GetDragSession();
1893
1894
  /*
1895
   * Initialize and set the dataTransfer field of an WidgetDragEvent.
1896
   */
1897
  static nsresult SetDataTransferInEvent(mozilla::WidgetDragEvent* aDragEvent);
1898
1899
  // filters the drag and drop action to fit within the effects allowed and
1900
  // returns it.
1901
  static uint32_t FilterDropEffect(uint32_t aAction, uint32_t aEffectAllowed);
1902
1903
  /*
1904
   * Return true if the target of a drop event is a content document that is
1905
   * an ancestor of the document for the source of the drag.
1906
   */
1907
  static bool CheckForSubFrameDrop(nsIDragSession* aDragSession,
1908
                                   mozilla::WidgetDragEvent* aDropEvent);
1909
1910
  /**
1911
   * Return true if aURI is a local file URI (i.e. file://).
1912
   */
1913
  static bool URIIsLocalFile(nsIURI *aURI);
1914
1915
  /**
1916
   * Get the application manifest URI for this document.  The manifest URI
1917
   * is specified in the manifest= attribute of the root element of the
1918
   * document.
1919
   *
1920
   * @param aDocument The document that lists the manifest.
1921
   * @param aURI The manifest URI.
1922
   */
1923
  static void GetOfflineAppManifest(nsIDocument *aDocument, nsIURI **aURI);
1924
1925
  /**
1926
   * Check whether an application should be allowed to use offline APIs.
1927
   */
1928
  static bool OfflineAppAllowed(nsIURI *aURI);
1929
1930
  /**
1931
   * Check whether an application should be allowed to use offline APIs.
1932
   */
1933
  static bool OfflineAppAllowed(nsIPrincipal *aPrincipal);
1934
1935
  /**
1936
   * If offline-apps.allow_by_default is true, we set offline-app permission
1937
   * for the principal and return true.  Otherwise false.
1938
   */
1939
  static bool MaybeAllowOfflineAppByDefault(nsIPrincipal *aPrincipal);
1940
1941
  /**
1942
   * Increases the count of blockers preventing scripts from running.
1943
   * NOTE: You might want to use nsAutoScriptBlocker rather than calling
1944
   * this directly
1945
   */
1946
  static void AddScriptBlocker();
1947
1948
  /**
1949
   * Decreases the count of blockers preventing scripts from running.
1950
   * NOTE: You might want to use nsAutoScriptBlocker rather than calling
1951
   * this directly
1952
   *
1953
   * WARNING! Calling this function could synchronously execute scripts.
1954
   */
1955
  static void RemoveScriptBlocker();
1956
1957
  /**
1958
   * Add a runnable that is to be executed as soon as it's safe to execute
1959
   * scripts.
1960
   * NOTE: If it's currently safe to execute scripts, aRunnable will be run
1961
   *       synchronously before the function returns.
1962
   *
1963
   * @param aRunnable  The nsIRunnable to run as soon as it's safe to execute
1964
   *                   scripts. Passing null is allowed and results in nothing
1965
   *                   happening. It is also allowed to pass an object that
1966
   *                   has not yet been AddRefed.
1967
   */
1968
  static void AddScriptRunner(already_AddRefed<nsIRunnable> aRunnable);
1969
  static void AddScriptRunner(nsIRunnable* aRunnable);
1970
1971
  /**
1972
   * Returns true if it's safe to execute content script and false otherwise.
1973
   *
1974
   * The only known case where this lies is mutation events. They run, and can
1975
   * run anything else, when this function returns false, but this is ok.
1976
   */
1977
  static bool IsSafeToRunScript() {
1978
    MOZ_ASSERT(NS_IsMainThread(),
1979
               "This static variable only makes sense on the main thread!");
1980
    return sScriptBlockerCount == 0;
1981
  }
1982
1983
  // XXXcatalinb: workaround for weird include error when trying to reference
1984
  // ipdl types in WindowWatcher.
1985
  static nsIWindowProvider*
1986
  GetWindowProviderForContentProcess();
1987
1988
  // Returns the browser window with the most recent time stamp that is
1989
  // not in private browsing mode.
1990
  static already_AddRefed<nsPIDOMWindowOuter>
1991
  GetMostRecentNonPBWindow();
1992
1993
  /**
1994
   * Call this function if !IsSafeToRunScript() and we fail to run the script
1995
   * (rather than using AddScriptRunner as we usually do). |aDocument| is
1996
   * optional as it is only used for showing the URL in the console.
1997
   */
1998
  static void WarnScriptWasIgnored(nsIDocument* aDocument);
1999
2000
  /**
2001
   * Add a "synchronous section", in the form of an nsIRunnable run once the
2002
   * event loop has reached a "stable state". |aRunnable| must not cause any
2003
   * queued events to be processed (i.e. must not spin the event loop).
2004
   * We've reached a stable state when the currently executing task/event has
2005
   * finished, see
2006
   * http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#synchronous-section
2007
   * In practice this runs aRunnable once the currently executing event
2008
   * finishes. If called multiple times per task/event, all the runnables will
2009
   * be executed, in the order in which RunInStableState() was called.
2010
   */
2011
  static void RunInStableState(already_AddRefed<nsIRunnable> aRunnable);
2012
2013
  /* Add a pending IDBTransaction to be cleaned up at the end of performing a
2014
   * microtask checkpoint.
2015
   * See the step of "Cleanup Indexed Database Transactions" in
2016
   * https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint
2017
   */
2018
  static void AddPendingIDBTransaction(already_AddRefed<nsIRunnable> aTransaction);
2019
2020
  /**
2021
   * Returns true if we are doing StableState/MetastableState.
2022
   */
2023
  static bool IsInStableOrMetaStableState();
2024
2025
  /* Process viewport META data. This gives us information for the scale
2026
   * and zoom of a page on mobile devices. We stick the information in
2027
   * the document header and use it later on after rendering.
2028
   *
2029
   * See Bug #436083
2030
   */
2031
  static nsresult ProcessViewportInfo(nsIDocument *aDocument,
2032
                                      const nsAString &viewportInfo);
2033
2034
  static JSContext *GetCurrentJSContext();
2035
2036
  /**
2037
   * Case insensitive comparison between two strings. However it only ignores
2038
   * case for ASCII characters a-z.
2039
   */
2040
  static bool EqualsIgnoreASCIICase(const nsAString& aStr1,
2041
                                    const nsAString& aStr2);
2042
2043
  /**
2044
   * Convert ASCII A-Z to a-z.
2045
   */
2046
  static void ASCIIToLower(nsAString& aStr);
2047
  static void ASCIIToLower(nsACString& aStr);
2048
  static void ASCIIToLower(const nsAString& aSource, nsAString& aDest);
2049
  static void ASCIIToLower(const nsACString& aSource, nsACString& aDest);
2050
2051
  /**
2052
   * Convert ASCII a-z to A-Z.
2053
   */
2054
  static void ASCIIToUpper(nsAString& aStr);
2055
  static void ASCIIToUpper(nsACString& aStr);
2056
  static void ASCIIToUpper(const nsAString& aSource, nsAString& aDest);
2057
  static void ASCIIToUpper(const nsACString& aSource, nsACString& aDest);
2058
2059
  /**
2060
   * Return whether aStr contains an ASCII uppercase character.
2061
   */
2062
  static bool StringContainsASCIIUpper(const nsAString& aStr);
2063
2064
  // Returns NS_OK for same origin, error (NS_ERROR_DOM_BAD_URI) if not.
2065
  static nsresult CheckSameOrigin(nsIChannel *aOldChannel, nsIChannel *aNewChannel);
2066
  static nsIInterfaceRequestor* SameOriginChecker();
2067
2068
  /**
2069
   * Get the Origin of the passed in nsIPrincipal or nsIURI. If the passed in
2070
   * nsIURI or the URI of the passed in nsIPrincipal does not have a host, the
2071
   * origin is set to 'null'.
2072
   *
2073
   * The ASCII versions return a ASCII strings that are puny-code encoded,
2074
   * suitable for, for example, header values. The UTF versions return strings
2075
   * containing international characters.
2076
   *
2077
   * @pre aPrincipal/aOrigin must not be null.
2078
   *
2079
   * @note this should be used for HTML5 origin determination.
2080
   */
2081
  static nsresult GetASCIIOrigin(nsIPrincipal* aPrincipal,
2082
                                 nsACString& aOrigin);
2083
  static nsresult GetASCIIOrigin(nsIURI* aURI, nsACString& aOrigin);
2084
  static nsresult GetUTFOrigin(nsIPrincipal* aPrincipal,
2085
                               nsAString& aOrigin);
2086
  static nsresult GetUTFOrigin(nsIURI* aURI, nsAString& aOrigin);
2087
2088
  /**
2089
   * This method creates and dispatches "command" event, which implements
2090
   * XULCommandEvent.
2091
   * If aShell is not null, dispatching goes via
2092
   * nsIPresShell::HandleDOMEventWithTarget.
2093
   */
2094
  static nsresult DispatchXULCommand(nsIContent* aTarget,
2095
                                     bool aTrusted,
2096
                                     mozilla::dom::Event* aSourceEvent = nullptr,
2097
                                     nsIPresShell* aShell = nullptr,
2098
                                     bool aCtrl = false,
2099
                                     bool aAlt = false,
2100
                                     bool aShift = false,
2101
                                     bool aMeta = false,
2102
                                     // Including MouseEventBinding here leads
2103
                                     // to incude loops, unfortunately.
2104
                                     uint16_t inputSource = 0 /* MouseEvent_Binding::MOZ_SOURCE_UNKNOWN */);
2105
2106
  static bool CheckMayLoad(nsIPrincipal* aPrincipal, nsIChannel* aChannel, bool aAllowIfInheritsPrincipal);
2107
2108
  /**
2109
   * The method checks whether the caller can access native anonymous content.
2110
   * If there is no JS in the stack or privileged JS is running, this
2111
   * method returns true, otherwise false.
2112
   */
2113
  static bool CanAccessNativeAnon();
2114
2115
  MOZ_MUST_USE
2116
  static nsresult WrapNative(JSContext *cx, nsISupports *native,
2117
                             const nsIID* aIID, JS::MutableHandle<JS::Value> vp,
2118
                             bool aAllowWrapping = true)
2119
1.62M
  {
2120
1.62M
    return WrapNative(cx, native, nullptr, aIID, vp, aAllowWrapping);
2121
1.62M
  }
2122
2123
  // Same as the WrapNative above, but use this one if aIID is nsISupports' IID.
2124
  MOZ_MUST_USE
2125
  static nsresult WrapNative(JSContext *cx, nsISupports *native,
2126
                             JS::MutableHandle<JS::Value> vp,
2127
                             bool aAllowWrapping = true)
2128
  {
2129
    return WrapNative(cx, native, nullptr, nullptr, vp, aAllowWrapping);
2130
  }
2131
2132
  MOZ_MUST_USE
2133
  static nsresult WrapNative(JSContext *cx, nsISupports *native,
2134
                             nsWrapperCache *cache,
2135
                             JS::MutableHandle<JS::Value> vp,
2136
                             bool aAllowWrapping = true)
2137
0
  {
2138
0
    return WrapNative(cx, native, cache, nullptr, vp, aAllowWrapping);
2139
0
  }
2140
2141
  /**
2142
   * Creates an arraybuffer from a binary string.
2143
   */
2144
  static nsresult CreateArrayBuffer(JSContext *aCx, const nsACString& aData,
2145
                                    JSObject** aResult);
2146
2147
  static void StripNullChars(const nsAString& aInStr, nsAString& aOutStr);
2148
2149
  /**
2150
   * Strip all \n, \r and nulls from the given string
2151
   * @param aString the string to remove newlines from [in/out]
2152
   */
2153
  static void RemoveNewlines(nsString &aString);
2154
2155
  /**
2156
   * Convert Windows and Mac platform linebreaks to \n.
2157
   * @param aString the string to convert the newlines inside [in/out]
2158
   */
2159
  static void PlatformToDOMLineBreaks(nsString &aString);
2160
  MOZ_MUST_USE
2161
  static bool PlatformToDOMLineBreaks(nsString &aString,
2162
                                      const mozilla::fallible_t&);
2163
2164
  /**
2165
   * Populates aResultString with the contents of the string-buffer aBuf, up
2166
   * to aBuf's null-terminator.  aBuf must not be null. Ownership of the string
2167
   * is not transferred.
2168
   */
2169
  static void PopulateStringFromStringBuffer(nsStringBuffer* aBuf,
2170
                                             nsAString& aResultString);
2171
2172
  static bool IsHandlingKeyBoardEvent()
2173
0
  {
2174
0
    return sIsHandlingKeyBoardEvent;
2175
0
  }
2176
2177
  static void SetIsHandlingKeyBoardEvent(bool aHandling)
2178
  {
2179
    sIsHandlingKeyBoardEvent = aHandling;
2180
  }
2181
2182
  /**
2183
   * Utility method for getElementsByClassName.  aRootNode is the node (either
2184
   * document or element), which getElementsByClassName was called on.
2185
   */
2186
  static already_AddRefed<nsContentList>
2187
  GetElementsByClassName(nsINode* aRootNode, const nsAString& aClasses)
2188
0
  {
2189
0
    MOZ_ASSERT(aRootNode, "Must have root node");
2190
0
2191
0
    return GetFuncStringContentList<nsCacheableFuncStringHTMLCollection>(aRootNode,
2192
0
                                                                         MatchClassNames,
2193
0
                                                                         DestroyClassNameArray,
2194
0
                                                                         AllocClassMatchingInfo,
2195
0
                                                                         aClasses);
2196
0
  }
2197
2198
  /**
2199
   * Returns a presshell for this document, if there is one. This will be
2200
   * aDoc's direct presshell if there is one, otherwise we'll look at all
2201
   * ancestor documents to try to find a presshell, so for example this can
2202
   * still find a presshell for documents in display:none frames that have
2203
   * no presentation. So you have to be careful how you use this presshell ---
2204
   * getting generic data like a device context or widget from it is OK, but it
2205
   * might not be this document's actual presentation.
2206
   */
2207
  static nsIPresShell* FindPresShellForDocument(const nsIDocument* aDoc);
2208
2209
  /**
2210
   * Returns the widget for this document if there is one. Looks at all ancestor
2211
   * documents to try to find a widget, so for example this can still find a
2212
   * widget for documents in display:none frames that have no presentation.
2213
   *
2214
   * You should probably use WidgetForContent() instead of this, unless you have
2215
   * a good reason to do otherwise.
2216
   */
2217
  static nsIWidget* WidgetForDocument(const nsIDocument* aDoc);
2218
2219
  /**
2220
   * Returns the appropriate widget for this element, if there is one. Unlike
2221
   * WidgetForDocument(), this returns the correct widget for content in popups.
2222
   *
2223
   * You should probably use this instead of WidgetForDocument().
2224
   */
2225
  static nsIWidget* WidgetForContent(const nsIContent* aContent);
2226
2227
  /**
2228
   * Returns a layer manager to use for the given document. Basically we
2229
   * look up the document hierarchy for the first document which has
2230
   * a presentation with an associated widget, and use that widget's
2231
   * layer manager.
2232
   *
2233
   * You should probably use LayerManagerForContent() instead of this, unless
2234
   * you have a good reason to do otherwise.
2235
   *
2236
   * @param aDoc the document for which to return a layer manager.
2237
   * @param aAllowRetaining an outparam that states whether the returned
2238
   * layer manager should be used for retained layers
2239
   */
2240
  static already_AddRefed<mozilla::layers::LayerManager>
2241
  LayerManagerForDocument(const nsIDocument *aDoc);
2242
2243
  /**
2244
   * Returns a layer manager to use for the given content. Unlike
2245
   * LayerManagerForDocument(), this returns the correct layer manager for
2246
   * content in popups.
2247
   *
2248
   * You should probably use this instead of LayerManagerForDocument().
2249
   */
2250
  static already_AddRefed<mozilla::layers::LayerManager>
2251
  LayerManagerForContent(const nsIContent *aContent);
2252
2253
  /**
2254
   * Returns a layer manager to use for the given document. Basically we
2255
   * look up the document hierarchy for the first document which has
2256
   * a presentation with an associated widget, and use that widget's
2257
   * layer manager. In addition to the normal layer manager lookup this will
2258
   * specifically request a persistent layer manager. This means that the layer
2259
   * manager is expected to remain the layer manager for the document in the
2260
   * forseeable future. This function should be used carefully as it may change
2261
   * the document's layer manager.
2262
   *
2263
   * @param aDoc the document for which to return a layer manager.
2264
   * @param aAllowRetaining an outparam that states whether the returned
2265
   * layer manager should be used for retained layers
2266
   */
2267
  static already_AddRefed<mozilla::layers::LayerManager>
2268
  PersistentLayerManagerForDocument(nsIDocument *aDoc);
2269
2270
  /**
2271
   * Determine whether a content node is focused or not,
2272
   *
2273
   * @param aContent the content node to check
2274
   * @return true if the content node is focused, false otherwise.
2275
   */
2276
  static bool IsFocusedContent(const nsIContent *aContent);
2277
2278
  /**
2279
   * Returns true if the DOM fullscreen API is enabled.
2280
   */
2281
  static bool IsFullscreenApiEnabled();
2282
2283
  /**
2284
   * Returns true if the unprefixed fullscreen API is enabled.
2285
   */
2286
  static bool IsUnprefixedFullscreenApiEnabled()
2287
0
    { return sIsUnprefixedFullscreenApiEnabled; }
2288
2289
  /**
2290
   * Returns true if requests for fullscreen are allowed in the current
2291
   * context. Requests are only allowed if the user initiated them (like with
2292
   * a mouse-click or key press), unless this check has been disabled by
2293
   * setting the pref "full-screen-api.allow-trusted-requests-only" to false.
2294
   */
2295
  static bool IsRequestFullscreenAllowed(mozilla::dom::CallerType aCallerType);
2296
2297
  /**
2298
   * Returns true if calling execCommand with 'cut' or 'copy' arguments
2299
   * is restricted to chrome code.
2300
   */
2301
  static bool IsCutCopyRestricted()
2302
0
  {
2303
0
    return !sIsCutCopyAllowed;
2304
0
  }
2305
2306
  /**
2307
   * Returns true if calling execCommand with 'cut' or 'copy' arguments is
2308
   * allowed for the given subject principal. These are only allowed if the user
2309
   * initiated them (like with a mouse-click or key press).
2310
   */
2311
  static bool IsCutCopyAllowed(nsIPrincipal* aSubjectPrincipal);
2312
2313
  /*
2314
   * Returns true if the performance timing APIs are enabled.
2315
   */
2316
  static bool IsPerformanceTimingEnabled()
2317
  {
2318
    return sIsPerformanceTimingEnabled;
2319
  }
2320
2321
  /*
2322
   * Returns true if the performance timing APIs are enabled.
2323
   */
2324
  static bool IsResourceTimingEnabled()
2325
0
  {
2326
0
    return sIsResourceTimingEnabled;
2327
0
  }
2328
2329
  /*
2330
   * Returns true if the performance timing APIs are enabled.
2331
   */
2332
  static bool IsPerformanceNavigationTimingEnabled()
2333
0
  {
2334
0
    return sIsPerformanceNavigationTimingEnabled;
2335
0
  }
2336
2337
  /*
2338
   * Returns true if notification should be sent for peformance timing events.
2339
   */
2340
  static bool SendPerformanceTimingNotifications()
2341
0
  {
2342
0
    return sSendPerformanceTimingNotifications;
2343
0
  }
2344
2345
  /*
2346
   * Returns true if the frame timing APIs are enabled.
2347
   */
2348
  static bool IsFrameTimingEnabled();
2349
2350
  /*
2351
   * Returns true if the browser should attempt to prevent the given caller type
2352
   * from collecting distinctive information about the browser that could
2353
   * be used to "fingerprint" and track the user across websites.
2354
   */
2355
  static bool ResistFingerprinting(mozilla::dom::CallerType aCallerType)
2356
0
  {
2357
0
    return aCallerType != mozilla::dom::CallerType::System &&
2358
0
           ShouldResistFingerprinting();
2359
0
  }
2360
2361
  /**
2362
   * Returns true if the browser should show busy cursor when loading page.
2363
   */
2364
  static bool UseActivityCursor()
2365
  {
2366
    return sUseActivityCursor;
2367
  }
2368
2369
  /**
2370
   * Returns true if the DOM Animations API should be enabled.
2371
   */
2372
  static bool AnimationsAPICoreEnabled()
2373
0
  {
2374
0
    return sAnimationsAPICoreEnabled;
2375
0
  }
2376
2377
  /**
2378
   * Returns true if the getBoxQuads API should be enabled.
2379
   */
2380
  static bool GetBoxQuadsEnabled()
2381
0
  {
2382
0
    return sGetBoxQuadsEnabled;
2383
0
  }
2384
2385
  /**
2386
   * Returns true if the requestIdleCallback API should be enabled.
2387
   */
2388
  static bool RequestIdleCallbackEnabled()
2389
0
  {
2390
0
    return sRequestIdleCallbackEnabled;
2391
0
  }
2392
2393
  /**
2394
   * Returns true if CSSOM origin check should be skipped for WebDriver
2395
   * based crawl to be able to collect data from cross-origin CSS style
2396
   * sheets. This can be enabled by setting environment variable
2397
   * MOZ_BYPASS_CSSOM_ORIGIN_CHECK.
2398
   */
2399
  static bool BypassCSSOMOriginCheck()
2400
  {
2401
#ifdef RELEASE_OR_BETA
2402
    return false;
2403
#else
2404
    return sBypassCSSOMOriginCheck;
2405
#endif
2406
  }
2407
2408
  /**
2409
   * Fire mutation events for changes caused by parsing directly into a
2410
   * context node.
2411
   *
2412
   * @param aDoc the document of the node
2413
   * @param aDest the destination node that got stuff appended to it
2414
   * @param aOldChildCount the number of children the node had before parsing
2415
   */
2416
  static void FireMutationEventsForDirectParsing(nsIDocument* aDoc,
2417
                                                 nsIContent* aDest,
2418
                                                 int32_t aOldChildCount);
2419
2420
  /**
2421
   * Returns true if the content is in a document and contains a plugin
2422
   * which we don't control event dispatch for, i.e. do any plugins in this
2423
   * doc tree receive key events outside of our control? This always returns
2424
   * false on MacOSX.
2425
   */
2426
  static bool HasPluginWithUncontrolledEventDispatch(nsIContent* aContent);
2427
2428
  /**
2429
   * Returns the root document in a document hierarchy. Normally this
2430
   * will be the chrome document.
2431
   */
2432
  static nsIDocument* GetRootDocument(nsIDocument* aDoc);
2433
2434
  /**
2435
   * Returns true if aWin and the current pointer lock document
2436
   * have common scriptable top window.
2437
   */
2438
  static bool IsInPointerLockContext(nsPIDOMWindowOuter* aWin);
2439
2440
  /**
2441
   * Returns the time limit on handling user input before
2442
   * EventStateManager::IsHandlingUserInput() stops returning true.
2443
   * This enables us to detect long running user-generated event handlers.
2444
   */
2445
  static TimeDuration HandlingUserInputTimeout();
2446
2447
  static void GetShiftText(nsAString& text);
2448
  static void GetControlText(nsAString& text);
2449
  static void GetMetaText(nsAString& text);
2450
  static void GetOSText(nsAString& text);
2451
  static void GetAltText(nsAString& text);
2452
  static void GetModifierSeparatorText(nsAString& text);
2453
2454
  /**
2455
   * Returns if aContent has a tabbable subdocument.
2456
   * A sub document isn't tabbable when it's a zombie document.
2457
   *
2458
   * @param aElement element to test.
2459
   *
2460
   * @return Whether the subdocument is tabbable.
2461
   */
2462
  static bool IsSubDocumentTabbable(nsIContent* aContent);
2463
2464
  /**
2465
   * Returns if aNode ignores user focus.
2466
   *
2467
   * @param aNode node to test
2468
   *
2469
   * @return Whether the node ignores user focus.
2470
   */
2471
  static bool IsUserFocusIgnored(nsINode* aNode);
2472
2473
  /**
2474
   * Returns if aContent has the 'scrollgrab' property.
2475
   * aContent may be null (in this case false is returned).
2476
   */
2477
  static bool HasScrollgrab(nsIContent* aContent);
2478
2479
  /**
2480
   * Flushes the layout tree (recursively)
2481
   *
2482
   * @param aWindow the window the flush should start at
2483
   *
2484
   */
2485
  static void FlushLayoutForTree(nsPIDOMWindowOuter* aWindow);
2486
2487
  /**
2488
   * Returns true if content with the given principal is allowed to use XUL
2489
   * and XBL and false otherwise.
2490
   */
2491
  static bool AllowXULXBLForPrincipal(nsIPrincipal* aPrincipal);
2492
2493
  /**
2494
   * Perform cleanup that's appropriate for XPCOM shutdown.
2495
   */
2496
  static void XPCOMShutdown();
2497
2498
  /**
2499
   * Checks if internal PDF viewer is enabled.
2500
   */
2501
  static bool IsPDFJSEnabled();
2502
2503
  /**
2504
   * Checks if internal SWF player is enabled.
2505
   */
2506
  static bool IsSWFPlayerEnabled();
2507
2508
  enum ContentViewerType
2509
  {
2510
      TYPE_UNSUPPORTED,
2511
      TYPE_CONTENT,
2512
      TYPE_PLUGIN,
2513
      TYPE_UNKNOWN
2514
  };
2515
2516
  static already_AddRefed<nsIDocumentLoaderFactory>
2517
  FindInternalContentViewer(const nsACString& aType,
2518
                            ContentViewerType* aLoaderType = nullptr);
2519
2520
  /**
2521
   * This helper method returns true if the aPattern pattern matches aValue.
2522
   * aPattern should not contain leading and trailing slashes (/).
2523
   * The pattern has to match the entire value not just a subset.
2524
   * aDocument must be a valid pointer (not null).
2525
   *
2526
   * This is following the HTML5 specification:
2527
   * http://dev.w3.org/html5/spec/forms.html#attr-input-pattern
2528
   *
2529
   * WARNING: This method mutates aPattern and aValue!
2530
   *
2531
   * @param aValue    the string to check.
2532
   * @param aPattern  the string defining the pattern.
2533
   * @param aDocument the owner document of the element.
2534
   * @result          whether the given string is matches the pattern.
2535
   */
2536
  static bool IsPatternMatching(nsAString& aValue, nsAString& aPattern,
2537
                                  nsIDocument* aDocument);
2538
2539
  /**
2540
   * Calling this adds support for
2541
   * ontouch* event handler DOM attributes.
2542
   */
2543
  static void InitializeTouchEventTable();
2544
2545
  /**
2546
   * Test whether the given URI always inherits a security context
2547
   * from the document it comes from.
2548
   */
2549
  static nsresult URIInheritsSecurityContext(nsIURI *aURI, bool *aResult);
2550
2551
  /**
2552
    * Called before a channel is created to query whether the new
2553
    * channel should inherit the principal.
2554
    *
2555
    * The argument aLoadingPrincipal must not be null. The argument
2556
    * aURI must be the URI of the new channel. If aInheritForAboutBlank
2557
    * is true, then about:blank will be told to inherit the principal.
2558
    * If aForceInherit is true, the new channel will be told to inherit
2559
    * the principal no matter what.
2560
    *
2561
    * The return value is whether the new channel should inherit
2562
    * the principal.
2563
    */
2564
  static bool ChannelShouldInheritPrincipal(nsIPrincipal* aLoadingPrincipal,
2565
                                            nsIURI* aURI,
2566
                                            bool aInheritForAboutBlank,
2567
                                            bool aForceInherit);
2568
2569
  static nsresult Btoa(const nsAString& aBinaryData,
2570
                       nsAString& aAsciiBase64String);
2571
2572
  static nsresult Atob(const nsAString& aAsciiString,
2573
                       nsAString& aBinaryData);
2574
2575
  /**
2576
   * Returns whether the input element passed in parameter has the autocomplete
2577
   * functionality enabled. It is taking into account the form owner.
2578
   * NOTE: the caller has to make sure autocomplete makes sense for the
2579
   * element's type.
2580
   *
2581
   * @param aInput the input element to check. NOTE: aInput can't be null.
2582
   * @return whether the input element has autocomplete enabled.
2583
   */
2584
  static bool IsAutocompleteEnabled(mozilla::dom::HTMLInputElement* aInput);
2585
2586
  enum AutocompleteAttrState : uint8_t
2587
  {
2588
    eAutocompleteAttrState_Unknown = 1,
2589
    eAutocompleteAttrState_Invalid,
2590
    eAutocompleteAttrState_Valid,
2591
  };
2592
  /**
2593
   * Parses the value of the autocomplete attribute into aResult, ensuring it's
2594
   * composed of valid tokens, otherwise the value "" is used.
2595
   * Note that this method is used for form fields, not on a <form> itself.
2596
   *
2597
   * @return whether aAttr was valid and can be cached.
2598
   */
2599
  static AutocompleteAttrState
2600
  SerializeAutocompleteAttribute(const nsAttrValue* aAttr,
2601
                                 nsAString& aResult,
2602
                                 AutocompleteAttrState aCachedState =
2603
                                   eAutocompleteAttrState_Unknown);
2604
2605
  /* Variation that is used to retrieve a dictionary of the parts of the
2606
   * autocomplete attribute.
2607
   *
2608
   * @return whether aAttr was valid and can be cached.
2609
   */
2610
  static AutocompleteAttrState
2611
  SerializeAutocompleteAttribute(const nsAttrValue* aAttr,
2612
                                 mozilla::dom::AutocompleteInfo& aInfo,
2613
                                 AutocompleteAttrState aCachedState =
2614
                                   eAutocompleteAttrState_Unknown,
2615
                                 bool aGrantAllValidValue = false);
2616
2617
  /**
2618
   * This will parse aSource, to extract the value of the pseudo attribute
2619
   * with the name specified in aName. See
2620
   * http://www.w3.org/TR/xml-stylesheet/#NT-StyleSheetPI for the specification
2621
   * which is used to parse aSource.
2622
   *
2623
   * @param aSource the string to parse
2624
   * @param aName the name of the attribute to get the value for
2625
   * @param aValue [out] the value for the attribute with name specified in
2626
   *                     aAttribute. Empty if the attribute isn't present.
2627
   * @return true     if the attribute exists and was successfully parsed.
2628
   *         false if the attribute doesn't exist, or has a malformed
2629
   *                  value, such as an unknown or unterminated entity.
2630
   */
2631
  static bool GetPseudoAttributeValue(const nsString& aSource, nsAtom *aName,
2632
                                      nsAString& aValue);
2633
2634
  /**
2635
   * Returns true if the language name is a version of JavaScript and
2636
   * false otherwise
2637
   */
2638
  static bool IsJavaScriptLanguage(const nsString& aName);
2639
2640
  static bool IsJavascriptMIMEType(const nsAString& aMIMEType);
2641
2642
  static void SplitMimeType(const nsAString& aValue, nsString& aType,
2643
                            nsString& aParams);
2644
2645
  /**
2646
   * Function checks if the user is idle.
2647
   *
2648
   * @param aRequestedIdleTimeInMS    The idle observer's requested idle time.
2649
   * @param aUserIsIdle               boolean indicating if the user
2650
   *                                  is currently idle or not.   *
2651
   * @return NS_OK                    NS_OK returned if the requested idle service and
2652
   *                                  the current idle time were successfully obtained.
2653
   *                                  NS_ERROR_FAILURE returned if the the requested
2654
   *                                  idle service or the current idle were not obtained.
2655
   */
2656
  static nsresult IsUserIdle(uint32_t aRequestedIdleTimeInMS, bool* aUserIsIdle);
2657
2658
  /**
2659
   * Takes a selection, and a text control element (<input> or <textarea>), and
2660
   * returns the offsets in the text content corresponding to the selection.
2661
   * The selection's anchor and focus must both be in the root node passed or a
2662
   * descendant.
2663
   *
2664
   * @param aSelection      Selection to check
2665
   * @param aRoot           Root <input> or <textarea> element
2666
   * @param aOutStartOffset Output start offset
2667
   * @param aOutEndOffset   Output end offset
2668
   */
2669
  static void GetSelectionInTextControl(mozilla::dom::Selection* aSelection,
2670
                                        Element* aRoot,
2671
                                        uint32_t& aOutStartOffset,
2672
                                        uint32_t& aOutEndOffset);
2673
2674
  /**
2675
   * Takes a frame for anonymous content within a text control (<input> or
2676
   * <textarea>), and returns an offset in the text content, adjusted for a
2677
   * trailing <br> frame.
2678
   *
2679
   * @param aOffsetFrame      Frame for the text content in which the offset
2680
   *                          lies
2681
   * @param aOffset           Offset as calculated by GetContentOffsetsFromPoint
2682
   * @param aOutOffset        Output adjusted offset
2683
   *
2684
   * @see GetSelectionInTextControl for the original basis of this function.
2685
   */
2686
  static int32_t GetAdjustedOffsetInTextControl(nsIFrame* aOffsetFrame,
2687
                                                int32_t aOffset);
2688
2689
  /**
2690
   * Returns pointer to HTML editor instance for the aPresContext when there is.
2691
   * The HTML editor is shared by contenteditable elements or used in
2692
   * designMode.  When there are no contenteditable elements and the document
2693
   * is not in designMode, this returns nullptr.
2694
   */
2695
  static mozilla::HTMLEditor* GetHTMLEditor(nsPresContext* aPresContext);
2696
2697
  /**
2698
   * Returns true if the privacy.donottrackheader.enabled pref is set.
2699
   */
2700
  static bool DoNotTrackEnabled();
2701
2702
  /**
2703
   * Returns a LogModule that dump calls from content script are logged to.
2704
   * This can be enabled with the 'Dump' module, and is useful for synchronizing
2705
   * content JS to other logging modules.
2706
   */
2707
  static mozilla::LogModule* DOMDumpLog();
2708
2709
  /**
2710
   * Returns whether a given header is forbidden for an XHR or fetch
2711
   * request.
2712
   */
2713
  static bool IsForbiddenRequestHeader(const nsACString& aHeader);
2714
2715
  /**
2716
   * Returns whether a given header is forbidden for a system XHR
2717
   * request.
2718
   */
2719
  static bool IsForbiddenSystemRequestHeader(const nsACString& aHeader);
2720
2721
  /**
2722
   * Returns whether a given Content-Type header value is allowed
2723
   * for a non-CORS XHR or fetch request.
2724
   */
2725
  static bool IsAllowedNonCorsContentType(const nsACString& aHeaderValue);
2726
2727
  /**
2728
   * Returns whether a given header is forbidden for an XHR or fetch
2729
   * response.
2730
   */
2731
  static bool IsForbiddenResponseHeader(const nsACString& aHeader);
2732
2733
  /**
2734
   * Returns the inner window ID for the window associated with a request.
2735
   */
2736
  static uint64_t GetInnerWindowID(nsIRequest* aRequest);
2737
2738
  /**
2739
   * Returns the inner window ID for the window associated with a load group.
2740
   */
2741
  static uint64_t GetInnerWindowID(nsILoadGroup* aLoadGroup);
2742
2743
  /**
2744
   * If the hostname for aURI is an IPv6 it encloses it in brackets,
2745
   * otherwise it just outputs the hostname in aHost.
2746
   */
2747
  static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsAString& aHost);
2748
  static nsresult GetHostOrIPv6WithBrackets(nsIURI* aURI, nsCString& aHost);
2749
2750
  /*
2751
   * Call the given callback on all remote children of the given top-level
2752
   * window. Return true from the callback to stop calling further children.
2753
   */
2754
  static void CallOnAllRemoteChildren(nsPIDOMWindowOuter* aWindow,
2755
                                      CallOnRemoteChildFunction aCallback,
2756
                                      void* aArg);
2757
2758
  /*
2759
   * Call nsPIDOMWindow::SetKeyboardIndicators all all remote children. This is
2760
   * in here rather than nsGlobalWindow because TabParent indirectly includes
2761
   * Windows headers which aren't allowed there.
2762
   */
2763
  static void SetKeyboardIndicatorsOnRemoteChildren(nsPIDOMWindowOuter* aWindow,
2764
                                                    UIStateChangeType aShowAccelerators,
2765
                                                    UIStateChangeType aShowFocusRings);
2766
2767
  /**
2768
   * Given an nsIFile, attempts to read it into aString.
2769
   *
2770
   * Note: Use sparingly! This causes main-thread I/O, which causes jank and all
2771
   * other bad things.
2772
   */
2773
  static nsresult SlurpFileToString(nsIFile* aFile, nsACString& aString);
2774
2775
  /**
2776
   * Returns true if the mime service thinks this file contains an image.
2777
   *
2778
   * The content type is returned in aType.
2779
   */
2780
  static bool IsFileImage(nsIFile* aFile, nsACString& aType);
2781
2782
  /**
2783
   * Given an IPCDataTransferItem that has a flavor for which IsFlavorImage
2784
   * returns true and whose IPCDataTransferData is of type nsCString (raw image
2785
   * data), construct an imgIContainer for the image encoded by the transfer
2786
   * item.
2787
   */
2788
  static nsresult DataTransferItemToImage(const mozilla::dom::IPCDataTransferItem& aItem,
2789
                                          imgIContainer** aContainer);
2790
2791
  /**
2792
   * Given a flavor obtained from an IPCDataTransferItem or nsITransferable,
2793
   * returns true if we should treat the data as an image.
2794
   */
2795
  static bool IsFlavorImage(const nsACString& aFlavor);
2796
2797
  static nsresult IPCTransferableToTransferable(const mozilla::dom::IPCDataTransfer& aDataTransfer,
2798
                                                const bool& aIsPrivateData,
2799
                                                nsIPrincipal* aRequestingPrincipal,
2800
                                                const nsContentPolicyType& aContentPolicyType,
2801
                                                nsITransferable* aTransferable,
2802
                                                mozilla::dom::nsIContentParent* aContentParent,
2803
                                                mozilla::dom::TabChild* aTabChild);
2804
2805
  static void TransferablesToIPCTransferables(nsIArray* aTransferables,
2806
                                              nsTArray<mozilla::dom::IPCDataTransfer>& aIPC,
2807
                                              bool aInSyncMessage,
2808
                                              mozilla::dom::nsIContentChild* aChild,
2809
                                              mozilla::dom::nsIContentParent* aParent);
2810
2811
  static void TransferableToIPCTransferable(nsITransferable* aTransferable,
2812
                                            mozilla::dom::IPCDataTransfer* aIPCDataTransfer,
2813
                                            bool aInSyncMessage,
2814
                                            mozilla::dom::nsIContentChild* aChild,
2815
                                            mozilla::dom::nsIContentParent* aParent);
2816
2817
  /*
2818
   * Get the pixel data from the given source surface and return it as a buffer.
2819
   * The length and stride will be assigned from the surface.
2820
   */
2821
  static mozilla::UniquePtr<char[]> GetSurfaceData(
2822
    mozilla::NotNull<mozilla::gfx::DataSourceSurface*> aSurface,
2823
    size_t* aLength, int32_t* aStride);
2824
2825
  /*
2826
   * Get the pixel data from the given source surface and fill it in Shmem.
2827
   * The length and stride will be assigned from the surface.
2828
   */
2829
  static mozilla::Maybe<mozilla::ipc::Shmem>
2830
  GetSurfaceData(mozilla::gfx::DataSourceSurface* aSurface,
2831
                 size_t* aLength, int32_t* aStride,
2832
                 mozilla::ipc::IShmemAllocator* aAlloc);
2833
2834
  // Helpers shared by the implementations of nsContentUtils methods and
2835
  // nsIDOMWindowUtils methods.
2836
  static mozilla::Modifiers GetWidgetModifiers(int32_t aModifiers);
2837
  static nsIWidget* GetWidget(nsIPresShell* aPresShell, nsPoint* aOffset);
2838
  static int16_t GetButtonsFlagForButton(int32_t aButton);
2839
  static mozilla::LayoutDeviceIntPoint ToWidgetPoint(const mozilla::CSSPoint& aPoint,
2840
                                                     const nsPoint& aOffset,
2841
                                                     nsPresContext* aPresContext);
2842
  static nsView* GetViewToDispatchEvent(nsPresContext* aPresContext,
2843
                                        nsIPresShell** aPresShell);
2844
2845
  /**
2846
   * Synthesize a mouse event to the given widget
2847
   * (see nsIDOMWindowUtils.sendMouseEvent).
2848
   */
2849
  MOZ_CAN_RUN_SCRIPT
2850
  static nsresult SendMouseEvent(const nsCOMPtr<nsIPresShell>& aPresShell,
2851
                                 const nsAString& aType,
2852
                                 float aX,
2853
                                 float aY,
2854
                                 int32_t aButton,
2855
                                 int32_t aButtons,
2856
                                 int32_t aClickCount,
2857
                                 int32_t aModifiers,
2858
                                 bool aIgnoreRootScrollFrame,
2859
                                 float aPressure,
2860
                                 unsigned short aInputSourceArg,
2861
                                 uint32_t aIdentifier,
2862
                                 bool aToWindow,
2863
                                 bool *aPreventDefault,
2864
                                 bool aIsDOMEventSynthesized,
2865
                                 bool aIsWidgetEventSynthesized);
2866
2867
  static void FirePageShowEvent(nsIDocShellTreeItem* aItem,
2868
                                mozilla::dom::EventTarget* aChromeEventHandler,
2869
                                bool aFireIfShowing,
2870
                                bool aOnlySystemGroup = false);
2871
2872
  static void FirePageHideEvent(nsIDocShellTreeItem* aItem,
2873
                                mozilla::dom::EventTarget* aChromeEventHandler,
2874
                                bool aOnlySystemGroup = false);
2875
2876
  static already_AddRefed<nsPIWindowRoot> GetWindowRoot(nsIDocument* aDoc);
2877
2878
  /*
2879
   * Implements step 3.1 and 3.3 of the Determine request's Referrer algorithm
2880
   * from the Referrer Policy specification.
2881
   *
2882
   * The referrer policy of the document is applied by Necko when using
2883
   * channels.
2884
   *
2885
   * For documents representing an iframe srcdoc attribute, the document sets
2886
   * its own URI correctly, so this method simply uses the document's original
2887
   * or current URI as appropriate.
2888
   *
2889
   * aDoc may be null.
2890
   *
2891
   * https://w3c.github.io/webappsec/specs/referrer-policy/#determine-requests-referrer
2892
   */
2893
  static nsresult SetFetchReferrerURIWithPolicy(nsIPrincipal* aPrincipal,
2894
                                                nsIDocument* aDoc,
2895
                                                nsIHttpChannel* aChannel,
2896
                                                mozilla::net::ReferrerPolicy aReferrerPolicy);
2897
2898
  /*
2899
   * If there is a Referrer-Policy response header in |aChannel|, parse a
2900
   * referrer policy from the header.
2901
   *
2902
   * @param the channel from which to get the Referrer-Policy header
2903
   * @return referrer policy from the response header in aChannel
2904
   */
2905
  static mozilla::net::ReferrerPolicy
2906
    GetReferrerPolicyFromChannel(nsIChannel* aChannel);
2907
2908
  /*
2909
   * Parse a referrer policy from a Referrer-Policy header
2910
   * https://www.w3.org/TR/referrer-policy/#parse-referrer-policy-from-header
2911
   *
2912
   * @param aHeader the response's Referrer-Policy header to parse
2913
   * @return referrer policy from the response header.
2914
   */
2915
  static mozilla::net::ReferrerPolicy GetReferrerPolicyFromHeader(const nsAString& aHeader);
2916
2917
  static bool IsNonSubresourceRequest(nsIChannel* aChannel);
2918
2919
  static bool IsNonSubresourceInternalPolicyType(nsContentPolicyType aType);
2920
2921
  // The order of these entries matters, as we use std::min for total ordering
2922
  // of permissions. Private Browsing is considered to be more limiting
2923
  // then session scoping
2924
  enum class StorageAccess {
2925
    // Don't allow access to the storage
2926
    eDeny = 0,
2927
    // Allow access to the storage, but only if it is secure to do so in a
2928
    // private browsing context.
2929
    ePrivateBrowsing = 1,
2930
    // Allow access to the storage, but only persist it for the current session
2931
    eSessionScoped = 2,
2932
    // Allow access to the storage
2933
    eAllow = 3,
2934
    // Keep this at the end.  Used for serialization, but not a valid value.
2935
    eNumValues = 4,
2936
  };
2937
2938
  /*
2939
   * Checks if storage for the given window is permitted by a combination of
2940
   * the user's preferences, and whether the window is a third-party iframe.
2941
   *
2942
   * This logic is intended to be shared between the different forms of
2943
   * persistent storage which are available to web pages. Cookies don't use
2944
   * this logic, and security logic related to them must be updated separately.
2945
   */
2946
  static StorageAccess StorageAllowedForWindow(nsPIDOMWindowInner* aWindow);
2947
2948
  /*
2949
   * Checks if storage for the given document is permitted by a combination of
2950
   * the user's preferences, and whether the document's window is a third-party
2951
   * iframe.
2952
   *
2953
   * Note, this may be used on documents during the loading process where
2954
   * the window's extant document has not been set yet.  The code in
2955
   * StorageAllowedForWindow(), however, will not work in these cases.
2956
   */
2957
  static StorageAccess StorageAllowedForDocument(nsIDocument* aDoc);
2958
2959
  /*
2960
   * Checks if storage should be allowed for a new window with the given
2961
   * principal, load URI, and parent.
2962
   */
2963
  static StorageAccess StorageAllowedForNewWindow(nsIPrincipal* aPrincipal,
2964
                                                  nsIURI* aURI,
2965
                                                  nsPIDOMWindowInner* aParent);
2966
2967
  /*
2968
   * Checks if storage should be allowed for the given channel.  The check will
2969
   * be based on the channel result principal and, depending on preferences and
2970
   * permissions, mozIThirdPartyUtil.isThirdPartyChannel().
2971
   */
2972
  static StorageAccess StorageAllowedForChannel(nsIChannel* aChannel);
2973
2974
  /*
2975
   * Checks if storage for the given principal is permitted by the user's
2976
   * preferences. The caller is assumed to not be a third-party iframe.
2977
   * (if that is possible, the caller should use StorageAllowedForWindow)
2978
   */
2979
  static StorageAccess StorageAllowedForPrincipal(nsIPrincipal* aPrincipal);
2980
2981
  /*
2982
   * Returns true if this document should disable storages because of the anti-tracking feature.
2983
   */
2984
  static bool StorageDisabledByAntiTracking(nsIDocument* aDocument,
2985
                                            nsIURI* aURI)
2986
0
  {
2987
0
    // Note that GetChannel() below may return null, but that's OK, since the callee
2988
0
    // is able to deal with a null channel argument, and if passed null, will only fail
2989
0
    // to notify the UI in case storage gets blocked.
2990
0
    return StorageDisabledByAntiTracking(aDocument->GetInnerWindow(),
2991
0
                                         aDocument->GetChannel(),
2992
0
                                         aDocument->NodePrincipal(),
2993
0
                                         aURI);
2994
0
  }
2995
2996
private:
2997
  /*
2998
   * Returns true if this window/channel/aPrincipal should disable storages
2999
   * because of the anti-tracking feature.
3000
   * Note that either aWindow or aChannel may be null when calling this function.
3001
   * If the caller wants the UI to be notified when the storage gets disabled,
3002
   * it must pass a non-null channel object.
3003
   */
3004
  static bool StorageDisabledByAntiTracking(nsPIDOMWindowInner* aWindow,
3005
                                            nsIChannel* aChannel,
3006
                                            nsIPrincipal* aPrincipal,
3007
                                            nsIURI* aURI);
3008
3009
public:
3010
  /*
3011
   * Returns true if this window/channel is a 3rd party context.
3012
   */
3013
  static bool IsThirdPartyWindowOrChannel(nsPIDOMWindowInner* aWindow,
3014
                                          nsIChannel* aChannel,
3015
                                          nsIURI* aURI);
3016
3017
  /*
3018
   * Returns true if this window's channel has been marked as a tracking
3019
   * resource.
3020
   */
3021
  static bool IsTrackingResourceWindow(nsPIDOMWindowInner* aWindow);
3022
3023
  /*
3024
   * Serializes a HTML nsINode into its markup representation.
3025
   */
3026
  static bool SerializeNodeToMarkup(nsINode* aRoot,
3027
                                    bool aDescendentsOnly,
3028
                                    nsAString& aOut);
3029
3030
  /*
3031
   * Returns true iff the provided JSObject is a global, and its URI matches
3032
   * the provided about: URI.
3033
   * @param aGlobal the JSObject whose URI to check, if it is a global.
3034
   * @param aUri the URI to match, e.g. "about:feeds"
3035
   */
3036
  static bool IsSpecificAboutPage(JSObject* aGlobal, const char* aUri);
3037
3038
  static void SetScrollbarsVisibility(nsIDocShell* aDocShell, bool aVisible);
3039
3040
  /*
3041
   * Return the associated presentation URL of the presented content.
3042
   * Will return empty string if the docshell is not in a presented content.
3043
   */
3044
  static void GetPresentationURL(nsIDocShell* aDocShell, nsAString& aPresentationUrl);
3045
3046
  /*
3047
   * Try to find the docshell corresponding to the given event target.
3048
   */
3049
  static nsIDocShell* GetDocShellForEventTarget(mozilla::dom::EventTarget* aTarget);
3050
3051
  /**
3052
   * Returns true if the "HTTPS state" of the document should be "modern". See:
3053
   *
3054
   * https://html.spec.whatwg.org/#concept-document-https-state
3055
   * https://fetch.spec.whatwg.org/#concept-response-https-state
3056
   */
3057
  static bool HttpsStateIsModern(nsIDocument* aDocument);
3058
3059
  /**
3060
   * Try to upgrade an element.
3061
   * https://html.spec.whatwg.org/multipage/custom-elements.html#concept-try-upgrade
3062
   */
3063
  static void TryToUpgradeElement(Element* aElement);
3064
3065
  /**
3066
   * Creates a new XUL or XHTML element applying any appropriate custom element
3067
   * definition.
3068
   */
3069
  static nsresult NewXULOrHTMLElement(Element** aResult, mozilla::dom::NodeInfo* aNodeInfo,
3070
                                      mozilla::dom::FromParser aFromParser, nsAtom* aIsAtom,
3071
                                      mozilla::dom::CustomElementDefinition* aDefinition);
3072
3073
  static mozilla::dom::CustomElementRegistry*
3074
    GetCustomElementRegistry(nsIDocument*);
3075
3076
  /**
3077
   * Looking up a custom element definition.
3078
   * https://html.spec.whatwg.org/#look-up-a-custom-element-definition
3079
   */
3080
  static mozilla::dom::CustomElementDefinition*
3081
    LookupCustomElementDefinition(nsIDocument* aDoc,
3082
                                  nsAtom* aNameAtom,
3083
                                  uint32_t aNameSpaceID,
3084
                                  nsAtom* aTypeAtom);
3085
3086
  static void RegisterCallbackUpgradeElement(Element* aElement,
3087
                                             nsAtom* aTypeName);
3088
3089
  static void RegisterUnresolvedElement(Element* aElement, nsAtom* aTypeName);
3090
  static void UnregisterUnresolvedElement(Element* aElement);
3091
3092
  static void EnqueueUpgradeReaction(Element* aElement,
3093
                                     mozilla::dom::CustomElementDefinition* aDefinition);
3094
3095
  static void EnqueueLifecycleCallback(nsIDocument::ElementCallbackType aType,
3096
                                       Element* aCustomElement,
3097
                                       mozilla::dom::LifecycleCallbackArgs* aArgs = nullptr,
3098
                                       mozilla::dom::LifecycleAdoptedCallbackArgs* aAdoptedCallbackArgs = nullptr,
3099
                                       mozilla::dom::CustomElementDefinition* aDefinition = nullptr);
3100
3101
  static bool AttemptLargeAllocationLoad(nsIHttpChannel* aChannel);
3102
3103
  /**
3104
   * Appends all "document level" native anonymous content subtree roots for
3105
   * aDocument to aElements.  Document level NAC subtrees are those created
3106
   * by ancestor frames of the document element's primary frame, such as
3107
   * the scrollbar elements created by the root scroll frame.
3108
   */
3109
  static void AppendDocumentLevelNativeAnonymousContentTo(
3110
      nsIDocument* aDocument,
3111
      nsTArray<nsIContent*>& aElements);
3112
3113
  /**
3114
   * Appends all native anonymous content subtree roots generated by `aContent`
3115
   * to `aKids`.
3116
   *
3117
   * See `AllChildrenIterator` for the description of the `aFlags` parameter.
3118
   */
3119
  static void AppendNativeAnonymousChildren(const nsIContent* aContent,
3120
                                            nsTArray<nsIContent*>& aKids,
3121
                                            uint32_t aFlags);
3122
3123
  /**
3124
   * Query triggeringPrincipal if there's a 'triggeringprincipal' attribute on
3125
   * aLoadingNode, if no such attribute is specified, aDefaultPrincipal is
3126
   * returned if it is provided, otherwise the NodePrincipal of aLoadingNode is
3127
   * returned.
3128
   *
3129
   * Return true if aLoadingNode has a 'triggeringprincipal' attribute, and
3130
   * the value 'triggeringprincipal' is also successfully deserialized, otherwise
3131
   * return false.
3132
   */
3133
  static bool
3134
  QueryTriggeringPrincipal(nsIContent* aLoadingNode,
3135
                           nsIPrincipal* aDefaultPrincipal,
3136
                           nsIPrincipal** aTriggeringPrincipal);
3137
3138
  static bool
3139
  QueryTriggeringPrincipal(nsIContent* aLoadingNode,
3140
                           nsIPrincipal** aTriggeringPrincipal)
3141
0
  {
3142
0
    return QueryTriggeringPrincipal(aLoadingNode, nullptr, aTriggeringPrincipal);
3143
0
  }
3144
3145
  /**
3146
   * Returns the content policy type that should be used for loading images
3147
   * for displaying in the UI.  The sources of such images can be <xul:image>,
3148
   * <xul:menuitem> on OSX where we load the image through nsMenuItemIconX, etc.
3149
   */
3150
  static void
3151
  GetContentPolicyTypeForUIImageLoading(nsIContent* aLoadingNode,
3152
                                        nsIPrincipal** aTriggeringPrincipal,
3153
                                        nsContentPolicyType& aContentPolicyType,
3154
                                        uint64_t* aRequestContextID);
3155
3156
  static nsresult
3157
  CreateJSValueFromSequenceOfObject(JSContext* aCx,
3158
                                    const mozilla::dom::Sequence<JSObject*>& aTransfer,
3159
                                    JS::MutableHandle<JS::Value> aValue);
3160
3161
  /**
3162
   * Returns whether or not UA Widget is enabled, controlled by pref
3163
   * dom.ua_widget.enabled.
3164
   *
3165
   * When enabled, UA Widget will replace legacy XBL when rendering JS-implemented
3166
   * web content widgets (videocontrols/datetimebox/etc.)
3167
   *
3168
   * It is really enabled only if Shadow DOM is also enabled.
3169
   */
3170
  static bool
3171
0
  IsUAWidgetEnabled() { return sIsShadowDOMEnabled && sIsUAWidgetEnabled; }
3172
3173
  static bool
3174
0
  IsShadowDOMEnabled() { return sIsShadowDOMEnabled; }
3175
3176
  /**
3177
   * Returns true if reserved key events should be prevented from being sent
3178
   * to their target. Instead, the key event should be handled by chrome only.
3179
   */
3180
  static bool ShouldBlockReservedKeys(mozilla::WidgetKeyboardEvent* aKeyEvent);
3181
3182
  /**
3183
   * Returns the nsIPluginTag for the plugin we should try to use for a given
3184
   * MIME type.
3185
   *
3186
   * @param aMIMEType  The MIME type of the document being loaded.
3187
   * @param aNoFakePlugin  If false then this method should consider JS plugins.
3188
   */
3189
  static already_AddRefed<nsIPluginTag>
3190
    PluginTagForType(const nsCString& aMIMEType, bool aNoFakePlugin);
3191
3192
  /**
3193
   * Returns one of the nsIObjectLoadingContent::TYPE_ values describing the
3194
   * content type which will be used for the given MIME type when loaded within
3195
   * an nsObjectLoadingContent.
3196
   *
3197
   * NOTE: This method doesn't take capabilities into account. The caller must
3198
   * take that into account.
3199
   *
3200
   * @param aMIMEType  The MIME type of the document being loaded.
3201
   * @param aNoFakePlugin  If false then this method should consider JS plugins.
3202
   * @param aContent The nsIContent object which is performing the load. May be
3203
   *                 nullptr in which case the docshell's plugin permissions
3204
   *                 will not be checked.
3205
   */
3206
  static uint32_t
3207
  HtmlObjectContentTypeForMIMEType(const nsCString& aMIMEType,
3208
                                   bool aNoFakePlugin,
3209
                                   nsIContent* aContent);
3210
3211
  static already_AddRefed<nsISerialEventTarget>
3212
  GetEventTargetByLoadInfo(nsILoadInfo* aLoadInfo, mozilla::TaskCategory aCategory);
3213
3214
  /**
3215
   * Detect whether a string is a local-url.
3216
   * https://drafts.csswg.org/css-values/#local-urls
3217
   */
3218
  static bool
3219
  IsLocalRefURL(const nsString& aString);
3220
3221
  /**
3222
   * Detect whether a string is a local-url.
3223
   * https://drafts.csswg.org/css-values/#local-urls
3224
   */
3225
  static bool
3226
  IsLocalRefURL(const nsACString& aString);
3227
3228
  static bool
3229
  IsCustomElementsEnabled() { return sIsCustomElementsEnabled; }
3230
3231
  /**
3232
   * Compose a tab id with process id and a serial number.
3233
   */
3234
  static uint64_t GenerateTabId();
3235
3236
  /**
3237
   * Generate an id for a BrowsingContext using a range of serial
3238
   * numbers reserved for the current process.
3239
   */
3240
  static uint64_t GenerateBrowsingContextId();
3241
3242
  /**
3243
   * Check whether we should skip moving the cursor for a same-value .value set
3244
   * on a text input or textarea.
3245
   */
3246
  static bool
3247
0
  SkipCursorMoveForSameValueSet() { return sSkipCursorMoveForSameValueSet; }
3248
3249
  /**
3250
   * Determine whether or not the user is currently interacting with the web
3251
   * browser. This method is safe to call from off of the main thread.
3252
   */
3253
  static bool
3254
  GetUserIsInteracting();
3255
3256
  // Check pref "privacy.trackingprotection.lower_network_priority" to see
3257
  // if we want to lower the priority of the channel.
3258
0
  static bool IsLowerNetworkPriority() { return sLowerNetworkPriority; }
3259
3260
  // Whether tracker tailing is turned on - "network.http.tailing.enabled".
3261
0
  static bool IsTailingEnabled() { return sTailingEnabled; }
3262
3263
  // Check pref "dom.placeholder.show_on_focus" to see
3264
  // if we want to show the placeholder inside input elements
3265
  // when they have focus.
3266
0
  static bool ShowInputPlaceholderOnFocus() { return sShowInputPlaceholderOnFocus; }
3267
3268
  // Check pref "browser.autofocus" to see if we want to enable autofocusing elements
3269
  // when the page requests it.
3270
0
  static bool AutoFocusEnabled() { return sAutoFocusEnabled; }
3271
3272
  // Check pref "dom.script_loader.bytecode_cache.enabled" to see
3273
  // if we want to cache JS bytecode on the cache entry.
3274
0
  static bool IsBytecodeCacheEnabled() { return sIsBytecodeCacheEnabled; }
3275
3276
  // Check pref "dom.script_loader.bytecode_cache.strategy" to see which
3277
  // heuristic strategy should be used to trigger the caching of the bytecode.
3278
0
  static int32_t BytecodeCacheStrategy() { return sBytecodeCacheStrategy; }
3279
3280
  // Alternate data MIME type used by the ScriptLoader to register and read
3281
  // bytecode out of the nsCacheInfoChannel.
3282
0
  static nsCString& JSBytecodeMimeType() { return *sJSBytecodeMimeType; }
3283
3284
  /**
3285
   * Checks if the passed-in name should override an existing name on the
3286
   * window. Values which should not override include: "", "_blank", "_top",
3287
   * "_parent" and "_self".
3288
   */
3289
  static bool IsOverridingWindowName(const nsAString& aName);
3290
3291
  /**
3292
   * If there is a SourceMap (higher precedence) or X-SourceMap (lower
3293
   * precedence) response header in |aChannel|, set |aResult| to the
3294
   * header's value and return true.  Otherwise, return false.
3295
   *
3296
   * @param aChannel The HTTP channel
3297
   * @param aResult The string result.
3298
   */
3299
  static bool GetSourceMapURL(nsIHttpChannel* aChannel, nsACString& aResult);
3300
3301
  /**
3302
   * Returns true if the passed-in mesasge is a pending InputEvent.
3303
   *
3304
   * @param aMsg  The message to check
3305
   */
3306
  static bool IsMessageInputEvent(const IPC::Message& aMsg);
3307
3308
  static void AsyncPrecreateStringBundles();
3309
3310
  static bool ContentIsLink(nsIContent* aContent);
3311
3312
  static already_AddRefed<mozilla::dom::ContentFrameMessageManager>
3313
  TryGetTabChildGlobal(nsISupports* aFrom);
3314
3315
  static PopupControlState
3316
  PushPopupControlState(PopupControlState aState, bool aForce)
3317
0
  {
3318
0
    MOZ_ASSERT(NS_IsMainThread());
3319
0
    PopupControlState old = sPopupControlState;
3320
0
    if (aState < old || aForce) {
3321
0
      sPopupControlState = aState;
3322
0
    }
3323
0
    return old;
3324
0
  }
3325
3326
  static void
3327
  PopPopupControlState(PopupControlState aState)
3328
0
  {
3329
0
    MOZ_ASSERT(NS_IsMainThread());
3330
0
    sPopupControlState = aState;
3331
0
  }
3332
3333
0
  static PopupControlState GetPopupControlState() { return sPopupControlState; }
3334
3335
  // Get a serial number for a newly created inner or outer window.
3336
  static uint32_t InnerOrOuterWindowCreated();
3337
  // Record that an inner or outer window has been destroyed.
3338
  static void InnerOrOuterWindowDestroyed();
3339
  // Get the current number of inner or outer windows.
3340
0
  static int32_t GetCurrentInnerOrOuterWindowCount() { return sInnerOrOuterWindowCount; }
3341
3342
  static bool CanShowPopup(nsIPrincipal* aPrincipal);
3343
3344
  /**
3345
   * Serializes a JSON-like JS::Value into a string.
3346
   *
3347
   * Usage:
3348
   *   nsAutoString serializedValue;
3349
   *   nsContentUtils::StringifyJSON(cx, &value, serializedValue);
3350
   */
3351
  static bool StringifyJSON(JSContext* aCx, JS::MutableHandle<JS::Value> vp, nsAString& aOutStr);
3352
3353
private:
3354
  static bool InitializeEventTable();
3355
3356
  static nsresult EnsureStringBundle(PropertiesFile aFile);
3357
3358
  static bool CanCallerAccess(nsIPrincipal* aSubjectPrincipal,
3359
                                nsIPrincipal* aPrincipal);
3360
3361
  static nsresult WrapNative(JSContext *cx, nsISupports *native,
3362
                             nsWrapperCache *cache, const nsIID* aIID,
3363
                             JS::MutableHandle<JS::Value> vp,
3364
                             bool aAllowWrapping);
3365
3366
  static nsresult DispatchEvent(nsIDocument* aDoc,
3367
                                nsISupports* aTarget,
3368
                                const nsAString& aEventName,
3369
                                CanBubble,
3370
                                Cancelable,
3371
                                Composed,
3372
                                Trusted,
3373
                                bool* aDefaultAction = nullptr,
3374
                                ChromeOnlyDispatch = ChromeOnlyDispatch::eNo);
3375
3376
  static nsresult DispatchEvent(nsIDocument* aDoc,
3377
                                nsISupports* aTarget,
3378
                                mozilla::WidgetEvent& aWidgetEvent,
3379
                                EventMessage aEventMessage,
3380
                                CanBubble,
3381
                                Cancelable,
3382
                                Trusted,
3383
                                bool* aDefaultAction = nullptr,
3384
                                ChromeOnlyDispatch = ChromeOnlyDispatch::eNo);
3385
3386
  static void InitializeModifierStrings();
3387
3388
  static void DropFragmentParsers();
3389
3390
  static bool MatchClassNames(mozilla::dom::Element* aElement,
3391
                              int32_t aNamespaceID,
3392
                              nsAtom* aAtom, void* aData);
3393
  static void DestroyClassNameArray(void* aData);
3394
  static void* AllocClassMatchingInfo(nsINode* aRootNode,
3395
                                      const nsString* aClasses);
3396
3397
  static mozilla::EventClassID
3398
  GetEventClassIDFromMessage(EventMessage aEventMessage);
3399
3400
  // Fills in aInfo with the tokens from the supplied autocomplete attribute.
3401
  static AutocompleteAttrState InternalSerializeAutocompleteAttribute(const nsAttrValue* aAttrVal,
3402
                                                                      mozilla::dom::AutocompleteInfo& aInfo,
3403
                                                                      bool aGrantAllValidValue = false);
3404
3405
  static bool CallOnAllRemoteChildren(mozilla::dom::MessageBroadcaster* aManager,
3406
                                      CallOnRemoteChildFunction aCallback,
3407
                                      void* aArg);
3408
3409
  /**
3410
   * Gets the current cookie lifetime policy for a given principal by checking
3411
   * with preferences and the permission manager.
3412
   *
3413
   * Used in the implementation of InternalStorageAllowedForPrincipal.
3414
   */
3415
  static void GetCookieLifetimePolicyForPrincipal(nsIPrincipal* aPrincipal,
3416
                                                  uint32_t* aLifetimePolicy);
3417
3418
  /*
3419
   * Checks if storage for a given principal is permitted by the user's
3420
   * preferences. If aWindow is non-null, its principal must be passed as
3421
   * aPrincipal, and the third-party iframe and sandboxing status of the window
3422
   * are also checked.  If aURI is non-null, then it is used as the comparison
3423
   * against aWindow to determine if this is a third-party load.  We also
3424
   * allow a channel instead of the window reference when determining 3rd party
3425
   * status.
3426
   *
3427
   * Used in the implementation of StorageAllowedForWindow and
3428
   * StorageAllowedForPrincipal.
3429
   */
3430
  static StorageAccess InternalStorageAllowedForPrincipal(nsIPrincipal* aPrincipal,
3431
                                                          nsPIDOMWindowInner* aWindow,
3432
                                                          nsIURI* aURI,
3433
                                                          nsIChannel* aChannel);
3434
3435
  static nsINode* GetCommonAncestorHelper(nsINode* aNode1, nsINode* aNode2);
3436
  static nsIContent* GetCommonFlattenedTreeAncestorHelper(nsIContent* aContent1,
3437
                                                          nsIContent* aContent2);
3438
3439
  static nsIXPConnect *sXPConnect;
3440
3441
  static nsIScriptSecurityManager *sSecurityManager;
3442
  static nsIPrincipal *sSystemPrincipal;
3443
  static nsIPrincipal *sNullSubjectPrincipal;
3444
3445
  static nsNameSpaceManager *sNameSpaceManager;
3446
3447
  static nsIIOService *sIOService;
3448
  static nsIUUIDGenerator *sUUIDGenerator;
3449
3450
  static nsIConsoleService* sConsoleService;
3451
3452
  static nsDataHashtable<nsRefPtrHashKey<nsAtom>, EventNameMapping>* sAtomEventTable;
3453
  static nsDataHashtable<nsStringHashKey, EventNameMapping>* sStringEventTable;
3454
  static nsTArray<RefPtr<nsAtom>>* sUserDefinedEvents;
3455
3456
  static nsIStringBundleService* sStringBundleService;
3457
  static nsIStringBundle* sStringBundles[PropertiesFile_COUNT];
3458
  class nsContentUtilsReporter;
3459
3460
  static nsIContentPolicy* sContentPolicyService;
3461
  static bool sTriedToGetContentPolicy;
3462
3463
  static RefPtr<mozilla::intl::LineBreaker> sLineBreaker;
3464
  static RefPtr<mozilla::intl::WordBreaker> sWordBreaker;
3465
3466
  static mozilla::StaticRefPtr<nsIBidiKeyboard> sBidiKeyboard;
3467
3468
  static bool sInitialized;
3469
  static uint32_t sScriptBlockerCount;
3470
  static uint32_t sDOMNodeRemovedSuppressCount;
3471
3472
  // Not an nsCOMArray because removing elements from those is slower
3473
  static AutoTArray<nsCOMPtr<nsIRunnable>, 8>* sBlockedScriptRunners;
3474
  static uint32_t sRunnersCountAtFirstBlocker;
3475
  static uint32_t sScriptBlockerCountWhereRunnersPrevented;
3476
3477
  static nsIInterfaceRequestor* sSameOriginChecker;
3478
3479
  static bool sIsHandlingKeyBoardEvent;
3480
  static bool sAllowXULXBL_for_file;
3481
  static bool sDisablePopups;
3482
  static bool sIsFullscreenApiEnabled;
3483
  static bool sIsUnprefixedFullscreenApiEnabled;
3484
  static bool sTrustedFullscreenOnly;
3485
  static bool sIsCutCopyAllowed;
3486
  static uint32_t sHandlingInputTimeout;
3487
  static bool sIsPerformanceTimingEnabled;
3488
  static bool sIsResourceTimingEnabled;
3489
  static bool sIsPerformanceNavigationTimingEnabled;
3490
  static bool sIsUpgradableDisplayContentPrefEnabled;
3491
  static bool sIsFrameTimingPrefEnabled;
3492
  static bool sIsFormAutofillAutocompleteEnabled;
3493
  static bool sIsUAWidgetEnabled;
3494
  static bool sIsShadowDOMEnabled;
3495
  static bool sIsCustomElementsEnabled;
3496
  static bool sSendPerformanceTimingNotifications;
3497
  static bool sUseActivityCursor;
3498
  static bool sAnimationsAPICoreEnabled;
3499
  static bool sGetBoxQuadsEnabled;
3500
  static bool sSkipCursorMoveForSameValueSet;
3501
  static bool sRequestIdleCallbackEnabled;
3502
  static bool sLowerNetworkPriority;
3503
  static bool sTailingEnabled;
3504
  static bool sShowInputPlaceholderOnFocus;
3505
  static bool sAutoFocusEnabled;
3506
#ifndef RELEASE_OR_BETA
3507
  static bool sBypassCSSOMOriginCheck;
3508
#endif
3509
  static bool sIsBytecodeCacheEnabled;
3510
  static int32_t sBytecodeCacheStrategy;
3511
  static uint32_t sCookiesLifetimePolicy;
3512
  static bool sAntiTrackingControlCenterUIEnabled;
3513
3514
  static int32_t sPrivacyMaxInnerWidth;
3515
  static int32_t sPrivacyMaxInnerHeight;
3516
3517
  class UserInteractionObserver;
3518
  static UserInteractionObserver* sUserInteractionObserver;
3519
3520
  static nsHtml5StringParser* sHTMLFragmentParser;
3521
  static nsIParser* sXMLFragmentParser;
3522
  static nsIFragmentContentSink* sXMLFragmentSink;
3523
3524
  /**
3525
   * True if there's a fragment parser activation on the stack.
3526
   */
3527
  static bool sFragmentParsingActive;
3528
3529
  static nsString* sShiftText;
3530
  static nsString* sControlText;
3531
  static nsString* sMetaText;
3532
  static nsString* sOSText;
3533
  static nsString* sAltText;
3534
  static nsString* sModifierSeparator;
3535
3536
  // Alternate data mime type, used by the ScriptLoader to register and read the
3537
  // bytecode out of the nsCacheInfoChannel.
3538
  static nsCString* sJSBytecodeMimeType;
3539
3540
  static bool sDoNotTrackEnabled;
3541
  static mozilla::LazyLogModule sDOMDumpLog;
3542
3543
  static PopupControlState sPopupControlState;
3544
3545
  static int32_t sInnerOrOuterWindowCount;
3546
  static uint32_t sInnerOrOuterWindowSerialCounter;
3547
};
3548
3549
/* static */ inline
3550
nsContentPolicyType
3551
nsContentUtils::InternalContentPolicyTypeToExternal(nsContentPolicyType aType)
3552
30
{
3553
30
  switch (aType) {
3554
30
  case nsIContentPolicy::TYPE_INTERNAL_SCRIPT:
3555
0
  case nsIContentPolicy::TYPE_INTERNAL_SCRIPT_PRELOAD:
3556
0
  case nsIContentPolicy::TYPE_INTERNAL_WORKER:
3557
0
  case nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER:
3558
0
  case nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER:
3559
0
  case nsIContentPolicy::TYPE_INTERNAL_WORKER_IMPORT_SCRIPTS:
3560
0
    return nsIContentPolicy::TYPE_SCRIPT;
3561
0
3562
0
  case nsIContentPolicy::TYPE_INTERNAL_EMBED:
3563
0
  case nsIContentPolicy::TYPE_INTERNAL_OBJECT:
3564
0
    return nsIContentPolicy::TYPE_OBJECT;
3565
0
3566
0
  case nsIContentPolicy::TYPE_INTERNAL_FRAME:
3567
0
  case nsIContentPolicy::TYPE_INTERNAL_IFRAME:
3568
0
    return nsIContentPolicy::TYPE_SUBDOCUMENT;
3569
0
3570
0
  case nsIContentPolicy::TYPE_INTERNAL_AUDIO:
3571
0
  case nsIContentPolicy::TYPE_INTERNAL_VIDEO:
3572
0
  case nsIContentPolicy::TYPE_INTERNAL_TRACK:
3573
0
    return nsIContentPolicy::TYPE_MEDIA;
3574
0
3575
0
  case nsIContentPolicy::TYPE_INTERNAL_XMLHTTPREQUEST:
3576
0
  case nsIContentPolicy::TYPE_INTERNAL_EVENTSOURCE:
3577
0
    return nsIContentPolicy::TYPE_XMLHTTPREQUEST;
3578
0
3579
0
  case nsIContentPolicy::TYPE_INTERNAL_IMAGE:
3580
0
  case nsIContentPolicy::TYPE_INTERNAL_IMAGE_PRELOAD:
3581
0
  case nsIContentPolicy::TYPE_INTERNAL_IMAGE_FAVICON:
3582
0
    return nsIContentPolicy::TYPE_IMAGE;
3583
0
3584
0
  case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET:
3585
0
  case nsIContentPolicy::TYPE_INTERNAL_STYLESHEET_PRELOAD:
3586
0
    return nsIContentPolicy::TYPE_STYLESHEET;
3587
0
3588
30
  default:
3589
30
    return aType;
3590
30
  }
3591
30
}
3592
3593
/* static */ inline
3594
nsContentPolicyType
3595
nsContentUtils::InternalContentPolicyTypeToExternalOrWorker(nsContentPolicyType aType)
3596
{
3597
  switch (aType) {
3598
  case nsIContentPolicy::TYPE_INTERNAL_WORKER:
3599
  case nsIContentPolicy::TYPE_INTERNAL_SHARED_WORKER:
3600
  case nsIContentPolicy::TYPE_INTERNAL_SERVICE_WORKER:
3601
    return aType;
3602
3603
  default:
3604
    return InternalContentPolicyTypeToExternal(aType);
3605
  }
3606
}
3607
3608
class MOZ_RAII nsAutoScriptBlocker {
3609
public:
3610
  explicit nsAutoScriptBlocker(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) {
3611
    MOZ_GUARD_OBJECT_NOTIFIER_INIT;
3612
    nsContentUtils::AddScriptBlocker();
3613
  }
3614
  ~nsAutoScriptBlocker() {
3615
    nsContentUtils::RemoveScriptBlocker();
3616
  }
3617
private:
3618
  MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
3619
};
3620
3621
class MOZ_STACK_CLASS nsAutoScriptBlockerSuppressNodeRemoved :
3622
                          public nsAutoScriptBlocker {
3623
public:
3624
  nsAutoScriptBlockerSuppressNodeRemoved() {
3625
    ++nsContentUtils::sDOMNodeRemovedSuppressCount;
3626
  }
3627
  ~nsAutoScriptBlockerSuppressNodeRemoved() {
3628
    --nsContentUtils::sDOMNodeRemovedSuppressCount;
3629
  }
3630
};
3631
3632
namespace mozilla {
3633
namespace dom {
3634
3635
class TreeOrderComparator {
3636
public:
3637
0
  bool Equals(nsINode* aElem1, nsINode* aElem2) const {
3638
0
    return aElem1 == aElem2;
3639
0
  }
3640
0
  bool LessThan(nsINode* aElem1, nsINode* aElem2) const {
3641
0
    return nsContentUtils::PositionIsBefore(aElem1, aElem2);
3642
0
  }
3643
};
3644
3645
} // namespace dom
3646
} // namespace mozilla
3647
3648
#define NS_INTERFACE_MAP_ENTRY_TEAROFF(_interface, _allocator)                \
3649
0
  if (aIID.Equals(NS_GET_IID(_interface))) {                                  \
3650
0
    foundInterface = static_cast<_interface *>(_allocator);                   \
3651
0
    if (!foundInterface) {                                                    \
3652
0
      *aInstancePtr = nullptr;                                                \
3653
0
      return NS_ERROR_OUT_OF_MEMORY;                                          \
3654
0
    }                                                                         \
3655
0
  } else
3656
3657
/*
3658
 * In the following helper macros we exploit the fact that the result of a
3659
 * series of additions will not be finite if any one of the operands in the
3660
 * series is not finite.
3661
 */
3662
#define NS_ENSURE_FINITE(f, rv)                                               \
3663
0
  if (!mozilla::IsFinite(f)) {                                                \
3664
0
    return (rv);                                                              \
3665
0
  }
3666
3667
#define NS_ENSURE_FINITE2(f1, f2, rv)                                         \
3668
  if (!mozilla::IsFinite((f1)+(f2))) {                                        \
3669
    return (rv);                                                              \
3670
  }
3671
3672
#define NS_ENSURE_FINITE4(f1, f2, f3, f4, rv)                                 \
3673
  if (!mozilla::IsFinite((f1)+(f2)+(f3)+(f4))) {                              \
3674
    return (rv);                                                              \
3675
  }
3676
3677
#define NS_ENSURE_FINITE5(f1, f2, f3, f4, f5, rv)                             \
3678
  if (!mozilla::IsFinite((f1)+(f2)+(f3)+(f4)+(f5))) {                         \
3679
    return (rv);                                                              \
3680
  }
3681
3682
#define NS_ENSURE_FINITE6(f1, f2, f3, f4, f5, f6, rv)                         \
3683
  if (!mozilla::IsFinite((f1)+(f2)+(f3)+(f4)+(f5)+(f6))) {                    \
3684
    return (rv);                                                              \
3685
  }
3686
3687
// Deletes a linked list iteratively to avoid blowing up the stack (bug 460444).
3688
#define NS_CONTENT_DELETE_LIST_MEMBER(type_, ptr_, member_)                   \
3689
0
  {                                                                           \
3690
0
    type_ *cur = (ptr_)->member_;                                             \
3691
0
    (ptr_)->member_ = nullptr;                                                 \
3692
0
    while (cur) {                                                             \
3693
0
      type_ *next = cur->member_;                                             \
3694
0
      cur->member_ = nullptr;                                                  \
3695
0
      delete cur;                                                             \
3696
0
      cur = next;                                                             \
3697
0
    }                                                                         \
3698
0
  }
3699
3700
#endif /* nsContentUtils_h___ */