コード例 #1
0
        public static string GetSafeHtml(string currentHtml, SafeHtmlFlags flags, out bool wasBad)
        {
            string newHtml = string.Empty;

            wasBad = BuildSafeHtml(currentHtml, flags, out newHtml);
            return(newHtml);
        }
コード例 #2
0
        /// <summary>
        /// Get a safe version of a given string representing HTML.  Note that this function is marked unsafe because
        /// it calls an unsafe extern function.
        /// </summary>
        /// <param name="currentHtml">HTML string to make a safe version of</param>
        /// <param name="flags">Flags as to how to process the string</param>
        /// <param name="newHtml">The safe HTML string</param>
        /// <returns>true if the given HTML string had potentially dangerous content, else false</returns>
        private static unsafe bool BuildSafeHtml(string existingHtml, SafeHtmlFlags flags, out string newHtml)
        {
            byte *rgbTmp = null;

            // Set newHtml to a blank string in case we encounter a failure
            newHtml = String.Empty;

            // Early exit if the existing Html is null or an empty string.
            // The native call below doesn't return when the existing Html is an empty string.
            if (existingHtml == null || existingHtml.Length == 0)
            {
                return(false);
            }

            try
            {
                byte[] rgbSrc = Encoding.UTF8.GetBytes(existingHtml);

                int iSrc  = rgbSrc.Length;
                int cbDst = 0;

                // Note that we do not have the SafeHtml component write out the "byte order mark" to indicate
                // Unicode/UTF-8 - that is handled separately by callers.
                uint returnCode = NativeMethods.OshFGetSafeHTMLAllocForManaged2(
                    rgbSrc,
                    iSrc,
                    (int)SafeHtmlCodePages.CodePageUTF8,
                    &rgbTmp,
                    out cbDst,
                    (int)SafeHtmlCodePages.CodePageUnicode,
                    (int)(flags | SafeHtmlFlags.DebugNoPopup | SafeHtmlFlags.IndicateIfUnsafe | SafeHtmlFlags.NoWriteBOM)
                    );

                StringBuilder Result = new StringBuilder(cbDst / 2);

                for (int i = 0; i < cbDst; i += 2)
                {
                    char ch = *(char *)(rgbTmp + i);
                    Result.Append(ch);
                }

                newHtml = Result.ToString();

                return(returnCode == 1);
            }
            finally
            {
                if (rgbTmp != null)
                {
                    NativeMethods.OshFreePv((void *)rgbTmp);
                }
            }
        }