DFA.pm untested

filter: Statementstmt 0.0% 0 / 484 Branchbran 0.0% 0 / 130 Conditioncond 0.0% 0 / 110 MC/DCmcdc 0.0% 0 / 63 Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 845 CC 66 SCAR 45.6
CC
66
Cov
0%
test
272.0
verify
240.0
add_transition
72.0
CRAP 96.0
1 =head1 DFA
2  
3 =head2 Introduction
4  
5 A DFA is a collection of L<IDS::Algorithm::DFAState>s. A DFA consists of the following:
6  
7 =over
8  
9 =item states
10  
11 A reference to a list of states. Functions that return information about
12 this variable: print, printvcg. Functions that indirectly return
13 information about this variable: test_instance, stats, verify.
14 Functions that manipulate this variable: load, add_transition,
15 collapse_states.
16  
17 =item tokens
18  
19 A reference to a hash. The index of the hash is the token, the value is
20 the state that that token will cause a transition into.
21  
22 Functions that manipulate this variable: rebuild_tokens, add_transition.
23 Used by: verify, test_instance.
24  
25 =item verbose
26  
27 The verbosity level; the higher the value, the more messages are
28 produced.
29  
30 TODO: define the verbosity levels.
31  
32 =item start
33  
34 A reference to the start state.
35  
36 =item accept
37  
38 A reference to the accept state.
39  
40 =back
41  
42 states[0] is the start state.
43 states[1] is the accept state.
44 However, relying on this is a bad idea; use the references to these
45 states.
46  
47 =head2 Methods
48  
49 =cut
50  
51 package IDS::Algorithm::DFA;
52 use base qw(IDS::Algorithm);
53  
54 use strict;
55 use warnings;
56 use IO::Handle;
57 use IDS::Algorithm::DFAState;
58 use Carp qw(cluck carp confess);
59  
60 $IDS::Algorithm::DFA::VERSION = "3.1";
61  
62 =over
63  
64 =item new()
65  
66 =item new(filehandle)
67  
68 Create a new DFA with two states, the start and accept states. If the
69 filehandle is supplied, load the DFA (in the format used by print()).
70  
71 =back
72  
73 =cut
74  
75 sub new {
76 my $invocant = shift;
77 my $class = ref($invocant) || $invocant;
78 my $self = {
79 states => [], # a set of states
80 tokens => {}, # token to a list of states that the token will
81 # cause a transition into
82 ### need to see if the list is ever larger than 1
83 };
84 bless($self, $class);
85 $self->default_parameters;
86 my $source = $self->handle_parameters(@_);
87 $self->load($source) if defined($source);
88  
89 $self->{"states"}[0] = IDS::Algorithm::DFAState->new($self->{"params"}{"verbose"}); # Start state
90 $self->{"start"} = $self->{"states"}[0];
91 $self->{"states"}[1] = IDS::Algorithm::DFAState->new($self->{"params"}{"verbose"}); # Accept state
92 $self->{"accept"} = $self->{"states"}[1];
93 ${$self->{"tokens"}}{'(ACCEPT)'} = $self->{"accept"};
94  
95 return $self;
96 }
97  
98 =over
99  
100 =item load(filehandle)
101  
102 Load a DFA from a file; this is the inverse of "print", and the format
103 we expect is that used in $self->print.
104  
105 =back
106  
107 =cut
108  
109 sub load {
110 my $self = shift;
111 my $fname = shift;
112 defined($fname) && $fname or
113 $fname = ${$self->{"params"}}{"state_file"};
114 defined($fname) && $fname or
115 confess *load{PACKAGE} . "::load missing filename";
116 my ($cnt, $from, $to, $token, $l, $fh);
117 my $verbose = ${$self->{"params"}}{"verbose"};
118  
119 $fh = new IO::File "<$fname" or
120 confess *load{PACKAGE} . "::load Unable to open $fname for reading: $!";
121
122 $l = 0;
123 while (<$fh>) {
124 chomp;
125 $l++;
126 ($from, $to, $cnt) = /^State (\d+) To (\d+) count (\d+) Token:$/;
127 defined($from) or confess *load{PACKAGE} . "::load missing 'from' on line $l";
128 defined($to) or confess *load{PACKAGE} . "::load missing 'to' on line $l";
129 defined($cnt) or confess *load{PACKAGE} . "::load missing 'cnt' on line $l";
130 $token = <$fh>;
131 defined($token) or confess *load{PACKAGE} . "::load missing 'token' on line $l";
132 $token =~ s/^ //;
133 chomp $token;
134 defined($self->{"states"}[$from]) or
135 $self->{"states"}[$from] = IDS::Algorithm::DFAState->new($verbose);
136 defined($self->{"states"}[$to]) or
137 $self->{"states"}[$to] = IDS::Algorithm::DFAState->new($verbose);
138 $self->{"states"}[$from]->add_outbound($token, $self->{"states"}[$to]);
139 $self->{"states"}[$to]->add_inbound($self->{"states"}[$from], $token);
140 $self->{"states"}[$from]->set_count($token, $cnt);
141 ${$self->{"tokens"}}{$token} = $self->{"states"}[$to];
142 }
143 $self->verify if $verbose; # paranoia
144 }
145  
146 =over
147  
148 =item stats()
149  
150 Return general statistics about the DFA.
151  
152 =back
153  
154 =cut
155  
156 sub stats {
157 my $self = shift;
158 my ($t, $v);
159  
160 my $states = $#{$self->{"states"}} + 1;
161 my $tokens = scalar keys %{$self->{"tokens"}};
162  
163 my $edges = 0;
164 for my $s (@{$self->{"states"}}) {
165 $edges += scalar $s->out_tokens();
166 }
167  
168 return "$states " . $self->plural("state", $states) .
169 " $tokens " . $self->plural("token", $tokens) .
170 " $edges " . $self->plural("edge", $edges);
171 }
172  
173 =over
174  
175 =item prune(threshold)
176 =item prune(node_threshold, edge_threshold)
177  
178 Delete nodes and edges used fewer than threshold times. If only one
179 threshold is provided, it is used for both.
180  
181 =back
182  
183 =cut
184  
185 sub prune {
186 my $self = shift;
187 my $node_thresh = shift;
188 defined($node_thresh) or
189 confess *prune{PACKAGE} . "::prune missing 'threshold'";
190 my $edge_thresh = shift;
191 defined($edge_thresh) or $edge_thresh = $node_thresh; # default
192 my ($state, $deleted, $d, $verbose, $i);
193
194 $verbose = ${$self->{"params"}}{"verbose"};
195  
196 ### node and edge pruning should be able to be combined into one
197 ### loop. They are separate to make consistency checking easier
198 ### (for tracking down bugs in the pruning process).
199  
200 print STDERR "About to prune\n" if $verbose;
201 ### TEST: is this clobbering the node map later?
202 #$deleted = $self->node_prune($node_thresh);
203 #print STDERR "node pruning deleted $deleted.\n" if $verbose;
204 $self->verify || warn "Verify failed ($deleted)\n"; ### will not want this in production; too slow
205  
206 $d = $self->edge_prune($edge_thresh);
207 $deleted += $d;
208 print STDERR "edge pruning deleted $d.\n" if $verbose;
209 $self->verify || warn "Verify failed ($deleted)\n"; ### will not want this in production; too slow
210  
211 ### TEST: is this clobbering the node map later?
212 # while (($d = $self->deadend_prune) > 0) {
213 # $deleted += $d;
214 # print STDERR "deadend pruning deleted $d.\n" if $verbose;
215 # }
216 # $self->verify || warn "Verify failed ($deleted)\n"; ### will not want this in production; too slow
217  
218 print STDERR $self->stats, "\n" if $verbose;
219 #$self->rebuild_tokens if $deleted;
220 #print STDERR "About to start final consistency check.\n" if $verbose;
221 #$self->verify || warn "Final verify failed ($deleted)\n"; ### will not want this in production; too slow
222  
223 return $deleted;
224 }
225  
226 sub deadend_prune {
227 my $self = shift;
228 my ($state, $deleted, %seen, @tovisit, $s, $d);
229  
230 # find the reachable nodes.
231 %seen = (); $seen{$self->{"start"}} = 1;
232 @tovisit = $self->{"start"}->out_states;
233 while ($#tovisit >= 0) {
234 $s = pop @tovisit;
235 $seen{$s} = 1;
236 for $d ($s->out_states) {
237 $seen{$d} or push @tovisit, $d;
238 }
239 }
240  
241 # Drop all states that became unreachable.
242 $deleted = 0;
243 for (my $i=0; $i <= $#{$self->{"states"}}; $i++) {
244 my $state = ${$self->{"states"}}[$i];
245  
246 # never prune the start and accept states
247 next if $state eq $self->{"start"} || $state eq $self->{"accept"};
248  
249 # below gets dead ends; should we keep them?
250 #if ($state->out_links == 0 || $state->in_links == 0) {
251  
252 # This gets rid of completely unreachable states.
253 unless (exists($seen{$state})) {
254 $state->drop_all_edges;
255 splice @{$self->{"states"}}, $i, 1;
256 $deleted++;
257 }
258 }
259 return $deleted;
260 }
261  
262 sub edge_prune {
263 my $self = shift;
264 my $edge_thresh = shift;
265 defined($edge_thresh) or
266 confess *edge_prune{PACKAGE} . "::edge_prune missing 'threshold'";
267 my ($state, $verbose);
268  
269 $verbose = ${$self->{"params"}}{"verbose"};
270  
271 for $state (@{$self->{"states"}}) {
272 # never prune the start and accept states
273 next if $state eq $self->{"start"} || $state eq $self->{"accept"};
274  
275 my $dropped = $state->drop_edges($edge_thresh);
276 print STDERR "Dropped $dropped edges from state $state\n"
277 if $verbose;
278 }
279 return $self->delete_empty;
280 }
281  
282 sub node_prune {
283 my $self = shift;
284 my $node_thresh = shift;
285 defined($node_thresh) or
286 confess *node_prune{PACKAGE} . "::node_prune missing 'threshold'";
287 my ($state, $deleted, $verbose);
288  
289 $verbose = ${$self->{"params"}}{"verbose"};
290 $deleted = 0;
291 for $state (@{$self->{"states"}}) {
292 # never prune the start and accept states
293 next if $state eq $self->{"start"} || $state eq $self->{"accept"};
294  
295 if ($state->visits < $node_thresh) {
296 print STDERR "Dropping $state; visits ", $state->visits,
297 " thresh $node_thresh\n" if $verbose;
298 #$state->print if $verbose;
299 #$state->browse("About to drop");
300 $state->drop_all_edges;
301 $deleted++;
302 }
303 }
304 $deleted += $self->delete_empty;
305  
306 return $deleted;
307 }
308  
309 # delete all of the empty states.
310 sub delete_empty {
311 my $self = shift;
312 my ($i, $state, $deleted);
313  
314 $deleted = 0;
315 for ($i=0; $i <= $#{$self->{"states"}}; $i++) {
316 $state = ${$self->{"states"}}[$i];
317 if ($state->out_links == 0 && $state->in_links == 0) {
318 splice @{$self->{"states"}}, $i, 1;
319 $deleted++;
320 $i--; # to account for the deleted entry.
321 }
322 }
323 return $deleted;
324 }
325  
326 =over
327  
328 =item rebuild_tokens()
329  
330 We deleted one or more states. Rebuild our list of what tokens go
331 where.
332  
333 =back
334  
335 =cut
336  
337 ### This whole function is a kludge; find a way of keeping things
338 ### straight.
339 sub rebuild_tokens {
340 my $self = shift;
341 my ($k, $v, $t, $state);
342
343 %{$self->{"tokens"}} = ();
344 # rebuild the list of tokens
345 for $state (@{$self->{"states"}}) {
346 for $t ($state->in_tokens()) {
347 defined($t) or confess "t state undefined\n";
348 if (exists(${$self->{"tokens"}}{$t})) {
349 my $clobbered = ${$self->{"tokens"}}{$t};
350 carp "clobbering an existing token ($clobbered) with $t";
351 }
352 ${$self->{"tokens"}}{$t} = $state;
353 }
354 }
355 }
356  
357 =over
358  
359 =item reset_counters()
360  
361 Reset all of the counters associated with node and edge use.
362  
363 =back
364  
365 =cut
366  
367 sub reset_counters {
368 my $self = shift;
369  
370 for my $state (@{$self->{"states"}}) {
371 $state->reset_counters;
372 }
373 }
374  
375 =over
376  
377 =item add(token_listref)
378  
379 The collection of tokens (in the list referenced by token_listref)
380 is a complete example of a list that should be accepted by the DFA.
381  
382 WE add the transition from the last token to the '(ACCEPT)' state.
383  
384 =back
385  
386 =head3 How learning occurs:
387  
388 =begin latex
389  
390 The learning algorithm is based on one by Burge \cite{Burge2003DFA}.
391 We chose this algorithm because it is straightforward to implement,
392 and it works well in our situation. The learning algorithm proceeds
393 as follows:
394 \begin{enumerate}
395 \item A parser breaks a HTTP request into a list of tokens; the
396 last token is the ``ACCEPT'' token.
397 \item The current state ($C$) is set to the ``START'' state.
398 \item For each token $T_i$ in the list of tokens, do
399 \begin{enumerate}
400 \item If a transition using $T_i$ exists from $C$ to some other state
401 $D$, set $C$ to $D$.
402 \item If no such transition exists, look for a node ($D$) which has
403 been the destination for the same token, but from some other node.
404 If $D$ exists, (it will be unique), add a transition from $C$ to $D$.
405 Set $C$ to $D$. A picture of this step is in
406 Figure~\ref{add_transition}.
407 \item If no node $D$ exists, create a new node ($E$) and create a
408 transition from $C$ to $E$. Set $C$ to $E$. A picture of this step is
409 in Figure~\ref{add_node}.
410 \end{enumerate}
411 \end{enumerate}
412  
413 \begin{figure*}
414 \input{DFA-learning-a.tex}
415 \caption{As the learner is traversing the DFA, it sometimes must add a
416 transition or new node. In (a), the current state is $C$ and the
417 next token ($T_i$) is the same token that caused the transition from $B$
418 to $D$. The learner will change the DFA to that in (b) by adding add
419 the
420 transition from $C$ to $D$.}
421 \label{add_transition}
422 \end{figure*}
423 \begin{figure*}
424 \input{DFA-learning-b.tex}
425 \caption{As the learner is traversing the DFA, it sometimes must add a
426 transition or new node. In (a), the current state is $C$ and no
427 existing transition for the token $T_i$ exists. Therefore, the
428 learner will change the DFA to that in (b) by adding both the node $E$
429 and the transition from $C$ to $E$.}
430 \label{add_node}
431 \end{figure*}
432  
433 =end latex
434  
435 =cut
436  
437 sub add {
438 my $self = shift;
439 my $data = shift or
440 confess *add{PACKAGE} . "::add missing data to add";
441 my ($current_state, $t);
442 my $verbose = ${$self->{"params"}}{"verbose"};
443  
444 $current_state = $self->{"start"};
445 print "Start $current_state\n" if $verbose;
446 $current_state->visited;
447 foreach $t (@{$data}) {
448 defined($t) or cluck("undefined token in add. List: '" .
449 join("' '", @{$data}) . "'");
450 print "Adding a transition from $current_state for $t\n" if $verbose;
451 $current_state = $self->add_transition($current_state, $t);
452 $current_state->visited;
453 print " New state $current_state\n" if $verbose;
454 }
455 print "Adding a transition from $current_state for (ACCEPT)\n" if $verbose;
456 $current_state = $self->add_transition($current_state, "(ACCEPT)");
457 }
458  
459 =over
460  
461 =item add_transition(from, token)
462  
463 Add a transition from one state to another when the specified token is
464 received. It is not an error to try to add an existing transition.
465 In that event, this function quietly returns. If no such transition
466 exists, we look for a transition on the token; if so, we add an edge to
467 the destination node for the existing edge. Finally, if there is no
468 other choice, we create a new state and add the edge.
469  
470 =back
471  
472 =cut
473  
474 sub add_transition {
475 my $self = shift;
476 my $from = shift;
477 defined($from) or
478 confess *add_transition{PACKAGE} . "::add_transition missing 'from'";
479 $from->isa("IDS::Algorithm::DFAState") or
480 confess *add_transition{PACKAGE} . "::add_transition 'from' is wrong type";
481 my $token = shift; # the token causing the transition
482 defined($token) or
483 confess *add_transition{PACKAGE} . "::add_transition missing 'token'";
484 my $verbose = ${$self->{"params"}}{"verbose"};
485 my ($next, $end, $s, $next_state, $n);
486  
487 # special handling for accept state
488 ### Commented out because if everything is properly set up (in new())
489 ### this part should not be necessary.
490 # if ($token eq "(ACCEPT)") {
491 # $end = $self->{"accept"};
492 # defined($end) or
493 # confess *add_transition{PACKAGE} . "::add_transition missing accept state in DFA";
494 # $next = $from->next($token);
495 # return if defined($next) && $end eq $next;
496 # $from->add_outbound($token, $end);
497 # return $end;
498 # }
499  
500 # First, see if a transition on this token already exists; if so,
501 # we will assume (valid?) that it is what we want.
502 $next = $from->next($token);
503 print " existing transition $next\n" if defined($next) && $verbose;
504 if (defined($next)) {
505 $from->followed($token);
506 return $next;
507 }
508  
509 print " No existing transition\n" if $verbose;
510 # OK, we know the transition does not exist. Does a *single*
511 # state exist that this token has caused a transition to in
512 # the past? If so, we assume (valid?) that we want to follow it.
513 # In this DFA, a token can cause only one transition.
514 if (exists ${$self->{"tokens"}}{$token}) {
515 $s = ${$self->{"tokens"}}{$token};
516 $from->add_outbound($token, $s);
517 $from->followed($token);
518 print " going to existing state $s\n" if $verbose;
519 return $s;
520 }
521  
522 print " No existing state\n" if $verbose;
523 # We have run out of re-use options. Create a new state and
524 # set up the transition into it.
525 $next_state = IDS::Algorithm::DFAState->new($verbose);
526 $from->add_outbound($token, $next_state);
527 $from->followed($token);
528 # done in add_outbound: $next_state->add_inbound($from, $token);
529 ${$self->{"tokens"}}{$token} = $next_state;
530 push @{$self->{"states"}}, $next_state;
531 $n = $#{$self->{"states"}};
532 print " State $n $next_state\n" if $verbose;
533 return $next_state;
534 }
535  
536 sub save {
537 my $self = shift;
538 my $dest = shift;
539 my $destfh;
540  
541 if (defined($dest) && ! $dest->isa("IO::Handle")) {
542 $destfh = IO::File->new("> $dest");
543 defined($destfh) or confess "Cannot open $dest: $!";
544 } else {
545 $destfh = $dest;
546 }
547  
548 return $self->print($destfh);
549 }
550  
551 =over
552  
553 =item print
554  
555 =item print(filehandle)
556  
557 Print in a form both usable by humans as well as for reading back in
558 with the load subroutine. If the filehandle is specified, print there;
559 otherwise, print to STDOUT.
560  
561 =back
562  
563 =cut
564  
565 sub print {
566 my $self = shift;
567 my $fh = $self->get_fh(shift);
568 my ($i, $s, $node_map);
569  
570 print $#{$self->{"states"}} + 1, " nodes\n";
571  
572 $i = 0;
573 for $s (@{$self->{"states"}}) {
574 $node_map->{$s} = $i++;
575 }
576  
577 for $s (@{$self->{"states"}}) {
578 $s->print_edges($node_map, $fh);
579 }
580 }
581  
582 =over
583  
584 =item printvcg
585  
586 =item printvcg(filehandle)
587  
588 Print in a form usable by VCG for printing the DFA.
589  
590 If the filehandle is specified, print there; otherwise, print to STDOUT.
591  
592 =back
593  
594 =cut
595  
596 sub printvcg {
597 my $self = shift;
598 my $fh = $self->get_fh(shift);
599 my ($i, $node_map, $s);
600  
601 print $fh "graph: { layoutalgorithm: minbackward\n" .
602 " manhattan_edges: yes\n" .
603 " splines: yes\n" .
604 " display_edge_labels: yes\n" .
605 " port_sharing: no\n" .
606 ' title: "HTTP DFA"' . "\n\n";
607  
608 # The nodes
609 $i = 0;
610 for $s (@{$self->{"states"}}) {
611 $s->print_vcg_node($i, $fh);
612 $node_map->{$s} = $i;
613 $i++;
614 }
615 print $fh "\n";
616  
617 # The transitions
618 # This loop cannot be combined with the one above because nodes have
619 # to be defined for vcg before they are referenced.
620 for $s (@{$self->{"states"}}) {
621 $s->print_vcg_edges($node_map, $fh);
622 }
623 print $fh "}\n";
624 }
625  
626 =over
627  
628 =item clean(type)
629  
630 Clean the DFA.
631  
632 Clean by collapsing states. We will do this until we get no changes in
633 the size of the DFA. This cleaning is appropriate for any time.
634  
635 If type eq "test", we collapse, then prune. Pruning only makes sense
636 if training has already occurred and we are testing.
637  
638 If type eq "train" or is undefined, we only collapse states.
639  
640 =back
641  
642 =cut
643  
644 sub clean {
645 my $self = shift;
646 my $type = shift;
647  
648 # Collapse
649 my $i = 0;
650 while ($self->collapse_states()) { $i++ };
651  
652 if (defined($type) && $type eq "test" &&
653 ${$self->{"params"}}{"prune_threshold"} > 0) {
654 $self->prune(${$self->{"params"}}{"prune_threshold"});
655 }
656 }
657  
658 =over
659  
660 =item generalize()
661  
662 Generalization is simply cleaning as if we were training. This function
663 exists to fit the IDS::Test framework.
664  
665 =back
666  
667 =cut
668  
669 sub generalize {
670 my $self = shift;
671  
672 $self->clean(undef);
673 }
674  
675 =over
676  
677 =item collapse_states()
678  
679 Look for identical transitions and collapse them into one state.
680  
681 TODO: More description here
682  
683 =back
684  
685 =cut
686  
687 sub collapse_states {
688 my $self = shift;
689 my $start = $#{$self->{"states"}}; # for stats on how many we collapsed
690 my $verbose = ${$self->{"params"}}{"verbose"};
691  
692 # loop through nodes, looking for duplicates. n^2 algorithm, sigh
693 ### change to alg where sort by source and dest nodes before
694 ### comparing; then O(n log n)
695 for (my $i=0; $i<$#{$self->{"states"}}; $i++) {
696 for (my $j=$i+1; $j<=$#{$self->{"states"}}; $j++) {
697 my ($si, $sj); # prettier code
698 $si = ${$self->{"states"}}[$i];
699 $sj = ${$self->{"states"}}[$j];
700 my $nstates = $#{$self->{"states"}};
701  
702 ### Kludge; should not need this, but something is apparently creating undefined entries in states
703 unless (defined($sj)) {
704 cluck "sj undefined: i $i j $j nstates $nstates";
705 #warn "Starting verify pass with verbose on\n";
706 #${$self->{"params"}}{"verbose"} = 1;
707 #$self->verify;
708 #warn "verify pass done\n";
709  
710 splice(@{$self->{"states"}}, $j, 1);
711 last if $j > $#{$self->{"states"}};
712 $sj = ${$self->{"states"}}[$j];
713 }
714 confess "si or sj undefined. nstates $nstates i $i j $j si '$si' sj '$sj'\n" unless defined($si) && defined($sj);
715  
716 if ($si->compare($sj) == 0) {
717 print STDERR "States $i ($si) and $j ($sj) are the same.\n"
718 if $verbose > 0;
719 # Change the state that a token causes a change into for
720 # the about-to-be-deleted state. A lot happens in these
721 # next three lines.
722 for my $token ($sj->in_tokens()) {
723 ${$self->{"tokens"}}{$token} = $si;
724 }
725 # the rest of the deletion is straightforward
726 $si->absorb($sj);
727 splice(@{$self->{"states"}}, $j, 1);
728 # readjust $j to account for the deletion
729 $j--;
730 }
731 }
732 }
733 my $end = $#{$self->{"states"}};
734 return $start - $end;
735 }
736  
737 =over
738  
739 =item test(tokensref)
740  
741 Test a list of tokens against the DFA by attempting to traverse the DFA
742 from the start to the (single) accept node. If no transition exists
743 for a token, this event is counted. The verifier then attempts to
744 resynchronize by looking at the next token in the stream. If the
745 edge corresponding to this token exists in the DFA, then the verifier
746 will traverse this edge (even though it was not in a state with this
747 outbound edge). If no such edge exists, another miss has occurred,
748 and the verifier tries again with the next token. The similarity
749 value returned is:
750  
751 =begin latex
752 \[
753 \frac{\mbox{\rm \# of tokens where a transition is taken}}{\mbox{\rm \#
754 of tokens in the HTTP request}}
755 \in [0,1]
756 \]
757  
758 =end latex
759  
760 Note: WE put in the '(ACCEPT)' token at the end of the list we are
761 passed.
762  
763 Q: do we want to update the counters only if the test indicates
764 normality? If so, it looks like we're commiting to two runs, one to
765 determine normality and the second to update the counters. For now,
766 we will update on the fly, but will hold this idea in reserve.
767  
768 =back
769  
770 =cut
771  
772 sub test {
773 my $self = shift;
774 my $tokensref = shift or # list of tokens making up the data to test
775 confess *test_instance{PACKAGE} . "::test_instance missing tokenref";
776  
777 my ($t, $misfires, $ntokens);
778 my $verbose = ${$self->{"params"}}{"verbose"};
779  
780 my $current_state = $self->{"start"};
781 defined($current_state) or
782 confess *test{PACKAGE} . "::test missing start state in DFA";
783  
784 $misfires = 0;
785 foreach $t (@{$tokensref}, "(ACCEPT)") { # note included eof token
786 if (defined($current_state)) {
787 $current_state->visited;
788 my $next = $current_state->next($t);
789 print STDERR "Looking for a transition for token '$t'\n"
790 if $verbose;
791 if (defined($next)) {
792 # if a transition exists, take it
793 print STDERR " Found existing state transition\n"
794 if $verbose;
795 $current_state->followed($t);
796 $current_state = $next;
797 } else {
798 # the transition does not exist; misfire + try to resync
799 print STDERR " Misfire\n" if $verbose;
800 $misfires++;
801 $current_state = defined(${$self->{"tokens"}}{$t})
802 ? ${$self->{"tokens"}}{$t}
803 : undef;
804 print STDERR "Resync failed on token '$t'\n"
805 if !defined($current_state) && $verbose;
806 }
807 } else { # we got lost earlier and are trying to resync
808 $misfires++;
809 $current_state = defined(${$self->{"tokens"}}{$t})
810 ? ${$self->{"tokens"}}{$t}
811 : undef;
812 print STDERR "able to resync\n"
813 if $verbose && defined($current_state);
814 }
815 }
816  
817 # see if we are in the accept state. If not, then count a misfire
818 if (defined($current_state)) {
819 unless ($self->{"accept"} eq $current_state) {
820 print STDERR "Misfire due to not ending in accept state\n" if $verbose;
821 $misfires++;
822 }
823 } else {
824 print STDERR "Misfire due to undefined current state\n" if $verbose;
825 $misfires++;
826 }
827  
828 $ntokens = $#{$tokensref} + 2; # 2 because of indexing starting at
829 # 0 and because of the end-of-input token
830 print STDERR "misfires $misfires ntokens $ntokens\n" if $verbose;
831 my $ret = 1 - ($misfires / $ntokens);
832 return $ret > 0 ? $ret : 0; # return value cannot be less than 0,
833 # but our calculation can be slightly
834 # negative in some really bad cases.
835 }
836  
837 =over
838  
839 =item verbose(level)
840  
841 Set the verbosity level. Higher values imply more output. Values over
842 2 are unlikely to be useful.
843  
844 =back
845  
846 =cut
847  
848 sub verbose {
849 my $self = shift;
850 my $old = ${$self->{"params"}}{"verbose"};
851 my $new = shift;
852 ${$self->{"params"}}{"verbose"} = $new if defined($new);
853  
854 return $old;
855 }
856  
857 =over
858  
859 =item verify
860  
861 Verify the consistency of the DFA; this function exists to aid in
862 debugging, when it may be that a bug is causing it to be corrupted.
863 Consider this a ``fsck'' for a DFA.
864  
865 =back
866  
867 =cut
868  
869 sub verify {
870 my $self = shift;
871 my $OK = 1; # assume we are OK till proven otherwise
872 my $warn = 0; # no warnings yet
873 my ($i, $s, $t, $d, %seen, @tovisit, $missing);
874 my $verbose = ${$self->{"params"}}{"verbose"};
875  
876 my $start = time if $verbose;
877 print STDERR "Verifying; start at $start\n" if $verbose;
878  
879 # look for (and remove?) undefined states
880 for ($i=0; $i < $#{$self->{"states"}}; $i++) {
881 next if defined(${$self->{"states"}}[$i]);
882 warn "State $i undefined. Removing.\n";
883 #splice @{$self->{"states"}}, $i, 1;
884 }
885  
886 # verify that every node (except START) claims to have inbound links
887 for $s (@{$self->{"states"}}) {
888 next if $s eq $self->{"start"};
889 if ($s->in_links == 0) {
890 warn "$s has no inbound states\n";
891 $warn = 1;
892 }
893 }
894 print STDERR "Verify: inbound link check done; OK $OK; " . (time - $start) . "sec\n" if $verbose;
895  
896 # verify that every node (except ACCEPT) has outbound links
897 for $s (@{$self->{"states"}}) {
898 next if $s eq $self->{"accept"};
899 if ($s->out_links == 0) {
900 warn "$s has no outbound states\n";
901 # $s->browse("dead-end; " . scalar($s));
902 $warn = 1;
903 }
904 }
905 print STDERR "Verify: outbound link check done; OK $OK; " . (time - $start) . "sec\n" if $verbose;
906  
907 # verify that every transition is listed in the inbound list of the
908 # destination.
909 for $s (@{$self->{"states"}}) {
910 for $t ($s->out_tokens) {
911 $d = $s->next($t);
912 unless ($d->exists_inbound_from($s)) {
913 warn "$d has no inbound from $s (on $t)\n";
914 $s->browse("mixed-up; " . scalar($s));
915 $OK = 0;
916 }
917 }
918 }
919 print STDERR "Verify: out-in check done; OK $OK; " . (time - $start) . "sec\n" if $verbose;
920  
921 # verify that every node is reachable from the start node.
922 %seen = (); $seen{$self->{"start"}} = 1;
923 @tovisit = $self->{"start"}->out_states;
924 while ($#tovisit >= 0) {
925 $s = pop @tovisit;
926 $seen{$s} = 1;
927 for $d ($s->out_states) {
928 $seen{$d} or push @tovisit, $d;
929 }
930 }
931 $missing = scalar(@{$self->{"states"}}) - scalar(keys %seen);
932 if ($missing) {
933 warn "Missing access to $missing states\n";
934 $OK = 0;
935 }
936 print STDERR "Verify: reachability check done; warn $warn; OK $OK; " . (time - $start) . "sec\n" if $verbose;
937 print STDERR "Verify: OK $OK total time: ", (time - $start), "sec\n" if $verbose;
938  
939 return $OK;
940 }
941  
942 sub plural {
943 my $self = shift;
944 my $word = shift or confess *plural{PACKAGE} . "::plural Missing 'word'";
945 my $num = shift or confess *plural{PACKAGE} . "::plural Missing 'num'";
946  
947 return $num > 1 ? ($word . "s") : $word;
948 }
949  
950 sub get_fh {
951 my $self = shift;
952 my $fh = shift;
953 my $dest_fh = shift; # not required; default is STDOUT
954 defined($dest_fh) or $dest_fh = fileno(STDOUT);
955  
956 unless (defined($fh)) {
957 $fh = new IO::Handle;
958 $fh->fdopen($dest_fh,"w") or
959 confess "Unable to fdopen STDOUT: $!\n";
960 }
961 return $fh;
962 }
963  
964 =head2 Functions required by IDS::Algorithm
965  
966 =over
967  
968 =item default_parameters()
969  
970 Sets all of the default values for the parameters. Normally called by
971 new() or one of its descendents.
972  
973 =back
974  
975 =cut
976  
977 sub default_parameters {
978 my $self = shift;
979  
980 %{$self->{"params"}} = (
981 "verbose" => 0,
982 "state_file" => 0,
983 "prune_threshold" => 0,
984 "auto_generalization_threshold" => 10,
985 );
986 }
987  
988 =over
989  
990 =item param_options()
991  
992 Command-line option specifiers for our parameters for GetOpt::Long.
993  
994 =back
995  
996 =cut
997  
998 sub param_options {
999 my $self = shift;
1000  
1001 return (
1002 "dfa_verbose=i" => \$self->{"verbose"},
1003 "ids_state=s" => \${$self->{"params"}}{"state_file"},
1004 "prune_threshold=i" => \${$self->{"params"}}{"prune_threshold"},
1005 "auto_generalization_threshold=i" => \${$self->{"params"}}{"auto_generalization_threshold"},
1006 );
1007 }
1008  
1009 =head2 Functions for the auto id of where generalization is necessary.
1010  
1011 =over
1012  
1013 =item generalization_needed
1014  
1015 Looks through the DFA for high out-degrees with a low usage count. The high out
1016 degree says that we found a high variability here. The low usage count says
1017 that rarely were tokens duplicated.
1018  
1019 This is not a DFA walk, but a scan through the nodes.
1020  
1021 =back
1022  
1023 =cut
1024  
1025 sub generalization_needed {
1026 my $self = shift;
1027 my ($state, $max, $min, $nvref, $tnv, %in_tokens, $summary, $outdegree, $score);
1028 my ($sortfunc);
1029 my $verbose = ${$self->{"params"}}{"verbose"};
1030  
1031 # parameters, still under investigation as to what is important and why
1032 $verbose = 1;
1033  
1034 # $sortfunc = sub { ($b->autogen_nums)[0] <=> ($a->autogen_nums)[0] };
1035 # $sortfunc = sub { ($b->autogen_nums)[1] <=> ($a->autogen_nums)[1] };
1036 # $sortfunc = sub { ($b->autogen_nums)[2] <=> ($a->autogen_nums)[2] };
1037 $sortfunc = sub { ($b->autogen_nums)[3] <=> ($a->autogen_nums)[3] };
1038 # $sortfunc = sub { ($b->autogen_nums)[4] <=> ($a->autogen_nums)[4] };
1039 for $state (sort $sortfunc @{$self->{"states"}}) {
1040 ($min, $max, $outdegree, $score, $nvref) = $state->autogen_nums;
1041 %in_tokens = ();
1042 map {$in_tokens{$_}++} $state->in_tokens;
1043 $summary = "";
1044 map {$summary .= "(" . ${$nvref}{$_} . ") " . $_ . "; " } keys %{$nvref};
1045 print join("; ", keys %in_tokens), "; out degree $outdegree; ",
1046 "min $min max $max; score: $score; ",
1047 "Token type(s): $summary\n" if $verbose;
1048 }
1049 }
1050  
1051 =head1 AUTHOR INFORMATION
1052  
1053 Copyright 2005-2007, Kenneth Ingham. All rights reserved.
1054  
1055 This library is free software; you can redistribute it and/or modify
1056 it under the same terms as Perl itself.
1057  
1058 Address bug reports and comments to: ids_test at i-pi.com. When sending
1059 bug reports, please provide the versions of IDS::Test.pm, IDS::Algorithm.pm,
1060 IDS::DataSource.pm, the version of Perl, and the name and version of the
1061 operating system you are using. Since Kenneth is a PhD student, the
1062 speed of the reponse depends on how the research is proceeding.
1063  
1064 =head1 BUGS
1065  
1066 Please report them.
1067  
1068 =head1 SEE ALSO
1069  
1070 L<IDS::Test>, L<IDS::DataSource>, L<IDS::Algorithm>
1071  
1072 =cut
1073  
1074 1;