blib/lib/HTML/Defang.pm

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