This is an automated email from the ASF dual-hosted git repository.

pjfanning pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/poi.git


The following commit(s) were added to refs/heads/trunk by this push:
     new 2aac6161d7 WordToHtmlConverter: escape font names written into the 
stylesheet (#1446)
2aac6161d7 is described below

commit 2aac6161d704bf3db5592796a95ca7877a848ce7
Author: Nayyar <[email protected]>
AuthorDate: Mon Oct 19 14:57:19 2026 +0530

    WordToHtmlConverter: escape font names written into the stylesheet (#1446)
    
    * WordToHtmlConverter: escape font names written into the stylesheet
    
    * Quote font names that are not CSS identifiers; split cssFontFamily test
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    ---------
    
    Co-authored-by: PJ Fanning <[email protected]>
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../poi/hwpf/converter/WordToHtmlConverter.java    |  2 +-
 .../apache/poi/hwpf/converter/WordToHtmlUtils.java | 59 ++++++++++++++-
 .../hwpf/converter/TestWordToHtmlConverter.java    | 84 ++++++++++++++++++----
 3 files changed, 130 insertions(+), 15 deletions(-)

diff --git 
a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/converter/WordToHtmlConverter.java
 
b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/converter/WordToHtmlConverter.java
index 6d7c1750da..a1f3a4fb14 100644
--- 
a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/converter/WordToHtmlConverter.java
+++ 
b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/converter/WordToHtmlConverter.java
@@ -201,7 +201,7 @@ public class WordToHtmlConverter extends 
AbstractWordConverter
                 && !Objects.equals( triplet.fontName,
                         blockProperies.pFontName ) )
         {
-            style.append("font-family:").append(triplet.fontName).append(";");
+            WordToHtmlUtils.addFontFamily( triplet.fontName, style );
         }
         if ( characterRun.getFontSize() / 2 != blockProperies.pFontSize )
         {
diff --git 
a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/converter/WordToHtmlUtils.java
 
b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/converter/WordToHtmlUtils.java
index 6bda01ee31..84cbec14e8 100644
--- 
a/poi-scratchpad/src/main/java/org/apache/poi/hwpf/converter/WordToHtmlUtils.java
+++ 
b/poi-scratchpad/src/main/java/org/apache/poi/hwpf/converter/WordToHtmlUtils.java
@@ -115,7 +115,64 @@ public class WordToHtmlUtils extends AbstractWordUtils
         if ( isEmpty( fontFamily ) )
             return;
 
-        style.append("font-family:").append(fontFamily).append(";");
+        
style.append("font-family:").append(cssFontFamily(fontFamily)).append(";");
+    }
+
+    /**
+     * The font name comes straight from the document and ends up in the text 
of the
+     * {@code <style>} element, which the html output method writes unescaped. 
Names whose
+     * space-separated words are all CSS identifiers (letters, digits, hyphens 
and underscores,
+     * not starting with a digit or a hyphen and digit) are written as they 
are; anything
+     * else is written as a CSS string, with quotes, backslashes, control 
characters and the
+     * HTML delimiters hex-escaped, so the name can neither close the style 
element nor add
+     * declarations of its own.
+     */
+    static String cssFontFamily( final String fontFamily )
+    {
+        if ( isCssIdentifiers( fontFamily ) )
+            return fontFamily;
+
+        StringBuilder sb = new StringBuilder( fontFamily.length() + 2 );
+        sb.append( '"' );
+        for ( int i = 0; i < fontFamily.length(); i++ )
+        {
+            char c = fontFamily.charAt( i );
+            if ( c < 0x20 || c == '"' || c == '\\' || c == '<' || c == '>' )
+            {
+                sb.append( '\\' ).append( Integer.toHexString( c ) ).append( ' 
' );
+            }
+            else
+            {
+                sb.append( c );
+            }
+        }
+        sb.append( '"' );
+        return sb.toString();
+    }
+
+    private static boolean isCssIdentifiers( final String fontFamily )
+    {
+        boolean wordStart = true;
+        for ( int i = 0; i < fontFamily.length(); i++ )
+        {
+            char c = fontFamily.charAt( i );
+            if ( c == ' ' )
+            {
+                wordStart = true;
+                continue;
+            }
+            if ( !Character.isLetterOrDigit( c ) && c != '-' && c != '_' )
+                return false;
+            if ( wordStart )
+            {
+                // an identifier must not start with a digit, or with a hyphen 
and a digit
+                char first = c == '-' && i + 1 < fontFamily.length() ? 
fontFamily.charAt( i + 1 ) : c;
+                if ( Character.isDigit( first ) )
+                    return false;
+                wordStart = false;
+            }
+        }
+        return true;
     }
 
     public static void addFontSize( final int fontSize, StringBuilder style )
diff --git 
a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java
 
b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java
index 2840ea17f6..694a116825 100644
--- 
a/poi-scratchpad/src/test/java/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java
+++ 
b/poi-scratchpad/src/test/java/org/apache/poi/hwpf/converter/TestWordToHtmlConverter.java
@@ -24,8 +24,12 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
 import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
 import java.time.Duration;
+import java.util.Arrays;
 import java.util.regex.Matcher;
 
 import javax.xml.transform.OutputKeys;
@@ -36,6 +40,7 @@ import javax.xml.transform.stream.StreamResult;
 import org.apache.poi.POIDataSamples;
 import org.apache.poi.POITestCase;
 import org.apache.poi.hwpf.HWPFDocument;
+import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 import org.apache.poi.util.XMLHelper;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
@@ -159,27 +164,80 @@ public class TestWordToHtmlConverter {
         });
     }
 
