/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* A namespace class for static content utilities. */ #ifndef nsContentUtils_h___ #define nsContentUtils_h___ #include #if defined(XP_WIN) || defined(XP_OS2) #include #endif #if defined(SOLARIS) #include #endif //A trick to handle IEEE floating point exceptions on FreeBSD - E.D. #ifdef __FreeBSD__ #include #if !defined(__i386__) && !defined(__x86_64__) static fp_except_t allmask = FP_X_INV|FP_X_OFL|FP_X_UFL|FP_X_DZ|FP_X_IMP; #else static fp_except_t allmask = FP_X_INV|FP_X_OFL|FP_X_UFL|FP_X_DZ|FP_X_IMP|FP_X_DNML; #endif static fp_except_t oldmask = fpsetmask(~allmask); #endif #include "nsAString.h" #include "nsIStatefulFrame.h" #include "nsNodeInfoManager.h" #include "nsIXPCScriptable.h" #include "nsDataHashtable.h" #include "nsIDOMEvent.h" #include "nsTArray.h" #include "nsReadableUtils.h" #include "nsINode.h" #include "nsIDOMNode.h" #include "nsHtml5StringParser.h" #include "nsIDocument.h" #include "nsContentSink.h" #include "nsMathUtils.h" #include "nsThreadUtils.h" #include "nsIContent.h" #include "nsCharSeparatedTokenizer.h" #include "mozilla/AutoRestore.h" #include "mozilla/GuardObjects.h" #include "mozilla/TimeStamp.h" struct nsNativeKeyEvent; // Don't include nsINativeKeyBindings.h here: it will force strange compilation error! class nsIDOMScriptObjectFactory; class nsIXPConnect; class nsIContent; class nsIDOMKeyEvent; class nsIDocument; class nsIDocumentObserver; class nsIDocShell; class nsINameSpaceManager; class nsIFragmentContentSink; class nsIScriptGlobalObject; class nsIScriptSecurityManager; class nsTextFragment; class nsIJSContextStack; class nsIThreadJSContextStack; class nsIParser; class nsIParserService; class nsIIOService; class nsIURI; class imgIContainer; class imgIDecoderObserver; class imgIRequest; class imgILoader; class imgICache; class nsIImageLoadingContent; class nsIDOMHTMLFormElement; class nsIDOMDocument; class nsIConsoleService; class nsIStringBundleService; class nsIStringBundle; class nsIContentPolicy; class nsILineBreaker; class nsIWordBreaker; class nsIJSRuntimeService; class nsEventListenerManager; class nsIScriptContext; class nsIRunnable; class nsIInterfaceRequestor; class nsINodeInfo; template class nsCOMArray; template class nsRefPtrHashtable; struct JSRuntime; class nsIWidget; class nsIDragSession; class nsIPresShell; class nsIXPConnectJSObjectHolder; #ifdef MOZ_XTF class nsIXTFService; #endif #ifdef IBMBIDI class nsIBidiKeyboard; #endif class nsIMIMEHeaderParam; class nsIObserver; class nsPresContext; class nsIChannel; class nsAutoScriptBlockerSuppressNodeRemoved; struct nsIntMargin; class nsPIDOMWindow; class nsIDocumentLoaderFactory; class nsIDOMHTMLInputElement; namespace mozilla { class Selection; namespace layers { class LayerManager; } // namespace layers namespace dom { class Element; } // namespace dom } // namespace mozilla extern const char kLoadAsData[]; enum EventNameType { EventNameType_None = 0x0000, EventNameType_HTML = 0x0001, EventNameType_XUL = 0x0002, EventNameType_SVGGraphic = 0x0004, // svg graphic elements EventNameType_SVGSVG = 0x0008, // the svg element EventNameType_SMIL = 0x0016, // smil elements EventNameType_HTMLXUL = 0x0003, EventNameType_All = 0xFFFF }; /** * Information retrieved from the tag. See * GetViewportInfo for more information on this functionality. */ struct ViewportInfo { // Default zoom indicates the level at which the display is 'zoomed in' // initially for the user, upon loading of the page. double defaultZoom; // The minimum zoom level permitted by the page. double minZoom; // The maximum zoom level permitted by the page. double maxZoom; // The width of the viewport, specified by the tag, // in CSS pixels. uint32_t width; // The height of the viewport, specified by the tag, // in CSS pixels. uint32_t height; // Whether or not we should automatically size the viewport to the device's // width. This is true if the document has been optimized for mobile, and // the width property of a specified tag is either // not specified, or is set to the special value 'device-width'. bool autoSize; // Whether or not the user can zoom in and out on the page. Default is true. bool allowZoom; }; struct EventNameMapping { nsIAtom* mAtom; uint32_t mId; int32_t mType; uint32_t mStructType; }; struct nsShortcutCandidate { nsShortcutCandidate(uint32_t aCharCode, bool aIgnoreShift) : mCharCode(aCharCode), mIgnoreShift(aIgnoreShift) { } uint32_t mCharCode; bool mIgnoreShift; }; class nsContentUtils { friend class nsAutoScriptBlockerSuppressNodeRemoved; typedef mozilla::dom::Element Element; typedef mozilla::TimeDuration TimeDuration; public: static nsresult Init(); /** * Get a JSContext from the document's scope object. */ static JSContext* GetContextFromDocument(nsIDocument *aDocument); /** * When a document's scope changes (e.g., from document.open(), call this * function to move all content wrappers from the old scope to the new one. */ static nsresult ReparentContentWrappersInScope(JSContext *cx, nsIScriptGlobalObject *aOldScope, nsIScriptGlobalObject *aNewScope); static bool IsCallerChrome(); static bool IsCallerTrustedForRead(); static bool IsCallerTrustedForWrite(); /** * Check whether a caller has UniversalXPConnect. */ static bool CallerHasUniversalXPConnect(); static bool IsImageSrcSetDisabled(); /** * Returns the parent node of aChild crossing document boundaries. */ static nsINode* GetCrossDocParentNode(nsINode* aChild); /** * Do not ever pass null pointers to this method. If one of your * nsIContents is null, you have to decide for yourself what * "IsDescendantOf" really means. * * @param aPossibleDescendant node to test for being a descendant of * aPossibleAncestor * @param aPossibleAncestor node to test for being an ancestor of * aPossibleDescendant * @return true if aPossibleDescendant is a descendant of * aPossibleAncestor (or is aPossibleAncestor). false * otherwise. */ static bool ContentIsDescendantOf(const nsINode* aPossibleDescendant, const nsINode* aPossibleAncestor); /** * Similar to ContentIsDescendantOf except it crosses document boundaries. */ static bool ContentIsCrossDocDescendantOf(nsINode* aPossibleDescendant, nsINode* aPossibleAncestor); /* * This method fills the |aArray| with all ancestor nodes of |aNode| * including |aNode| at the zero index. */ static nsresult GetAncestors(nsINode* aNode, nsTArray& aArray); /* * This method fills |aAncestorNodes| with all ancestor nodes of |aNode| * including |aNode| (QI'd to nsIContent) at the zero index. * For each ancestor, there is a corresponding element in |aAncestorOffsets| * which is the IndexOf the child in relation to its parent. * * This method just sucks. */ static nsresult GetAncestorsAndOffsets(nsIDOMNode* aNode, int32_t aOffset, nsTArray* aAncestorNodes, nsTArray* aAncestorOffsets); /* * The out parameter, |aCommonAncestor| will be the closest node, if any, * to both |aNode| and |aOther| which is also an ancestor of each. * Returns an error if the two nodes are disconnected and don't have * a common ancestor. */ static nsresult GetCommonAncestor(nsIDOMNode *aNode, nsIDOMNode *aOther, nsIDOMNode** aCommonAncestor); /** * Returns the common ancestor, if any, for two nodes. Returns null if the * nodes are disconnected. */ static nsINode* GetCommonAncestor(nsINode* aNode1, nsINode* aNode2); /** * Returns true if aNode1 is before aNode2 in the same connected * tree. */ static bool PositionIsBefore(nsINode* aNode1, nsINode* aNode2) { return (aNode2->CompareDocPosition(aNode1) & (nsIDOMNode::DOCUMENT_POSITION_PRECEDING | nsIDOMNode::DOCUMENT_POSITION_DISCONNECTED)) == nsIDOMNode::DOCUMENT_POSITION_PRECEDING; } /** * Utility routine to compare two "points", where a point is a * node/offset pair * Returns -1 if point1 < point2, 1, if point1 > point2, * 0 if error or if point1 == point2. * NOTE! If the two nodes aren't in the same connected subtree, * the result is 1, and the optional aDisconnected parameter * is set to true. */ static int32_t ComparePoints(nsINode* aParent1, int32_t aOffset1, nsINode* aParent2, int32_t aOffset2, bool* aDisconnected = nullptr); static int32_t ComparePoints(nsIDOMNode* aParent1, int32_t aOffset1, nsIDOMNode* aParent2, int32_t aOffset2, bool* aDisconnected = nullptr); /** * Brute-force search of the element subtree rooted at aContent for * an element with the given id. aId must be nonempty, otherwise * this method may return nodes even if they have no id! */ static Element* MatchElementId(nsIContent *aContent, const nsAString& aId); /** * Similar to above, but to be used if one already has an atom for the ID */ static Element* MatchElementId(nsIContent *aContent, const nsIAtom* aId); /** * Reverses the document position flags passed in. * * @param aDocumentPosition The document position flags to be reversed. * * @return The reversed document position flags. * * @see nsIDOMNode */ static uint16_t ReverseDocumentPosition(uint16_t aDocumentPosition); static uint32_t CopyNewlineNormalizedUnicodeTo(const nsAString& aSource, uint32_t aSrcOffset, PRUnichar* aDest, uint32_t aLength, bool& aLastCharCR); static uint32_t CopyNewlineNormalizedUnicodeTo(nsReadingIterator& aSrcStart, const nsReadingIterator& aSrcEnd, nsAString& aDest); static const nsDependentSubstring TrimCharsInSet(const char* aSet, const nsAString& aValue); template static const nsDependentSubstring TrimWhitespace(const nsAString& aStr, bool aTrimTrailing = true); /** * Returns true if aChar is of class Ps, Pi, Po, Pf, or Pe. */ static bool IsFirstLetterPunctuation(uint32_t aChar); static bool IsFirstLetterPunctuationAt(const nsTextFragment* aFrag, uint32_t aOffset); /** * Returns true if aChar is of class Lu, Ll, Lt, Lm, Lo, Nd, Nl or No */ static bool IsAlphanumeric(uint32_t aChar); static bool IsAlphanumericAt(const nsTextFragment* aFrag, uint32_t aOffset); /* * Is the character an HTML whitespace character? * * We define whitespace using the list in HTML5 and css3-selectors: * U+0009, U+000A, U+000C, U+000D, U+0020 * * HTML 4.01 also lists U+200B (zero-width space). */ static bool IsHTMLWhitespace(PRUnichar aChar); /** * Is the HTML local name a block element? */ static bool IsHTMLBlock(nsIAtom* aLocalName); /** * Is the HTML local name a void element? */ static bool IsHTMLVoid(nsIAtom* aLocalName); /** * Parse a margin string of format 'top, right, bottom, left' into * an nsIntMargin. * * @param aString the string to parse * @param aResult the resulting integer * @return whether the value could be parsed */ static bool ParseIntMarginValue(const nsAString& aString, nsIntMargin& aResult); /** * Parse the value of the attribute according to the HTML5 * spec as of April 16, 2012. * * @param aValue the value to parse * @return 1 to 7, or 0 if the value couldn't be parsed */ static int32_t ParseLegacyFontSize(const nsAString& aValue); static void Shutdown(); /** * Checks whether two nodes come from the same origin. */ static nsresult CheckSameOrigin(nsINode* aTrustedNode, nsIDOMNode* aUnTrustedNode); static nsresult CheckSameOrigin(nsINode* aTrustedNode, nsINode* unTrustedNode); // Check if the (JS) caller can access aNode. static bool CanCallerAccess(nsIDOMNode *aNode); // Check if the (JS) caller can access aWindow. // aWindow can be either outer or inner window. static bool CanCallerAccess(nsPIDOMWindow* aWindow); /** * Get the window through the JS context that's currently on the stack. * If there's no JS context currently on the stack, returns null. */ static nsPIDOMWindow *GetWindowFromCaller(); /** * The two GetDocumentFrom* functions below allow a caller to get at a * document that is relevant to the currently executing script. * * GetDocumentFromCaller gets its document by looking at the last called * function and finding the document that the function itself relates to. * For example, consider two windows A and B in the same origin. B has a * function which does something that ends up needing the current document. * If a script in window A were to call B's function, GetDocumentFromCaller * would find that function (in B) and return B's document. * * GetDocumentFromContext gets its document by looking at the currently * executing context's global object and returning its document. Thus, * given the example above, GetDocumentFromCaller would see that the * currently executing script was in window A, and return A's document. */ /** * Get the document from the currently executing function. This will return * the document that the currently executing function is in/from. * * @return The document or null if no JS Context. */ static nsIDOMDocument *GetDocumentFromCaller(); /** * Get the document through the JS context that's currently on the stack. * If there's no JS context currently on the stack it will return null. * This will return the document of the calling script. * * @return The document or null if no JS context */ static nsIDOMDocument *GetDocumentFromContext(); // Check if a node is in the document prolog, i.e. before the document // element. static bool InProlog(nsINode *aNode); static nsIParserService* GetParserService(); static nsINameSpaceManager* NameSpaceManager() { return sNameSpaceManager; } static nsIIOService* GetIOService() { return sIOService; } #ifdef MOZ_XTF static nsIXTFService* GetXTFService(); #endif #ifdef IBMBIDI static nsIBidiKeyboard* GetBidiKeyboard(); #endif /** * Get the cache security manager service. Can return null if the layout * module has been shut down. */ static nsIScriptSecurityManager* GetSecurityManager() { return sSecurityManager; } static nsresult GenerateStateKey(nsIContent* aContent, const nsIDocument* aDocument, nsIStatefulFrame::SpecialStateID aID, nsACString& aKey); /** * Create a new nsIURI from aSpec, using aBaseURI as the base. The * origin charset of the new nsIURI will be the document charset of * aDocument. */ static nsresult NewURIWithDocumentCharset(nsIURI** aResult, const nsAString& aSpec, nsIDocument* aDocument, nsIURI* aBaseURI); /** * Convert aInput (in charset aCharset) to UTF16 in aOutput. * * @param aCharset the name of the charset; if empty, we assume UTF8 */ static nsresult ConvertStringFromCharset(const nsACString& aCharset, const nsACString& aInput, nsAString& aOutput); /** * Determine whether a buffer begins with a BOM for UTF-8, UTF-16LE, * UTF-16BE * * @param aBuffer the buffer to check * @param aLength the length of the buffer * @param aCharset empty if not found * @return boolean indicating whether a BOM was detected. */ static bool CheckForBOM(const unsigned char* aBuffer, uint32_t aLength, nsACString& aCharset, bool *bigEndian = nullptr); static nsresult GuessCharset(const char *aData, uint32_t aDataLen, nsACString &aCharset); /** * Determine whether aContent is in some way associated with aForm. If the * form is a container the only elements that are considered to be associated * with a form are the elements that are contained within the form. If the * form is a leaf element then all elements will be accepted into this list, * since this can happen due to content fixup when a form spans table rows or * table cells. */ static bool BelongsInForm(nsIContent *aForm, nsIContent *aContent); static nsresult CheckQName(const nsAString& aQualifiedName, bool aNamespaceAware = true, const PRUnichar** aColon = nullptr); static nsresult SplitQName(const nsIContent* aNamespaceResolver, const nsAFlatString& aQName, int32_t *aNamespace, nsIAtom **aLocalName); static nsresult GetNodeInfoFromQName(const nsAString& aNamespaceURI, const nsAString& aQualifiedName, nsNodeInfoManager* aNodeInfoManager, uint16_t aNodeType, nsINodeInfo** aNodeInfo); static void SplitExpatName(const PRUnichar *aExpatName, nsIAtom **aPrefix, nsIAtom **aTagName, int32_t *aNameSpaceID); // Get a permission-manager setting for the given principal and type. // If the pref doesn't exist or if it isn't ALLOW_ACTION, false is // returned, otherwise true is returned. Always returns true for the // system principal, and false for a null principal. static bool IsSitePermAllow(nsIPrincipal* aPrincipal, const char* aType); // Get a permission-manager setting for the given principal and type. // If the pref doesn't exist or if it isn't DENY_ACTION, false is // returned, otherwise true is returned. Always returns false for the // system principal, and true for a null principal. static bool IsSitePermDeny(nsIPrincipal* aPrincipal, const char* aType); // Returns true if aDoc1 and aDoc2 have equal NodePrincipal()s. static bool HaveEqualPrincipals(nsIDocument* aDoc1, nsIDocument* aDoc2); static nsILineBreaker* LineBreaker() { return sLineBreaker; } static nsIWordBreaker* WordBreaker() { return sWordBreaker; } /** * Regster aObserver as a shutdown observer. A strong reference is held * to aObserver until UnregisterShutdownObserver is called. */ static void RegisterShutdownObserver(nsIObserver* aObserver); static void UnregisterShutdownObserver(nsIObserver* aObserver); /** * @return true if aContent has an attribute aName in namespace aNameSpaceID, * and the attribute value is non-empty. */ static bool HasNonEmptyAttr(const nsIContent* aContent, int32_t aNameSpaceID, nsIAtom* aName); /** * Method that gets the primary presContext for the node. * * @param aContent The content node. * @return the presContext, or nullptr if the content is not in a document * (if GetCurrentDoc returns nullptr) */ static nsPresContext* GetContextForContent(const nsIContent* aContent); /** * Method to do security and content policy checks on the image URI * * @param aURI uri of the image to be loaded * @param aContext the context the image is loaded in (eg an element) * @param aLoadingDocument the document we belong to * @param aLoadingPrincipal the principal doing the load * @param aImageBlockingStatus the nsIContentPolicy blocking status for this * image. This will be set even if a security check fails for the * image, to some reasonable REJECT_* value. This out param will only * be set if it's non-null. * @return true if the load can proceed, or false if it is blocked. * Note that aImageBlockingStatus, if set will always be an ACCEPT * status if true is returned and always be a REJECT_* status if * false is returned. */ static bool CanLoadImage(nsIURI* aURI, nsISupports* aContext, nsIDocument* aLoadingDocument, nsIPrincipal* aLoadingPrincipal, int16_t* aImageBlockingStatus = nullptr); /** * Method to start an image load. This does not do any security checks. * This method will attempt to make aURI immutable; a caller that wants to * keep a mutable version around should pass in a clone. * * @param aURI uri of the image to be loaded * @param aLoadingDocument the document we belong to * @param aLoadingPrincipal the principal doing the load * @param aReferrer the referrer URI * @param aObserver the observer for the image load * @param aLoadFlags the load flags to use. See nsIRequest * @return the imgIRequest for the image load */ static nsresult LoadImage(nsIURI* aURI, nsIDocument* aLoadingDocument, nsIPrincipal* aLoadingPrincipal, nsIURI* aReferrer, imgIDecoderObserver* aObserver, int32_t aLoadFlags, imgIRequest** aRequest); /** * Obtain an image loader that respects the given document/channel's privacy status. * Null document/channel arguments return the public image loader. */ static imgILoader* GetImgLoaderForDocument(nsIDocument* aDoc); static imgILoader* GetImgLoaderForChannel(nsIChannel* aChannel); /** * Returns whether the given URI is in the image cache. */ static bool IsImageInCache(nsIURI* aURI, nsIDocument* aDocument); /** * Method to get an imgIContainer from an image loading content * * @param aContent The image loading content. Must not be null. * @param aRequest The image request [out] * @return the imgIContainer corresponding to the first frame of the image */ static already_AddRefed GetImageFromContent(nsIImageLoadingContent* aContent, imgIRequest **aRequest = nullptr); /** * Helper method to call imgIRequest::GetStaticRequest. */ static already_AddRefed GetStaticRequest(imgIRequest* aRequest); /** * Method that decides whether a content node is draggable * * @param aContent The content node to test. * @return whether it's draggable */ static bool ContentIsDraggable(nsIContent* aContent); /** * Method that decides whether a content node is a draggable image * * @param aContent The content node to test. * @return whether it's a draggable image */ static bool IsDraggableImage(nsIContent* aContent); /** * Method that decides whether a content node is a draggable link * * @param aContent The content node to test. * @return whether it's a draggable link */ static bool IsDraggableLink(const nsIContent* aContent); /** * Convenience method to create a new nodeinfo that differs only by name * from aNodeInfo. */ static nsresult NameChanged(nsINodeInfo *aNodeInfo, nsIAtom *aName, nsINodeInfo** aResult) { nsNodeInfoManager *niMgr = aNodeInfo->NodeInfoManager(); *aResult = niMgr->GetNodeInfo(aName, aNodeInfo->GetPrefixAtom(), aNodeInfo->NamespaceID(), aNodeInfo->NodeType(), aNodeInfo->GetExtraName()).get(); return *aResult ? NS_OK : NS_ERROR_OUT_OF_MEMORY; } /** * Returns the appropriate event argument names for the specified * namespace and event name. Added because we need to switch between * SVG's "evt" and the rest of the world's "event", and because onerror * takes 3 args. */ static void GetEventArgNames(int32_t aNameSpaceID, nsIAtom *aEventName, uint32_t *aArgCount, const char*** aArgNames); /** * If aNode is not an element, return true exactly when aContent's binding * parent is null. * * If aNode is an element, return true exactly when aContent's binding parent * is the same as aNode's. * * This method is particularly useful for callers who are trying to ensure * that they are working with a non-anonymous descendant of a given node. If * aContent is a descendant of aNode, a return value of false from this * method means that it's an anonymous descendant from aNode's point of view. * * Both arguments to this method must be non-null. */ static bool IsInSameAnonymousTree(const nsINode* aNode, const nsIContent* aContent); /** * Return the nsIXPConnect service. */ static nsIXPConnect *XPConnect() { return sXPConnect; } /** * Report a localized error message to the error console. * @param aErrorFlags See nsIScriptError. * @param aCategory Name of module reporting error. * @param aDocument Reference to the document which triggered the message. * @param aFile Properties file containing localized message. * @param aMessageName Name of localized message. * @param [aParams=nullptr] (Optional) Parameters to be substituted into localized message. * @param [aParamsLength=0] (Optional) Length of aParams. * @param [aURI=nullptr] (Optional) URI of resource containing error. * @param [aSourceLine=EmptyString()] (Optional) The text of the line that contains the error (may be empty). * @param [aLineNumber=0] (Optional) Line number within resource containing error. * @param [aColumnNumber=0] (Optional) Column number within resource containing error. If aURI is null, then aDocument->GetDocumentURI() is used. */ enum PropertiesFile { eCSS_PROPERTIES, eXBL_PROPERTIES, eXUL_PROPERTIES, eLAYOUT_PROPERTIES, eFORMS_PROPERTIES, ePRINTING_PROPERTIES, eDOM_PROPERTIES, eHTMLPARSER_PROPERTIES, eSVG_PROPERTIES, eBRAND_PROPERTIES, eCOMMON_DIALOG_PROPERTIES, PropertiesFile_COUNT }; static nsresult ReportToConsole(uint32_t aErrorFlags, const char *aCategory, nsIDocument* aDocument, PropertiesFile aFile, const char *aMessageName, const PRUnichar **aParams = nullptr, uint32_t aParamsLength = 0, nsIURI* aURI = nullptr, const nsAFlatString& aSourceLine = EmptyString(), uint32_t aLineNumber = 0, uint32_t aColumnNumber = 0); /** * Get the localized string named |aKey| in properties file |aFile|. */ static nsresult GetLocalizedString(PropertiesFile aFile, const char* aKey, nsXPIDLString& aResult); /** * A helper function that parses a sandbox attribute (of an