blib/lib/HTML/Defang.pm

filter: Statementstmt 91.5% 586 / 640 Branchbran 69.1% 322 / 466 Conditioncond 54.9% 127 / 231 MC/DCmcdc 34.1% 43 / 126 Subroutinesub 86.8% 33 / 38 Podpod 47.8% 11 / 23 totaltotal 73.6% 1122 / 1524 CC 328 SCAR 37.7
CC
328
Cov
77%
get_applicable_charset
90.0
defang
75.8
cleanup_style
67.7
CRAP 43.4
↑ Summary
1 package HTML::Defang;
2  
3 =head1 NAME
4  
5 HTML::Defang - Cleans HTML as well as CSS of scripting and other executable contents, and neutralises XSS attacks.
6  
7 =head1 SYNOPSIS
8  
9 my $InputHtml = "<html><body></body></html>";
10  
11 my $Defang = HTML::Defang->new(
12 context => $Self,
13 fix_mismatched_tags => 1,
14 tags_to_callback => [ br embed img ],
15 tags_callback => \&DefangTagsCallback,
16 url_callback => \&DefangUrlCallback,
17 css_callback => \&DefangCssCallback,
18 attribs_to_callback => [ qw(border src) ],
19 attribs_callback => \&DefangAttribsCallback,
20 content_callback => \&ContentCallback,
21 );
22  
23 my $SanitizedHtml = $Defang->defang($InputHtml);
24  
25 # Callback for custom handling specific HTML tags
26 sub DefangTagsCallback {
27 my ($Self, $Defang, $OpenAngle, $lcTag, $IsEndTag, $AttributeHash, $CloseAngle, $HtmlR, $OutR) = @_;
28  
29 # Explicitly defang this tag, eventhough safe
30 return DEFANG_ALWAYS if $lcTag eq 'br';
31  
32 # Explicitly whitelist this tag, eventhough unsafe
33 return DEFANG_NONE if $lcTag eq 'embed';
34  
35 # I am not sure what to do with this tag, so process as HTML::Defang normally would
36 return DEFANG_DEFAULT if $lcTag eq 'img';
37 }
38  
39 # Callback for custom handling URLs in HTML attributes as well as style tag/attribute declarations
40 sub DefangUrlCallback {
41 my ($Self, $Defang, $lcTag, $lcAttrKey, $AttrValR, $AttributeHash, $HtmlR) = @_;
42  
43 # Explicitly allow this URL in tag attributes or stylesheets
44 return DEFANG_NONE if $$AttrValR =~ /safesite.com/i;
45  
46 # Explicitly defang this URL in tag attributes or stylesheets
47 return DEFANG_ALWAYS if $$AttrValR =~ /evilsite.com/i;
48 }
49  
50 # Callback for custom handling style tags/attributes
51 sub DefangCssCallback {
52 my ($Self, $Defang, $Selectors, $SelectorRules, $Tag, $IsAttr) = @_;
53 my $i = 0;
54 foreach (@$Selectors) {
55 my $SelectorRule = $$SelectorRules[$i];
56 foreach my $KeyValueRules (@$SelectorRule) {
57 foreach my $KeyValueRule (@$KeyValueRules) {
58 my ($Key, $Value) = @$KeyValueRule;
59  
60 # Comment out any '!important' directive
61 $$KeyValueRule[2] = DEFANG_ALWAYS if $Value =~ '!important';
62  
63 # Comment out any 'position=fixed;' declaration
64 $$KeyValueRule[2] = DEFANG_ALWAYS if $Key =~ 'position' && $Value =~ 'fixed';
65 }
66 }
67 $i++;
68 }
69 }
70  
71 # Callback for custom handling HTML tag attributes
72 sub DefangAttribsCallback {
73 my ($Self, $Defang, $lcTag, $lcAttrKey, $AttrValR, $HtmlR) = @_;
74  
75 # Change all 'border' attribute values to zero.
76 $$AttrValR = '0' if $lcAttrKey eq 'border';
77  
78 # Defang all 'src' attributes
79 return DEFANG_ALWAYS if $lcAttrKey eq 'src';
80  
81 return DEFANG_NONE;
82 }
83  
84 # Callback for all content between tags (except <style>, <script>, etc)
85 sub DefangContentCallback {
86 my ($Self, $Defang, $ContentR) = @_;
87  
88 $$ContentR =~ s/remove this content//;
89 }
90  
91 =head1 DESCRIPTION
92  
93 This module accepts an input HTML and/or CSS string and removes any executable code including scripting, embedded objects, applets, etc., and neutralises any XSS attacks. A whitelist based approach is used which means only HTML known to be safe is allowed through.
94  
95 HTML::Defang uses a custom html tag parser. The parser has been designed and tested to work with nasty real world html and to try and emulate as close as possible what browsers actually do with strange looking constructs. The test suite has been built based on examples from a range of sources such as http://ha.ckers.org/xss.html and http://imfo.ru/csstest/css_hacks/import.php to ensure that as many as possible XSS attack scenarios have been dealt with.
96  
97 HTML::Defang can make callbacks to client code when it encounters the following:
98  
99 =over 4
100  
101 =item *
102  
103 When a specified tag is parsed
104  
105 =item *
106  
107 When a specified attribute is parsed
108  
109 =item *
110  
111 When a URL is parsed as part of an HTML attribute, or CSS property value.
112  
113 =item *
114  
115 When style data is parsed, as part of an HTML style attribute, or as part of an HTML <style> tag.
116  
117 =back
118  
119 The callbacks include details about the current tag/attribute that is being parsed, and also gives a scalar reference to the input HTML. Querying pos() on the input HTML should indicate where the module is with parsing. This gives the client code flexibility in working with HTML::Defang.
120  
121 HTML::Defang can defang whole tags, any attribute in a tag, any URL that appear as an attribute or style property, or any CSS declaration in a declaration block in a style rule. This helps to precisely block the most specific unwanted elements in the contents(for example, block just an offending attribute instead of the whole tag), while retaining any safe HTML/CSS.
122  
123 =cut
124  
125 9 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
126 9 our @ISA = ('Exporter');
127 9 %EXPORT_TAGS = (all => [qw(@FormTags DEFANG_NONE DEFANG_ALWAYS DEFANG_DEFAULT)]);
128 9 Exporter::export_ok_tags('all');
129  
130 9 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
131 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
132 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
133  
134 9 our $VERSION=1.09;
135  
136 9 ▶use constant DEFANG_NONE => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
137 9 ▶use constant DEFANG_ALWAYS => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
138 9 ▶use constant DEFANG_DEFAULT => 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
139  
140 9 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
141  
142 9 my $HasScalarReadonly = 0;
143 0 ▶BEGIN { eval "use Scalar::Readonly qw(readonly_on);" && ($HasScalarReadonly = 1); }
Subroutine BEGIN: called CC=2 SCAR=9.2
Subroutine BEGIN: called CC=1 SCAR=1.2
Branch: 1 branch
BranchTrueFalseTotal
eval "use Scalar::Readonly qw(readonly_on);" and $HasScalarReadonly = 1 0 9 9
144  
145 9 our @FormTags = qw(form input textarea select option button fieldset label legend multicol nextid optgroup);
146  
147 # Some regexps for matching HTML tags + key=value attributes
148 9 my $AttrKeyStartLineRE = qr/(?:[^=<>\s\/\\]{1,}|[\/](?!\s*>))/;
149 9 my $AttrKeyRE = qr/(?<=[\s'"\/])$AttrKeyStartLineRE/;
150 9 my $AttrValRE = qr/[^>\s'"`][^>\s]*|'[^']*?'|"[^"]*?"|`[^`]*?`/;
151 9 my $AttributesRE = qr/(?:(?:$AttrKeyRE\s*)?(?:=\s*$AttrValRE\s*)?)*/;
152 9 my $TagNameRE = qr/[A-Za-z][A-Za-z0-9\#\&\;\:\!_-]*/;
153  
154 9 my $StyleSelectors = qr/[^{}\s][^{}]{0,1024}?/;
155 9 my $StyleName = qr/[^:}\s][^:{}]*?/;
156 9 my $StyleValue = qr/[^;}\s][^;}]*|.*$/;
157 9 my $StyleRule = qr/$StyleName\s*:\s*$StyleValue\s*/;
158 9 my $StyleRules = qr/\s*(?:$StyleRule)?(?:;\s*$StyleRule)*(?:;\s*)*/;
159 9 my $StyleMediaSelector = qr/\@media\b[^{]*/;
160 9 my $RECStyleMediaSelector = qr{\G(\s*)($StyleMediaSelector)(\{)(\s*)}so;
161 9 my $RECStyleNaked = qr/\G(\s*)()()()($StyleRules)()(\s*)/o;
162 9 my $RECStyleSelected = qr/\G(\s*)((?:$StyleSelectors)?)(\s*)(\{)($StyleRules)(\})(\s*)/o;
163  
164 9 my $Fonts = qr/["']?([A-Za-z0-9\s-]+)["']?/;
165 9 my $Alignments = qr/(absbottom|absmiddle|all|autocentre|baseline|bottom|center|justify|left|middle|none|right|texttop|top)/;
166  
167 9 my $Executables = '([^@]\.com|'.
168 '.*\.(exe|cmd|bat|pif|scr|sys|sct|lnk|dll'.
169 '|vbs?|vbe|hta|shb|shs|hlp|chm|eml|wsf|wsh|js'.
170 '|asx|wm.|mdb|mht|msi|msp|cpl|lib|reg))';
171 9 my $SrcBanStd = qr/^([A-Za-z]*script|.*\&\{|mocha|about|opera|mailto:|hcp:|\/(dev|proc)|\\|file|smb|cid:${Executables}(@|\?|$))/i;
172  
173 9 my %Rules =
174 (
175 # Disallow unknown tags by default
176 "_unknown" => qr/.*/,
177 "align" => qr/^${Alignments}$/i,
178 "alnum" => qr/^[A-Za-z0-9_.-]+$/,
179 "boolean" => qr/^(0|1|true|yes|no|false)$/,
180 "charset" => qr/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/,
181 "class" => qr/^[A-Za-z0-9_.:\s-]*$/,
182 "color" => qr/^#?[0-9A-Z]+$/i,
183 "coords" => qr/^(\d+,)+\d+$/i,
184 "datetime" => qr/^\d\d\d\d-\d\d-\d\d.{0,5}\d\d:\d\d:\d\d.{0,5}$/,
185 "dir" => qr/^(ltr|rtl)$/i,
186 "empty" => qr/^$/i,
187 "eudora" => qr/^(autourl)$/i,
188 "font-face" => qr/^((${Fonts})[,\s]*)+$/i,
189 "form-enctype" => qr/^(application\/x-www-form-urlencoded|multipart\/form-data)$/i,
190 "form-method" => qr/^(get|post)$/i,
191 "frame" => qr/^(void|above|below|hsides|vsides|lhs|rhs|box|border)$/i,
192 # href: Not javascript, vbs or vbscript
193 "href" => [ qr/^((?:[a-z]*script|mocha|opera|about|data|tcl)\s*:|.*\&\{|hcp|smb|\/dev\/|<)/i ],
194 "usemap-href" => qr/^#[A-Za-z0-9_.-]+$/, # this is not really a href at all!
195 "input-size" => qr/^(\d{1,4})$/, # some browsers freak out with very large widgets
196 "input-type" => qr/^(button|checkbox|file|hidden|image|password|radio|readonly|reset|submit|text)$/i,
197 "integer" => qr/^(-|\+)?\d+$/,
198 "number" => qr/^(-|\+)?[\d.,]+$/,
199 # language: Not javascript, vbs or vbscript
200 "language" => qr/^(XML)$/i,
201 "media" => qr/^((screen|print|projection|braille|speech|all)[,\s]*)+$/i,
202 "meta:name" => qr/^(author|progid|originator|generator|keywords|description|content-type|pragma|expires)$/i,
203 # mime-type: Not javascript
204 "mime-type" => qr/^(cite|text\/(plain|css|html|xml))$/i,
205 "list-type" => qr/^(none,a,i,upper-alpha,lower-alpha,upper-roman,lower-roman,decimal,disc,square,circle,round)$/i,
206 # "rel" => qr/^((copyright|author|stylesheet)\s*)+$/i,
207 "rel" => qr/^((copyright|author)\s*)+$/i, # XXX external stylesheets can contain scripting, so kill them
208 "rules" => qr/^(none|groups|rows|cols|all)$/i,
209 "scope" => qr/^(row|col|rowgroup|colgroup)$/i,
210 "shape" => qr/^(rect|rectangle|circ|circle|poly|polygon)$/i,
211 # The following two are for URLs we expect to be auto-loaded by the browser,
212 # because they are within a frame, image or something like that.
213 # "src" => qr/^([a-z]+):|^[\w\.\/\%]+$/i,
214 "src" => qr/^https?:\/\/|^[\w.\/%]+$/i,
215 # "style" => qr/^([A-Za-z0-9_-]+\\s*:\\s*(yes|no)|text-align\\s*:\\s*$alignments|((background|(background-|font-)?color)\\s*:\\s*(\\#?[A-Z0-9]+)?|((margin|padding|border)-(right|left)|tab-interval|height|width)\\s*:\\s*[\\d\\.]+(pt|px)|font(-family|-size|-weight|)\\s*:(\\s*[\\d\\.]+(pt|px)|\\s*$fonts)+)[;\\s]*)+\$/i,
216 # "style" => qr/expression|eval|script:|mocha:|\&{|\@import|(?<!background-)position:|background-image/i, # XXX there are probably a million more ways to cause trouble with css!
217 "style" => qr/^.*$/s,
218 #kc In addition to this, we could strip all 'javascript:|expression|' etc. from all attributes(in attribute_cleanup())
219 "stylesheet" => [ qr/expression|eval|script:|mocha:|\&\{|\@import/i ], # stylesheets are forbidden if Embedded => 1. css positioning can be allowed in an iframe.
220 # NB see also `process_stylesheet' below
221 "style-type" => [ qr/script|mocha/i ],
222 "size" => qr/^[\+\-]?[\d.]+(px|%)?$/i,
223 "target" => qr/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/,
224 "base-href" => qr/^https?:\/\/[\w.\/]+$/,
225 "anything" => qr/^.*$/, #[ 0, 0 ],
226 "meta:content" => [ qr// ],
227 );
228  
229 9 my %CommonAttributes =
230 (
231 # Core attributes
232 "class" => "class",
233 "id" => "alnum",
234 "name" => "alnum",
235 "style" => "style",
236 "accesskey" => "alnum",
237 "tabindex" => "integer",
238 "title" => "anything",
239 # Language attributes
240 "dir" => "dir",
241 "lang" => "alnum",
242 "language" => "language",
243 "longdesc" => "anything",
244 # Height, width, alignment, etc.
245 "align" => "align",
246 "bgcolor" => "color",
247 "bottommargin" => "size",
248 "clear" => "align",
249 "color" => "color",
250 "height" => "size",
251 "leftmargin" => "size",
252 "marginheight" => "size",
253 "marginwidth" => "size",
254 "nowrap" => "anything",
255 "rightmargin" => "size",
256 "scroll" => "boolean",
257 "scrolling" => "boolean",
258 "topmargin" => "size",
259 "type" => "mime-type",
260 "valign" => "align",
261 "width" => "size",
262 "/" => "empty",
263 );
264  
265 9 my %ListAttributes =
266 (
267 "compact" => "anything",
268 "start" => "integer",
269 "type" => "list-type",
270 );
271  
272 9 my %TableAttributes =
273 (
274 "axis" => "alnum",
275 "background" => "src",
276 "border" => "number",
277 "bordercolor" => "color",
278 "bordercolordark" => "color",
279 "bordercolorlight" => "color",
280 "padding" => "integer",
281 "spacing" => "integer",
282 "cellpadding" => "integer",
283 "cellspacing" => "integer",
284 "cols" => "anything",
285 "colspan" => "integer",
286 "char" => "alnum",
287 "charoff" => "integer",
288 "datapagesize" => "integer",
289 "frame" => "frame",
290 "frameborder" => "boolean",
291 "framespacing" => "integer",
292 "headers" => "anything",
293 "rows" => "anything",
294 "rowspan" => "size",
295 "rules" => "rules",
296 "scope" => "scope",
297 "span" => "integer",
298 "summary" => "anything"
299 );
300  
301 9 my %UrlRules = (
302 "src" => 1,
303 "href" => 1,
304 "base-href" => 1,
305 # cite => 1,
306 # action => 1,
307 );
308  
309 9 my %Tags = (
310 script => \&defang_script_tag,
311 style => \&defang_style_tag,
312 "html" => 100,
313 #
314 # Safe elements commonly found in the <head> block follow.
315 #
316 "head" => 2,
317 "base" =>
318 {
319 "href" => "base-href",
320 "target" => "target",
321 },
322 # TODO: Deal with link below later
323 #"link" => \$r_link,
324 # {
325 # "rel" => "rel",
326 # "rev" => "rel",
327 # "src" => "src",
328 # "href" => "src", # Might be auto-loaded by the browser!!
329 # "charset" => "charset",
330 # "media" => "media",
331 # "target" => "target",
332 # "type" => "mime-type",
333 # },
334 "meta" =>
335 {
336 "_score" => 2,
337 "content" => "meta:content",
338 "http-equiv" => "meta:name",
339 "name" => "meta:name",
340 "charset" => "charset",
341 },
342 "title" => 2,
343 #
344 # Safe elements commonly found in the <body> block follow.
345 #
346 "body" =>
347 {
348 "_score" => 2,
349 "link" => "color",
350 "alink" => "color",
351 "vlink" => "color",
352 "background" => "src",
353 "nowrap" => "boolean",
354 "text" => "color",
355 "vlink" => "color",
356 },
357 "a" =>
358 {
359 "charset" => "charset",
360 "coords" => "coords",
361 "href" => "href",
362 "shape" => "shape",
363 "target" => "target",
364 "type" => "mime-type",
365 "eudora" => "eudora",
366 "notrack" => "anything",
367 },
368 "address" => 1,
369 "area" =>
370 {
371 "alt" => "anything",
372 "coords" => "coords",
373 "href" => "href",
374 "nohref" => "anything",
375 "shape" => "shape",
376 "target" => "target",
377 },
378 "article" => 1,
379 "applet" => 0,
380 "basefont" =>
381 {
382 "face" => "font-face",
383 "family" => "font-face",
384 "back" => "color",
385 "size" => "number",
386 "ptsize" => "number",
387 },
388 "bdo" => 1,
389 "bgsound" =>
390 {
391 "balance" => "integer",
392 "delay" => "integer",
393 "loop" => "alnum",
394 "src" => "src",
395 "volume" => "integer",
396 },
397 "blockquote" =>
398 {
399 "cite" => "href",
400 "type" => "mime-type",
401 },
402 "br" => 1,
403 "button" => # FORM
404 {
405 "type" => "input-type",
406 "disabled" => "anything",
407 "value" => "anything",
408 "tabindex" => "number",
409 },
410 "caption" => 1,
411 "center" => 1,
412 "col" => \%TableAttributes,
413 "colgroup" => \%TableAttributes,
414 "comment" => 1,
415 "dd" => 1,
416 "del" =>
417 {
418 "cite" => "href",
419 "datetime" => "datetime",
420 },
421 "dir" => \%ListAttributes,
422 "div" => 1,
423 "dl" => \%ListAttributes,
424 "dt" => 1,
425 "embed" => 0,
426 "fieldset" => 1, # FORM
427 "font" =>
428 {
429 "face" => "font-face",
430 "family" => "font-face",
431 "back" => "color",
432 "size" => "number",
433 "ptsize" => "number",
434 },
435 "footer" => 1,
436 "form" => # FORM
437 {
438 "method" => "form-method",
439 "action" => "href",
440 "enctype" => "form-enctype",
441 "accept" => "anything",
442 "accept-charset" => "anything",
443 },
444 "header" => 1,
445 "hr" =>
446 {
447 "size" => "number",
448 "noshade" => "anything",
449 },
450 "h1" => 1,
451 "h2" => 1,
452 "h3" => 1,
453 "h4" => 1,
454 "h5" => 1,
455 "h6" => 1,
456 "iframe" => 0,
457 "ilayer" => 0,
458 "img" =>
459 {
460 "alt" => "anything",
461 "border" => "size",
462 "dynsrc" => "src",
463 "hspace" => "size",
464 "ismap" => "anything",
465 "loop" => "alnum",
466 "lowsrc" => "src",
467 "nosend" => "alnum",
468 "src" => "src",
469 "start" => "alnum",
470 "usemap" => "usemap-href",
471 "vspace" => "size",
472 },
473 "inlineinput" => 0,
474 "input" => # FORM
475 {
476 "type" => "input-type",
477 "disabled" => "anything",
478 "value" => "anything",
479 "maxlength" => "input-size",
480 "size" => "input-size",
481 "readonly" => "anything",
482 "tabindex" => "number",
483 "checked" => "anything",
484 "accept" => "anything",
485 # for type "image":
486 "alt" => "anything",
487 "border" => "size",
488 "dynsrc" => "src",
489 "hspace" => "size",
490 "ismap" => "anything",
491 "loop" => "alnum",
492 "lowsrc" => "src",
493 "nosend" => "alnum",
494 "src" => "src",
495 "start" => "alnum",
496 "usemap" => "usemap-href",
497 "vspace" => "size",
498 },
499 "ins" =>
500 {
501 "cite" => "href",
502 "datetime" => "datetime",
503 },
504 "isindex" => 0,
505 "keygen" => 0,
506 "label" => # FORM
507 {
508 "for" => "alnum",
509 },
510 "layer" => 0,
511 "legend" => 1, # FORM
512 "li" => {
513 "value" => "integer",
514 },
515 "listing" => 0,
516 "map" => 1,
517 "marquee" => 0,
518 "menu" => \%ListAttributes,
519 "multicol" => 0,
520 "nextid" => 0,
521 "nobr" => 0,
522 "noembed" => 1,
523 "nolayer" => 1,
524 # Pretend our defang result is going into a non-scripting environment,
525 # even though javascript is likely enabled, so just defang all noscript tags
526 "noscript" => 0,
527 "noembed" => 1,
528 "object" => 0,
529 "ol" => \%ListAttributes,
530 "optgroup" => # FORM
531 {
532 "disabled" => "anything",
533 "label" => "anything",
534 },
535 "option" => # FORM
536 {
537 "disabled" => "anything",
538 "label" => "anything",
539 "selected" => "anything",
540 "value" => "anything",
541 },
542 "o:p" => 1,
543 "p" => 1,
544 "param" => 0,
545 "plaintext"=> 0,
546 "pre" => 1,
547 "rt" => 0,
548 "ruby" => 0,
549 "section" => 1,
550 "select" => # FORM
551 {
552 "disabled" => "anything",
553 "multiple" => "anything",
554 "size" => "input-size",
555 "tabindex" => "number",
556 },
557 "spacer" => 0,
558 "span" => 1,
559 "spell" => 0,
560 "sound" =>
561 {
562 "delay" => "number",
563 "loop" => "integer",
564 "src" => "src",
565 },
566 "table" => \%TableAttributes,
567 "tbody" => \%TableAttributes,
568 "textarea" => # FORM
569 {
570 "cols" => "input-size",
571 "rows" => "input-size",
572 "disabled" => "anything",
573 "readonly" => "anything",
574 "tabindex" => "number",
575 "wrap" => "anything",
576 },
577 "td" => \%TableAttributes,
578 "tfoot" => \%TableAttributes,
579 "th" => \%TableAttributes,
580 "thead" => \%TableAttributes,
581 "tr" => \%TableAttributes,
582 "ul" => \%ListAttributes,
583 "wbr" => 1,
584 "xml" => 0,
585 "xmp" => 0,
586 "x-html" => 0,
587 "x-tab" => 1,
588 "x-sigsep" => 1,
589 # Character formatting
590 "abbr" => 1,
591 "acronym"=> 1,
592 "big" => 1,
593 "blink" => 0,
594 "b" => 1,
595 "cite" => 1,
596 "code" => 1,
597 "dfn" => 1,
598 "em" => 1,
599 "i" => 1,
600 "kbd" => 1,
601 "q" => 1,
602 "s" => 1,
603 "samp" => 1,
604 "small" => 1,
605 "strike" => 1,
606 "strong" => 1,
607 "sub" => 1,
608 "sup" => 1,
609 "tt" => 1,
610 "u" => 1,
611 "var" => 1,
612 #
613 # Safe elements commonly found in the <frameset> block follow.
614 #
615 "frameset" => 0,
616 "frame" => 0,
617 "noframes" => 1,
618 );
619  
620 9 my %MathMLTags = (
621 mi => 1,
622 mn => 1,
623 mo => 1,
624 mtext => 1,
625 mspace => 1,
626 ms => 1,
627 mglyph => 1,
628 mrow => 1,
629 mfrac => 1,
630 msqrt => 1,
631 mroot => 1,
632 mstyle => 1,
633 merror => 1,
634 mpadded => 1,
635 mphantom => 1,
636 mfenced => 1,
637 menclose => 1,
638 msub => 1,
639 msup => 1,
640 msubsup => 1,
641 munder => 1,
642 mover => 1,
643 munderover => 1,
644 mmultiscripts => 1,
645 mtable => 1,
646 mtr => 1,
647 mtd => 1,
648 maligngroup => 1,
649 malignmark => 1,
650 mlabeledtr => 1,
651 maction => 1,
652 );
653  
654 # Some entity conversions for attributes
655 9 my $CtrlChars = qr/[\x00-\x08\x0b-\x1f]/;
656 9 my %EntityToChar = (quot => '"', apos => "'", amp => '&', 'lt' => '<', 'gt' => '>');
657 9 my %CharToEntity = ((reverse %EntityToChar), ' ' => '#x20', '/' => '#x2f', "\x09" => '#x09', "\x0a" => '#x0a');
658 9 my %QuoteRe = ('"' => qr/(["&<>\x09\x0a])/, "'" => qr/(['&<>\x09\x0a])/, "" => qr/(['"&<> \/\x09\x0a])/);
659  
660 # When fixing mismatched tags, sometimes a close tag
661 # shouldn't close all the way out
662 # For example, consider:
663 # <table><tr><td><table><tr></td>
664 # A naive version would see the ending </td>, and thus
665 # try to fix the mismatched tags by doing:
666 # <table><tr><td><table><tr></tr></table></td>
667 # This is not what a browser does. So given a tag, we
668 # give a list of closing tags which cause us to stop
669 # and not close any more
670 9 my %MismatchedTagNest = (
671 table => [ qw(tbody thead tfoot tr th td caption colgroup col) ],
672 tbody => [ qw(tr th td) ],
673 tr => [ qw(th td) ],
674 font => [ '' ],
675 );
676 # Convert to hash of hashes
677 9 $_ = { map { $_ => 1 } @$_ } for values %MismatchedTagNest;
678  
679 # If we see a table, we should expect to see a tbody
680 # next. If not, we need to add it because the browser
681 # will implicitly open it!
682 # For each tag, give list of tags that should follow. If
683 # we don't find one of them following, we open a new
684 # implicit tag of the first one in the list
685 # eg. <table><td> -> <table><tr><td>
686 9 my %ImplicitOpenTags = (
687 table => [ qw(tr tbody thead tfoot caption colgroup col) ],
688 thead => [ qw(tr) ],
689 tbody => [ qw(tr) ],
690 tr => [ qw(td th) ],
691 );
692 # Convert to hash of hashes
693 9 $_ = { default => $_->[0], map { $_ => 1 } @$_ } for values %ImplicitOpenTags;
694  
695 9 my %TableTags = map { $_ => 1 } qw(table tbody thead tfoot tr td th caption colgroup col);
696 9 my %BlockTags = map { $_ => 1 } qw(h1 h2 h3 h4 h5 h6 p div pre plaintext address blockquote center form table tbody thead tfoot tr td th caption colgroup col dl ul ol li fieldset);
697 9 my %InlineTags = map { $_ => 1 } qw(span abbr acronym q sub sup cite code em kbd samp strong var dfn strike b i u s tt small big nobr a font);
698 9 my %NestInlineTags = map { $_ => 1 } qw(span abbr acronym q sub sup cite code em kbd samp strong var dfn strike b i u s tt small big nobr);
699  
700 # Default list of mismatched tags to track
701 9 my %MismatchedTags = (%BlockTags, %InlineTags);
702  
703 # Elements whose contents are RCDATA (title, textarea) or RAWTEXT (noembed,
704 # noframes): the browser does not parse comments or nested tags inside them,
705 # only a matching end tag. We must consume their content as opaque text
706 # rather than parsing it as HTML, or an attacker can smuggle a literal end
707 # tag + active markup past us. See defang_rcdata_content(). (<script>,
708 # <style> and the defanged raw-text tags like <xmp>/<iframe> are handled
709 # separately.)
710 9 my %RawTextTags = map { $_ => 1 } qw(title textarea noembed noframes);
711  
712 =head1 CONSTRUCTOR
713  
714 =over 4
715  
716 =cut
717  
718 =item I<HTML::Defang-E<gt>new(%Options)>
719  
720 Constructs a new HTML::Defang object. The following options are supported:
721  
722 =over 4
723  
724 =item B<Options>
725  
726 =over 4
727  
728 =item B<tags_to_callback>
729  
730 Array reference of tags for which a call back should be made. If a tag in this array is parsed, the subroutine tags_callback() is invoked.
731  
732 =item B<attribs_to_callback>
733  
734 Array reference of tag attributes for which a call back should be made. If an attribute in this array is parsed, the subroutine attribs_callback() is invoked.
735  
736 =item B<tags_callback>
737  
738 Subroutine reference to be invoked when a tag listed in @$tags_to_callback is parsed.
739  
740 =item B<attribs_callback>
741  
742 Subroutine reference to be invoked when an attribute listed in @$attribs_to_callback is parsed.
743  
744 =item B<url_callback>
745  
746 Subroutine reference to be invoked when a URL is detected in an HTML tag attribute or a CSS property.
747  
748 =item B<css_callback>
749  
750 Subroutine reference to be invoked when CSS data is found either as the contents of a 'style' attribute in an HTML tag, or as the contents of a <style> HTML tag.
751  
752 =item B<content_callback>
753  
754 Subroutine reference to be invoked when standard content between HTML tags in found.
755  
756 =item B<fix_mismatched_tags>
757  
758 This property, if set, fixes mismatched tags in the HTML input. By default, tags present in the default %mismatched_tags_to_fix hash are fixed. This set of tags can be overridden by passing in an array reference $mismatched_tags_to_fix to the constructor. Any opened tags in the set are automatically closed if no corresponding closing tag is found. If an unbalanced closing tag is found, that is commented out.
759  
760 =item B<mismatched_tags_to_fix>
761  
762 Array reference of tags for which the code would check for matching opening and closing tags. See the property $fix_mismatched_tags.
763  
764 =item B<context>
765  
766 You can pass an arbitrary scalar as a 'context' value that's then passed as the first parameter to all callback functions. Most commonly this is something like '$Self'
767  
768 =item B<allow_double_defang>
769  
770 If this is true, then tag names and attribute names which already begin
771 with the defang string ("defang_" by default) will have an additional
772 copy of the defang string prepended if they are flagged to be defanged
773 by the return value of a callback, or if the tag or attribute name
774 is unknown.
775  
776 The default is to assume that tag names and attribute names beginning
777 with the defang string are already made safe, and need no further
778 modification, even if they are flagged to be defanged by the
779 return value of a callback. Any tag or attribute modifications made
780 directly by a callback are still performed.
781  
782 =item B<delete_defang_content>
783  
784 Normally defanged tags are turned into comments and prefixed by defang_,
785 and defanged styles are surrounded by /* ... */. If this is set to
786 true, then defanged content is deleted instead
787  
788 =item B<Debug>
789  
790 If set, prints debugging output.
791  
792 =back
793  
794 =back
795  
796 =cut
797  
798 26 ▶sub new {
Subroutine new: called CC=7 SCAR=20.2
Pod documented
799 26 my $Proto = shift;
800 26 ▶ my $Class = ref($Proto) || $Proto;
Condition33%1/3
ref $Proto || $Proto
l!l&&r!l&&!r
0260
MC/DC0%0/2
ref $Proto || $Proto
ref $Proto $Proto
Truth table33%1/3
A || B
A= ref $ProtoB= $Proto
ABresult
1X1
011
000
801  
802 26 my %Opts = @_;
803  
804 my ($tags_to_callback, $attribs_to_callback, $empty_tags_to_collapse, $mismatched_tags_to_fix)
805 26 = @Opts{qw(tags_to_callback attribs_to_callback empty_tags_to_collapse mismatched_tags_to_fix)};
806 26 my %tags_to_callback;
807 26 ▶ %tags_to_callback = map { $_ => 1 } @$tags_to_callback if $tags_to_callback;
Branch: 1 branch
BranchTrueFalseTotal
if $tags_to_callback 10 16 26
808 26 my %attribs_to_callback;
809 0 ▶ %attribs_to_callback = map { $_ => 1 } @$attribs_to_callback if $attribs_to_callback;
Branch: 1 branch
BranchTrueFalseTotal
if $attribs_to_callback 0 26 26
810 26 my %empty_tags_to_collapse;
811 0 ▶ %empty_tags_to_collapse = map { $_ => 1 } @$empty_tags_to_collapse if $empty_tags_to_collapse;
Branch: 1 branch
BranchTrueFalseTotal
if $empty_tags_to_collapse 0 26 26
812 26 my %mismatched_tags_to_fix = %MismatchedTags;
813 26 ▶ %mismatched_tags_to_fix = map { $_ => 1 } @$mismatched_tags_to_fix if $mismatched_tags_to_fix;
Branch: 1 branch
BranchTrueFalseTotal
if $mismatched_tags_to_fix 1 25 26
814  
815 my $Self = {
816 defang_string => 'defang_',
817 defang_re => qr/^defang_/,
818 defang_default => (defined $Opts{defang_default} ? $Opts{defang_default} : DEFANG_DEFAULT),
819 allow_double_defang => $Opts{allow_double_defang},
820 tags_to_callback => \%tags_to_callback,
821 tags_callback => $Opts{tags_callback},
822 attribs_to_callback => \%attribs_to_callback,
823 attribs_callback => $Opts{attribs_callback},
824 url_callback => $Opts{url_callback},
825 css_callback => $Opts{css_callback},
826 content_callback => $Opts{content_callback},
827 mismatched_tags_to_fix => \%mismatched_tags_to_fix,
828 fix_mismatched_tags => $Opts{fix_mismatched_tags},
829 context => $Opts{context},
830 opened_tags => [],
831 opened_tags_count => {},
832 closed_into_block_tags => [],
833 empty_tags_to_collapse => \%empty_tags_to_collapse,
834 quiet => $Opts{quiet},
835 delete_defang_content => $Opts{delete_defang_content},
836 Debug => $Opts{Debug},
837 26 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
defined $Opts{'defang_default'} ? : 0 26 26
838  
839 26 bless ($Self, $Class);
840 26 return $Self;
841 }
842  
843 =item I<HTML::Defang-E<gt>new_bodyonly(%Options)>
844  
845 Constructs a new HTML::Defang object that has the following
846 implicit options
847  
848 =over 4
849  
850 =item B<fix_mismatched_tags = 1>
851  
852 =item B<delete_defang_content = 1>
853  
854 =item B<tags_to_callback = [ qw(html head link body meta title bgsound) ]>
855  
856 =item B<tags_callback = { ... remove all above tags and related content ... }>
857  
858 =item B<url_callback = { ... explicity DEFANG_NONE to leave everything alone ... }>
859  
860 =back
861  
862 Basically this is a easy way to remove all html boiler plate
863 content and return only the html body content.
864  
865 =cut
866  
867 0 ▶sub new_bodyonly {
Subroutine new_bodyonly: not called CC=1 SCAR=6.9
Pod documented
868 return shift->new(
869 fix_mismatched_tags => 1,
870 delete_defang_content => 1,
871 tags_to_callback => [ qw(html head link body meta title bgsound) ],
872 0 ▶ tags_callback => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
873 0 my (undef, $Defang, $Angle, $lcTag, $IsEndTag, $AttributeHash, $AttributesEnd, $HtmlR, $OutR) = @_;
874 0 ▶ $$HtmlR =~ m{\G.*?(?=</title|</head)}gcis if $lcTag eq 'title' && !$IsEndTag;
Branch: 1 branch
BranchTrueFalseTotal
if $lcTag eq "title" and not $IsEndTag 0 0 0
Condition0%0/3
$lcTag eq "title" and not $IsEndTag
!ll&&!rl&&r
000
MC/DC0%0/2
$lcTag eq "title" and not $IsEndTag
$lcTag eq "title" not $IsEndTag
Truth table0%0/3
A and not(B)
A= $lcTag eq "title"B= not $IsEndTag
ABresult
0X0
100
111
875 0 return DEFANG_ALWAYS;
876 },
877 0 ▶ url_callback => sub { return DEFANG_NONE; },
Subroutine __ANON__: not called CC=1 SCAR=6.9
878 @_
879 0 );
880 }
881  
882 =back
883  
884 =cut
885  
886 =head1 CALLBACK METHODS
887  
888 =over 4
889  
890 =cut
891  
892 =item B<COMMON PARAMETERS>
893  
894 A number of the callbacks share the same parameters. These common parameters are documented here. Certain variables may have specific meanings in certain callbacks, so be sure to check the documentation for that method first before referring this section.
895  
896 =over 4
897  
898 =item I<$context>
899  
900 You can pass an arbitrary scalar as a 'context' value that's then passed as the first parameter to all callback functions. Most commonly this is something like '$Self'
901  
902 =item I<$Defang>
903  
904 Current HTML::Defang instance
905  
906 =item I<$OpenAngle>
907  
908 Opening angle(<) sign of the current tag.
909  
910 =item I<$lcTag>
911  
912 Lower case version of the HTML tag that is currently being parsed.
913  
914 =item I<$IsEndTag>
915  
916 Has the value '/' if the current tag is a closing tag.
917  
918 =item I<$AttributeHash>
919  
920 A reference to a hash containing the attributes of the current tag and
921 their values. Each value is a scalar reference to the value, rather
922 than just a scalar value. You can add attributes (remember to make it a
923 scalar ref, eg $AttributeHash{"newattr"} = \"newval"), delete attributes,
924 or modify attribute values in this hash, and any changes you make will
925 be incorporated into the output HTML stream.
926  
927 The attribute values will have any entity references decoded before
928 being passed to you, and any unsafe values we be re-encoded back into
929 the HTML stream.
930  
931 So for instance, the tag:
932  
933 <div title="&lt;&quot;Hi there &#x003C;">
934  
935 Will have the attribute hash:
936  
937 { title => \q[<"Hi there <] }
938  
939 And will be turned back into the HTML on output:
940  
941 <div title="&lt;&quot;Hi there &lt;">
942  
943 =item I<$CloseAngle>
944  
945 Anything after the end of last attribute including the closing HTML angle(>)
946  
947 =item I<$HtmlR>
948  
949 A scalar reference to the input HTML. The input HTML is parsed using
950 m/\G$SomeRegex/c constructs, so to continue from where HTML:Defang left,
951 clients can use m/\G$SomeRegex/c for further processing on the input. This
952 will resume parsing from where HTML::Defang left. One can also use the
953 pos() function to determine where HTML::Defang left off. This combined
954 with the add_to_output() method should give reasonable flexibility for
955 the client to process the input.
956  
957 =item I<$OutR>
958  
959 A scalar reference to the processed output HTML so far.
960  
961 =back
962  
963 =item I<tags_callback($context, $Defang, $OpenAngle, $lcTag, $IsEndTag, $AttributeHash, $CloseAngle, $HtmlR, $OutR)>
964  
965 If $Defang->{tags_callback} exists, and HTML::Defang has parsed a tag preset in $Defang->{tags_to_callback}, the above callback is made to the client code. The return value of this method determines whether the tag is defanged or not. More details below.
966  
967 =over 4
968  
969 =item B<Return values>
970  
971 =over 4
972  
973 =item DEFANG_NONE
974  
975 The current tag will not be defanged.
976  
977 =item DEFANG_ALWAYS
978  
979 The current tag will be defanged.
980  
981 =item DEFANG_DEFAULT
982  
983 The current tag will be processed normally by HTML:Defang as if there was no callback method specified.
984  
985 =back
986  
987 =back
988  
989 =item I<attribs_callback($context, $Defang, $lcTag, $lcAttrKey, $AttrVal, $HtmlR, $OutR)>
990  
991 If $Defang->{attribs_callback} exists, and HTML::Defang has parsed an attribute present in $Defang->{attribs_to_callback}, the above callback is made to the client code. The return value of this method determines whether the attribute is defanged or not. More details below.
992  
993 =over 4
994  
995 =item B<Method parameters>
996  
997 =over 4
998  
999 =item I<$lcAttrKey>
1000  
1001 Lower case version of the HTML attribute that is currently being parsed.
1002  
1003 =item I<$AttrVal>
1004  
1005 Reference to the HTML attribute value that is currently being parsed.
1006  
1007 See $AttributeHash for details of decoding.
1008  
1009 =back
1010  
1011 =item B<Return values>
1012  
1013 =over 4
1014  
1015 =item DEFANG_NONE
1016  
1017 The current attribute will not be defanged.
1018  
1019 =item DEFANG_ALWAYS
1020  
1021 The current attribute will be defanged.
1022  
1023 =item DEFANG_DEFAULT
1024  
1025 The current attribute will be processed normally by HTML:Defang as if there was no callback method specified.
1026  
1027 =back
1028  
1029 =back
1030  
1031 =item I<url_callback($context, $Defang, $lcTag, $lcAttrKey, $AttrVal, $AttributeHash, $HtmlR, $OutR)>
1032  
1033 If $Defang->{url_callback} exists, and HTML::Defang has parsed a URL, the above callback is made to the client code. The return value of this method determines whether the attribute containing the URL is defanged or not. URL callbacks can be made from <style> tags as well style attributes, in which case the particular style declaration will be commented out. More details below.
1034  
1035 =over 4
1036  
1037 =item B<Method parameters>
1038  
1039 =over 4
1040  
1041 =item I<$lcAttrKey>
1042  
1043 Lower case version of the HTML attribute that is currently being parsed. However if this callback is made as a result of parsing a URL in a style attribute, $lcAttrKey will be set to the string I<style>, or will be set to I<undef> if this callback is made as a result of parsing a URL inside a style tag.
1044  
1045 =item I<$AttrVal>
1046  
1047 Reference to the URL value that is currently being parsed.
1048  
1049 =item I<$AttributeHash>
1050  
1051 A reference to a hash containing the attributes of the current tag and their values. Each value is a scalar reference to the value,
1052 rather than just a scalar value. You can add attributes (remember to make it a scalar ref, eg $AttributeHash{"newattr"} = \"newval"), delete attributes, or modify attribute values in this hash, and any changes you make will be incorporated into the output HTML stream. Will be set to I<undef> if the callback is made due to URL in a <style> tag or attribute.
1053  
1054 =back
1055  
1056 =item B<Return values>
1057  
1058 =over 4
1059  
1060 =item DEFANG_NONE
1061  
1062 The current URL will not be defanged.
1063  
1064 =item DEFANG_ALWAYS
1065  
1066 The current URL will be defanged.
1067  
1068 =item DEFANG_DEFAULT
1069  
1070 The current URL will be processed normally by HTML:Defang as if there was no callback method specified.
1071  
1072 =back
1073  
1074 =back
1075  
1076 =item I<css_callback($context, $Defang, $Selectors, $SelectorRules, $lcTag, $IsAttr, $OutR)>
1077  
1078 If $Defang->{css_callback} exists, and HTML::Defang has parsed a <style> tag or style attribtue, the above callback is made to the client code. The return value of this method determines whether a particular declaration in the style rules is defanged or not. More details below.
1079  
1080 =over 4
1081  
1082 =item B<Method parameters>
1083  
1084 =over 4
1085  
1086 =item I<$Selectors>
1087  
1088 Reference to an array containing the selectors in a style tag or attribute.
1089  
1090 =item I<$SelectorRules>
1091  
1092 Reference to an array containing the style declaration blocks of all selectors in a style tag or attribute. Consider the below CSS:
1093  
1094 a { b:c; d:e}
1095 j { k:l; m:n}
1096  
1097 The declaration blocks will get parsed into the following data structure:
1098  
1099 [
1100 [
1101 [ "b", "c", DEFANG_DEFAULT ],
1102 [ "d", "e", DEFANG_DEFAULT ]
1103 ],
1104 [
1105 [ "k", "l", DEFANG_DEFAULT ],
1106 [ "m", "n", DEFANG_DEFAULT ]
1107 ]
1108 ]
1109  
1110 So, generally each property:value pair in a declaration is parsed into an array of the form
1111  
1112 ["property", "value", X]
1113  
1114 where X can be DEFANG_NONE, DEFANG_ALWAYS or DEFANG_DEFAULT, and DEFANG_DEFAULT the default value. A client can manipulate this value to instruct HTML::Defang to defang this property:value pair.
1115  
1116 DEFANG_NONE - Do not defang
1117  
1118 DEFANG_ALWAYS - Defang the style:property value
1119  
1120 DEFANG_DEFAULT - Process this as if there is no callback specified
1121  
1122 =item I<$IsAttr>
1123  
1124 True if the currently processed item is a style attribute. False if the currently processed item is a style tag.
1125  
1126 =back
1127  
1128 =back
1129  
1130 =back
1131  
1132 =cut
1133  
1134 =head1 METHODS
1135  
1136 =over 4
1137  
1138 =item B<PUBLIC METHODS>
1139  
1140 =over 4
1141  
1142 =cut
1143  
1144 =item I<defang($InputHtml, \%Opts)>
1145  
1146 Cleans up $InputHtml of any executable code including scripting, embedded objects, applets, etc., and defang any XSS attacks.
1147  
1148 =over 4
1149  
1150 =item B<Method parameters>
1151  
1152 =over 4
1153  
1154 =item I<$InputHtml>
1155  
1156 The input HTML string that needs to be sanitized.
1157  
1158 =back
1159  
1160 =back
1161  
1162 Returns the cleaned HTML. If fix_mismatched_tags is set, any tags that appear in @$mismatched_tags_to_fix that are unbalanced are automatically commented or closed.
1163  
1164 =cut
1165 354 ▶sub defang {
Subroutine defang: called CC=65 SCAR=43.3
Pod documented
1166 354 my $Self = shift;
1167  
1168 354 my $I = shift;
1169 354 my $Opts = shift;
1170  
1171 354 my $Debug = $Self->{Debug};
1172  
1173 354 my $HeaderCharset = $Opts->{header_charset};
1174 354 ▶ warn("defang HeaderCharset=$HeaderCharset") if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 354 354
1175 354 my $FallbackCharset = $Opts->{fallback_charset};
1176 354 ▶ warn("defang FallbackCharset=$FallbackCharset") if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 354 354
1177  
1178 354 $Self->{Reentrant}++;
1179  
1180 # Output buffer
1181 354 ▶ local $Self->{OutR} = $Opts->{add_to_existing} ? $Self->{OutR} : \(my $O = "");
Branch: 1 branch
BranchTrueFalseTotal
$Opts->{'add_to_existing'} ? : 0 354 354
1182 354 my $OutR = $Self->{OutR};
1183  
1184 # Get encoded characters
1185 # $Self->{Charset} = $Self->get_applicable_charset($_, $HeaderCharset, $FallbackCharset);
1186 # warn("defang Charset=$Self->{Charset}") if $Self->{Debug};
1187  
1188 # if ($Self->{Charset}) {
1189 # $I =~ s/(.)/chr(ord($1) & 127)/ge if $Self->{Charset} eq "US-ASCII";
1190 # my $Encoder = Encode::Encoder->new($I, $Self->{Charset});
1191 # $I = $Encoder->bytes($Self->{Charset});
1192 # }
1193  
1194 # We pass a ref to $I to each callback. It should
1195 # never be modified because we use a m/\G.../gc loop
1196 # on it. If possible, stop people modifying it
1197 354 ▶ readonly_on($I) if $HasScalarReadonly;
Branch: 1 branch
BranchTrueFalseTotal
if $HasScalarReadonly 0 354 354
1198  
1199 # It seems regexp matching on perl unicode strings can be *way*
1200 # slower than byte string (defang 1M email = 100 seconds unicode,
1201 # 5 seconds bytes).
1202 # So we're going to do a bit of a hack. Engaged "use bytes" to do
1203 # byte matching everywhere, but since we know we'll be matching
1204 # on correct boundaries to make up full code points in utf-8, we'll
1205 # turn on the magic utf-8 flag again for those values
1206 354 my $UTF8Input = $Self->{UTF8Input} = Encode::is_utf8($I);
1207  
1208 # Force byte matching everywhere (see above)
1209 9 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
1210  
1211 354 ▶ Carp::cluck() if !defined $I;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $I 0 354 354
1212  
1213 # Strip all NUL chars
1214 354 $I =~ s/\0//g;
1215  
1216 # This parser uses standard /\G.../gc matching, so have to be careful
1217 # to not reset pos() on the string
1218 #
1219 # Previously we tried an "eating" parser (s/^.../, or /^.../ + substr),
1220 # which in theory should be fast with perls internal string offset
1221 # feature, but it seems offset doesn't work on unicode strings,
1222 # so you end up with a slow parser because of string reallocations
1223  
1224 354 while (1) {
1225  
1226 # walk to next < (testing in 5.8.8 shows .*? is faster than [^<]* or [^<]*?)
1227 1472 ▶ if ($I =~ m{\G(.*?)<}gcso) {
Branch: 1 branch
BranchTrueFalseTotal
if ($I =~ /\G(.*?)</cogs) 1118 354 1472
1228  
1229 1118 my $Content = $1;
1230  
1231 # Call content callback if present
1232 $Self->{content_callback}->($Self->{context}, $Self, \$Content)
1233 1118 ▶ if $Self->{content_callback};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"content_callback"} 0 1118 1118
1234  
1235 # Everything before tag goes into the output
1236 1118 $$OutR .= $Content;
1237  
1238 # All tags default to open/close with </>
1239 1118 my ($OpenAngle, $CloseAngle) = ('<', '>');
1240 1118 ▶ my $IsEndTag = $I =~ m{\G/}gcso ? '/' : '';
Branch: 1 branch
BranchTrueFalseTotal
$I =~ m[\G/]cogs ? : 237 881 1118
1241  
1242 # It's a standard tag
1243 1118 ▶ if ($I =~ m{\G($TagNameRE)}gcso) {
Branch: 3 branches
BranchTrueFalseTotal
if ($I =~ /\G($TagNameRE)/cogs) { } 1078 40 1118
elsif ($I =~ /\G(!)((?:\[CDATA\[|--)?)/cgis) { } 30 10 40
elsif ($I =~ /\G(\?)/cgs) { } 8 2 10
1244  
1245 1078 my $Tag = $1;
1246 1078 ▶ my $TagTrail = $I =~ m{\G([\s/]+)}gcso ? $1 : '';
Branch: 1 branch
BranchTrueFalseTotal
$I =~ m[\G([\s/]+)]cogs ? : 590 488 1078
1247  
1248 1078 ▶ warn "defang IsEndTag=$IsEndTag Tag=$Tag" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 1078 1078
1249  
1250 # Skip attribute parsing if none
1251 1078 my @Attributes;
1252 1078 ▶ goto NoParseAttributes if $I =~ m{\G>}gcso;
Branch: 1 branch
BranchTrueFalseTotal
if $I =~ /\G>/cogs 493 585 1078
1253  
1254 # Pull off any trailing component after the tag
1255 # Now match all key=value attributes
1256 585 ▶ while ($I =~ m{\G(?:($AttrKeyStartLineRE)(\s*))?(?:(=\s*)($AttrValRE)(\s*))?}gcso) {
Branch: 1 branch
BranchTrueFalseTotal
if ($I =~ /\G(?:($AttrKeyStartLineRE)(\s*))?(?:(=\s*)($AttrValRE)(\s*))?/cogs) 1315 0 1315
1257  
1258 1315 ▶ last if !defined($1) && !defined($4);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $1 or defined $4 585 730 1315
Condition100%3/3
defined $1 or defined $4
l!l&&r!l&&!r
7282585
MC/DC100%2/2
defined $1 or defined $4
defined $1 defined $4
Truth table100%3/3
A or B
A= defined $1B= defined $4
ABresult
1X1
011
000
1259 730 my ($Attribute, $AttrTrail, $Equals, $AttrVal, $AttrValTrail) = ($1, $2, $3, $4, $5);
1260 730 my ($AttrQuote, $AttrValWithoutQuote) = '';
1261 730 ▶ if (defined($4) && $4 =~ /^([`"']?)(.*)\1$/s) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $4 and $4 =~ /^([`"']?)(.*)\1$/s) 718 12 730
Condition66%2/3
defined $4 and $4 =~ /^([`"']?)(.*)\1$/s
!ll&&!rl&&r
120718
MC/DC50%1/2
defined $4 and $4 =~ /^([`"']?)(.*)\1$/s
defined $4 $4 =~ /^([`"']?)(.*)\1$/s
Truth table66%2/3
A and B
A= defined $4B= $4 =~ /^([`"']?)(.*)\1$/s
ABresult
0X0
100
111
1262 # IE supports `, but nothing else does, turn it into "
1263 718 ▶ $AttrQuote = $1 eq '`' ? '"' : $1;
Branch: 1 branch
BranchTrueFalseTotal
$1 eq '`' ? : 6 712 718
1264 718 $AttrValWithoutQuote = $2;
1265 }
1266  
1267 # Turn on utf-8 for things that might be
1268 730 ▶ Encode::_utf8_on($Attribute) if $UTF8Input;
Branch: 1 branch
BranchTrueFalseTotal
if $UTF8Input 4 726 730
1269 730 ▶ Encode::_utf8_on($AttrValWithoutQuote) if $UTF8Input;
Branch: 1 branch
BranchTrueFalseTotal
if $UTF8Input 4 726 730
1270  
1271 730 push @Attributes, [ $Attribute, $AttrTrail, $Equals, $AttrQuote, $AttrValWithoutQuote, $AttrQuote, $AttrValTrail ];
1272 730 ▶ warn "defang AttributeKey=$1 AttrQuote=$AttrQuote AttributeValue=$Attribute" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 730 730
1273 }
1274  
1275 # Better be at end of attributes, or attach our own ending tag
1276 585 ▶ if ($I =~ m{\G(?:(\s*[/\\]*\s*(?:--)?\s*)?>|([\s/-]*))}gcs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($I =~ m(\G(?:(\s*[/\\]*\s*(?:--)?\s*)?>|([\s/-]*)))cgs) 579 6 585
1277 579 ▶ $CloseAngle = $1 ? $1 . '>' : ($2 ? $2 . '>' : '>');
Branch: 2 branches
BranchTrueFalseTotal
$1 ? : 13 566 579
$2 ? : 0 566 566
1278 }
1279  
1280 NoParseAttributes:
1281 1078 my $Defang = DEFANG_ALWAYS;
1282  
1283 1078 my $lcTag = lc $Tag;
1284 1078 my $TagOps = $Tags{$lcTag};
1285  
1286 # Process this tag
1287 1078 ▶ if (!exists $Self->{tags_to_callback}->{$lcTag} && ref $TagOps eq "CODE") {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $Self->{'tags_to_callback'}{$lcTag} and ref $TagOps eq 'CODE') { } 273 805 1078
Condition100%3/3
not exists $Self->{"tags_to_callback"}{$lcTag} and ref $TagOps eq "CODE"
!ll&&!rl&&r
95710273
MC/DC100%2/2
not exists $Self->{"tags_to_callback"}{$lcTag} and ref $TagOps eq "CODE"
not exists $Self->{"tags_to_callback"}{$lcTag} ref $TagOps eq "CODE"
Truth table100%3/3
not(A) and B
A= not exists $Self->{"tags_to_callback"}{$lcTag}B= ref $TagOps eq "CODE"
ABresult
0X0
100
111
1288  
1289 273 ▶ warn "process_tag Found CODE reference" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 273 273
1290 273 $Defang = $Self->${TagOps}($OutR, \$I, $TagOps, \$OpenAngle, $IsEndTag, $lcTag, $TagTrail, \@Attributes, \$CloseAngle);
1291  
1292 } else {
1293  
1294 805 ▶ warn "process_tag Found regular tag" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 805 805
1295 805 $Defang = $Self->defang_attributes($OutR, \$I, $TagOps, \$OpenAngle, $IsEndTag, $lcTag, $TagTrail, \@Attributes, \$CloseAngle);
1296  
1297 }
1298 1078 ▶ die "Callback reset pos on Tag=$Tag IsEndTag=$IsEndTag" if !defined pos($I);
Branch: 1 branch
BranchTrueFalseTotal
unless defined pos $I 0 1078 1078
1299 1078 ▶ warn "defang Defang=$Defang" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 1078 1078
1300  
1301 # RCDATA/RAWTEXT elements (title, textarea, noembed, noframes): their
1302 # content is opaque text to a browser, not HTML. Consume it verbatim
1303 # up to the matching end tag so we don't parse comments/tags inside
1304 # it (which would let an attacker smuggle a literal end tag + active
1305 # markup past the defanger). Skipped if a user tags_callback owns the
1306 # tag, since it is then responsible for the content.
1307 1078 ▶ if (!$IsEndTag && $RawTextTags{$lcTag}
Branch: 1 branch
BranchTrueFalseTotal
if (not $IsEndTag and $RawTextTags{$lcTag} and not exists $Self->{"tags_to_callback"}{$lcTag}) 12 1066 1078
Condition83%5/6
not $IsEndTag and $RawTextTags{$lcTag} and not exists $Self->{"tags_to_callback"}{$lcTag}
!ll&&!rl&&r
1066012
not $IsEndTag and $RawTextTags{$lcTag}
!ll&&!rl&&r
23782912
MC/DC66%2/3
not $IsEndTag and $RawTextTags{$lcTag} and not exists $Self->{"tags_to_callback"}{$lcTag}
not $IsEndTag $RawTextTags{$lcTag} not exists $Self->{"tags_to_callback"}{$lcTag}
Truth table75%3/4
not(A) and B and not(C)
A= not $IsEndTagB= $RawTextTags{$lcTag}C= not exists $Self->{"tags_to_callback"}{$lcTag}
ABCresult
0XX0
10X0
1100
1111
1308 && !exists $Self->{tags_to_callback}->{$lcTag}) {
1309 12 $Self->defang_rcdata_content(\$I, $lcTag);
1310 }
1311  
1312 # Build tag content, because if we defang, we have to remove --'s within it
1313  
1314 # @Attributes can have unicode values, but we're within "use bytes", so it's flattened ok
1315 1078 my $TagContent = $TagTrail . join("", grep { defined } map { @$_ } @Attributes);
1316  
1317 1078 ▶ if ($Self->{fix_mismatched_tags} && ($Defang == DEFANG_NONE)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"fix_mismatched_tags"} and $Defang == 0) 91 987 1078
Condition100%3/3
$Self->{"fix_mismatched_tags"} and $Defang == 0
!ll&&!rl&&r
984391
MC/DC100%2/2
$Self->{"fix_mismatched_tags"} and $Defang == 0
$Self->{"fix_mismatched_tags"} $Defang == 0
Truth table100%3/3
A and B
A= $Self->{"fix_mismatched_tags"}B= $Defang == 0
ABresult
0X0
100
111
1318 91 ▶ if (!$IsEndTag) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $IsEndTag) { } 70 21 91
1319 70 $Defang = $Self->open_tag(0, $OutR, \$I, $lcTag, \$TagContent);
1320 } else {
1321 21 $Defang = $Self->close_tag(0, $OutR, \$I, $lcTag);
1322 21 ▶ goto SkipOutput if $Defang == DEFANG_ALWAYS;
Branch: 1 branch
BranchTrueFalseTotal
if $Defang == 1 4 17 21
1323 }
1324 }
1325  
1326 # defang unknown tags
1327 1074 ▶ if ($Defang != DEFANG_NONE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Defang != 0) 164 910 1074
1328 164 ▶ warn "defang Defanging $Tag" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 164 164
1329 164 ▶ if ($Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{'delete_defang_content'}) { } 0 164 164
1330 0 $OpenAngle = $IsEndTag = $Tag = $TagContent = $CloseAngle = '';
1331 } else {
1332 $Tag = $Self->{defang_string} . $Tag
1333 164 ▶ if $Self->{allow_double_defang} || $Tag !~ $Self->{defang_re};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"allow_double_defang"} or not $Tag =~ /$Self->{"defang_re"}/ 164 0 164
Condition33%1/3
$Self->{"allow_double_defang"} or not $Tag =~ /$Self->{"defang_re"}/
l!l&&r!l&&!r
01640
MC/DC0%0/2
$Self->{"allow_double_defang"} or not $Tag =~ /$Self->{"defang_re"}/
$Self->{"allow_double_defang"} not $Tag =~ /$Self->{"defang_re"}/
Truth table33%1/3
A or not(B)
A= $Self->{"allow_double_defang"}B= not $Tag =~ /$Self->{"defang_re"}/
ABresult
1X1
011
000
1334 164 $TagContent =~ s/--//g;
1335 164 $Tag =~ s/--//g;
1336 164 $OpenAngle =~ s/^</<!--/;
1337 164 $CloseAngle =~ s/>$/-->/;
1338 }
1339 }
1340  
1341 # And put it all back together into the output string
1342 1074 $$OutR .= $OpenAngle . $IsEndTag . $Tag . $TagContent . $CloseAngle;
1343 SkipOutput:
1344  
1345 # It's a comment of some sort. We are looking for regular HTML comment, XML CDATA section
1346 1078 } elsif ($I =~ m{\G(!)((?:\[CDATA\[|--)?)}gcis) {
1347  
1348 30 my ($Comment, $CommentDelim) = ($1, $2);
1349 30 ▶ warn "defang Comment=$Comment CommentDelim=$CommentDelim" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 30 30
1350  
1351 # Find the appropriate closing delimiter
1352 30 my $IsCDATA = $CommentDelim eq "[CDATA[";
1353 30 ▶ my $ClosingCommentDelim = $IsCDATA ? "]]" : $CommentDelim;
Branch: 1 branch
BranchTrueFalseTotal
$IsCDATA ? : 6 24 30
1354  
1355 30 ▶ warn "defang ClosingCommentDelim=$ClosingCommentDelim" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 30 30
1356  
1357 30 my ($CommentStartText, $CommentEndText) = ("--/*SC*/", "/*EC*/--");
1358  
1359 # Convert to regular HTML comment
1360 30 ▶ if (!$Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Self->{"delete_defang_content"}) 30 0 30
1361 30 $$OutR .= $OpenAngle . $Comment . $CommentStartText;
1362 }
1363  
1364 # Find closing comment
1365 30 ▶ if ($I =~ m{\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)}gcis || $I =~ m{\G(.*?)(--)(>)}gcis) {
Branch: 1 branch
BranchTrueFalseTotal
if ($I =~ /\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)/cgis or $I =~ /\G(.*?)(--)(>)/cgis) { } 24 6 30
Condition66%2/3
$I =~ /\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)/cgis or $I =~ /\G(.*?)(--)(>)/cgis
l!l&&r!l&&!r
2406
MC/DC50%1/2
$I =~ /\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)/cgis or $I =~ /\G(.*?)(--)(>)/cgis
$I =~ /\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)/cgis $I =~ /\G(.*?)(--)(>)/cgis
Truth table66%2/3
A or B
A= $I =~ /\G(.*?)(\Q$ClosingCommentDelim\E!?\s*)(>)/cgisB= $I =~ /\G(.*?)(--)(>)/cgis
ABresult
1X1
011
000
1366  
1367 24 my ( $StartTag, $CommentData, $ClosingTag, $CloseAngle ) =
1368 ( $CommentDelim, $1, $2, $3 );
1369  
1370 # Strip all HTML comment markers
1371 24 $StartTag =~ s/--//g;
1372 24 $CommentData =~ s/--//g;
1373 24 $ClosingTag =~ s/--//g;
1374  
1375 24 ▶ if (!$Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Self->{"delete_defang_content"}) 24 0 24
1376 # Put it all into the output
1377 24 $$OutR .= $StartTag
1378 . $CommentData
1379 . $ClosingTag
1380 . $CommentEndText
1381 . $CloseAngle;
1382 }
1383  
1384 # No closing comment, so we add that
1385 } else {
1386  
1387 6 ▶ $I =~ m/\G(.*)$/gcs || die "Remainder of line match failed";
Branch: 1 branch
BranchTrueFalseTotal
$I =~ /\G(.*)$/cgs or die "Remainder of line match failed" 6 0 6
1388
1389 6 my $Data = $1;
1390 6 $Data =~ s/--//g;
1391
1392 # Output
1393 6 ▶ if (!$Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Self->{"delete_defang_content"}) 6 0 6
1394 6 $$OutR .= $Data . $CommentEndText . ">";
1395 }
1396  
1397 }
1398  
1399 # XML processing instruction
1400 } elsif ($I =~ m{\G(\?)}gcs) {
1401 8 my ($Processing) = ($1);
1402 8 ▶ warn "defang XML processing instruction" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 8 8
1403
1404 8 my $Data;
1405 8 ▶ if ($I =~ m{\G(.*?\??)>}gcs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($I =~ /\G(.*?\??)>/cgs) { } 6 2 8
1406 6 $Data = $1;
1407 } else {
1408 2 $I =~ m{\G(.*)$}gcs;
1409 2 $Data = $1;
1410 }
1411
1412 8 $Data =~ s{--}{}g;
1413  
1414 8 ▶ if (!$Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Self->{"delete_defang_content"}) 8 0 8
1415 8 $$OutR .= $OpenAngle . '!--' . $Processing . $Data . '-->';
1416 }
1417  
1418 }
1419 # Some other thing starting with <, keep looking
1420  
1421 1118 ▶ if (exists $Self->{TrackedAppendOutput}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Self->{"TrackedAppendOutput"}) 3 1115 1118
1422 3 for (@{delete $Self->{TrackedAppendOutput}}) {
1423 3 $Self->open_tag(1, $OutR, \$I, $_->[0], \$_->[1], 1);
1424 }
1425 }
1426 1118 ▶ if (exists $Self->{AppendOutput}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Self->{"AppendOutput"}) 150 968 1118
1427 150 $$OutR .= delete $Self->{AppendOutput};
1428 }
1429 1118 ▶ if (exists $Self->{DelayedAppendOutput}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Self->{"DelayedAppendOutput"}) 0 1118 1118
1430 0 $Self->defang(delete $Self->{DelayedAppendOutput}, { add_to_existing => 1 });
1431 }
1432 1118 next;
1433 }
1434
1435 # No tag found, just copy rest
1436 354 ▶ warn "defang OutputRemainder" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 354 354
1437 354 $I =~ m/\G(.*)$/gcs;
1438  
1439 354 ▶ $$OutR .= $1 if $1;
Branch: 1 branch
BranchTrueFalseTotal
if $1 306 48 354
1440  
1441 # Exit if we got here
1442 354 last;
1443 }
1444  
1445 # If not a recursive call, close mismatched tags
1446 354 ▶ if ($Self->{Reentrant}-- <= 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"Reentrant"}-- <= 1) 354 0 354
1447 354 $Self->close_all_tags($OutR, \$I);
1448 }
1449  
1450 # Turn on utf-8 flag again
1451 354 ▶ Encode::_utf8_on($$OutR) if $UTF8Input;
Branch: 1 branch
BranchTrueFalseTotal
if $UTF8Input 2 352 354
1452  
1453 354 return $$OutR;
1454 }
1455  
1456 =item I<add_to_output($String)>
1457  
1458 Appends $String to the output after the current parsed tag ends. Can be used by client code in callback methods to add HTML text to the processed output. If the HTML text needs to be defanged, client code can safely call HTML::Defang->defang() recursively from within the callback.
1459  
1460 =over 4
1461  
1462 =item B<Method parameters>
1463  
1464 =over 4
1465  
1466 =item I<$String>
1467  
1468 The string that is added after the current parsed tag ends.
1469  
1470 =back
1471  
1472 =back
1473  
1474 =back
1475  
1476 =cut
1477 152 ▶sub add_to_output {
Subroutine add_to_output: called CC=2 SCAR=6.9
Pod documented
1478 # Callbacks call this method
1479 152 my $Self = shift;
1480 152 ▶ $Self->{AppendOutput} = '' if !defined $Self->{AppendOutput};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Self->{"AppendOutput"} 150 2 152
1481 152 $Self->{AppendOutput} .= shift;
1482 }
1483  
1484 0 ▶sub defang_and_add_to_output {
Subroutine defang_and_add_to_output: not called CC=2 SCAR=17.9
Pod undocumented
1485 0 my $Self = shift;
1486 0 ▶ $Self->{DelayedAppendOutput} = '' if !defined $Self->{DelayedAppendOutput};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Self->{"DelayedAppendOutput"} 0 0 0
1487 0 $Self->{DelayedAppendOutput} .= shift;
1488 }
1489  
1490 3 ▶sub track_and_add_tag_to_output {
Subroutine track_and_add_tag_to_output: called CC=1 SCAR=0.0
Pod undocumented
1491 3 my $Self = shift;
1492 3 push @{$Self->{TrackedAppendOutput}}, shift;
1493 }
1494  
1495 =item B<INTERNAL METHODS>
1496  
1497 Generally these methods never need to be called by users of the class, because they'll be called internally as the appropriate tags are
1498 encountered, but they may be useful for some users in some cases.
1499  
1500 =over 4
1501  
1502 =cut
1503  
1504 =item I<defang_script_tag($OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $Tag, $TagTrail, $Attributes, $CloseAngle)>
1505  
1506 This method is invoked when a <script> tag is parsed. Defangs the <script> opening tag, and any closing tag. Any scripting content is also commented out, so browsers don't display them.
1507  
1508 Returns 1 to indicate that the <script> tag must be defanged.
1509  
1510 =over 4
1511  
1512 =item B<Method parameters>
1513  
1514 =over 4
1515  
1516 =item I<$OutR>
1517  
1518 A reference to the processed output HTML before the tag that is currently being parsed.
1519  
1520 =item I<$HtmlR>
1521  
1522 A scalar reference to the input HTML.
1523  
1524 =item I<$TagOps>
1525  
1526 Indicates what operation should be done on a tag. Can be undefined, integer or code reference. Undefined indicates an unknown tag to HTML::Defang, 1 indicates a known safe tag, 0 indicates a known unsafe tag, and a code reference indicates a subroutine that should be called to parse the current tag. For example, <style> and <script> tags are parsed by dedicated subroutines.
1527  
1528 =item I<$OpenAngle>
1529  
1530 Opening angle(<) sign of the current tag.
1531  
1532 =item I<$IsEndTag>
1533  
1534 Has the value '/' if the current tag is a closing tag.
1535  
1536 =item I<$Tag>
1537  
1538 The HTML tag that is currently being parsed.
1539  
1540 =item I<$TagTrail>
1541  
1542 Any space after the tag, but before attributes.
1543  
1544 =item I<$Attributes>
1545  
1546 A reference to an array of the attributes and their values, including any surrouding spaces. Each element of the array is added by 'push' calls like below.
1547  
1548 push @$Attributes, [ $AttributeName, $SpaceBeforeEquals, $EqualsAndSubsequentSpace, $QuoteChar, $AttributeValue, $QuoteChar, $SpaceAfterAtributeValue ];
1549  
1550 =item I<$CloseAngle>
1551  
1552 Anything after the end of last attribute including the closing HTML angle(>)
1553  
1554 =back
1555  
1556 =back
1557  
1558 =cut
1559 51 ▶sub defang_script_tag {
Subroutine defang_script_tag: called CC=7 SCAR=19.6
Pod documented
1560 51 my $Self = shift;
1561 51 my ($OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $lcTag, $TagTrail, $Attributes, $CloseAngle) = @_;
1562 51 ▶ warn "defang_script Processing <script> tag" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 51 51
1563  
1564 51 ▶ if (!$IsEndTag) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($IsEndTag) 26 25 51
1565  
1566 # If we just parsed a starting <script> tag, find up to end tag
1567 # There's all sort of possible mess around this:
1568 # </script<foo> - not really an end tag
1569 # </script foo="bar > yes, still in a attribute"> - a valid end tag
1570 # For weird cases, we end script tag early and end up defanging script
1571 # content as HTML content, which is still safe
1572 26 ▶ if ($$HtmlR =~ m{\G(.*?)(?=</script\b)}gcsi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$HtmlR =~ m[\G(.*?)(?=</script\b)]cgis) 23 3 26
1573 23 my $ScriptTagContents = $1;
1574 23 ▶ warn "defang_script ScriptTagContents $ScriptTagContents" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 23 23
1575 23 ▶ if (!$Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Self->{"delete_defang_content"}) 23 0 23
1576 23 ▶ 1 while $ScriptTagContents =~ s/<!--|-->|--//g;
Branch: 1 branch
BranchTrueFalseTotal
$ScriptTagContents =~ s/<!--|-->|--//g and do { '???' } 4 23 27
1577 23 $ScriptTagContents = "<!-- " . $ScriptTagContents . " -->";
1578 23 $Self->add_to_output($ScriptTagContents);
1579 }
1580 }
1581 }
1582  
1583 # Also defang tag
1584 51 return DEFANG_ALWAYS;
1585 }
1586  
1587 =item I<defang_rcdata_content($HtmlR, $lcTag)>
1588  
1589 Consume the RCDATA/RAWTEXT content of a "text" element and pass it straight
1590 through to the output as opaque text.
1591  
1592 The elements this applies to are C<< <title> >> and C<< <textarea> >>
1593 (RCDATA) and C<< <noembed> >> and C<< <noframes> >> (RAWTEXT) - see the
1594 listing in C<%RawTextTags>. Per the HTML5 tree construction/tokenization
1595 spec, a start tag for one of these switches the tokenizer into a raw text
1596 mode in which the browser does I<not> parse comments or nested tags - the
1597 only markup it recognises is a matching C<< </tag >> end tag, everything
1598 else is text (RCDATA additionally decodes character references). Comments in
1599 particular are not a thing inside these elements.
1600  
1601 If we instead let the normal HTML parser loose on the content it would
1602 happily interpret C<< <!-- ... --> >> comments and nested tags inside. That
1603 diverges from the browser and is exploitable: an attacker can hide a literal
1604 end tag plus active markup inside what we think is an inert comment or
1605 attribute value, e.g.
1606  
1607 <title><!-- </title> <img src=x onerror=alert(1)> --></title>
1608  
1609 We would emit the C<< <img> >> unchanged (believing it comment data), but a
1610 browser closes the title at the literal C<< </title> >> and then runs the
1611 C<< <img> >> as live markup.
1612  
1613 So, like <script> and <style>, we consume everything up to the matching
1614 C<< </tag >> (whose name is C<$lcTag>) as opaque text. That content contains
1615 no C<< </tag >> (we stop before the first one), so re-parsed as raw text it
1616 stays inert right up to the end tag that follows it in the output.
1617  
1618 =cut
1619 12 ▶sub defang_rcdata_content {
Subroutine defang_rcdata_content: called CC=7 SCAR=21.1
Pod documented
1620 12 my ($Self, $HtmlR, $lcTag) = @_;
1621  
1622 12 ▶ warn "defang_rcdata_content Tag=$lcTag" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 12 12
1623  
1624 # Do the raw text scan in byte mode (see defang())
1625 9 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
1626  
1627 # Consume raw content verbatim up to the matching end tag (or EOF if
1628 # there's no closing tag, just as a browser would leave the element open)
1629 12 ▶ if ($$HtmlR =~ m{\G(.*?)(?=</\Q$lcTag\E\b)}gcis || $$HtmlR =~ m{\G(.*)$}gcs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$HtmlR =~ m[\G(.*?)(?=</\Q$lcTag\E\b)]cgis or $$HtmlR =~ /\G(.*)$/cgs) 12 0 12
Condition66%2/3
$$HtmlR =~ m[\G(.*?)(?=</\Q$lcTag\E\b)]cgis or $$HtmlR =~ /\G(.*)$/cgs
l!l&&r!l&&!r
1110
MC/DC0%0/2
$$HtmlR =~ m[\G(.*?)(?=</\Q$lcTag\E\b)]cgis or $$HtmlR =~ /\G(.*)$/cgs
$$HtmlR =~ m[\G(.*?)(?=</\Q$lcTag\E\b)]cgis $$HtmlR =~ /\G(.*)$/cgs
Truth table66%2/3
A or B
A= $$HtmlR =~ m[\G(.*?)(?=</\Q$lcTag\E\b)]cgisB= $$HtmlR =~ /\G(.*)$/cgs
ABresult
1X1
011
000
1630 12 my $Content = $1;
1631 12 ▶ warn "defang_rcdata_content Content=$Content" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 12 12
1632 12 ▶ $Self->add_to_output($Content) if defined($Content) && length($Content);
Branch: 1 branch
BranchTrueFalseTotal
if defined $Content and length $Content 12 0 12
Condition33%1/3
defined $Content and length $Content
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $Content and length $Content
defined $Content length $Content
Truth table33%1/3
A and B
A= defined $ContentB= length $Content
ABresult
0X0
100
111
1633 }
1634  
1635 12 return;
1636 }
1637  
1638 222 ▶sub defang_style_tag {
Subroutine defang_style_tag: called CC=12 SCAR=26.4
Pod undocumented
1639 222 my ($Self, $OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $lcTag, $TagTrail, $Attributes, $CloseAngle) = @_;
1640  
1641 222 ▶ warn "defang_style_tag Tag=$lcTag IsEndTag=$IsEndTag" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 222 222
1642  
1643 # Defang attributes
1644 222 my $Defang = $Self->defang_attributes($OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $lcTag, $TagTrail, $Attributes, $CloseAngle);
1645  
1646 # Nothing to do if end tag
1647 222 ▶ return $Defang if $IsEndTag;
Branch: 1 branch
BranchTrueFalseTotal
if $IsEndTag 110 112 222
1648  
1649 # Do all style work in byte mode
1650 9 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
1651  
1652 112 my $Content = '';
1653 112 my $ClosingStyleTagPresent = 1;
1654  
1655 112 for ($$HtmlR) {
1656 112 ▶ if (m{\G(.*?)(?=</style\b)}gcis) {
Branch: 2 branches
BranchTrueFalseTotal
if (m[\G(.*?)(?=</style\b)]cgis) { } 110 2 112
elsif (/\G([^<]*)/cgis) { } 2 0 2
1657 110 $Content = $1;
1658  
1659 # No ending style tag
1660 } elsif (m{\G([^<]*)}gcis) {
1661 2 $Content = $1;
1662 2 $ClosingStyleTagPresent = 0;
1663 }
1664 }
1665  
1666 # Handle any wrapping HTML comments. If no comments, we add
1667 112 my ($OpeningHtmlComment, $ClosingHtmlComment) = ('', '');
1668 112 ▶ $OpeningHtmlComment = $Content =~ s{^(\s*<!--)}{} ? $1 . " " : "<!-- ";
Branch: 1 branch
BranchTrueFalseTotal
$Content =~ s/^(\s*<!--)// ? : 4 108 112
1669 112 ▶ $ClosingHtmlComment = $Content =~ s{(-->\s*)$}{} ? " " . $1 : " -->";
Branch: 1 branch
BranchTrueFalseTotal
$Content =~ s/(-->\s*)$// ? : 4 108 112
1670  
1671 # Check for large bogus style data with mostly HTML tags and blat it
1672 112 ▶ if (length $Content > 16384) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $Content > 16384) 0 112 112
1673 0 my $TagCount = 0;
1674 0 ▶ $TagCount++ while $Content =~ m{</?\w+\b[^>]*>}g;
Branch: 1 branch
BranchTrueFalseTotal
$Content =~ m[</?\w+\b[^>]*>]g and do { ++$TagCount } 0 0 0
1675 0 ▶ if ($TagCount > length($Content)/256) {
Branch: 1 branch
BranchTrueFalseTotal
if ($TagCount > length($Content) / 256) 0 0 0
1676 0 $Content = '';
1677 }
1678 }
1679  
1680 112 my $StyleOut = $Self->defang_style_text($Content, $lcTag, 0, undef, $HtmlR, $OutR);
1681  
1682 112 $Self->add_to_output($OpeningHtmlComment . $StyleOut . $ClosingHtmlComment);
1683 112 ▶ $Self->add_to_output("</style>") if !$ClosingStyleTagPresent;
Branch: 1 branch
BranchTrueFalseTotal
unless $ClosingStyleTagPresent 2 110 112
1684  
1685 112 return $Defang;
1686 }
1687  
1688 =item I<defang_style_text($Content, $lcTag, $IsAttr, $AttributeHash, $HtmlR, $OutR)>
1689  
1690 Defang some raw css data and return the defanged content
1691  
1692 =over 4
1693  
1694 =item B<Method parameters>
1695  
1696 =over 4
1697  
1698 =item I<$Content>
1699  
1700 The input style string that is defanged.
1701  
1702 =item I<$IsAttr>
1703  
1704 True if $Content is from an attribute, otherwise from a <style> block
1705  
1706 =back
1707  
1708 =back
1709  
1710 =cut
1711 316 ▶sub defang_style_text {
Subroutine defang_style_text: called CC=33 SCAR=37.5
Pod documented
1712 316 my ($Self, $Content, $lcTag, $IsAttr, $AttributeHash, $HtmlR, $OutR) = @_;
1713  
1714 # Clean up all comments, expand character escapes and such
1715 316 $Self->cleanup_style($Content, $IsAttr);
1716  
1717 # Style attributes can optionally have selector type elements, so we check whether we
1718 # have a '{' in $Content: if yes, its style data with selector type elements
1719 316 my $Naked = $Content !~ m/\{/;
1720 316 ▶ warn "defang_style Naked=$Naked" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 316 316
1721  
1722 # And suitably change the regex to match the data
1723 316 ▶ my $SelectorRuleRE = $Naked ? $RECStyleNaked : $RECStyleSelected;
Branch: 1 branch
BranchTrueFalseTotal
$Naked ? : 137 179 316
1724  
1725 316 my (@Selectors, @SelectorRules, @ExtraData, @InMedia);
1726  
1727 # Now we parse the selectors and declarations
1728 316 while (1) {
1729 707 ▶ if ($Content =~ m{$RECStyleMediaSelector}sgco) {
Branch: 7 branches
BranchTrueFalseTotal
if ($Content =~ /$RECStyleMediaSelector/cogs) { } 2 705 707
elsif (@InMedia and $Content =~ /\G(\s*)(\})(\s*)/cgs) { } 2 703 705
elsif ($Content =~ /$SelectorRuleRE/cgs) { } 522 181 703
elsif (not $Naked and $Content =~ /\G\s*$StyleSelectors\s*$/cgs) { } 2 179 181
elsif (not $Naked and $Content =~ m[\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+]cgs) { } 0 179 179
elsif ($Content =~ /\G\s+/cgs) { } 0 179 179
elsif ($Content =~ /\G[^\s<]+/cgs or $Content =~ /\G<+/cgs) { } 0 179 179
1730 2 push @InMedia, $2;
1731 2 push @Selectors, $2;
1732 2 push @SelectorRules, "";
1733 2 push @ExtraData, [ $1, "", $3, "", $4 ];
1734 ▶ } elsif (@InMedia && $Content =~ m{\G(\s*)(\})(\s*)}sgc) {
Condition100%3/3
@InMedia and $Content =~ /\G(\s*)(\})(\s*)/cgs
!ll&&!rl&&r
70122
MC/DC100%2/2
@InMedia and $Content =~ /\G(\s*)(\})(\s*)/cgs
@InMedia $Content =~ /\G(\s*)(\})(\s*)/cgs
Truth table100%3/3
A and B
A= @InMediaB= $Content =~ /\G(\s*)(\})(\s*)/cgs
ABresult
0X0
100
111
1735 2 pop @InMedia;
1736 2 push @Selectors, "";
1737 2 push @SelectorRules, "";
1738 2 push @ExtraData, [ $1, "", "", $2, $3 ];
1739 } elsif ($Content =~ m{$SelectorRuleRE}sgc) {
1740 522 my ($Selector, $SelectorRule) = ($2, $5);
1741 522 ▶ last if $Selector eq '' && $SelectorRule =~ /^[;\s]*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $Selector eq "" and $SelectorRule =~ /^[;\s]*$/ 137 385 522
Condition100%3/3
$Selector eq "" and $SelectorRule =~ /^[;\s]*$/
!ll&&!rl&&r
253132137
MC/DC100%2/2
$Selector eq "" and $SelectorRule =~ /^[;\s]*$/
$Selector eq "" $SelectorRule =~ /^[;\s]*$/
Truth table100%3/3
A and B
A= $Selector eq ""B= $SelectorRule =~ /^[;\s]*$/
ABresult
0X0
100
111
1742 385 ▶ $Selector = join("\000", @InMedia, $Selector) if @InMedia;
Branch: 1 branch
BranchTrueFalseTotal
if @InMedia 2 383 385
1743 385 push @Selectors, $Selector;
1744 385 push @SelectorRules, $SelectorRule;
1745 385 push @ExtraData, [ $1, $3, $4, $6, $7];
1746 385 ▶ warn "defang_style Selector=$Selector" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 385 385
1747 385 ▶ warn "defang_style SelectorRule=$SelectorRule" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 385 385
1748  
1749 # Just a large bunch of selectors and no rules, suck up and discard
1750 ▶ } elsif (!$Naked && $Content =~ m{\G\s*$StyleSelectors\s*$}sgc) {
Condition66%2/3
not $Naked and $Content =~ /\G\s*$StyleSelectors\s*$/cgs
!ll&&!rl&&r
01792
MC/DC50%1/2
not $Naked and $Content =~ /\G\s*$StyleSelectors\s*$/cgs
not $Naked $Content =~ /\G\s*$StyleSelectors\s*$/cgs
Truth table66%2/3
not(A) and B
A= not $NakedB= $Content =~ /\G\s*$StyleSelectors\s*$/cgs
ABresult
0X0
100
111
1751 # Looks like an html tag, suck up and discard
1752 ▶ } elsif (!$Naked && $Content =~ m{\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+}sgc) {
Condition33%1/3
not $Naked and $Content =~ m[\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+]cgs
!ll&&!rl&&r
01790
MC/DC0%0/2
not $Naked and $Content =~ m[\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+]cgs
not $Naked $Content =~ m[\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+]cgs
Truth table33%1/3
not(A) and B
A= not $NakedB= $Content =~ m[\G(?:</?$TagNameRE(?:\s[^>\{\}]*)?>\s*)+]cgs
ABresult
0X0
100
111
1753  
1754 # If content didn't match a rule, suck up whitespace
1755 } elsif ($Content =~ m{\G\s+}sgc) {
1756 # Or any non-whitespace, but try and sync to <...> tags
1757 ▶ } elsif ($Content =~ m{\G[^\s<]+}sgc || $Content =~ m{\G<+}sgc) {
Condition33%1/3
$Content =~ /\G[^\s<]+/cgs or $Content =~ /\G<+/cgs
l!l&&r!l&&!r
00179
MC/DC0%0/2
$Content =~ /\G[^\s<]+/cgs or $Content =~ /\G<+/cgs
$Content =~ /\G[^\s<]+/cgs $Content =~ /\G<+/cgs
Truth table33%1/3
A or B
A= $Content =~ /\G[^\s<]+/cgsB= $Content =~ /\G<+/cgs
ABresult
1X1
011
000
1758  
1759 # Nothing matched, must be at end
1760 179 } else { last; }
1761 }
1762  
1763 # Check declaration elements for defanging
1764 316 $Self->defang_stylerule(\@Selectors, \@SelectorRules, $lcTag, $IsAttr, $AttributeHash, $HtmlR, $OutR);
1765  
1766 316 my $StyleOut = "";
1767  
1768 # Re-create the style data
1769 316 foreach my $Selector (@Selectors) {
1770  
1771 389 my $SelectorRule = shift @SelectorRules;
1772 389 my $Spaces = shift @ExtraData;
1773 389 ▶ my ($BeforeSelector, $AfterSelector, $OpenBrace, $CloseBrace, $AfterRule) = @$Spaces if $Spaces;
Branch: 1 branch
BranchTrueFalseTotal
if $Spaces 389 0 389
1774 389 ▶ ($BeforeSelector, $AfterSelector, $AfterRule) = ("", " ", "\n") unless $Spaces;
Branch: 1 branch
BranchTrueFalseTotal
unless $Spaces 0 389 389
1775 389 ▶ ($OpenBrace, $CloseBrace) = ("{", "}") if !$Spaces && !$IsAttr;
Branch: 1 branch
BranchTrueFalseTotal
unless $Spaces or $IsAttr 0 389 389
Condition33%1/3
$Spaces or $IsAttr
l!l&&r!l&&!r
38900
MC/DC0%0/2
$Spaces or $IsAttr
$Spaces $IsAttr
Truth table33%1/3
A or B
A= $SpacesB= $IsAttr
ABresult
1X1
011
000
1776
1777 # Put back the rule together
1778 389 ▶ if (defined($Selector)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Selector) 389 0 389
1779 389 ▶ $StyleOut .= $BeforeSelector if defined($BeforeSelector);
Branch: 1 branch
BranchTrueFalseTotal
if defined $BeforeSelector 389 0 389
1780 389 ▶ $StyleOut .= $Selector =~ /\000/ ? (reverse split /\000/, $Selector)[0] : $Selector;
Branch: 1 branch
BranchTrueFalseTotal
$Selector =~ /\000/ ? : 2 387 389
1781 389 ▶ $StyleOut .= $AfterSelector if defined($AfterSelector);
Branch: 1 branch
BranchTrueFalseTotal
if defined $AfterSelector 389 0 389
1782 389 ▶ $StyleOut .= $OpenBrace if defined($OpenBrace);
Branch: 1 branch
BranchTrueFalseTotal
if defined $OpenBrace 389 0 389
1783 389 ▶ $StyleOut .= $SelectorRule if defined($SelectorRule);
Branch: 1 branch
BranchTrueFalseTotal
if defined $SelectorRule 350 39 389
1784 389 ▶ $StyleOut .= $CloseBrace if defined($CloseBrace);
Branch: 1 branch
BranchTrueFalseTotal
if defined $CloseBrace 389 0 389
1785 389 ▶ $StyleOut .= $AfterRule if defined($AfterRule);
Branch: 1 branch
BranchTrueFalseTotal
if defined $AfterRule 389 0 389
1786 }
1787
1788 }
1789  
1790 316 ▶ warn "defang_style StyleOut=$StyleOut" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 316 316
1791  
1792 316 return $StyleOut;
1793 }
1794  
1795 =item I<cleanup_style($StyleString)>
1796  
1797 Helper function to clean up CSS data. This function directly operates on the input string without taking a copy.
1798  
1799 =over 4
1800  
1801 =item B<Method parameters>
1802  
1803 =over 4
1804  
1805 =item I<$StyleString>
1806  
1807 The input style string that is cleaned.
1808  
1809 =back
1810  
1811 =back
1812  
1813 =cut
1814 316 ▶sub cleanup_style {
Subroutine cleanup_style: called CC=26 SCAR=42.1
Pod documented
1815 316 my $Self = shift;
1816
1817 316 for ($_[0]) {
1818 316 my $UnicodeEntity = 0;
1819 # Expand unicode \ refs
1820 316 s{(?:\\)(0?[\da-f]{1,6});?}{
1821 31 ▶ my $V = (defined($1) && hex($1)) || undef;
Condition40%2/5
defined $1 && hex $1 || undef
l!l
310
defined $1 and hex $1
!ll&&!rl&&r
0031
MC/DC0%0/2
defined $1 && hex $1 || undef
defined $1 hex $1
Truth table33%1/3
A and B
A= defined $1B= hex $1
ABresult
111
0X0
100
1822 31 ▶ $UnicodeEntity = 1 if $V && $V > 127;
Branch: 1 branch
BranchTrueFalseTotal
if $V and $V > 127 0 31 31
Condition33%1/3
$V and $V > 127
!ll&&!rl&&r
0310
MC/DC0%0/2
$V and $V > 127
$V $V > 127
Truth table33%1/3
A and B
A= $VB= $V > 127
ABresult
0X0
100
111
1823 31 ▶ $V && $V < 1_114_111 && $V != 65535 && !($V > 55295 && $V < 57344) ? chr($V) : ""
Branch: 1 branch
BranchTrueFalseTotal
$V && $V < 1114111 && $V != 65535 && !($V > 55295 && $V < 57344) ? : 31 0 31
Condition33%4/12
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
!ll&&!rl&&r
0031
$V and $V < 1114111 and $V != 65535
!ll&&!rl&&r
0031
$V and $V < 1114111
!ll&&!rl&&r
0031
$V > 55295 && $V < 57344
!ll&&!rl&&r
3100
MC/DC0%0/5
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
$V $V < 1114111 $V != 65535 $V > 55295 $V < 57344
Truth table16%1/6
A and B and C and not(D && E)
A= $VB= $V < 1114111C= $V != 65535D= $V > 55295E= $V < 57344
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
1824 }egi;
1825 # Remove all remaining invalid escapes TODO This probably is not correct. Backslashes are required to be left alone by the CSS syntax
1826 316 s/\\//g;
1827  
1828 # Second param is true if it's an attribute, which means these have already been done
1829 316 ▶ if (!$_[1]) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_[1]) 112 204 316
1830 # Expand escapes
1831 112 s{&#(?:x(0?[\da-f]{1,6})|([\d]{1,7}));?}{
1832 126 ▶ my $V = (defined($1) && hex($1)) || (defined($2) && int($2)) || undef;
Condition54%6/11
defined $1 && hex $1 || defined $2 && int $2 || undef
l!l
1260
defined $1 and hex $1 or defined $2 and int $2
l!l&&r!l&&!r
11250
defined $1 and hex $1
!ll&&!rl&&r
12501
defined $2 and int $2
!ll&&!rl&&r
00125
MC/DC0%0/4
defined $1 && hex $1 || defined $2 && int $2 || undef
defined $1 hex $1 defined $2 int $2
Truth table28%2/7
A and B or C and D
A= defined $1B= hex $1C= defined $2D= int $2
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
1833 126 ▶ $UnicodeEntity = 1 if $V && $V > 127;
Branch: 1 branch
BranchTrueFalseTotal
if $V and $V > 127 1 125 126
Condition66%2/3
$V and $V > 127
!ll&&!rl&&r
01251
MC/DC50%1/2
$V and $V > 127
$V $V > 127
Truth table66%2/3
A and B
A= $VB= $V > 127
ABresult
0X0
100
111
1834 126 ▶ $V && $V < 1_114_111 && $V != 65535 && !($V > 55295 && $V < 57344) ? chr($V) : "";
Branch: 1 branch
BranchTrueFalseTotal
$V && $V < 1114111 && $V != 65535 && !($V > 55295 && $V < 57344) ? : 126 0 126
Condition33%4/12
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
!ll&&!rl&&r
00126
$V and $V < 1114111 and $V != 65535
!ll&&!rl&&r
00126
$V and $V < 1114111
!ll&&!rl&&r
00126
$V > 55295 && $V < 57344
!ll&&!rl&&r
12600
MC/DC0%0/5
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
$V $V < 1114111 $V != 65535 $V > 55295 $V < 57344
Truth table16%1/6
A and B and C and not(D && E)
A= $VB= $V < 1114111C= $V != 65535D= $V > 55295E= $V < 57344
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
1835 }egi;
1836 112 ▶ s/&(quot|apos|amp|lt|gt);?/$EntityToChar{lc($1)} || warn "no entity for: $1"/egi;
Condition50%1/2
$EntityToChar{lc $1} || warn("no entity for: $1")
l!l
10
MC/DC0%0/1
$EntityToChar{lc $1} || warn("no entity for: $1")
$EntityToChar{lc $1}
Truth table50%1/2
A
A= $EntityToChar{lc $1}
Aresult
11
00
1837 }
1838  
1839 # Remove all CSS comments
1840 316 s{/\*.*?\*/}{}sg;
1841  
1842 # Remove any CSS imports
1843 316 s{(\@import[^;]+;?)}{}sg;
1844  
1845 # Have to upgrade string to unicode string if entity expansion
1846 # resulted in non-ascii char
1847 316 ▶ utf8::upgrade($_) if $UnicodeEntity;
Branch: 1 branch
BranchTrueFalseTotal
if $UnicodeEntity 1 315 316
1848  
1849 316 ▶ warn "cleanup_style Content=$_" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 316 316
1850 }
1851  
1852 }
1853  
1854 =item I<defang_stylerule($SelectorsIn, $StyleRules, $lcTag, $IsAttr, $AttributeHash, $HtmlR, $OutR)>
1855  
1856 Defangs style data.
1857  
1858 =over 4
1859  
1860 =item B<Method parameters>
1861  
1862 =over 4
1863  
1864 =item I<$SelectorsIn>
1865  
1866 An array reference to the selectors in the style tag/attribute contents.
1867  
1868 =item I<$StyleRules>
1869  
1870 An array reference to the declaration blocks in the style tag/attribute contents.
1871  
1872 =item I<$lcTag>
1873  
1874 Lower case version of the HTML tag that is currently being parsed.
1875  
1876 =item I<$IsAttr>
1877  
1878 Whether we are currently parsing a style attribute or style tag. $IsAttr will be true if we are currently parsing a style attribute.
1879  
1880 =item I<$HtmlR>
1881  
1882 A scalar reference to the input HTML.
1883  
1884 =item I<$OutR>
1885  
1886 A scalar reference to the processed output so far.
1887  
1888 =back
1889  
1890 =back
1891  
1892 =cut
1893 316 ▶sub defang_stylerule {
Subroutine defang_stylerule: called CC=41 SCAR=37.6
Pod documented
1894 316 my ($Self, $SelectorsIn, $StyleRules, $lcTag, $IsAttr, $AttributeHash, $HtmlR, $OutR) = @_;
1895  
1896 316 my (@SelectorStyleKeyValues, %SelectorStyleKeyExtraData);
1897  
1898 316 my (@Selectors, @SelectorRules);
1899  
1900 316 foreach my $Selector (@$SelectorsIn) {
1901  
1902 389 ▶ warn "defang_stylerule Selector=$Selector" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 389 389
1903 389 my $Rule = shift @$StyleRules;
1904 389 my (@SelectorRule, @KeyValueRules, %StyleKeyExtraData);
1905  
1906 # Split style declaration to basic elements
1907 389 ▶ while($Rule =~ s{^(\{?\s*)([^:]+?)(\s*:\s*)((?:)?)([^;\}]+)()?(\s*;?)(\s*\}?)}{}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Rule =~ s/^(\{?\s*)([^:]+?)(\s*:\s*)((?:)?)([^;\}]+)()?(\s*;?)(\s*\}?)//) 548 389 937
1908 548 my ($KeyPilot, $Key, $Separator, $QuoteStart, $Value, $QuoteEnd, $ValueEnd, $ValueTrail) = ($1, $2, $3, $4, $5, $6, $7, $8);
1909
1910 548 ▶ warn "defang_stylerule Key=$Key Value=$Value Separator=$Separator ValueEnd=$ValueEnd" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 548 548
1911 # Store everything except style property and value in a hash
1912 548 $StyleKeyExtraData{lc $Key} = [$KeyPilot, $Separator, $QuoteStart, $QuoteEnd, $ValueEnd, $ValueTrail];
1913 548 my $DefangStyleRule = $Self->{defang_default};
1914  
1915 # If the style value has a URL in it and URL callback has been supplied, make a url_callback
1916 548 ▶ if ($Self->{url_callback}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"url_callback"}) 11 537 548
1917 11 our $StartPos = 0;
1918 11 ▶ while ($Value =~ m/\G\s*url\(\s*((?:['"])?)(?{ $StartPos = pos; })(.*?)\1\s*\)/gci) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Value =~ /\G\s*url\(\s*((?:['"])?)(?{ $HTML::Defang::StartPos = pos $_; })(.*?)\1\s*\)/cig) 11 11 22
1919 11 ▶ my ($UrlOrig, $Url) = $2 ? ($2, $2) : ('', '');
Branch: 1 branch
BranchTrueFalseTotal
$2 ? : 11 0 11
1920 11 my $EndPos = pos($Value);
1921 11 ▶ warn "defang_stylerule Url found in style property value. Url=$Url" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 11 11
1922 11 ▶ my $lcAttrKey = $IsAttr ? "style" : undef;
Branch: 1 branch
BranchTrueFalseTotal
$IsAttr ? : 2 9 11
1923 11 ▶ $DefangStyleRule = $Self->{url_callback}->($Self->{context}, $Self, $lcTag, $lcAttrKey, \$Url, $AttributeHash, $HtmlR, $OutR, lc $Key) if $Url;
Branch: 1 branch
BranchTrueFalseTotal
if $Url 11 0 11
1924 # Save back any changes
1925 11 ▶ warn "defang_stylerule After URL callback, Value=$Value DefangStyleRule=$DefangStyleRule" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 11 11
1926 11 ▶ if ($UrlOrig) {
Branch: 1 branch
BranchTrueFalseTotal
if ($UrlOrig) 11 0 11
1927 11 substr($Value, $StartPos, length($UrlOrig), $Url);
1928 11 pos($Value) = $EndPos - length($UrlOrig) + length($Url);
1929 }
1930 }
1931 }
1932  
1933 # Save the style property, value and defang flag
1934 548 push @KeyValueRules, [$Key, $Value, $DefangStyleRule];
1935 548 ▶ warn "defang_stylerule Key=$Key Value=$Value DefangStyleRule=$DefangStyleRule" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 548 548
1936  
1937 }
1938  
1939 389 push (@SelectorRule, \@KeyValueRules);
1940 389 push (@Selectors, $Selector);
1941 389 push (@SelectorRules, \@SelectorRule);
1942 389 $SelectorStyleKeyExtraData{$Selector} = \%StyleKeyExtraData;
1943  
1944 }
1945  
1946 # If a CSS callback is supplied, we call that
1947 316 ▶ $Self->{css_callback}->($Self->{context}, $Self, \@Selectors, \@SelectorRules, $lcTag, $IsAttr, $OutR) if $Self->{css_callback};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"css_callback"} 163 153 316
1948  
1949 warn "defang_stylerule More selectors($#Selectors) than selector rules($#SelectorRules)" if $Self->{Debug}
1950 316 ▶ && $#Selectors > $#SelectorRules;
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} and $#Selectors > $#SelectorRules 0 316 316
Condition33%1/3
$Self->{"Debug"} and $#Selectors > $#SelectorRules
!ll&&!rl&&r
31600
MC/DC0%0/2
$Self->{"Debug"} and $#Selectors > $#SelectorRules
$Self->{"Debug"} $#Selectors > $#SelectorRules
Truth table33%1/3
A and B
A= $Self->{"Debug"}B= $#Selectors > $#SelectorRules
ABresult
0X0
100
111
1951  
1952 316 my $Counter = 0;
1953 316 foreach my $Selector (@Selectors) {
1954  
1955 389 my $SelectorRule = $SelectorRules[$Counter];
1956 389 my $ExtraData = $SelectorStyleKeyExtraData{$Selector};
1957 389 my $Rule;
1958  
1959 389 ▶ for (my $j = 0; $j < @$SelectorRule; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @$SelectorRule) 389 389 778
1960 389 my $KeyValueRules = $SelectorRule->[$j];
1961
1962 389 ▶ for (my $k = 0; $k < @$KeyValueRules; $k++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k < @$KeyValueRules) 605 389 994
1963 605 my ($Key, $Value, $Defang) = @{$KeyValueRules->[$k]};
1964  
1965 605 ▶ my $v = ($ExtraData->{lc $Key} ||= []);
Condition100%2/2
$$ExtraData{lc $Key} ||= []
l!l
494111
MC/DC100%1/1
$$ExtraData{lc $Key} ||= []
$$ExtraData{lc $Key}
Truth table100%2/2
A
A= $$ExtraData{lc $Key}
Aresult
11
00
1966 605 my ($KeyPilot, $Separator, $QuoteStart, $QuoteEnd, $ValueEnd, $ValueTrail) = @$v;
1967  
1968 # Always need a separator
1969 605 ▶ $v->[1] = defined $v->[1] ? $v->[1] : ':';
Branch: 1 branch
BranchTrueFalseTotal
defined $v->[1] ? : 494 111 605
1970 # If an intermediate style property-value pair doesn't have a terminating semi-colon, add it
1971 605 ▶ if ($k < @$KeyValueRules - 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k < @$KeyValueRules - 1) 255 350 605
1972 255 ▶ $v->[4] .= ";" if !defined $v->[4] || $v->[4] !~ m/;/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v->[4] and $v->[4] =~ /;/ 91 164 255
Condition100%3/3
defined $v->[4] and $v->[4] =~ /;/
!ll&&!rl&&r
5437164
MC/DC100%2/2
defined $v->[4] and $v->[4] =~ /;/
defined $v->[4] $v->[4] =~ /;/
Truth table100%3/3
A and B
A= defined $v->[4]B= $v->[4] =~ /;/
ABresult
0X0
100
111
1973 }
1974  
1975 }
1976
1977 }
1978  
1979 389 $Counter++;
1980 }
1981
1982 316 $Counter = 0;
1983 316 foreach my $Selector (@Selectors) {
1984
1985 389 ▶ $SelectorsIn->[$Counter] = $Selector if $SelectorsIn->[$Counter] && !$IsAttr;
Branch: 1 branch
BranchTrueFalseTotal
if $SelectorsIn->[$Counter] and not $IsAttr 105 284 389
Condition100%3/3
$SelectorsIn->[$Counter] and not $IsAttr
!ll&&!rl&&r
134150105
MC/DC100%2/2
$SelectorsIn->[$Counter] and not $IsAttr
$SelectorsIn->[$Counter] not $IsAttr
Truth table100%3/3
A and not(B)
A= $SelectorsIn->[$Counter]B= not $IsAttr
ABresult
0X0
100
111
1986 389 my $SelectorRule = $SelectorRules[$Counter];
1987 389 my $ExtraData = $SelectorStyleKeyExtraData{$Selector};
1988 389 my $Rule;
1989
1990 389 foreach my $KeyRules (@$SelectorRule) {
1991
1992 389 foreach my $KeyValueRule (@$KeyRules) {
1993
1994 605 my ($Key, $Value, $Defang) = @$KeyValueRule;
1995 605 my $v = $ExtraData->{lc $Key};
1996 605 ▶ my ($KeyPilot, $Separator, $QuoteStart, $QuoteEnd, $ValueEnd, $ValueTrail) = @{$v || []};
Condition50%1/2
$v || []
l!l
6050
MC/DC0%0/1
$v || []
$v
Truth table50%1/2
A
A= $v
Aresult
11
00
1997  
1998 # Flag to defang if a url, expression or unallowed character found
1999 605 ▶ if ($Defang == DEFANG_DEFAULT) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Defang == 2) 329 276 605
2000 329 ▶ $Defang = $Value =~ m{^\s*[a-z0-9%!"'`:()#\s.,\/+-]+\s*;?\s*$}i ? DEFANG_NONE : DEFANG_ALWAYS;
Branch: 1 branch
BranchTrueFalseTotal
$Value =~ m[^\s*[a-z0-9%!"'`:()#\s.,\/+-]+\s*;?\s*$]i ? : 326 3 329
2001 329 ▶ $Defang = $Value =~ m{\burl\s*\(}i ? DEFANG_ALWAYS : $Defang;
Branch: 1 branch
BranchTrueFalseTotal
$Value =~ /\burl\s*\(/i ? : 25 304 329
2002 329 ▶ $Defang = $Value =~ m{\bexpression\s*\(}i ? DEFANG_ALWAYS : $Defang;
Branch: 1 branch
BranchTrueFalseTotal
$Value =~ /\bexpression\s*\(/i ? : 3 326 329
2003 }
2004  
2005 ($KeyPilot, $Key, $Separator, $QuoteStart, $Value, $QuoteEnd, $ValueEnd, $ValueTrail) =
2006 605 ▶ map { defined($_) ? $_ : "" }
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 4339 501 4840
2007 ($KeyPilot, $Key, $Separator, $QuoteStart, $Value, $QuoteEnd, $ValueEnd, $ValueTrail);
2008
2009 # Comment out the style property-value pair if $Defang
2010 605 my $CommentDefang = 0;
2011 605 ▶ if ($Defang != DEFANG_NONE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Defang != 0) 109 496 605
2012 109 ▶ if ($Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{'delete_defang_content'}) { } 0 109 109
2013 0 $KeyPilot = $Key = $Separator = $QuoteStart = $Value = $QuoteEnd = $ValueEnd = $ValueTrail = '';
2014 } else {
2015 109 $CommentDefang = 1;
2016 }
2017 }
2018  
2019 # Put the rule together back
2020 605 ▶ if (defined($Key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Key) 605 0 605
2021 605 my $RuleContent = join "", $Key, $Separator, $QuoteStart, $Value, $QuoteEnd, $ValueEnd;
2022 605 ▶ if ($CommentDefang) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CommentDefang) 109 496 605
2023 # Strip any mismatched comment markers, then add our own
2024 109 $RuleContent =~ s{/\*}{}g;
2025 109 $RuleContent =~ s{\*/}{}g;
2026 109 $RuleContent = "/*" . $RuleContent . "*/";
2027 }
2028 605 $Rule .= join "", $KeyPilot, $RuleContent, $ValueTrail;
2029 }
2030
2031 605 ▶ warn "defang_stylerule Rule=$Rule" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 605 605
2032  
2033 }
2034  
2035 }
2036  
2037 # Modify the original array
2038 389 $StyleRules->[$Counter] = $Rule;
2039 389 $Counter++;
2040 }
2041  
2042 }
2043  
2044 =item I<defang_attributes($OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $Tag, $TagTrail, $Attributes, $CloseAngle)>
2045  
2046 Defangs attributes, defangs tags, does tag, attrib, css and url callbacks.
2047  
2048 =over 4
2049  
2050 =item B<Method parameters>
2051  
2052 For a description of the method parameters, see documentation of defang_script_tag() method
2053  
2054 =back
2055  
2056 =cut
2057 1027 ▶sub defang_attributes {
Subroutine defang_attributes: called CC=41 SCAR=40.9
Pod documented
2058 1027 my ($Self, $OutR, $HtmlR, $TagOps, $OpenAngle, $IsEndTag, $lcTag, $TagTrail, $Attributes, $CloseAngle) = @_;
2059  
2060 1027 my $Debug = $Self->{Debug};
2061  
2062 1027 my $DefangTag = $Self->{defang_default};
2063 1027 my ($DefangTagUrlOverride, $DefangTagAttrOverride);
2064  
2065 # Create a key -> \value mapping of all attributes up front
2066 # so we have a complete hash for each callback
2067 1027 my %AttributeHash;
2068 1027 for my $Attr (@$Attributes) {
2069 707 my ($AttrKey, $AttrValR) = ($Attr->[0], \$Attr->[4]);
2070  
2071 707 ▶ my $lcAttrKey = $Attr->[7] = defined $AttrKey ? lc($AttrKey) : "";
Branch: 1 branch
BranchTrueFalseTotal
defined $AttrKey ? : 706 1 707
2072  
2073 # Get the attribute value cleaned up
2074 707 $$AttrValR = $Self->cleanup_attribute($$AttrValR);
2075 707 ▶ warn "defang_attributes cleaned AttrVal=$$AttrValR" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 707 707
2076  
2077 707 $AttributeHash{$lcAttrKey} = $AttrValR;
2078 }
2079  
2080 # Callback if the tag is in @$tags_to_callback
2081 1027 ▶ if (exists($Self->{tags_to_callback}->{$lcTag})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $Self->{"tags_to_callback"}{$lcTag}) 95 932 1027
2082 95 ▶ warn "defang_attributes Calling tags_callback for $lcTag" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 95 95
2083 95 $DefangTag = $Self->{tags_callback}->($Self->{context}, $Self, $OpenAngle, $lcTag, $IsEndTag, \%AttributeHash, $CloseAngle, $HtmlR, $OutR);
2084 }
2085  
2086 # Now process each attribute
2087 1027 foreach my $Attr (@$Attributes) {
2088 707 my ($lcAttrKey, $AttrKey, $AttrValR) = ($Attr->[7], $Attr->[0], \$Attr->[4]);
2089  
2090 707 ▶ warn "defang_attributes Tag=$lcTag lcAttrKey=$lcAttrKey AttrVal=$$AttrValR" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 707 707
2091  
2092 707 my $AttribRule = "";
2093 707 ▶ if (ref($Tags{$lcTag}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $Tags{$lcTag} eq "HASH") 629 78 707
2094 629 $AttribRule = $Tags{$lcTag}{$lcAttrKey};
2095 }
2096  
2097 707 my $DefangAttrib = $Self->{defang_default};
2098  
2099 707 ▶ $AttribRule ||= $CommonAttributes{$lcAttrKey};
Condition100%3/3
$AttribRule ||= $CommonAttributes{$lcAttrKey}
l!l&&r!l&&!r
221253233
MC/DC100%2/2
$AttribRule ||= $CommonAttributes{$lcAttrKey}
$AttribRule $CommonAttributes{$lcAttrKey}
Truth table100%3/3
A ||= B
A= $AttribRuleB= $CommonAttributes{$lcAttrKey}
ABresult
1X1
011
000
2100 707 ▶ warn "defang_attributes AttribRule=$AttribRule" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 707 707
2101
2102 # If this is a URL type $AttrKey and URL callback method is supplied, make a url_callback
2103 707 ▶ if ($Self->{url_callback} && $AttribRule && exists($UrlRules{$AttribRule})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"url_callback"} and $AttribRule and exists $UrlRules{$AttribRule}) 6 701 707
Condition83%5/6
$Self->{"url_callback"} and $AttribRule and exists $UrlRules{$AttribRule}
!ll&&!rl&&r
691106
$Self->{"url_callback"} and $AttribRule
!ll&&!rl&&r
691016
MC/DC66%2/3
$Self->{"url_callback"} and $AttribRule and exists $UrlRules{$AttribRule}
$Self->{"url_callback"} $AttribRule exists $UrlRules{$AttribRule}
Truth table75%3/4
A and B and C
A= $Self->{"url_callback"}B= $AttribRuleC= exists $UrlRules{$AttribRule}
ABCresult
0XX0
10X0
1100
1111
2104 6 ▶ warn "defang_attributes Making URL callback" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 6 6
2105 6 ($DefangAttrib, $DefangTagUrlOverride) = $Self->{url_callback}->($Self->{context}, $Self, $lcTag, $lcAttrKey, $AttrValR, \%AttributeHash, $HtmlR, $OutR, { defang_attrib => $DefangAttrib, attrib_rule => $AttribRule });
2106 6 ▶ die "url_callback reset" if !defined pos($$HtmlR);
Branch: 1 branch
BranchTrueFalseTotal
unless defined pos $$HtmlR 0 6 6
2107 }
2108  
2109 # We have a style attribute, so we call defang_style
2110 707 ▶ if ($lcAttrKey eq "style") {
Branch: 1 branch
BranchTrueFalseTotal
if ($lcAttrKey eq "style") 204 503 707
2111 204 ▶ warn "defang_attributes Found style attribute, calling defang_style" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 204 204
2112 204 $$AttrValR = $Self->defang_style_text($$AttrValR, $lcTag, 1, \%AttributeHash, $HtmlR, $OutR);
2113 }
2114  
2115 # If a attribute callback is supplied and its interested in this attribute, we make a attribs_callback
2116 707 ▶ if ($Self->{attribs_callback} && exists($Self->{attribs_to_callback}->{$lcAttrKey})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"attribs_callback"} and exists $Self->{"attribs_to_callback"}{$lcAttrKey}) 0 707 707
Condition33%1/3
$Self->{"attribs_callback"} and exists $Self->{"attribs_to_callback"}{$lcAttrKey}
!ll&&!rl&&r
70700
MC/DC0%0/2
$Self->{"attribs_callback"} and exists $Self->{"attribs_to_callback"}{$lcAttrKey}
$Self->{"attribs_callback"} exists $Self->{"attribs_to_callback"}{$lcAttrKey}
Truth table33%1/3
A and B
A= $Self->{"attribs_callback"}B= exists $Self->{"attribs_to_callback"}{$lcAttrKey}
ABresult
0X0
100
111
2117 0 ▶ warn "defang_attributes Making attribute callback for Tag=$lcTag AttrKey=$AttrKey" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 0 0
2118 0 (my $DefangResult, $DefangTagAttrOverride) = $Self->{attribs_callback}->($Self->{context}, $Self, $lcTag, $lcAttrKey, $AttrValR, $HtmlR, $OutR);
2119 # Only use new result if not already DEFANG_ALWAYS from url_callback
2120 0 ▶ $DefangAttrib = $DefangResult if $DefangAttrib != DEFANG_ALWAYS;
Branch: 1 branch
BranchTrueFalseTotal
if $DefangAttrib != 1 0 0 0
2121 }
2122  
2123 # Check if the final attribute value needs defanging
2124 707 $DefangAttrib = $Self->defang_attribute_value($AttrValR, $AttribRule, $DefangAttrib);
2125  
2126 # Store the attribute defang flag
2127 707 $Attr->[8] = $DefangAttrib;
2128  
2129 }
2130  
2131 1027 my @OutputAttributes;
2132  
2133 1027 foreach my $Attr (@$Attributes) {
2134
2135 707 my $lcAttr = $Attr->[7];
2136  
2137 # If the attribute is deleted don't output it
2138 707 ▶ unless ($AttributeHash{$lcAttr}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($AttributeHash{$lcAttr}) 25 682 707
2139 25 ▶ warn "defang_attributes Marking attribute $lcAttr for deletion" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 25 25
2140 25 next;
2141 }
2142  
2143 # And we attach the defang string here, if the attribute should be defanged
2144 # (attribute could be undef for buggy html, eg <ahref=blah>)
2145 682 ▶ if ($Attr->[8] != DEFANG_NONE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Attr->[8] != 0) 350 332 682
2146 350 ▶ if ($Self->{delete_defang_content}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{'delete_defang_content'}) { } 0 350 350
2147 0 @$Attr = ('') x 7;
2148 } else {
2149 $Attr->[0] = $Self->{defang_string} . ($Attr->[0] || '')
2150 350 ▶ if $Self->{allow_double_defang} || ($Attr->[0] || '') !~ $Self->{defang_re};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"allow_double_defang"} or not +($Attr->[0] || "") =~ /$Self->{"defang_re"}/ 350 0 350
Condition71%5/7
$Self->{"allow_double_defang"} or not +($Attr->[0] || "") =~ /$Self->{"defang_re"}/
l!l&&r!l&&!r
03500
$Attr->[0] || ''
l!l
3491
$Attr->[0] || ''
l!l
3491
MC/DC50%1/2
$Self->{"allow_double_defang"} or not +($Attr->[0] || "") =~ /$Self->{"defang_re"}/
$Self->{"allow_double_defang"} $Attr->[0]
Truth table66%2/3
A or not(B)
A= $Self->{"allow_double_defang"}B= $Attr->[0]
ABresult
1X1
001
010
2151 }
2152 }
2153  
2154 # Remove non-attribute values so they're not in the output
2155 682 splice(@$Attr, 7);
2156  
2157 # Requote specials in attribute value
2158 682 ▶ if (defined $Attr->[4]) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Attr->[4]) 682 0 682
2159 682 ▶ my $QuoteRe = $QuoteRe{$Attr->[3]} || $QuoteRe{""};
Condition33%1/3
$QuoteRe{$Attr->[3]} || $QuoteRe{''}
l!l&&r!l&&!r
68200
MC/DC0%0/2
$QuoteRe{$Attr->[3]} || $QuoteRe{''}
$QuoteRe{$Attr->[3]} $QuoteRe{''}
Truth table33%1/3
A || B
A= $QuoteRe{$Attr->[3]}B= $QuoteRe{''}
ABresult
1X1
011
000
2160 682 $Attr->[4] =~ s/$CtrlChars//go; # strip ctrls
2161 682 $Attr->[4] =~ s/$QuoteRe/'&'.$CharToEntity{$1}.';'/eg;
2162 }
2163  
2164 # Add to attributes to output
2165 682 push @OutputAttributes, $Attr;
2166  
2167 # Remove all processed attributes in the hash, so we can track ones that we added
2168 682 delete $AttributeHash{$lcAttr};
2169 }
2170  
2171 # Append all remaining attribute keys (which must have been newly added attributes by
2172 # the callback)and values in no particular order
2173 1027 my $QuoteRe = $QuoteRe{'"'};
2174 1027 ▶ while (my ($Key,$Value) = each %AttributeHash ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %AttributeHash) 29 1027 1056
2175 29 my $Attr = [" " . $Key, "", "=", '"', $$Value, '"', ""];
2176 29 ▶ if (defined $Attr->[4]) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Attr->[4]) { } 28 1 29
2177 28 $Attr->[4] =~ s/$CtrlChars//g; # strip ctrls
2178 0 $Attr->[4] =~ s/$QuoteRe/'&'.$CharToEntity{$1}.';'/eg
2179 } else {
2180 1 @$Attr[2..6] = (undef) x 5;
2181 }
2182 29 push @OutputAttributes, $Attr;
2183 }
2184  
2185 # Replace attributes array with just the ones we want to output
2186 1027 @$Attributes = @OutputAttributes;
2187  
2188 # If its a known tag, we whitelist it
2189 1027 ▶ if ($DefangTag == DEFANG_DEFAULT && (my $TagOps = $Tags{$lcTag})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($DefangTag == 2 and my $TagOps = $Tags{$lcTag}) 890 137 1027
Condition100%3/3
$DefangTag == 2 and my $TagOps = $Tags{$lcTag}
!ll&&!rl&&r
5582890
MC/DC100%2/2
$DefangTag == 2 and my $TagOps = $Tags{$lcTag}
$DefangTag == 2 my $TagOps = $Tags{$lcTag}
Truth table100%3/3
A and B
A= $DefangTag == 2B= my $TagOps = $Tags{$lcTag}
ABresult
0X0
100
111
2190 890 $DefangTag = DEFANG_NONE;
2191 }
2192 # Unless we have overrides
2193 1027 ▶ $DefangTag = DEFANG_ALWAYS
Branch: 1 branch
BranchTrueFalseTotal
if defined $DefangTagUrlOverride and $DefangTagUrlOverride == 1 0 1027 1027
Condition33%1/3
defined $DefangTagUrlOverride and $DefangTagUrlOverride == 1
!ll&&!rl&&r
102700
MC/DC0%0/2
defined $DefangTagUrlOverride and $DefangTagUrlOverride == 1
defined $DefangTagUrlOverride $DefangTagUrlOverride == 1
Truth table33%1/3
A and B
A= defined $DefangTagUrlOverrideB= $DefangTagUrlOverride == 1
ABresult
0X0
100
111
2194 if defined($DefangTagUrlOverride) && $DefangTagUrlOverride == DEFANG_ALWAYS;
2195 1027 ▶ $DefangTag = DEFANG_ALWAYS
Branch: 1 branch
BranchTrueFalseTotal
if defined $DefangTagAttrOverride and $DefangTagAttrOverride == 1 0 1027 1027
Condition33%1/3
defined $DefangTagAttrOverride and $DefangTagAttrOverride == 1
!ll&&!rl&&r
102700
MC/DC0%0/2
defined $DefangTagAttrOverride and $DefangTagAttrOverride == 1
defined $DefangTagAttrOverride $DefangTagAttrOverride == 1
Truth table33%1/3
A and B
A= defined $DefangTagAttrOverrideB= $DefangTagAttrOverride == 1
ABresult
0X0
100
111
2196 if defined($DefangTagAttrOverride) && $DefangTagAttrOverride == DEFANG_ALWAYS;
2197  
2198 1027 return $DefangTag;
2199 }
2200  
2201 707 ▶sub defang_attribute_value {
Subroutine defang_attribute_value: called CC=12 SCAR=25.0
Pod undocumented
2202 707 my ($Self, $AttrValR, $AttribRule, $DefangAttrib) = @_;
2203  
2204 707 my $Debug = $Self->{Debug};
2205  
2206 707 my $AttrValStripped = $Self->strip_attribute($$AttrValR);
2207  
2208 707 ▶ warn "defang_attribute_value AttrVal=$$AttrValR AttrValStripped=$AttrValStripped" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 707 707
2209  
2210 707 ▶ if (($DefangAttrib == DEFANG_DEFAULT) && $AttribRule) {
Branch: 2 branches
BranchTrueFalseTotal
if ($DefangAttrib == 2 and $AttribRule) { } 468 239 707
elsif (not $AttribRule and $DefangAttrib != 0) { } 233 12 245
Condition100%3/3
$DefangAttrib == 2 and $AttribRule
!ll&&!rl&&r
6233468
MC/DC100%2/2
$DefangAttrib == 2 and $AttribRule
$DefangAttrib == 2 $AttribRule
Truth table100%3/3
A and B
A= $DefangAttrib == 2B= $AttribRule
ABresult
0X0
100
111
2211 468 my $Rule = $Rules{$AttribRule};
2212 468 ▶ warn "defang_attributes AttribRule=$AttribRule Rule=$Rule" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 468 468
2213  
2214 # We whitelist the attribute if the value matches the rule
2215 468 ▶ if (ref($Rule) eq "Regexp") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $Rule eq "Regexp") 386 82 468
2216 386 ▶ $DefangAttrib = ($AttrValStripped =~ $Rule) ? DEFANG_NONE : DEFANG_ALWAYS;
Branch: 1 branch
BranchTrueFalseTotal
$AttrValStripped =~ /$Rule/ ? : 331 55 386
2217 }
2218  
2219 # Hack. Ref to array is a blacklist regexp
2220 468 ▶ if (ref($Rule) eq "ARRAY") {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $Rule eq "ARRAY") 82 386 468
2221 82 ▶ $DefangAttrib = ($AttrValStripped =~ $Rule->[0]) ? DEFANG_ALWAYS : DEFANG_NONE;
Branch: 1 branch
BranchTrueFalseTotal
$AttrValStripped =~ /$Rule->[0]/i ? : 73 9 82
2222 }
2223
2224 ▶ } elsif (!$AttribRule && $DefangAttrib != DEFANG_NONE) {
Condition66%2/3
not $AttribRule and $DefangAttrib != 0
!ll&&!rl&&r
60233
MC/DC50%1/2
not $AttribRule and $DefangAttrib != 0
not $AttribRule $DefangAttrib != 0
Truth table66%2/3
not(A) and B
A= not $AttribRuleB= $DefangAttrib != 0
ABresult
0X0
100
111
2225 233 $DefangAttrib = DEFANG_ALWAYS;
2226 }
2227  
2228 707 ▶ warn "defang_attribute_value DefangAttrib=$DefangAttrib" if $Debug;
Branch: 1 branch
BranchTrueFalseTotal
if $Debug 0 707 707
2229  
2230 707 return $DefangAttrib;
2231 }
2232  
2233 87 ▶sub track_implicit_tags {
Subroutine track_implicit_tags: called CC=9 SCAR=22.0
Pod undocumented
2234 87 my ($Self, $OutR, $HtmlR, $lcTag, $IsEndTag) = @_;
2235  
2236 87 my $OpenedTags = $Self->{opened_tags};
2237 87 ▶ return if !@$OpenedTags;
Branch: 1 branch
BranchTrueFalseTotal
unless @$OpenedTags 35 52 87
2238  
2239 # If just closing the last tag, nothing to do
2240 52 my $LastTag = $OpenedTags->[-1]->[0];
2241  
2242 # Are we expecting a particular tag based on last open tag?
2243 52 ▶ if (my $ImplicitTags = $ImplicitOpenTags{$LastTag}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ImplicitTags = $ImplicitOpenTags{$LastTag}) 20 32 52
2244  
2245 # We didn't get a tag we were expecting (eg <table><div> rather
2246 # than <table><tbody><tr><td><div>), so insert opening tags recursively
2247 20 $LastTag = $lcTag;
2248 20 ▶ while ($ImplicitTags && (!$ImplicitTags->{$LastTag} || $IsEndTag)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ImplicitTags and !$ImplicitTags->{$LastTag} || $IsEndTag) 6 19 25
Condition83%5/6
$ImplicitTags and !$ImplicitTags->{$LastTag} || $IsEndTag
!ll&&!rl&&r
2176
not $ImplicitTags->{$LastTag} or $IsEndTag
l!l&&r!l&&!r
6017
MC/DC66%2/3
$ImplicitTags and !$ImplicitTags->{$LastTag} || $IsEndTag
$ImplicitTags not $ImplicitTags->{$LastTag} $IsEndTag
Truth table75%3/4
A and not(B) or C
A= $ImplicitTagsB= not $ImplicitTags->{$LastTag}C= $IsEndTag
ABCresult
0XX0
1000
11X1
1011
2249 6 my $Tag = $ImplicitTags->{default};
2250 # Don't insert implicit tag if it's actually the one we actually just parsed
2251 6 ▶ last if !$IsEndTag && $Tag eq $lcTag;
Branch: 1 branch
BranchTrueFalseTotal
if not $IsEndTag and $Tag eq $lcTag 1 5 6
Condition100%3/3
not $IsEndTag and $Tag eq $lcTag
!ll&&!rl&&r
231
MC/DC100%2/2
not $IsEndTag and $Tag eq $lcTag
not $IsEndTag $Tag eq $lcTag
Truth table100%3/3
not(A) and B
A= not $IsEndTagB= $Tag eq $lcTag
ABresult
0X0
100
111
2252 5 $Self->open_tag(1, $OutR, $HtmlR, $Tag, \"");
2253 5 ▶ $$OutR .= "<!-- $Tag implicit open due to $LastTag -->" unless $Self->{quiet};
Branch: 1 branch
BranchTrueFalseTotal
unless $Self->{"quiet"} 5 0 5
2254 5 $LastTag = $Tag;
2255 5 $ImplicitTags = $ImplicitOpenTags{$LastTag};
2256 }
2257 }
2258 }
2259  
2260 132 ▶sub track_in_to_block_tags {
Subroutine track_in_to_block_tags: called CC=6 SCAR=17.9
Pod undocumented
2261 132 my ($Self, $OutR, $HtmlR, $lcTag) = @_;
2262  
2263 # If we've got a block tag, then close any inline tags
2264 # before the block tag. We'll re-opened them again below
2265 132 ▶ if ($BlockTags{$lcTag} && !$TableTags{$lcTag}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($BlockTags{$lcTag} and not $TableTags{$lcTag}) 33 99 132
Condition100%3/3
$BlockTags{$lcTag} and not $TableTags{$lcTag}
!ll&&!rl&&r
336633
MC/DC100%2/2
$BlockTags{$lcTag} and not $TableTags{$lcTag}
$BlockTags{$lcTag} not $TableTags{$lcTag}
Truth table100%3/3
A and not(B)
A= $BlockTags{$lcTag}B= not $TableTags{$lcTag}
ABresult
0X0
100
111
2266 my ($OpenedTags, $ClosedIntoBlockTags, $Quiet)
2267 33 = @$Self{qw(opened_tags closed_into_block_tags quiet)};
2268  
2269 33 ▶ while (@$OpenedTags && $InlineTags{$OpenedTags->[-1]->[0]}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$OpenedTags and $InlineTags{$OpenedTags->[-1][0]}) 3 33 36
Condition100%3/3
@$OpenedTags and $InlineTags{$OpenedTags->[-1][0]}
!ll&&!rl&&r
7263
MC/DC100%2/2
@$OpenedTags and $InlineTags{$OpenedTags->[-1][0]}
@$OpenedTags $InlineTags{$OpenedTags->[-1][0]}
Truth table100%3/3
A and B
A= @$OpenedTagsB= $InlineTags{$OpenedTags->[-1][0]}
ABresult
0X0
100
111
2270 3 push @$ClosedIntoBlockTags, my $POTD = $OpenedTags->[-1];
2271 3 ▶ $$OutR .= "<!-- close inline tag into block -->" unless $Quiet;
Branch: 1 branch
BranchTrueFalseTotal
unless $Quiet 3 0 3
2272 3 $Self->close_tag(1, $OutR, $HtmlR, $POTD->[0], 1);
2273 }
2274 }
2275 }
2276  
2277 128 ▶sub track_out_of_block_tags {
Subroutine track_out_of_block_tags: called CC=10 SCAR=23.7
Pod undocumented
2278 128 my ($Self, $OutR, $HtmlR, $lcTag) = @_;
2279  
2280 128 my $ClosedIntoBlockTags = $Self->{closed_into_block_tags};
2281 128 ▶ return if !@$ClosedIntoBlockTags;
Branch: 1 branch
BranchTrueFalseTotal
unless @$ClosedIntoBlockTags 125 3 128
2282  
2283 # Re-open inline tags into this block
2284  
2285 # Peek ahead. If another block tag, don't do this
2286 return if $$HtmlR =~ m{\G(?=\s*</?($TagNameRE))}gc
2287 3 ▶ && $BlockTags{lc "$1"} && !$TableTags{lc "$1"};
Branch: 1 branch
BranchTrueFalseTotal
if $$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cg and $BlockTags{lc "$1"} and not $TableTags{lc "$1"} 0 3 3
Condition66%4/6
$$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cg and $BlockTags{lc "$1"} and not $TableTags{lc "$1"}
!ll&&!rl&&r
210
$$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cg and $BlockTags{lc "$1"}
!ll&&!rl&&r
201
MC/DC0%0/3
$$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cg and $BlockTags{lc "$1"} and not $TableTags{lc "$1"}
$$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cg $BlockTags{lc "$1"} not $TableTags{lc "$1"}
Truth table50%2/4
A and B and not(C)
A= $$HtmlR =~ m[\G(?=\s*</?($TagNameRE))]cgB= $BlockTags{lc "$1"}C= not $TableTags{lc "$1"}
ABCresult
0XX0
10X0
1100
1111
2288  
2289 3 my ($SpanCount, $SpanAttrs) = (0, '');
2290 3 ▶ while (my $POTD = pop @$ClosedIntoBlockTags) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $POTD = pop @$ClosedIntoBlockTags) 3 3 6
2291  
2292 # Don't add more than 3 span tags with same attrs in a row
2293 3 ▶ if ($SpanCount < 3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($SpanCount < 3) 3 0 3
2294 # Add after the current tag is output
2295 3 $Self->track_and_add_tag_to_output($POTD);
2296 3 ▶ $Self->add_to_output("<!-- reopen inline tag after block -->") unless $Self->{quiet};
Branch: 1 branch
BranchTrueFalseTotal
unless $Self->{"quiet"} 3 0 3
2297 }
2298 3 ▶ $SpanCount = $POTD->[0] eq 'span' && $POTD->[1] eq $SpanAttrs ? $SpanCount+1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$POTD->[0] eq 'span' && $POTD->[1] eq $SpanAttrs ? : 2 1 3
Condition66%2/3
$POTD->[0] eq "span" and $POTD->[1] eq $SpanAttrs
!ll&&!rl&&r
102
MC/DC50%1/2
$POTD->[0] eq "span" and $POTD->[1] eq $SpanAttrs
$POTD->[0] eq "span" $POTD->[1] eq $SpanAttrs
Truth table66%2/3
A and B
A= $POTD->[0] eq "span"B= $POTD->[1] eq $SpanAttrs
ABresult
0X0
100
111
2299 3 $SpanAttrs = $POTD->[1];
2300 }
2301 }
2302  
2303 78 ▶sub open_tag {
Subroutine open_tag: called CC=5 SCAR=16.1
Pod undocumented
2304 78 my ($Self, $AddOutput, $OutR, $HtmlR, $lcTag, $TagContentR, $NoBlockCheck) = @_;
2305  
2306 78 $Self->track_implicit_tags($OutR, $HtmlR, $lcTag, 0);
2307 78 ▶ $Self->track_in_to_block_tags($OutR, $HtmlR, $lcTag)
Branch: 1 branch
BranchTrueFalseTotal
unless $NoBlockCheck 75 3 78
2308 unless $NoBlockCheck;
2309  
2310 # Track this tag that was opened (and all attributes, so we can re-open with the same if needed)
2311 78 ▶ if ($Self->{mismatched_tags_to_fix}->{$lcTag}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"mismatched_tags_to_fix"}{$lcTag}) 52 26 78
2312 52 push @{$Self->{opened_tags}}, [ $lcTag, $$TagContentR ];
2313 52 $Self->{opened_tags_count}->{$lcTag}++;
2314 }
2315 78 ▶ if ($AddOutput) {
Branch: 1 branch
BranchTrueFalseTotal
if ($AddOutput) 8 70 78
2316 8 $$OutR .= "<${lcTag}${$TagContentR}>";
2317 }
2318  
2319 78 ▶ $Self->track_out_of_block_tags($OutR, $HtmlR, $lcTag)
Branch: 1 branch
BranchTrueFalseTotal
unless $NoBlockCheck 75 3 78
2320 unless $NoBlockCheck;
2321  
2322 78 return DEFANG_NONE;
2323 }
2324  
2325 9 my %RECache;
2326 60 ▶sub close_tag {
Subroutine close_tag: called CC=24 SCAR=40.5
Pod undocumented
2327 60 my ($Self, $AddOutput, $OutR, $HtmlR, $lcTag, $NoBlockCheck) = @_;
2328  
2329 my ($OpenedTags, $OpenedTagsCount, $Quiet)
2330 60 = @$Self{qw(opened_tags opened_tags_count quiet)};
2331  
2332 # If just closing the last tag, nothing to do
2333 60 ▶ if (@$OpenedTags && $OpenedTags->[-1]->[0] ne $lcTag) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$OpenedTags and $OpenedTags->[-1][0] ne $lcTag) 9 51 60
Condition100%3/3
@$OpenedTags and $OpenedTags->[-1][0] ne $lcTag
!ll&&!rl&&r
3489
MC/DC100%2/2
@$OpenedTags and $OpenedTags->[-1][0] ne $lcTag
@$OpenedTags $OpenedTags->[-1][0] ne $lcTag
Truth table100%3/3
A and B
A= @$OpenedTagsB= $OpenedTags->[-1][0] ne $lcTag
ABresult
0X0
100
111
2334 9 $Self->track_implicit_tags($OutR, $HtmlR, $lcTag, 1);
2335 }
2336  
2337 60 ▶ $Self->track_in_to_block_tags($OutR, $HtmlR, $lcTag)
Branch: 1 branch
BranchTrueFalseTotal
unless $NoBlockCheck 57 3 60
2338 unless $NoBlockCheck;
2339  
2340 # Check for correctly nested closing tags
2341 60 my $IsTagToFix = $Self->{mismatched_tags_to_fix}->{$lcTag};
2342 60 ▶ if ($IsTagToFix) {
Branch: 1 branch
BranchTrueFalseTotal
if ($IsTagToFix) 56 4 60
2343 56 my ($Found, $ClosingTags) = (0, '');
2344  
2345 # Tag not even open, just defang it
2346 56 ▶ return DEFANG_ALWAYS if !$OpenedTagsCount->{$lcTag};
Branch: 1 branch
BranchTrueFalseTotal
unless $OpenedTagsCount->{$lcTag} 4 52 56
2347  
2348 # Check tag stack up to find mismatches
2349 52 ▶ while (@$OpenedTags) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$OpenedTags) 58 0 58
2350 58 my ($PreviousOpenedTag) = @{$OpenedTags->[-1]};
2351  
2352 58 ▶ if ($PreviousOpenedTag eq $lcTag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($PreviousOpenedTag eq $lcTag) 52 6 58
2353 52 $Found = 1;
2354 52 last;
2355 }
2356  
2357 # Check for tags that don't break out further
2358 6 ▶ if (my $NestList = $MismatchedTagNest{$PreviousOpenedTag}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $NestList = $MismatchedTagNest{$PreviousOpenedTag}) 0 6 6
2359 0 ▶ last if $NestList->{""} || $NestList->{$lcTag};
Branch: 1 branch
BranchTrueFalseTotal
if $NestList->{""} or $NestList->{$lcTag} 0 0 0
Condition0%0/3
$NestList->{""} or $NestList->{$lcTag}
l!l&&r!l&&!r
000
MC/DC0%0/2
$NestList->{""} or $NestList->{$lcTag}
$NestList->{""} $NestList->{$lcTag}
Truth table0%0/3
A or B
A= $NestList->{""}B= $NestList->{$lcTag}
ABresult
1X1
011
000
2360 }
2361  
2362 # Close this mismatched tag
2363 6 ▶ $$OutR .= "<!-- close mismatched tag -->" unless $Quiet;
Branch: 1 branch
BranchTrueFalseTotal
unless $Quiet 6 0 6
2364 6 $Self->close_tag(1, $OutR, $HtmlR, $PreviousOpenedTag);
2365 }
2366  
2367 # Otherwise hit tag that stops breaking out, defang it
2368 52 ▶ if (!$Found) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Found) 0 52 52
2369 0 return DEFANG_ALWAYS;
2370 }
2371 }
2372  
2373 56 my $Result = DEFANG_NONE;
2374  
2375 56 ▶ if ($IsTagToFix && $Self->{empty_tags_to_collapse}->{$lcTag}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($IsTagToFix and $Self->{"empty_tags_to_collapse"}{$lcTag}) 0 56 56
Condition66%2/3
$IsTagToFix and $Self->{"empty_tags_to_collapse"}{$lcTag}
!ll&&!rl&&r
4520
MC/DC0%0/2
$IsTagToFix and $Self->{"empty_tags_to_collapse"}{$lcTag}
$IsTagToFix $Self->{"empty_tags_to_collapse"}{$lcTag}
Truth table66%2/3
A and B
A= $IsTagToFixB= $Self->{"empty_tags_to_collapse"}{$lcTag}
ABresult
0X0
100
111
2376  
2377 # Check if previous output is open tag, or just comments
2378 0 my $LastTagPos = rindex($$OutR, '<');
2379 0 ▶ while ($LastTagPos >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($LastTagPos >= 0) 0 0 0
2380 0 pos($$OutR) = $LastTagPos;
2381 0 ▶ my $RE = (defined $RECache{$lcTag} ? $RECache{$lcTag} : qr/\G<${lcTag}\b[^<>]*>\s*(?:<|$)/);
Branch: 1 branch
BranchTrueFalseTotal
defined $RECache{$lcTag} ? : 0 0 0
2382 0 ▶ if ($$OutR =~ /$RE/gc) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$OutR =~ /$RE/cg) { } 0 0 0
elsif ($$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/cg and $LastTagPos > 0) { } 0 0 0
2383 0 substr($$OutR, $LastTagPos) = '';
2384 0 ($AddOutput, $Result) = (0, DEFANG_ALWAYS);
2385 0 last;
2386 ▶ } elsif ($$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/gc && $LastTagPos > 0) {
Condition0%0/3
$$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/cg and $LastTagPos > 0
!ll&&!rl&&r
000
MC/DC0%0/2
$$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/cg and $LastTagPos > 0
$$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/cg $LastTagPos > 0
Truth table0%0/3
A and B
A= $$OutR =~ /\G<!--(?!KEEP)[^<>]*-->\s*(?:<|$)/cgB= $LastTagPos > 0
ABresult
0X0
100
111
2387 0 $LastTagPos = rindex($$OutR, '<', $LastTagPos-1);
2388 } else {
2389 0 last;
2390 }
2391 }
2392 }
2393  
2394 56 ▶ if ($IsTagToFix) {
Branch: 1 branch
BranchTrueFalseTotal
if ($IsTagToFix) 52 4 56
2395 52 ▶ if ($lcTag eq $Self->{opened_tags}->[-1]->[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lcTag eq $Self->{'opened_tags'}[-1][0]) { } 52 0 52
2396 52 pop @{$Self->{opened_tags}};
2397 52 $Self->{opened_tags_count}->{$lcTag}--;
2398 } else {
2399 0 warn "Unexpected tag stack. Expected $lcTag, found " . $Self->{opened_tags}->[-1]->[0];
2400 }
2401 }
2402 56 ▶ if ($AddOutput) {
Branch: 1 branch
BranchTrueFalseTotal
if ($AddOutput) 39 17 56
2403 39 $$OutR .= "</$lcTag>";
2404 }
2405  
2406 56 ▶ $Self->track_out_of_block_tags($OutR, $HtmlR, $lcTag)
Branch: 1 branch
BranchTrueFalseTotal
unless $NoBlockCheck 53 3 56
2407 unless $NoBlockCheck;
2408  
2409 56 return $Result;
2410 }
2411  
2412 354 ▶sub close_all_tags {
Subroutine close_all_tags: called CC=5 SCAR=19.1
Pod undocumented
2413 354 my ($Self, $OutR, $HtmlR) = @_;
2414  
2415 354 my $RemainingClosingTags = '';
2416  
2417 my ($OpenedTags, $OpenedTagsCount, $Quiet)
2418 354 = @$Self{qw(opened_tags opened_tags_count quiet)};
2419  
2420 354 for (reverse @$OpenedTags) {
2421 30 ▶ $$OutR .= "<!-- close unclosed tag -->" unless $Quiet;
Branch: 1 branch
BranchTrueFalseTotal
unless $Quiet 30 0 30
2422 30 $Self->close_tag(1, $OutR, $HtmlR, $_->[0]);
2423 }
2424  
2425 # Also clear implicit tags
2426 354 $Self->{opened_nested_tags} = [];
2427  
2428 354 ▶ if ($Self->{Debug}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Self->{"Debug"}) 0 354 354
2429 0 warn "Check all tags closed and counts zeroed";
2430 0 ▶ die "Not all tags closed" if grep { $_ > 0 } values %$OpenedTagsCount;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_ > 0;} values %$OpenedTagsCount 0 0 0
2431 }
2432 }
2433  
2434 =item I<cleanup_attribute($AttributeString)>
2435  
2436 Helper function to cleanup attributes
2437  
2438 =over 4
2439  
2440 =item B<Method parameters>
2441  
2442 =over 4
2443  
2444 =item I<$AttributeString>
2445  
2446 The value of the attribute.
2447  
2448 =back
2449  
2450 =back
2451  
2452 =back
2453  
2454 =back
2455  
2456 =cut
2457 707 ▶sub cleanup_attribute {
Subroutine cleanup_attribute: called CC=16 SCAR=32.6
Pod documented
2458 707 my ($Self, $AttrVal) = @_;
2459  
2460 707 ▶ return (undef, '') unless defined($AttrVal);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $AttrVal 9 698 707
2461  
2462 # Create a "stripped" attribute value which removes all embedded whitespace and control characters
2463  
2464 # Substitute character entities with actual characters
2465 # - in HTML, &#xa; &#x0a; &#x000a; &#10; are all character codes
2466 # - in IE, &#xajavascript is same as &#xa;javascript
2467 # - avoid invalid chars + surrogate pairs
2468 698 my $UnicodeEntity = 0;
2469 698 $AttrVal =~ s{&#(?:x(0?[\da-f]{1,6})|([\d]{1,7}));?}{
2470 137 ▶ my $V = (defined($1) && hex($1)) || (defined($2) && int($2)) || undef;
Condition54%6/11
defined $1 && hex $1 || defined $2 && int $2 || undef
l!l
1370
defined $1 and hex $1 or defined $2 and int $2
l!l&&r!l&&!r
75620
defined $1 and hex $1
!ll&&!rl&&r
62075
defined $2 and int $2
!ll&&!rl&&r
0062
MC/DC0%0/4
defined $1 && hex $1 || defined $2 && int $2 || undef
defined $1 hex $1 defined $2 int $2
Truth table28%2/7
A and B or C and D
A= defined $1B= hex $1C= defined $2D= int $2
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
2471 137 ▶ $UnicodeEntity = 1 if $V && $V > 127;
Branch: 1 branch
BranchTrueFalseTotal
if $V and $V > 127 1 136 137
Condition66%2/3
$V and $V > 127
!ll&&!rl&&r
01361
MC/DC50%1/2
$V and $V > 127
$V $V > 127
Truth table66%2/3
A and B
A= $VB= $V > 127
ABresult
0X0
100
111
2472 137 ▶ $V && $V < 1_114_111 && $V != 65535 && !($V > 55295 && $V < 57344) ? chr($V) : "";
Branch: 1 branch
BranchTrueFalseTotal
$V && $V < 1114111 && $V != 65535 && !($V > 55295 && $V < 57344) ? : 137 0 137
Condition33%4/12
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
!ll&&!rl&&r
00137
$V and $V < 1114111 and $V != 65535
!ll&&!rl&&r
00137
$V and $V < 1114111
!ll&&!rl&&r
00137
$V > 55295 && $V < 57344
!ll&&!rl&&r
13700
MC/DC0%0/5
$V and $V < 1114111 and $V != 65535 and not $V > 55295 && $V < 57344
$V $V < 1114111 $V != 65535 $V > 55295 $V < 57344
Truth table16%1/6
A and B and C and not(D && E)
A= $VB= $V < 1114111C= $V != 65535D= $V > 55295E= $V < 57344
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
2473 }egi;
2474  
2475 # These get requoted when we output the attribute
2476 698 ▶ $AttrVal =~ s/&(quot|apos|amp|lt|gt);?/$EntityToChar{lc($1)} || warn "no entity for: $1"/egi;
Condition50%1/2
$EntityToChar{lc $1} || warn("no entity for: $1")
l!l
130
MC/DC0%0/1
$EntityToChar{lc $1} || warn("no entity for: $1")
$EntityToChar{lc $1}
Truth table50%1/2
A
A= $EntityToChar{lc $1}
Aresult
11
00
2477  
2478 # Have to upgrade string to unicode string if entity expansion
2479 # resulted in non-ascii char
2480 698 ▶ utf8::upgrade($AttrVal) if $UnicodeEntity;
Branch: 1 branch
BranchTrueFalseTotal
if $UnicodeEntity 1 697 698
2481  
2482 698 ▶ warn "cleanup_attribute AttrVal=$AttrVal" if $Self->{Debug};
Branch: 1 branch
BranchTrueFalseTotal
if $Self->{"Debug"} 0 698 698
2483 698 return $AttrVal;
2484 }
2485  
2486 707 ▶sub strip_attribute {
Subroutine strip_attribute: called CC=6 SCAR=28.6
Pod undocumented
2487 707 my ($Self, $AttrVal) = @_;
2488  
2489 # In JS, \u000a is unicode char (note &#x5c;&#x75;&#x30;&#x30;&#x37;&#x32; -> \u0072 -> r, so do HTML entities first)
2490 # This can't be undone, so only do on stripped value
2491 0 ▶ $AttrVal =~ s/\\u(0?[\da-f]{1,6});?/defined($1) && hex($1) < 1_114_111 && hex($1) != 65535 && !(hex($1) > 55295 && hex($1) < 57344) ? chr(hex($1)) : ""/egi;
Branch: 1 branch
BranchTrueFalseTotal
defined $1 && hex $1 < 1114111 && hex $1 != 65535 && !(hex $1 > 55295 && hex $1 < 57344) ? : 0 0 0
Condition0%0/12
defined $1 and hex $1 < 1114111 and hex $1 != 65535 and not hex $1 > 55295 && hex $1 < 57344
!ll&&!rl&&r
000
defined $1 and hex $1 < 1114111 and hex $1 != 65535
!ll&&!rl&&r
000
defined $1 and hex $1 < 1114111
!ll&&!rl&&r
000
hex $1 > 55295 && hex $1 < 57344
!ll&&!rl&&r
000
MC/DC0%0/5
defined $1 and hex $1 < 1114111 and hex $1 != 65535 and not hex $1 > 55295 && hex $1 < 57344
defined $1 hex $1 < 1114111 hex $1 != 65535 hex $1 > 55295 hex $1 < 57344
Truth table0%0/6
A and B and C and not(D && E)
A= defined $1B= hex $1 < 1114111C= hex $1 != 65535D= hex $1 > 55295E= hex $1 < 57344
ABCDEresult
0XXXX0
10XXX0
110XX0
111110
1110X1
111101
2492  
2493 # Also undo URL decoding for "stripped" value
2494 # (can't do this above, because it's non-reversible, eg "http://...?a=%25" => "http://...?a=?",
2495 # how would we know which ? to requote when outputting?)
2496 707 $AttrVal =~ s/%([\da-f]{2})/chr(hex($1))/egi;
2497 707 $AttrVal =~ s/[\x00-\x19]+//g;
2498 707 $AttrVal =~ s/^[\x20]+//g; # http://ha.ckers.org/xss.html#XSS_Spaces_meta_chars
2499  
2500 707 return $AttrVal;
2501 }
2502  
2503 0 ▶sub get_applicable_charset {
Subroutine get_applicable_charset: not called CC=9 SCAR=45.0
Pod undocumented
2504  
2505 0 my $Self = shift;
2506 0 local $_ = shift;
2507 0 my $Charset = shift;
2508  
2509 0 ▶ if(!$Charset) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Charset) 0 0 0
2510 # Look for <meta> tags
2511 0 my @MetaAttrs = /<meta[\s\/]+(${AttributesRE})/gi;
2512  
2513 0 for(@MetaAttrs) {
2514 0 my %Attrs;
2515  
2516 # Get attributes and their values
2517 0 ▶ while(s/(?:($AttrKeyStartLineRE)(\s*))?(?:(=\s*)($AttrValRE)(\s*))?//so) {
Branch: 1 branch
BranchTrueFalseTotal
if (s/(?:($AttrKeyStartLineRE)(\s*))?(?:(=\s*)($AttrValRE)(\s*))?//os) 0 0 0
2518 0 ▶ last if !defined($1) && !defined($4);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $1 or defined $4 0 0 0
Condition0%0/3
defined $1 or defined $4
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $1 or defined $4
defined $1 defined $4
Truth table0%0/3
A or B
A= defined $1B= defined $4
ABresult
1X1
011
000
2519 0 $Attrs{lc $1} = $4;
2520 }
2521  
2522 # Look for charset information
2523 0 ▶ if($Attrs{"content"}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Attrs{"content"}) 0 0 0
2524 0 ▶ $Charset = $Attrs{"content"} =~ m/charset\s*=\s*([^\s;'"`]+)[\s;'"`]*/i ? $1 : $Charset;
Branch: 1 branch
BranchTrueFalseTotal
$Attrs{'content'} =~ /charset\s*=\s*([^\s;'"`]+)[\s;'"`]*/i ? : 0 0 0
2525 }
2526 }
2527 }
2528  
2529 # Return fallback charset if no header or meta charset found
2530 0 ▶ return $Charset ? $Charset : shift;
Branch: 1 branch
BranchTrueFalseTotal
$Charset ? : 0 0 0
2531 }
2532  
2533 =head1 SEE ALSO
2534  
2535 L<http://mailtools.anomy.net/>, L<http://htmlcleaner.sourceforge.net/>, I<HTML::StripScripts>, I<HTML::Detoxifier>, I<HTML::Sanitizer>, I<HTML::Scrubber>
2536  
2537 =cut
2538  
2539 =head1 AUTHOR
2540  
2541 Kurian Jose Aerthail E<lt>cpan@kurianja.fastmail.fmE<gt>. Thanks to Rob Mueller E<lt>cpan@robm.fastmail.fmE<gt> for initial code, guidance and support and bug fixes.
2542  
2543 =cut
2544  
2545 =head1 COPYRIGHT AND LICENSE
2546  
2547 Copyright (C) 2003-2013 by FastMail Pty Ltd
2548  
2549 This library is free software; you can redistribute it and/or modify
2550 it under the same terms as Perl itself.
2551  
2552 =cut
2553  
2554 9 1;
2555  
↑ Summary