summaryrefslogtreecommitdiff
path: root/src/main/org/owasp/html/examples/UrlTextExample.java
blob: 87f3ce8f3a3fdaa4a7071fcdaa8c5af40a7464b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// Copyright (c) 2011, Mike Samuel
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the OWASP nor the names of its contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

package org.owasp.html.examples;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.owasp.html.Handler;
import org.owasp.html.HtmlPolicyBuilder;
import org.owasp.html.HtmlSanitizer;
import org.owasp.html.HtmlStreamEventReceiver;
import org.owasp.html.HtmlStreamRenderer;
import org.owasp.html.HtmlTextEscapingMode;
import org.owasp.html.PolicyFactory;
import org.owasp.html.TagBalancingHtmlStreamEventReceiver;

/**
 * Uses a custom event receiver to emit the domain of a link or inline image
 * after the link or image.
 */
public class UrlTextExample {

  /** An event receiver that emits the domain of a link or image after it. */
  static class AppendDomainAfterText implements HtmlStreamEventReceiver {
    final HtmlStreamEventReceiver underlying;
    private final List<String> pendingText = new ArrayList<String>();

    AppendDomainAfterText(HtmlStreamEventReceiver underlying) {
      this.underlying = underlying;
    }

    public void openDocument() {
      underlying.openDocument();
    }
    public void closeDocument() {
      underlying.closeDocument();
    }
    public void openTag(String elementName, List<String> attribs) {
      underlying.openTag(elementName, attribs);

      if (!HtmlTextEscapingMode.isVoidElement(elementName)) {
        String trailingText = null;

        if (!attribs.isEmpty()) {
          // Figure out which attribute we should look for.
          String urlAttrName = null;
          if ("a".equals(elementName)) {
            urlAttrName = "href";
          } else if ("img".equals(elementName)) {
            urlAttrName = "src";
          }
          if (urlAttrName != null) {
            // Look for the attribute, and after it for its value.
            for (int i = 0, n = attribs.size(); i < n; i += 2) {
              if (urlAttrName.equals(attribs.get(i))) {
                String url = attribs.get(i+1);
                trailingText = domainOf(url);
                break;
              }
            }
          }
        }
        // Push the trailing text onto a stack so when we see the corresponding
        // close tag, we can emit the text.
        pendingText.add(trailingText);
      }
    }
    public void closeTag(String elementName) {
      underlying.closeTag(elementName);
      // Pull the trailing text for the recently closed element off the stack.
      int pendingTextSize = pendingText.size();
      if (pendingTextSize != 0) {
        String trailingText = pendingText.remove(pendingTextSize - 1);
        // Emit it with a separator.
        if (trailingText != null) {
          text(" - " + trailingText);
        }
      }
    }
    public void text(String text) {
      underlying.text(text);
    }
  }


  public static void run(Appendable out, String... argv) throws IOException {
    PolicyFactory policyBuilder = new HtmlPolicyBuilder()
      .allowAttributes("src").onElements("img")
      .allowAttributes("href").onElements("a")
      // Allow some URLs through.
      .allowStandardUrlProtocols()
      .allowElements(
          "a", "label", "h1", "h2", "h3", "h4", "h5", "h6",
          "p", "i", "b", "u", "strong", "em", "small", "big", "pre", "code",
          "cite", "samp", "sub", "sup", "strike", "center", "blockquote",
          "hr", "br", "col", "font", "span", "div", "img",
          "ul", "ol", "li", "dd", "dt", "dl", "tbody", "thead", "tfoot",
          "table", "td", "th", "tr", "colgroup", "fieldset", "legend"
      ).toFactory();

    StringBuilder htmlOut = new StringBuilder();
    HtmlSanitizer.Policy policy = policyBuilder.apply(
        // The tag balancer passes events to AppendDomainAfterText which
        // assumes that openTag and closeTag events line up with one-another.
        new TagBalancingHtmlStreamEventReceiver(
            // The domain appender forwards events to the HTML renderer,
            new AppendDomainAfterText(
                // which puts tags and text onto the output buffer.
                HtmlStreamRenderer.create(htmlOut, Handler.DO_NOTHING)
            )
        )
    );

    for (String input : argv) {
      HtmlSanitizer.sanitize(input, policy);
    }

    out.append(htmlOut);
  }

  public static void main(String... argv) throws IOException {
    run(System.out, argv);
    System.out.println();
  }


  /**
   * The domain (actually authority component) of an HTML5 URL.
   * If the input is not hierarchical, then this has undefined behavior.
   */
  private static String domainOf(String url) {
    int start = -1;
    if (url.startsWith("//")) {
      start = 2;
    } else {
      start = url.indexOf("://");
      if (start >= 0) { start += 3; }
    }
    if (start < 0) { return null; }
    for (int i = 0; i < start - 3; ++i) {
      switch (url.charAt(i)) {
      case '/': case '?': case '#': return null;
      }
    }
    int end = url.length();
    for (int i = start; i < end; ++i) {
      switch (url.charAt(i)) {
      case '/': case '?': case '#': end = i; break;
      }
    }
    if (start < end) {
      return url.substring(start, end);
    } else {
      return null;
    }
  }
}