| 1 | |||
| 2 | ############################################################################ | ||
| 3 | # base class for packet flows | ||
| 4 | ############################################################################ | ||
| 5 | |||
| 6 | use strict; | ||
| 7 | use warnings; | ||
| 8 | |||
| 9 | package Net::Inspect::Flow; | ||
| 10 | use fields qw(upper_flow); | ||
| 11 | |||
| 12 | sub new { | ||
| 13 | my ($class,$flow) = @_; | ||
| 14 | if ( ! ref($class)) { | ||
| 15 | # create new | ||
| 16 | my $self = fields::new($class); | ||
| 17 | $self->{upper_flow} = $flow; | ||
| 18 | return $self; | ||
| 19 | } else { | ||
| 20 | my $self = fields::new(ref($class)); | ||
| 21 | $self->{upper_flow} = $flow | ||
| 22 | || ( $class->{upper_flow} && $class->{upper_flow}->new ); # clone | ||
| 23 | return $self; | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | sub new_any { | ||
| 28 | shift; | ||
| 29 | return Net::Inspect::Flow::Any->new(@_) | ||
| 30 | } | ||
| 31 | |||
| 32 | # does nothing per default | ||
| 33 | sub expire {} | ||
| 34 | |||
| 35 | package Net::Inspect::Flow::Any; | ||
| 36 | use Digest::MD5 'md5_hex'; | ||
| 37 | use fields qw(flows); | ||
| 38 | |||
| 39 | sub new { | ||
| 40 | my ($class,@methods) = @_; | ||
| 41 | if (@methods) { | ||
| 42 | my $clname = "Net::Inspect::Flow::Any::". | ||
| 43 | md5_hex(join("\0",sort @methods)); | ||
| 44 | if ( ! UNIVERSAL::can($clname,'new') ) { | ||
| 45 | # dynamically create class | ||
| 46 | eval "package $clname; use base 'Net::Inspect::Flow::Any';1" | ||
| 47 | or die $@; | ||
| 48 | for my $method (@methods) { | ||
| 49 | no strict 'refs'; | ||
| 50 | *{ "${clname}::$method" } = sub { | ||
| 51 | my $self = shift; | ||
| 52 | for my $flow (@{$self->{flows}}) { | ||
| 53 | if ( wantarray ) { | ||
| 54 | my @rv = $flow->$method(@_) or next; | ||
| 55 | return @rv | ||
| 56 | } else { | ||
| 57 | defined( my $rv = $flow->$method(@_)) or next; | ||
| 58 | return $rv | ||
| 59 | } | ||
| 60 | } | ||
| 61 | return; | ||
| 62 | }; | ||
| 63 | } | ||
| 64 | } | ||
| 65 | return $clname->new; | ||
| 66 | } | ||
| 67 | |||
| 68 | |||
| 69 | if ( ! ref $class ) { | ||
| 70 | my $self = fields::new($class); | ||
| 71 | $self->{flows} = []; | ||
| 72 | return $self | ||
| 73 | } else { | ||
| 74 | my $self = fields::new(ref($class)); | ||
| 75 | # clone attached flows | ||
| 76 | $self->{flows} = [ map { $_->new } @{ $class->{flows} } ]; | ||
| 77 | return $self; | ||
| 78 | } | ||
| 79 | } | ||
| 80 | |||
| 81 | sub attach { | ||
| 82 | my ($self,$flow) = @_; | ||
| 83 | push @{ $self->{flows} }, $flow; | ||
| 84 | } | ||
| 85 | |||
| 86 | sub detach { | ||
| 87 | my ($self,$flow) = @_; | ||
| 88 | @{ $self->{flows} } = grep { $_ != $flow } @{ $self->{flows} }; | ||
| 89 | } | ||
| 90 | |||
| 91 | sub attached { | ||
| 92 | my $self = shift; | ||
| 93 | return @{ $self->{flows} } | ||
| 94 | } | ||
| 95 | |||
| 96 | 1; | ||
| 97 | |||
| 98 | __END__ |