+    @Test
+    void testFontNameInStylesheet() throws Exception {
+        // the font name is written into the text of the <style> element, 
which the html output
+        // method does not escape, so a crafted name used to close the element 
and add markup
+        String fontName = "</style><p>x";
+        try (POIFSFileSystem fs = new 
POIFSFileSystem(SAMPLES.openResourceAsStream("SampleDoc.doc"))) {
+            renameFont(fs, "Times New Roman", fontName);
+
+            try (HWPFDocument hwpfDocument = new HWPFDocument(fs)) {
+                String result = getHtmlText(hwpfDocument, true);
+                assertNotContains(result, "</style><p>");
+                assertContains(result, "font-family:\"\\3c /style\\3e \\3c 
p\\3e x\";");
+            }
+        }
+    }
+
+    @Test
+    void testCssFontFamily() {
+        assertEquals("Times New Roman", WordToHtmlUtils.cssFontFamily("Times 
New Roman"));
+        assertEquals("MS-Mincho_2", 
WordToHtmlUtils.cssFontFamily("MS-Mincho_2"));
+        assertEquals("\"3M Sans\"", WordToHtmlUtils.cssFontFamily("3M Sans"));
+        assertEquals("\"Font -1\"", WordToHtmlUtils.cssFontFamily("Font -1"));
+        assertEquals("\"a\\22 b\\5c c\\a d\"", 
WordToHtmlUtils.cssFontFamily("a\"b\\c\nd"));
+    }
+
+    /**
+     * Overwrites the name of a font in the font table of the table stream, in 
place: the new
+     * name must not be longer than the old one, the rest of the entry is 
padded with zeros.
+     */
+    private static void renameFont(POIFSFileSystem fs, String oldName, String 
newName) throws IOException {
+        // not closed, as that would close the file system too
+        HWPFDocument hwpfDocument = new HWPFDocument(fs);
+        byte[] table = hwpfDocument.getTableStream();
+        String tableName = 
hwpfDocument.getFileInformationBlock().getFibBase().isFWhichTblStm() ? "1Table" 
: "0Table";
+        int start = hwpfDocument.getFileInformationBlock().getFcSttbfffn();
+        int end = start + 
hwpfDocument.getFileInformationBlock().getLcbSttbfffn();
+
+        byte[] oldBytes = (oldName + "\0").getBytes(StandardCharsets.UTF_16LE);
+        byte[] newBytes = 
Arrays.copyOf(newName.getBytes(StandardCharsets.UTF_16LE), oldBytes.length);
+        for (int i = start; i + oldBytes.length <= end; i++) {
+            if (Arrays.equals(oldBytes, Arrays.copyOfRange(table, i, i + 
oldBytes.length))) {
+                System.arraycopy(newBytes, 0, table, i, newBytes.length);
+                fs.createOrUpdateDocument(new ByteArrayInputStream(table), 
tableName);
+                return;
+            }
+        }
+        throw new IllegalStateException("font " + oldName + " not found");
+    }
+
     private static String getHtmlText(final String sampleFileName, boolean 
emulatePictureStorage) throws Exception {
+        try (HWPFDocument hwpfDocument = new 
HWPFDocument(SAMPLES.openResourceAsStream(sampleFileName))) {
+            return getHtmlText(hwpfDocument, emulatePictureStorage);
+        }
+    }
+
+    private static String getHtmlText(HWPFDocument hwpfDocument, boolean 
emulatePictureStorage) throws Exception {
         Document newDocument = XMLHelper.newDocumentBuilder().newDocument();
         WordToHtmlConverter wordToHtmlConverter = new 
WordToHtmlConverter(newDocument);
 
-        try (HWPFDocument hwpfDocument = new 
HWPFDocument(SAMPLES.openResourceAsStream(sampleFileName))) {
-            if (emulatePictureStorage) {
-                wordToHtmlConverter.setPicturesManager((content, pictureType, 
suggestedName, widthInches, heightInches) -> suggestedName);
-            }
+        if (emulatePictureStorage) {
+            wordToHtmlConverter.setPicturesManager((content, pictureType, 
suggestedName, widthInches, heightInches) -> suggestedName);
+        }
 
-            wordToHtmlConverter.processDocument(hwpfDocument);
+        wordToHtmlConverter.processDocument(hwpfDocument);
 
-            StringWriter stringWriter = new StringWriter();
+        StringWriter stringWriter = new StringWriter();
 
-            Transformer transformer = XMLHelper.newTransformer();
-            transformer.setOutputProperty(OutputKeys.METHOD, "html");
-            transformer.transform(
-                new DOMSource(wordToHtmlConverter.getDocument()),
-                new StreamResult(stringWriter));
+        Transformer transformer = XMLHelper.newTransformer();
+        transformer.setOutputProperty(OutputKeys.METHOD, "html");
+        transformer.transform(
+            new DOMSource(wordToHtmlConverter.getDocument()),
+            new StreamResult(stringWriter));
 
-            return stringWriter.toString();
-        }
+        return stringWriter.toString();
     }
 
 


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to